diff --git a/.travis.yml b/.travis.yml index ece420eaa5..eae37104fc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -267,3 +267,4 @@ matrix: script: - echo 'Checking that there is no GPL licence text in code' - ! git grep -q --ignore-case "gnu general public"; + - ! git grep -q --ignore-case "gnu library general public"; diff --git a/README.md b/README.md index 68b9acaaf0..778ef47831 100644 --- a/README.md +++ b/README.md @@ -33,3 +33,9 @@ We have a [developer website](https://os.mbed.com) for asking questions, engagin ## Getting started for contributors We also have a [contributing and publishing guide](https://os.mbed.com/contributing/) that covers licensing, contributor agreements and style guidelines. + +## Documentation + +For more information about Mbed OS, please see [our published documentation](https://os.mbed.com/docs/latest). It includes published Doxygen for our APIs, step-by-step tutorials, porting information and background reference materials about our architecture and tools. + +To contribute to this documentation, please see the [mbed-os-5-docs repo](https://github.com/ARMmbed/mbed-os-5-docs). diff --git a/TESTS/host_tests/system_reset.py b/TESTS/host_tests/system_reset.py index 7899e3783e..4093804213 100644 --- a/TESTS/host_tests/system_reset.py +++ b/TESTS/host_tests/system_reset.py @@ -36,9 +36,6 @@ class SystemResetTest(BaseHostTest): def __init__(self): super(SystemResetTest, self).__init__() self.reset = False - cycle_s = self.get_config_item('program_cycle_s') - self.program_cycle_s = cycle_s if cycle_s is not None else DEFAULT_CYCLE_PERIOD - self.test_steps_sequence = self.test_steps() # Advance the coroutine to it's first yield statement. self.test_steps_sequence.send(None) @@ -61,16 +58,18 @@ class SystemResetTest(BaseHostTest): """Reset the device and check the status """ system_reset = yield - self.reset = False + + wait_after_reset = self.get_config_item('forced_reset_timeout') + wait_after_reset = wait_after_reset if wait_after_reset is not None else DEFAULT_CYCLE_PERIOD + self.send_kv(MSG_KEY_DEVICE_RESET, MSG_VALUE_DUMMY) - time.sleep(self.program_cycle_s) + time.sleep(wait_after_reset) self.send_kv(MSG_KEY_SYNC, MSG_VALUE_DUMMY) system_reset = yield - if self.reset == False: raise RuntimeError('Platform did not reset as expected.') # The sequence is correct -- test passed. - yield True \ No newline at end of file + yield True diff --git a/TESTS/host_tests/trng_reset.py b/TESTS/host_tests/trng_reset.py new file mode 100644 index 0000000000..33dfffc987 --- /dev/null +++ b/TESTS/host_tests/trng_reset.py @@ -0,0 +1,145 @@ +""" +Copyright (c) 2018 ARM Limited +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +""" +This script is the host script for trng test sequence, it send the +step signaling sequence and receive and transmit data to the device after +reset if necesarry (default loading and storing mechanism while reseting the device +is NVstore, in case NVstore isn't enabled we'll use current infrastructure, +for more details see main.cpp file) +""" + +import time +from mbed_host_tests import BaseHostTest +from mbed_host_tests.host_tests_runner.host_test_default import DefaultTestSelector +from time import sleep + +DEFAULT_CYCLE_PERIOD = 1.0 +MSG_VALUE_DUMMY = '0' +MSG_TRNG_READY = 'ready' +MSG_TRNG_BUFFER = 'buffer' +MSG_TRNG_TEST_STEP1 = 'check_step1' +MSG_TRNG_TEST_STEP2 = 'check_step2' +MSG_KEY_SYNC = '__sync' +MSG_KEY_RESET_COMPLETE = 'reset_complete' +MSG_KEY_TEST_SUITE_ENDED = 'Test_suite_ended' +MSG_KEY_EXIT = 'exit' + +class TRNGResetTest(BaseHostTest): + """Test for the TRNG API. + """ + + def __init__(self): + super(TRNGResetTest, self).__init__() + self.did_reset = False + self.ready = False + self.suite_ended = False + self.buffer = 0 + self.test_steps_sequence = self.test_steps() + # Advance the coroutine to it's first yield statement. + self.test_steps_sequence.send(None) + + #define callback functions for msg handling + def setup(self): + self.register_callback(MSG_TRNG_READY, self.cb_device_ready) + self.register_callback(MSG_TRNG_BUFFER, self.cb_trng_buffer) + self.register_callback(MSG_KEY_TEST_SUITE_ENDED, self.cb_device_test_suit_ended) + self.register_callback(MSG_KEY_RESET_COMPLETE, self.cb_reset_complete) + + #receive sent data from device before reset + def cb_trng_buffer(self, key, value, timestamp): + """Acknowledge device rebooted correctly and feed the test execution + """ + self.buffer = value + + try: + if self.test_steps_sequence.send(value): + self.notify_complete(True) + except (StopIteration, RuntimeError) as exc: + self.notify_complete(False) + + def cb_device_ready(self, key, value, timestamp): + """Acknowledge device rebooted correctly and feed the test execution + """ + self.ready = True + + try: + if self.test_steps_sequence.send(value): + self.notify_complete(True) + except (StopIteration, RuntimeError) as exc: + self.notify_complete(False) + + def cb_reset_complete(self, key, value, timestamp): + """Acknowledge reset complete + """ + self.did_reset = True + + try: + if self.test_steps_sequence.send(value): + self.notify_complete(True) + except (StopIteration, RuntimeError) as exc: + self.notify_complete(False) + + def cb_device_test_suit_ended(self, key, value, timestamp): + """Acknowledge device finished a test step correctly and feed the test execution + """ + self.suite_ended = True + + try: + if self.test_steps_sequence.send(value): + self.notify_complete(True) + except (StopIteration, RuntimeError) as exc: + self.notify_complete(False) + + #define test steps and actions + def test_steps(self): + """Test step 1 + """ + wait_for_communication = yield + + self.ready = False + self.did_reset = False + self.suite_ended = False + self.send_kv(MSG_TRNG_TEST_STEP1, MSG_VALUE_DUMMY) + wait_for_communication = yield + if self.buffer == 0: + raise RuntimeError('Phase 1: No buffer received.') + + self.reset() + + """Test step 2 (After reset) + """ + wait_for_communication = yield + if self.did_reset == False: + raise RuntimeError('Phase 1: Platform did not reset as expected.') + + self.send_kv(MSG_KEY_SYNC, MSG_VALUE_DUMMY) + + wait_for_communication = yield + + if self.ready == False: + raise RuntimeError('Phase 1: Platform not ready as expected.') + + self.send_kv(MSG_TRNG_TEST_STEP2, self.buffer) + + wait_for_communication = yield + + if self.suite_ended == False: + raise RuntimeError('Test failed.') + + self.send_kv(MSG_KEY_EXIT, MSG_VALUE_DUMMY) + + # The sequence is correct -- test passed. + yield \ No newline at end of file diff --git a/TESTS/mbed_hal/common_tickers/main.cpp b/TESTS/mbed_hal/common_tickers/main.cpp index 98f879e70e..e1a26dc79e 100644 --- a/TESTS/mbed_hal/common_tickers/main.cpp +++ b/TESTS/mbed_hal/common_tickers/main.cpp @@ -473,11 +473,14 @@ void ticker_speed_test(void) /* ---- Test fire_interrupt function. ---- */ counter = NUM_OF_CALLS; + /* Disable ticker interrupt which would interfere with speed test */ + core_util_critical_section_enter(); start = us_ticker_read(); while (counter--) { intf->fire_interrupt(); } stop = us_ticker_read(); + core_util_critical_section_exit(); TEST_ASSERT(diff_us(start, stop, us_ticker_info) < (NUM_OF_CALLS * (MAX_FUNC_EXEC_TIME_US + DELTA_FUNC_EXEC_TIME_US))); @@ -569,7 +572,7 @@ utest::v1::status_t lp_ticker_teardown(const Case *const source, const size_t pa utest::v1::status_t test_setup(const size_t number_of_cases) { - GREENTEA_SETUP(30, "default_auto"); + GREENTEA_SETUP(80, "default_auto"); return verbose_test_setup_handler(number_of_cases); } diff --git a/TESTS/mbed_hal/qspi/flash_configs/MX25R6435F_config.h b/TESTS/mbed_hal/qspi/flash_configs/MX25R6435F_config.h deleted file mode 100644 index 6cd588d487..0000000000 --- a/TESTS/mbed_hal/qspi/flash_configs/MX25R6435F_config.h +++ /dev/null @@ -1,192 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2018-2018 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef MBED_QSPI_FLASH_MX25R6435F_H -#define MBED_QSPI_FLASH_MX25R6435F_H - - -#define QSPI_FLASH_CHIP_STRING "macronix MX25R6435F" - -// Command for reading status register -#define QSPI_CMD_RDSR 0x05 -// Command for reading configuration register -#define QSPI_CMD_RDCR0 0x15 -// Command for writing status/configuration register -#define QSPI_CMD_WRSR 0x01 -// Command for reading security register -#define QSPI_CMD_RDSCUR 0x2B - -// Command for setting Reset Enable -#define QSPI_CMD_RSTEN 0x66 -// Command for setting Reset -#define QSPI_CMD_RST 0x99 - -// Command for setting write enable -#define QSPI_CMD_WREN 0x06 -// Command for setting write disable -#define QSPI_CMD_WRDI 0x04 - -// WRSR operations max time [us] (datasheet max time + 15%) -#define QSPI_WRSR_MAX_TIME 34500 // 30ms -// general wait max time [us] -#define QSPI_WAIT_MAX_TIME 100000 // 100ms - - -// Commands for writing (page programming) -#define QSPI_CMD_WRITE_1IO 0x02 // 1-1-1 mode -#define QSPI_CMD_WRITE_4IO 0x38 // 1-4-4 mode - -// write operations max time [us] (datasheet max time + 15%) -#define QSPI_PAGE_PROG_MAX_TIME 11500 // 10ms - -#define QSPI_PAGE_SIZE 256 // 256B - -// Commands for reading -#define QSPI_CMD_READ_1IO_FAST 0x0B // 1-1-1 mode -#define QSPI_CMD_READ_1IO 0x03 // 1-1-1 mode -#define QSPI_CMD_READ_2IO 0xBB // 1-2-2 mode -#define QSPI_CMD_READ_1I2O 0x3B // 1-1-2 mode -#define QSPI_CMD_READ_4IO 0xEB // 1-4-4 mode -#define QSPI_CMD_READ_1I4O 0x6B // 1-1-4 mode - -#define QSPI_READ_1IO_DUMMY_CYCLE 0 -#define QSPI_READ_FAST_DUMMY_CYCLE 8 -#define QSPI_READ_2IO_DUMMY_CYCLE 4 -#define QSPI_READ_1I2O_DUMMY_CYCLE 8 -#define QSPI_READ_4IO_DUMMY_CYCLE 6 -#define QSPI_READ_1I4O_DUMMY_CYCLE 8 - -// Commands for erasing -#define QSPI_CMD_ERASE_SECTOR 0x20 // 4kB -#define QSPI_CMD_ERASE_BLOCK_32 0x52 // 32kB -#define QSPI_CMD_ERASE_BLOCK_64 0xD8 // 64kB -#define QSPI_CMD_ERASE_CHIP 0x60 // or 0xC7 - -// erase operations max time [us] (datasheet max time + 15%) -#define QSPI_ERASE_SECTOR_MAX_TIME 276000 // 240 ms -#define QSPI_ERASE_BLOCK_32_MAX_TIME 3450000 // 3s -#define QSPI_ERASE_BLOCK_64_MAX_TIME 4025000 // 3.5s - -// max frequency for basic rw operation -#define QSPI_COMMON_MAX_FREQUENCY 32000000 - -#define QSPI_STATUS_REG_SIZE 1 -#define QSPI_CONFIG_REG_0_SIZE 2 -#define QSPI_SECURITY_REG_SIZE 1 -#define QSPI_MAX_REG_SIZE 2 - -// status register -#define STATUS_BIT_WIP (1 << 0) // write in progress bit -#define STATUS_BIT_WEL (1 << 1) // write enable latch -#define STATUS_BIT_BP0 (1 << 2) // -#define STATUS_BIT_BP1 (1 << 3) // -#define STATUS_BIT_BP2 (1 << 4) // -#define STATUS_BIT_BP3 (1 << 5) // -#define STATUS_BIT_QE (1 << 6) // Quad Enable -#define STATUS_BIT_SRWD (1 << 7) // status register write protect - -// configuration register 0 -// bit 0, 1, 2, 4, 5, 7 reserved -#define CONFIG0_BIT_TB (1 << 3) // Top/Bottom area protect -#define CONFIG0_BIT_DC (1 << 6) // Dummy Cycle - -// configuration register 1 -// bit 0, 2, 3, 4, 5, 6, 7 reserved -#define CONFIG1_BIT_LH (1 << 1) // 0 = Ultra Low power mode, 1 = High performance mode - - -// single quad enable flag for both dual and quad mode -#define QUAD_ENABLE() \ - \ - uint8_t reg_data[QSPI_STATUS_REG_SIZE]; \ - \ - if (write_enable(qspi) != QSPI_STATUS_OK) { \ - return QSPI_STATUS_ERROR; \ - } \ - WAIT_FOR(WRSR_MAX_TIME, qspi); \ - \ - reg_data[0] = STATUS_BIT_QE; \ - qspi.cmd.build(QSPI_CMD_WRSR); \ - \ - if (qspi_command_transfer(&qspi.handle, qspi.cmd.get(), \ - reg_data, QSPI_STATUS_REG_SIZE, NULL, 0) != QSPI_STATUS_OK) { \ - return QSPI_STATUS_ERROR; \ - } \ - WAIT_FOR(WRSR_MAX_TIME, qspi); \ - \ - memset(reg_data, 0, QSPI_STATUS_REG_SIZE); \ - if (read_register(STATUS_REG, reg_data, \ - QSPI_STATUS_REG_SIZE, qspi) != QSPI_STATUS_OK) { \ - return QSPI_STATUS_ERROR; \ - } \ - \ - return ((reg_data[0] & STATUS_BIT_QE) != 0 ? \ - QSPI_STATUS_OK : QSPI_STATUS_ERROR) - - - -#define QUAD_DISABLE() \ - \ - uint8_t reg_data[QSPI_STATUS_REG_SIZE]; \ - \ - if (write_enable(qspi) != QSPI_STATUS_OK) { \ - return QSPI_STATUS_ERROR; \ - } \ - WAIT_FOR(WRSR_MAX_TIME, qspi); \ - \ - reg_data[0] = 0; \ - qspi.cmd.build(QSPI_CMD_WRSR); \ - \ - if (qspi_command_transfer(&qspi.handle, qspi.cmd.get(), \ - reg_data, QSPI_STATUS_REG_SIZE, NULL, 0) != QSPI_STATUS_OK) { \ - return QSPI_STATUS_ERROR; \ - } \ - WAIT_FOR(WRSR_MAX_TIME, qspi); \ - \ - reg_data[0] = 0; \ - if (read_register(STATUS_REG, reg_data, \ - QSPI_STATUS_REG_SIZE, qspi) != QSPI_STATUS_OK) { \ - return QSPI_STATUS_ERROR; \ - } \ - \ - return ((reg_data[0] & STATUS_BIT_QE) == 0 ? \ - QSPI_STATUS_OK : QSPI_STATUS_ERROR) - - - -#define FAST_MODE_ENABLE() \ - \ - qspi_status_t ret; \ - const int32_t reg_size = QSPI_STATUS_REG_SIZE + QSPI_CONFIG_REG_0_SIZE; \ - uint8_t reg_data[reg_size]; \ - \ - if (read_register(STATUS_REG, reg_data, \ - QSPI_STATUS_REG_SIZE, qspi) != QSPI_STATUS_OK) { \ - return QSPI_STATUS_ERROR; \ - } \ - if (read_register(CONFIG_REG0, reg_data + QSPI_STATUS_REG_SIZE, \ - QSPI_CONFIG_REG_0_SIZE, qspi) != QSPI_STATUS_OK) { \ - return QSPI_STATUS_ERROR; \ - } \ - \ - reg_data[2] |= CONFIG1_BIT_LH; \ - qspi.cmd.build(QSPI_CMD_WRSR); \ - \ - return qspi_command_transfer(&qspi.handle, qspi.cmd.get(), \ - reg_data, reg_size, NULL, 0) - - - -#endif // MBED_QSPI_FLASH_MX25R6435F_H diff --git a/TESTS/mbed_hal/qspi/flash_configs/MX25R3235F_config.h b/TESTS/mbed_hal/qspi/flash_configs/MX25RXX35F_config.h similarity index 59% rename from TESTS/mbed_hal/qspi/flash_configs/MX25R3235F_config.h rename to TESTS/mbed_hal/qspi/flash_configs/MX25RXX35F_config.h index cb0df22990..141dff403a 100644 --- a/TESTS/mbed_hal/qspi/flash_configs/MX25R3235F_config.h +++ b/TESTS/mbed_hal/qspi/flash_configs/MX25RXX35F_config.h @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef MBED_QSPI_FLASH_MX25R3235F_H -#define MBED_QSPI_FLASH_MX25R3235F_H +#ifndef MBED_QSPI_FLASH_MX25RXX35F_H +#define MBED_QSPI_FLASH_MX25RXX35F_H -#define QSPI_FLASH_CHIP_STRING "macronix MX25R3235F" +#define QSPI_FLASH_CHIP_STRING "macronix MX25RXX35F" // Command for reading status register #define QSPI_CMD_RDSR 0x05 @@ -52,6 +52,8 @@ #define QSPI_PAGE_PROG_MAX_TIME 11500 // 10ms #define QSPI_PAGE_SIZE 256 // 256B +#define QSPI_SECTOR_SIZE 4096 // 4kB +#define QSPI_SECTOR_COUNT 32 // adjusted to MX25R1035F smallest one from MX25RXX35F family // Commands for reading #define QSPI_CMD_READ_1IO_FAST 0x0B // 1-1-1 mode @@ -79,7 +81,7 @@ #define QSPI_ERASE_BLOCK_32_MAX_TIME 3450000 // 3s #define QSPI_ERASE_BLOCK_64_MAX_TIME 4025000 // 3.5s -// max frequency for basic rw operation +// max frequency for basic rw operation (for fast mode) #define QSPI_COMMON_MAX_FREQUENCY 32000000 #define QSPI_STATUS_REG_SIZE 1 @@ -107,21 +109,28 @@ #define CONFIG1_BIT_LH (1 << 1) // 0 = Ultra Low power mode, 1 = High performance mode -// single quad enable flag for both dual and quad mode -#define QUAD_ENABLE() \ + +#define EXTENDED_SPI_ENABLE() \ \ - uint8_t reg_data[QSPI_STATUS_REG_SIZE]; \ + const int32_t reg_size = QSPI_STATUS_REG_SIZE + QSPI_CONFIG_REG_0_SIZE; \ + uint8_t reg_data[reg_size] = { 0 }; \ + \ + if (read_register(STATUS_REG, reg_data, \ + QSPI_STATUS_REG_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + if (read_register(CONFIG_REG0, reg_data + QSPI_STATUS_REG_SIZE, \ + QSPI_CONFIG_REG_0_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ \ if (write_enable(qspi) != QSPI_STATUS_OK) { \ return QSPI_STATUS_ERROR; \ } \ - WAIT_FOR(WRSR_MAX_TIME, qspi); \ \ reg_data[0] = STATUS_BIT_QE; \ - qspi.cmd.build(QSPI_CMD_WRSR); \ - \ - if (qspi_command_transfer(&qspi.handle, qspi.cmd.get(), \ - reg_data, QSPI_STATUS_REG_SIZE, NULL, 0) != QSPI_STATUS_OK) { \ + if (write_register(QSPI_CMD_WRSR, reg_data, \ + reg_size, qspi) != QSPI_STATUS_OK) { \ return QSPI_STATUS_ERROR; \ } \ WAIT_FOR(WRSR_MAX_TIME, qspi); \ @@ -137,20 +146,28 @@ -#define QUAD_DISABLE() \ +#define EXTENDED_SPI_DISABLE() \ \ - uint8_t reg_data[QSPI_STATUS_REG_SIZE]; \ + const int32_t reg_size = QSPI_STATUS_REG_SIZE + QSPI_CONFIG_REG_0_SIZE; \ + uint8_t reg_data[reg_size] = { 0 }; \ + \ + if (read_register(STATUS_REG, reg_data, \ + QSPI_STATUS_REG_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + if (read_register(CONFIG_REG0, reg_data + QSPI_STATUS_REG_SIZE, \ + QSPI_CONFIG_REG_0_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ \ if (write_enable(qspi) != QSPI_STATUS_OK) { \ return QSPI_STATUS_ERROR; \ } \ - WAIT_FOR(WRSR_MAX_TIME, qspi); \ \ - reg_data[0] = 0; \ - qspi.cmd.build(QSPI_CMD_WRSR); \ + reg_data[0] &= ~(STATUS_BIT_QE); \ \ - if (qspi_command_transfer(&qspi.handle, qspi.cmd.get(), \ - reg_data, QSPI_STATUS_REG_SIZE, NULL, 0) != QSPI_STATUS_OK) { \ + if (write_register(QSPI_CMD_WRSR, reg_data, \ + reg_size, qspi) != QSPI_STATUS_OK) { \ return QSPI_STATUS_ERROR; \ } \ WAIT_FOR(WRSR_MAX_TIME, qspi); \ @@ -168,7 +185,6 @@ #define FAST_MODE_ENABLE() \ \ - qspi_status_t ret; \ const int32_t reg_size = QSPI_STATUS_REG_SIZE + QSPI_CONFIG_REG_0_SIZE; \ uint8_t reg_data[reg_size]; \ \ @@ -181,12 +197,58 @@ return QSPI_STATUS_ERROR; \ } \ \ - reg_data[2] |= CONFIG1_BIT_LH; \ - qspi.cmd.build(QSPI_CMD_WRSR); \ + if (write_enable(qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ \ - return qspi_command_transfer(&qspi.handle, qspi.cmd.get(), \ - reg_data, reg_size, NULL, 0) + reg_data[2] |= CONFIG1_BIT_LH; \ + if (write_register(QSPI_CMD_WRSR, reg_data, \ + reg_size, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + WAIT_FOR(WRSR_MAX_TIME, qspi); \ + \ + if (read_register(CONFIG_REG0, reg_data, \ + QSPI_CONFIG_REG_0_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + \ + return ((reg_data[1] & CONFIG1_BIT_LH) != 0 ? \ + QSPI_STATUS_OK : QSPI_STATUS_ERROR) +#define FAST_MODE_DISABLE() \ + \ + const int32_t reg_size = QSPI_STATUS_REG_SIZE + QSPI_CONFIG_REG_0_SIZE; \ + uint8_t reg_data[reg_size]; \ + \ + if (read_register(STATUS_REG, reg_data, \ + QSPI_STATUS_REG_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + if (read_register(CONFIG_REG0, reg_data + QSPI_STATUS_REG_SIZE, \ + QSPI_CONFIG_REG_0_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + \ + if (write_enable(qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + \ + reg_data[2] &= ~(CONFIG1_BIT_LH); \ + if (write_register(QSPI_CMD_WRSR, reg_data, \ + reg_size, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + WAIT_FOR(WRSR_MAX_TIME, qspi); \ + \ + if (read_register(CONFIG_REG0, reg_data, \ + QSPI_CONFIG_REG_0_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + \ + return ((reg_data[1] & CONFIG1_BIT_LH) == 0 ? \ + QSPI_STATUS_OK : QSPI_STATUS_ERROR) -#endif // MBED_QSPI_FLASH_MX25R3235F_H + +#endif // MBED_QSPI_FLASH_MX25RXX35F_H diff --git a/TESTS/mbed_hal/qspi/flash_configs/N25Q128A_config.h b/TESTS/mbed_hal/qspi/flash_configs/N25Q128A_config.h index 138844abe6..30590b7c93 100644 --- a/TESTS/mbed_hal/qspi/flash_configs/N25Q128A_config.h +++ b/TESTS/mbed_hal/qspi/flash_configs/N25Q128A_config.h @@ -58,18 +58,24 @@ #define QSPI_CMD_WRITE_1IO 0x02 // 1-1-1 mode #define QSPI_CMD_WRITE_2IO 0xD2 // 1-2-2 mode #define QSPI_CMD_WRITE_4IO 0x12 // 1-4-4 mode +#define QSPI_CMD_WRITE_DPI 0xD2 // 2-2-2 mode +#define QSPI_CMD_WRITE_QPI 0x12 // 4-4-4 mode // write operations max time [us] (datasheet max time + 15%) #define QSPI_PAGE_PROG_MAX_TIME 5750 // 5ms #define QSPI_PAGE_SIZE 256 // 256B +#define QSPI_SECTOR_SIZE 4096 // 4kB +#define QSPI_SECTOR_COUNT 4096 // Commands for reading #define QSPI_CMD_READ_1IO_FAST 0x0B // 1-1-1 mode #define QSPI_CMD_READ_1IO 0x03 // 1-1-1 mode #define QSPI_CMD_READ_2IO 0xBB // 1-2-2 mode +#define QSPI_CMD_READ_DPI 0xBB // 2-2-2 mode #define QSPI_CMD_READ_1I2O 0x3B // 1-1-2 mode #define QSPI_CMD_READ_4IO 0xEB // 1-4-4 mode +#define QSPI_CMD_READ_QPI 0xEB // 4-4-4 mode #define QSPI_CMD_READ_1I4O 0x6B // 1-1-4 mode @@ -88,7 +94,7 @@ #define QSPI_CMD_ERASE_CHIP 0x60 // or 0xC7 // erase operations max time [us] (datasheet max time + 15%) -#define QSPI_ERASE_SECTOR_MAX_TIME 276000 // 240 ms +#define QSPI_ERASE_SECTOR_MAX_TIME 920000 // 0.8s #define QSPI_ERASE_BLOCK_32_MAX_TIME 3000000 // 3s #define QSPI_ERASE_BLOCK_64_MAX_TIME 3500000 // 3.5s @@ -155,28 +161,122 @@ #define DUAL_ENABLE() \ - /* TODO: add implementation */ \ - return QSPI_STATUS_OK + \ + uint8_t reg_data[QSPI_CONFIG_REG_2_SIZE]; \ + \ + memset(reg_data, 0, QSPI_CONFIG_REG_2_SIZE); \ + if (read_register(QSPI_CMD_RDCR2, reg_data, \ + QSPI_CONFIG_REG_2_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + if (write_enable(qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + \ + reg_data[0] = reg_data[0] & ~(CONFIG2_BIT_DE); \ + if (write_register(QSPI_CMD_WRCR2, reg_data, \ + QSPI_CONFIG_REG_2_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + qspi.cmd.configure(MODE_2_2_2, ADDR_SIZE_24, ALT_SIZE_8); \ + WAIT_FOR(WRSR_MAX_TIME, qspi); \ + memset(reg_data, 0, QSPI_CONFIG_REG_2_SIZE); \ + if (read_register(QSPI_CMD_RDCR2, reg_data, \ + QSPI_CONFIG_REG_2_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + \ + return ((reg_data[0] & (CONFIG2_BIT_DE)) == 0 ? \ + QSPI_STATUS_OK : QSPI_STATUS_ERROR) #define DUAL_DISABLE() \ - /* TODO: add implementation */ \ - return QSPI_STATUS_OK + \ + uint8_t reg_data[QSPI_CONFIG_REG_2_SIZE]; \ + \ + memset(reg_data, 0, QSPI_CONFIG_REG_2_SIZE); \ + if (read_register(QSPI_CMD_RDCR2, reg_data, \ + QSPI_CONFIG_REG_2_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + if (write_enable(qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + \ + reg_data[0] = reg_data[0] | (CONFIG2_BIT_DE); \ + if (write_register(QSPI_CMD_WRCR2, reg_data, \ + QSPI_CONFIG_REG_2_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + WAIT_FOR(WRSR_MAX_TIME, qspi); \ + qspi.cmd.configure(MODE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8); \ + memset(reg_data, 0, QSPI_CONFIG_REG_2_SIZE); \ + if (read_register(QSPI_CMD_RDCR2, reg_data, \ + QSPI_CONFIG_REG_2_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + \ + return ((reg_data[0] & CONFIG2_BIT_DE) != 1 ? \ + QSPI_STATUS_OK : QSPI_STATUS_ERROR) #define QUAD_ENABLE() \ - /* TODO: add implementation */ \ - return QSPI_STATUS_OK + \ + uint8_t reg_data[QSPI_CONFIG_REG_2_SIZE]; \ + \ + memset(reg_data, 0, QSPI_CONFIG_REG_2_SIZE); \ + if (read_register(QSPI_CMD_RDCR2, reg_data, \ + QSPI_CONFIG_REG_2_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + if (write_enable(qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + \ + reg_data[0] = reg_data[0] & ~(CONFIG2_BIT_QE); \ + if (write_register(QSPI_CMD_WRCR2, reg_data, \ + QSPI_CONFIG_REG_2_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + qspi.cmd.configure(MODE_4_4_4, ADDR_SIZE_24, ALT_SIZE_8); \ + WAIT_FOR(WRSR_MAX_TIME, qspi); \ + memset(reg_data, 0, QSPI_CONFIG_REG_2_SIZE); \ + if (read_register(QSPI_CMD_RDCR2, reg_data, \ + QSPI_CONFIG_REG_2_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + \ + return ((reg_data[0] & (CONFIG2_BIT_QE)) == 0 ? \ + QSPI_STATUS_OK : QSPI_STATUS_ERROR) #define QUAD_DISABLE() \ - /* TODO: add implementation */ \ - return QSPI_STATUS_OK - - -#define FAST_MODE_ENABLE() \ - /* TODO: add implementation */ \ - return QSPI_STATUS_OK - + \ + uint8_t reg_data[QSPI_CONFIG_REG_2_SIZE]; \ + \ + memset(reg_data, 0, QSPI_CONFIG_REG_2_SIZE); \ + if (read_register(QSPI_CMD_RDCR2, reg_data, \ + QSPI_CONFIG_REG_2_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + if (write_enable(qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + \ + reg_data[0] = reg_data[0] | (CONFIG2_BIT_QE); \ + if (write_register(QSPI_CMD_WRCR2, reg_data, \ + QSPI_CONFIG_REG_2_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + WAIT_FOR(WRSR_MAX_TIME, qspi); \ + qspi.cmd.configure(MODE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8); \ + memset(reg_data, 0, QSPI_CONFIG_REG_2_SIZE); \ + if (read_register(QSPI_CMD_RDCR2, reg_data, \ + QSPI_CONFIG_REG_2_SIZE, qspi) != QSPI_STATUS_OK) { \ + return QSPI_STATUS_ERROR; \ + } \ + \ + return ((reg_data[0] & CONFIG2_BIT_QE) != 1 ? \ + QSPI_STATUS_OK : QSPI_STATUS_ERROR) #endif // MBED_QSPI_FLASH_N25Q128A_H diff --git a/TESTS/mbed_hal/qspi/flash_configs/NORDIC/NRF52840_DK/flash_config.h b/TESTS/mbed_hal/qspi/flash_configs/NORDIC/NRF52840_DK/flash_config.h index ed288ba50a..d47d1a47e3 100644 --- a/TESTS/mbed_hal/qspi/flash_configs/NORDIC/NRF52840_DK/flash_config.h +++ b/TESTS/mbed_hal/qspi/flash_configs/NORDIC/NRF52840_DK/flash_config.h @@ -16,7 +16,7 @@ #ifndef MBED_QSPI_FLASH_CONFIG_H #define MBED_QSPI_FLASH_CONFIG_H -#include "../../MX25R6435F_config.h" +#include "../../MX25RXX35F_config.h" // NRF doesn't uses read/write opcodes, instead it uses commands id's. // Before sending it to H/W opcodes are mapped to id's in Mbed hal qspi implementation @@ -29,5 +29,9 @@ #undef QSPI_CMD_READ_1IO #define QSPI_CMD_READ_1IO QSPI_CMD_READ_1IO_FAST +#ifdef QSPI_SECTOR_COUNT +#undef QSPI_SECTOR_COUNT +#define QSPI_SECTOR_COUNT 2048 // for MX25R6435F +#endif #endif // MBED_QSPI_FLASH_CONFIG_H diff --git a/TESTS/mbed_hal/qspi/flash_configs/STM/DISCO_L475VG_IOT01A/flash_config.h b/TESTS/mbed_hal/qspi/flash_configs/STM/DISCO_L475VG_IOT01A/flash_config.h index 76cb739bb5..41b576d8ea 100644 --- a/TESTS/mbed_hal/qspi/flash_configs/STM/DISCO_L475VG_IOT01A/flash_config.h +++ b/TESTS/mbed_hal/qspi/flash_configs/STM/DISCO_L475VG_IOT01A/flash_config.h @@ -16,7 +16,7 @@ #ifndef MBED_QSPI_FLASH_CONFIG_H #define MBED_QSPI_FLASH_CONFIG_H -#include "../../MX25R6435F_config.h" +#include "../../MX25RXX35F_config.h" #endif // MBED_QSPI_FLASH_CONFIG_H diff --git a/TESTS/mbed_hal/qspi/flash_configs/SiliconLabs/EFM32GG11_STK3701/flash_config.h b/TESTS/mbed_hal/qspi/flash_configs/SiliconLabs/EFM32GG11_STK3701/flash_config.h index c27dd0d212..58a9c1e626 100644 --- a/TESTS/mbed_hal/qspi/flash_configs/SiliconLabs/EFM32GG11_STK3701/flash_config.h +++ b/TESTS/mbed_hal/qspi/flash_configs/SiliconLabs/EFM32GG11_STK3701/flash_config.h @@ -16,7 +16,11 @@ #ifndef MBED_QSPI_FLASH_CONFIG_H #define MBED_QSPI_FLASH_CONFIG_H -#include "../../MX25R3235F_config.h" +#include "../../MX25RXX35F_config.h" +#ifdef QSPI_SECTOR_COUNT +#undef QSPI_SECTOR_COUNT +#define QSPI_SECTOR_COUNT 1024 // for MX25R3235F +#endif #endif // MBED_QSPI_FLASH_CONFIG_H diff --git a/TESTS/mbed_hal/qspi/main.cpp b/TESTS/mbed_hal/qspi/main.cpp index 44ba33e52d..647f7cc467 100644 --- a/TESTS/mbed_hal/qspi/main.cpp +++ b/TESTS/mbed_hal/qspi/main.cpp @@ -52,7 +52,7 @@ uint8_t rx_buf[DATA_SIZE_1024]; #define TEST_FLASH_ADDRESS 0x0 #define TEST_REPEAT_SINGLE 1 -#define TEST_REPEAT_MULTIPLE 16 +#define TEST_REPEAT_MULTIPLE 4 // write block of data in single write operation #define WRITE_SINGLE 1 @@ -74,6 +74,13 @@ uint8_t rx_buf[DATA_SIZE_1024]; #define QCSN static_cast(QSPI_FLASH1_CSN) +static uint32_t gen_flash_address() +{ + srand(ticker_read(get_us_ticker_data())); + uint32_t address = (((uint32_t)rand()) % QSPI_SECTOR_COUNT) * QSPI_SECTOR_SIZE; + return address; +} + static void log_data(const char *str, uint8_t *data, uint32_t size) { utest_printf("%s: ", str); @@ -100,7 +107,6 @@ static void _qspi_write_read_test(Qspi &qspi, qspi_bus_width_t write_inst_width, size_t buf_len = data_size; for (uint32_t tc = 0; tc < test_count; tc++) { - qspi.cmd.configure(MODE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8); srand(ticker_read(get_us_ticker_data())); for (uint32_t i = 0; i < data_size; i++) { @@ -125,6 +131,11 @@ static void _qspi_write_read_test(Qspi &qspi, qspi_bus_width_t write_inst_width, WAIT_FOR(WAIT_MAX_TIME, qspi); } + // switching to extended-SPI/DPI/QPI mode here for write operation + // for DPI/QPI qspi.cmd is automatically switched to 2_2_2/4_4_4 mode + ret = mode_enable(qspi, write_inst_width, write_addr_width, write_data_width); + TEST_ASSERT_EQUAL(QSPI_STATUS_OK, ret); + const uint32_t write_size = data_size / write_count; for (uint32_t wc = 0, write_start = flash_addr; wc < write_count; wc++, write_start += write_size) { ret = write_enable(qspi); @@ -140,18 +151,32 @@ static void _qspi_write_read_test(Qspi &qspi, qspi_bus_width_t write_inst_width, TEST_ASSERT_EQUAL(QSPI_STATUS_OK, ret); TEST_ASSERT_EQUAL(write_size, buf_len); - qspi.cmd.configure(MODE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8); + if(is_extended_mode(write_inst_width, write_addr_width, write_data_width)) { + // on some flash chips in extended-SPI mode, control commands works only in 1-1-1 mode + // so switching back to 1-1-1 mode + qspi.cmd.configure(MODE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8); + } + WAIT_FOR(PAGE_PROG_MAX_TIME, qspi); timer.stop(); write_time = timer.read_us(); } + // switching back to single channel SPI + ret = mode_disable(qspi, write_inst_width, write_addr_width, write_data_width); + TEST_ASSERT_EQUAL(QSPI_STATUS_OK, ret); + if (read_frequency != QSPI_NONE) { qspi_frequency(&qspi.handle, read_frequency); WAIT_FOR(WAIT_MAX_TIME, qspi); } + // switching to extended-SPI/DPI/QPI mode here for read operation + // for DPI/QPI qspi.cmd is automatically switched to 2_2_2/4_4_4 mode + ret = mode_enable(qspi, read_inst_width, read_addr_width, read_data_width); + TEST_ASSERT_EQUAL(QSPI_STATUS_OK, ret); + memset(rx_buf, 0, sizeof(rx_buf)); const uint32_t read_size = data_size / read_count; qspi.cmd.configure(read_inst_width, read_addr_width, read_data_width, read_alt_width, read_addr_size, read_alt_size, read_dummy_cycles); @@ -168,6 +193,17 @@ static void _qspi_write_read_test(Qspi &qspi, qspi_bus_width_t write_inst_width, timer.stop(); read_time = timer.read_us(); } + qspi.cmd.set_dummy_cycles(0); + + if(is_extended_mode(read_inst_width, read_addr_width, read_data_width)) { + // on some flash chips in extended-SPI mode, control commands works only in 1-1-1 mode + // so switching back to 1-1-1 mode + qspi.cmd.configure(MODE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8); + } + + // switching back to single channel SPI + ret = mode_disable(qspi, read_inst_width, read_addr_width, read_data_width); + TEST_ASSERT_EQUAL(QSPI_STATUS_OK, ret); for (uint32_t i = 0; i < data_size; i++) { if (tx_buf[i] != rx_buf[i]) { @@ -217,43 +253,29 @@ void qspi_write_read_test(void) { qspi_status_t ret; Qspi qspi; + + uint32_t addr = flash_addr; + if (addr == 0) { + // if no specified address selected, use random one to extend flash life + addr = gen_flash_address(); + } + qspi_init(&qspi.handle, QPIN_0, QPIN_1, QPIN_2, QPIN_3, QSCK, QCSN, QSPI_COMMON_MAX_FREQUENCY, 0); qspi.cmd.configure(MODE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8); flash_init(qspi); - if (is_dual_cmd(write_inst_width, write_addr_width, write_data_width) || - is_dual_cmd(read_inst_width, read_addr_width, read_data_width)) { - ret = dual_enable(qspi); - TEST_ASSERT_EQUAL(QSPI_STATUS_OK, ret); - WAIT_FOR(WRSR_MAX_TIME, qspi); - } - - if (is_quad_cmd(write_inst_width, write_addr_width, write_data_width) || - is_quad_cmd(read_inst_width, read_addr_width, read_data_width)) { - ret = quad_enable(qspi); - TEST_ASSERT_EQUAL(QSPI_STATUS_OK, ret); - WAIT_FOR(WRSR_MAX_TIME, qspi); - } - - ret = write_enable(qspi); - TEST_ASSERT_EQUAL(QSPI_STATUS_OK, ret); - WAIT_FOR(WRSR_MAX_TIME, qspi); + // switch memory to high performance mode (if available) ret = fast_mode_enable(qspi); TEST_ASSERT_EQUAL(QSPI_STATUS_OK, ret); - WAIT_FOR(WRSR_MAX_TIME, qspi); #ifdef QSPI_TEST_LOG_FLASH_STATUS - //utest_printf("Status register:\r\n"); log_register(STATUS_REG, QSPI_STATUS_REG_SIZE, qspi, "Status register"); - //utest_printf("Config register 0:\r\n"); log_register(CONFIG_REG0, QSPI_CONFIG_REG_0_SIZE, qspi, "Config register 0"); #ifdef CONFIG_REG1 - //utest_printf("Config register 1:\r\n"); log_register(CONFIG_REG1, QSPI_CONFIG_REG_1_SIZE, qspi, "Config register 1"); #endif #ifdef CONFIG_REG2 - //utest_printf("Config register 2:\r\n"); log_register(CONFIG_REG2, QSPI_CONFIG_REG_2_SIZE, qspi, "Config register 2"); #endif #endif @@ -262,23 +284,10 @@ void qspi_write_read_test(void) write_addr_size, write_alt_size, write_frequency, write_count, read_inst_width, read_addr_width, read_data_width, read_alt_width, read_cmd, read_dummy_cycles, read_addr_size, read_alt_size, read_frequency, read_count, test_count, - data_size, flash_addr); + data_size, addr); - qspi.cmd.configure(MODE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8); - - if (is_dual_cmd(write_inst_width, write_addr_width, write_data_width) || - is_dual_cmd(read_inst_width, read_addr_width, read_data_width)) { - ret = dual_disable(qspi); - TEST_ASSERT_EQUAL(QSPI_STATUS_OK, ret); - WAIT_FOR(WRSR_MAX_TIME, qspi); - } - - if (is_quad_cmd(write_inst_width, write_addr_width, write_data_width) || - is_quad_cmd(read_inst_width, read_addr_width, read_data_width)) { - ret = quad_disable(qspi); - TEST_ASSERT_EQUAL(QSPI_STATUS_OK, ret); - WAIT_FOR(WRSR_MAX_TIME, qspi); - } + ret = fast_mode_disable(qspi); + TEST_ASSERT_EQUAL(QSPI_STATUS_OK, ret); qspi_free(&qspi.handle); } @@ -315,16 +324,12 @@ void qspi_init_free_test(void) flash_init(qspi); #ifdef QSPI_TEST_LOG_FLASH_STATUS - //utest_printf("Status register:\r\n"); log_register(STATUS_REG, QSPI_STATUS_REG_SIZE, qspi, "Status register"); - //utest_printf("Config register 0:\r\n"); log_register(CONFIG_REG0, QSPI_CONFIG_REG_0_SIZE, qspi, "Config register 0"); #ifdef CONFIG_REG1 - //utest_printf("Config register 1:\r\n"); log_register(CONFIG_REG1, QSPI_CONFIG_REG_1_SIZE, qspi, "Config register 1"); #endif #ifdef CONFIG_REG2 - //utest_printf("Config register 2:\r\n"); log_register(CONFIG_REG2, QSPI_CONFIG_REG_2_SIZE, qspi, "Config register 2"); #endif #endif @@ -338,37 +343,33 @@ void qspi_frequency_test(void) { Qspi qspi; qspi_status_t ret; + int freq = QSPI_COMMON_MAX_FREQUENCY; - ret = qspi_init(&qspi.handle, QPIN_0, QPIN_1, QPIN_2, QPIN_3, QSCK, QCSN, QSPI_COMMON_MAX_FREQUENCY, 0); + ret = qspi_init(&qspi.handle, QPIN_0, QPIN_1, QPIN_2, QPIN_3, QSCK, QCSN, freq, 0); TEST_ASSERT_EQUAL(QSPI_STATUS_OK, ret); - ret = qspi_frequency(&qspi.handle, QSPI_COMMON_MAX_FREQUENCY); - TEST_ASSERT_EQUAL(QSPI_STATUS_OK, ret); // check if the memory is working properly qspi.cmd.configure(MODE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8); flash_init(qspi); - _qspi_write_read_test(qspi, WRITE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8, QSPI_NONE, WRITE_SINGLE, READ_1_1_1, ADDR_SIZE_24, ALT_SIZE_8, QSPI_NONE, READ_SINGLE, TEST_REPEAT_SINGLE, DATA_SIZE_256, TEST_FLASH_ADDRESS); + _qspi_write_read_test(qspi, WRITE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8, freq, WRITE_SINGLE, READ_1_1_1, ADDR_SIZE_24, ALT_SIZE_8, freq, READ_SINGLE, TEST_REPEAT_SINGLE, DATA_SIZE_256, TEST_FLASH_ADDRESS); - ret = qspi_frequency(&qspi.handle, QSPI_COMMON_MAX_FREQUENCY / 2); - TEST_ASSERT_EQUAL(QSPI_STATUS_OK, ret); + freq /= 2; // check if the memory is working properly qspi.cmd.configure(MODE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8); flash_init(qspi); - _qspi_write_read_test(qspi, WRITE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8, QSPI_NONE, WRITE_SINGLE, READ_1_1_1, ADDR_SIZE_24, ALT_SIZE_8, QSPI_NONE, READ_SINGLE, TEST_REPEAT_SINGLE, DATA_SIZE_256, TEST_FLASH_ADDRESS); + _qspi_write_read_test(qspi, WRITE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8, freq, WRITE_SINGLE, READ_1_1_1, ADDR_SIZE_24, ALT_SIZE_8, freq, READ_SINGLE, TEST_REPEAT_SINGLE, DATA_SIZE_256, TEST_FLASH_ADDRESS); - ret = qspi_frequency(&qspi.handle, QSPI_COMMON_MAX_FREQUENCY / 4); - TEST_ASSERT_EQUAL(QSPI_STATUS_OK, ret); + freq /= 2; // check if the memory is working properly qspi.cmd.configure(MODE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8); flash_init(qspi); - _qspi_write_read_test(qspi, WRITE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8, QSPI_NONE, WRITE_SINGLE, READ_1_1_1, ADDR_SIZE_24, ALT_SIZE_8, QSPI_NONE, READ_SINGLE, TEST_REPEAT_SINGLE, DATA_SIZE_256, TEST_FLASH_ADDRESS); + _qspi_write_read_test(qspi, WRITE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8, freq, WRITE_SINGLE, READ_1_1_1, ADDR_SIZE_24, ALT_SIZE_8, freq, READ_SINGLE, TEST_REPEAT_SINGLE, DATA_SIZE_256, TEST_FLASH_ADDRESS); - ret = qspi_frequency(&qspi.handle, QSPI_COMMON_MAX_FREQUENCY / 8); - TEST_ASSERT_EQUAL(QSPI_STATUS_OK, ret); + freq /= 2; // check if the memory is working properly qspi.cmd.configure(MODE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8); flash_init(qspi); - _qspi_write_read_test(qspi, WRITE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8, QSPI_NONE, WRITE_SINGLE, READ_1_1_1, ADDR_SIZE_24, ALT_SIZE_8, QSPI_NONE, READ_SINGLE, TEST_REPEAT_SINGLE, DATA_SIZE_256, TEST_FLASH_ADDRESS); + _qspi_write_read_test(qspi, WRITE_1_1_1, ADDR_SIZE_24, ALT_SIZE_8, freq, WRITE_SINGLE, READ_1_1_1, ADDR_SIZE_24, ALT_SIZE_8, freq, READ_SINGLE, TEST_REPEAT_SINGLE, DATA_SIZE_256, TEST_FLASH_ADDRESS); qspi_free(&qspi.handle); } @@ -387,69 +388,184 @@ Case cases[] = { // read/x1 write/x1 - read/write block of data in single write/read operation // read/x4 write/x4 - read/write block of data in adjacent locations in multiple write/read operations // repeat/xN - test repeat count (new data pattern each time) + // 1-1-1 - single channel SPI + // 1-1-2 - Dual data (extended SPI) + // 1-2-2 - Dual I/O (extended SPI) + // 1-1-4 - Quad data (extended SPI) + // 1-4-4 - Quad I/O (extended SPI) + // 2-2-2 - DPI (multi-channel SPI) + // 4-4-4 - QPI (multi-channel SPI) Case("qspi write(1-1-1)/x1 read(1-1-1)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-1-1)/x4 read(1-1-1)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-1-1)/x1 read(1-1-1)/x4 repeat/x1 test", qspi_write_read_test), - Case("qspi write(1-1-1)/x1 read(1-1-1)/x1 repeat/x16 test", qspi_write_read_test), + Case("qspi write(1-1-1)/x1 read(1-1-1)/x1 repeat/x4 test", qspi_write_read_test), Case("qspi write(1-1-1)/x1 read(1-1-2)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-1-1)/x4 read(1-1-2)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-1-1)/x1 read(1-1-2)/x4 repeat/x1 test", qspi_write_read_test), - Case("qspi write(1-1-1)/x1 read(1-1-2)/x1 repeat/x16 test", qspi_write_read_test), + Case("qspi write(1-1-1)/x1 read(1-1-2)/x1 repeat/x4 test", qspi_write_read_test), Case("qspi write(1-1-1)/x1 read(1-2-2)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-1-1)/x4 read(1-2-2)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-1-1)/x1 read(1-2-2)/x4 repeat/x1 test", qspi_write_read_test), - Case("qspi write(1-1-1)/x1 read(1-2-2)/x1 repeat/x16 test", qspi_write_read_test), + Case("qspi write(1-1-1)/x1 read(1-2-2)/x1 repeat/x4 test", qspi_write_read_test), +#ifdef READ_2_2_2 + Case("qspi write(1-1-1)/x1 read(2-2-2)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(1-1-1)/x4 read(2-2-2)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(1-1-1)/x1 read(2-2-2)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(1-1-1)/x1 read(2-2-2)/x1 repeat/x4 test", qspi_write_read_test), +#endif Case("qspi write(1-1-1)/x1 read(1-1-4)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-1-1)/x4 read(1-1-4)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-1-1)/x1 read(1-1-4)/x4 repeat/x1 test", qspi_write_read_test), - Case("qspi write(1-1-1)/x1 read(1-1-4)/x1 repeat/x16 test", qspi_write_read_test), + Case("qspi write(1-1-1)/x1 read(1-1-4)/x1 repeat/x4 test", qspi_write_read_test), Case("qspi write(1-1-1)/x1 read(1-4-4)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-1-1)/x4 read(1-4-4)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-1-1)/x1 read(1-4-4)/x4 repeat/x1 test", qspi_write_read_test), - Case("qspi write(1-1-1)/x1 read(1-4-4)/x1 repeat/x16 test", qspi_write_read_test), -#ifdef QSPI_CMD_WRITE_2IO + Case("qspi write(1-1-1)/x1 read(1-4-4)/x1 repeat/x4 test", qspi_write_read_test), +#ifdef READ_4_4_4 + Case("qspi write(1-1-1)/x1 read(4-4-4)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(1-1-1)/x4 read(4-4-4)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(1-1-1)/x1 read(4-4-4)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(1-1-1)/x1 read(4-4-4)/x1 repeat/x4 test", qspi_write_read_test), +#endif + +#ifdef WRITE_1_2_2 Case("qspi write(1-2-2)/x1 read(1-1-1)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-2-2)/x4 read(1-1-1)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-2-2)/x1 read(1-1-1)/x4 repeat/x1 test", qspi_write_read_test), - Case("qspi write(1-2-2)/x1 read(1-1-1)/x1 repeat/x16 test", qspi_write_read_test), + Case("qspi write(1-2-2)/x1 read(1-1-1)/x1 repeat/x4 test", qspi_write_read_test), Case("qspi write(1-2-2)/x1 read(1-1-2)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-2-2)/x4 read(1-1-2)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-2-2)/x1 read(1-1-2)/x4 repeat/x1 test", qspi_write_read_test), - Case("qspi write(1-2-2)/x1 read(1-1-2)/x1 repeat/x16 test", qspi_write_read_test), + Case("qspi write(1-2-2)/x1 read(1-1-2)/x1 repeat/x4 test", qspi_write_read_test), Case("qspi write(1-2-2)/x1 read(1-2-2)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-2-2)/x4 read(1-2-2)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-2-2)/x1 read(1-2-2)/x4 repeat/x1 test", qspi_write_read_test), - Case("qspi write(1-2-2)/x1 read(1-2-2)/x1 repeat/x16 test", qspi_write_read_test), + Case("qspi write(1-2-2)/x1 read(1-2-2)/x1 repeat/x4 test", qspi_write_read_test), +#ifdef READ_2_2_2 + Case("qspi write(1-2-2)/x1 read(2-2-2)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(1-2-2)/x4 read(2-2-2)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(1-2-2)/x1 read(2-2-2)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(1-2-2)/x1 read(2-2-2)/x1 repeat/x4 test", qspi_write_read_test), +#endif Case("qspi write(1-2-2)/x1 read(1-1-4)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-2-2)/x4 read(1-1-4)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-2-2)/x1 read(1-1-4)/x4 repeat/x1 test", qspi_write_read_test), - Case("qspi write(1-2-2)/x1 read(1-1-4)/x1 repeat/x16 test", qspi_write_read_test), + Case("qspi write(1-2-2)/x1 read(1-1-4)/x1 repeat/x4 test", qspi_write_read_test), Case("qspi write(1-2-2)/x1 read(1-4-4)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-2-2)/x4 read(1-4-4)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-2-2)/x1 read(1-4-4)/x4 repeat/x1 test", qspi_write_read_test), - Case("qspi write(1-2-2)/x1 read(1-4-4)/x1 repeat/x16 test", qspi_write_read_test), + Case("qspi write(1-2-2)/x1 read(1-4-4)/x1 repeat/x4 test", qspi_write_read_test), +#ifdef READ_4_4_4 + Case("qspi write(1-2-2)/x1 read(4-4-4)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(1-2-2)/x4 read(4-4-4)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(1-2-2)/x1 read(4-4-4)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(1-2-2)/x1 read(4-4-4)/x1 repeat/x4 test", qspi_write_read_test), #endif -#ifdef QSPI_CMD_WRITE_4IO +#endif + +#ifdef WRITE_2_2_2 + Case("qspi write(2-2-2)/x1 read(1-1-1)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x4 read(1-1-1)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x1 read(1-1-1)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x1 read(1-1-1)/x1 repeat/x4 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x1 read(1-1-2)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x4 read(1-1-2)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x1 read(1-1-2)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x1 read(1-1-2)/x1 repeat/x4 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x1 read(1-2-2)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x4 read(1-2-2)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x1 read(1-2-2)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x1 read(1-2-2)/x1 repeat/x4 test", qspi_write_read_test), +#ifdef READ_2_2_2 + Case("qspi write(2-2-2)/x1 read(2-2-2)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x4 read(2-2-2)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x1 read(2-2-2)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x1 read(2-2-2)/x1 repeat/x4 test", qspi_write_read_test), +#endif + Case("qspi write(2-2-2)/x1 read(1-1-4)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x4 read(1-1-4)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x1 read(1-1-4)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x1 read(1-1-4)/x1 repeat/x4 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x1 read(1-4-4)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x4 read(1-4-4)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x1 read(1-4-4)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x1 read(1-4-4)/x1 repeat/x4 test", qspi_write_read_test), +#ifdef READ_4_4_4 + Case("qspi write(2-2-2)/x1 read(4-4-4)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x4 read(4-4-4)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x1 read(4-4-4)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(2-2-2)/x1 read(4-4-4)/x1 repeat/x4 test", qspi_write_read_test), +#endif +#endif + +#ifdef WRITE_1_4_4 Case("qspi write(1-4-4)/x1 read(1-1-1)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-4-4)/x4 read(1-1-1)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-4-4)/x1 read(1-1-1)/x4 repeat/x1 test", qspi_write_read_test), - Case("qspi write(1-4-4)/x1 read(1-1-1)/x1 repeat/x16 test", qspi_write_read_test), + Case("qspi write(1-4-4)/x1 read(1-1-1)/x1 repeat/x4 test", qspi_write_read_test), Case("qspi write(1-4-4)/x1 read(1-1-2)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-4-4)/x4 read(1-1-2)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-4-4)/x1 read(1-1-2)/x4 repeat/x1 test", qspi_write_read_test), - Case("qspi write(1-4-4)/x1 read(1-1-2)/x1 repeat/x16 test", qspi_write_read_test), + Case("qspi write(1-4-4)/x1 read(1-1-2)/x1 repeat/x4 test", qspi_write_read_test), Case("qspi write(1-4-4)/x1 read(1-2-2)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-4-4)/x4 read(1-2-2)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-4-4)/x1 read(1-2-2)/x4 repeat/x1 test", qspi_write_read_test), - Case("qspi write(1-4-4)/x1 read(1-2-2)/x1 repeat/x16 test", qspi_write_read_test), + Case("qspi write(1-4-4)/x1 read(1-2-2)/x1 repeat/x4 test", qspi_write_read_test), +#ifdef READ_2_2_2 + Case("qspi write(1-4-4)/x1 read(2-2-2)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(1-4-4)/x4 read(2-2-2)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(1-4-4)/x1 read(2-2-2)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(1-4-4)/x1 read(2-2-2)/x1 repeat/x4 test", qspi_write_read_test), +#endif Case("qspi write(1-4-4)/x1 read(1-1-4)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-4-4)/x4 read(1-1-4)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-4-4)/x1 read(1-1-4)/x4 repeat/x1 test", qspi_write_read_test), - Case("qspi write(1-4-4)/x1 read(1-1-4)/x1 repeat/x16 test", qspi_write_read_test), + Case("qspi write(1-4-4)/x1 read(1-1-4)/x1 repeat/x4 test", qspi_write_read_test), Case("qspi write(1-4-4)/x1 read(1-4-4)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-4-4)/x4 read(1-4-4)/x1 repeat/x1 test", qspi_write_read_test), Case("qspi write(1-4-4)/x1 read(1-4-4)/x4 repeat/x1 test", qspi_write_read_test), - Case("qspi write(1-4-4)/x1 read(1-4-4)/x1 repeat/x16 test", qspi_write_read_test), + Case("qspi write(1-4-4)/x1 read(1-4-4)/x1 repeat/x4 test", qspi_write_read_test), +#ifdef READ_4_4_4 + Case("qspi write(1-4-4)/x1 read(4-4-4)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(1-4-4)/x4 read(4-4-4)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(1-4-4)/x1 read(4-4-4)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(1-4-4)/x1 read(4-4-4)/x1 repeat/x4 test", qspi_write_read_test), +#endif +#endif + +#ifdef WRITE_4_4_4 + Case("qspi write(4-4-4)/x1 read(1-1-1)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x4 read(1-1-1)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x1 read(1-1-1)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x1 read(1-1-1)/x1 repeat/x4 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x1 read(1-1-2)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x4 read(1-1-2)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x1 read(1-1-2)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x1 read(1-1-2)/x1 repeat/x4 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x1 read(1-2-2)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x4 read(1-2-2)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x1 read(1-2-2)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x1 read(1-2-2)/x1 repeat/x4 test", qspi_write_read_test), +#ifdef READ_2_2_2 + Case("qspi write(4-4-4)/x1 read(2-2-2)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x4 read(2-2-2)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x1 read(2-2-2)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x1 read(2-2-2)/x1 repeat/x4 test", qspi_write_read_test), +#endif + Case("qspi write(4-4-4)/x1 read(1-1-4)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x4 read(1-1-4)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x1 read(1-1-4)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x1 read(1-1-4)/x1 repeat/x4 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x1 read(1-4-4)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x4 read(1-4-4)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x1 read(1-4-4)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x1 read(1-4-4)/x1 repeat/x4 test", qspi_write_read_test), +#ifdef READ_4_4_4 + Case("qspi write(4-4-4)/x1 read(4-4-4)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x4 read(4-4-4)/x1 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x1 read(4-4-4)/x4 repeat/x1 test", qspi_write_read_test), + Case("qspi write(4-4-4)/x1 read(4-4-4)/x1 repeat/x4 test", qspi_write_read_test), +#endif #endif }; diff --git a/TESTS/mbed_hal/qspi/qspi_test_utils.cpp b/TESTS/mbed_hal/qspi/qspi_test_utils.cpp index 8ee85f7ffc..f1386534fb 100644 --- a/TESTS/mbed_hal/qspi/qspi_test_utils.cpp +++ b/TESTS/mbed_hal/qspi/qspi_test_utils.cpp @@ -26,6 +26,12 @@ #include "flash_configs/flash_configs.h" #include "mbed.h" +static qspi_status_t extended_enable(Qspi &qspi); +static qspi_status_t extended_disable(Qspi &qspi); +static qspi_status_t dual_enable(Qspi &qspi); +static qspi_status_t dual_disable(Qspi &qspi); +static qspi_status_t quad_enable(Qspi &qspi); +static qspi_status_t quad_disable(Qspi &qspi); void QspiCommand::configure(qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width, qspi_bus_width_t alt_width, @@ -44,6 +50,11 @@ void QspiCommand::configure(qspi_bus_width_t inst_width, qspi_bus_width_t addr_w _cmd.dummy_count = dummy_cycles; } +void QspiCommand::set_dummy_cycles(int dummy_cycles) +{ + _cmd.dummy_count = dummy_cycles; +} + void QspiCommand::build(int instruction, int address, int alt) { _cmd.instruction.disabled = (instruction == QSPI_NONE); @@ -188,46 +199,116 @@ qspi_status_t erase(uint32_t erase_cmd, uint32_t flash_addr, Qspi &qspi) return qspi_command_transfer(&qspi.handle, qspi.cmd.get(), NULL, 0, NULL, 0); } -qspi_status_t dual_enable(Qspi &qspi) +qspi_status_t mode_enable(Qspi &qspi, qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width) +{ + if(is_extended_mode(inst_width, addr_width, data_width)) { + return extended_enable(qspi); + } else if(is_dual_mode(inst_width, addr_width, data_width)) { + return dual_enable(qspi); + } else if(is_quad_mode(inst_width, addr_width, data_width)) { + return quad_enable(qspi); + } else { + return QSPI_STATUS_OK; + } +} + +qspi_status_t mode_disable(Qspi &qspi, qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width) +{ + if(is_extended_mode(inst_width, addr_width, data_width)) { + return extended_disable(qspi); + } else if(is_dual_mode(inst_width, addr_width, data_width)) { + return dual_disable(qspi); + } else if(is_quad_mode(inst_width, addr_width, data_width)) { + return quad_disable(qspi); + } else { + return QSPI_STATUS_OK; + } +} + +static qspi_status_t extended_enable(Qspi &qspi) +{ +#ifdef EXTENDED_SPI_ENABLE + EXTENDED_SPI_ENABLE(); +#else + return QSPI_STATUS_OK; +#endif +} + +static qspi_status_t extended_disable(Qspi &qspi) +{ +#ifdef EXTENDED_SPI_DISABLE + EXTENDED_SPI_DISABLE(); +#else + return QSPI_STATUS_OK; +#endif +} + +static qspi_status_t dual_enable(Qspi &qspi) { #ifdef DUAL_ENABLE DUAL_ENABLE(); #else - QUAD_ENABLE(); + return QSPI_STATUS_OK; #endif } -qspi_status_t dual_disable(Qspi &qspi) +static qspi_status_t dual_disable(Qspi &qspi) { #ifdef DUAL_DISABLE DUAL_DISABLE(); #else - QUAD_DISABLE(); + return QSPI_STATUS_OK; #endif } -qspi_status_t quad_enable(Qspi &qspi) +static qspi_status_t quad_enable(Qspi &qspi) { +#ifdef QUAD_ENABLE QUAD_ENABLE(); +#else + return QSPI_STATUS_OK; +#endif } -qspi_status_t quad_disable(Qspi &qspi) +static qspi_status_t quad_disable(Qspi &qspi) { +#ifdef QUAD_DISABLE QUAD_DISABLE(); +#else + return QSPI_STATUS_OK; +#endif } qspi_status_t fast_mode_enable(Qspi &qspi) { +#ifdef FAST_MODE_ENABLE FAST_MODE_ENABLE(); +#else + return QSPI_STATUS_OK; +#endif } -bool is_dual_cmd(qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width) +qspi_status_t fast_mode_disable(Qspi &qspi) { - return (inst_width == QSPI_CFG_BUS_DUAL) || (addr_width == QSPI_CFG_BUS_DUAL) || (data_width == QSPI_CFG_BUS_DUAL); +#ifdef FAST_MODE_DISABLE + FAST_MODE_DISABLE(); +#else + return QSPI_STATUS_OK; +#endif } -bool is_quad_cmd(qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width) +bool is_extended_mode(qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width) { - return (inst_width == QSPI_CFG_BUS_QUAD) || (addr_width == QSPI_CFG_BUS_QUAD) || (data_width == QSPI_CFG_BUS_QUAD); + return (inst_width == QSPI_CFG_BUS_SINGLE) && ((addr_width != QSPI_CFG_BUS_SINGLE) || (data_width != QSPI_CFG_BUS_SINGLE)); +} + +bool is_dual_mode(qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width) +{ + return (inst_width == QSPI_CFG_BUS_DUAL) && (addr_width == QSPI_CFG_BUS_DUAL) && (data_width == QSPI_CFG_BUS_DUAL); +} + +bool is_quad_mode(qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width) +{ + return (inst_width == QSPI_CFG_BUS_QUAD) && (addr_width == QSPI_CFG_BUS_QUAD) && (data_width == QSPI_CFG_BUS_QUAD); } diff --git a/TESTS/mbed_hal/qspi/qspi_test_utils.h b/TESTS/mbed_hal/qspi/qspi_test_utils.h index 7f54a439f4..3344abb510 100644 --- a/TESTS/mbed_hal/qspi/qspi_test_utils.h +++ b/TESTS/mbed_hal/qspi/qspi_test_utils.h @@ -34,6 +34,8 @@ public: qspi_bus_width_t alt_width, qspi_address_size_t addr_size, qspi_alt_size_t alt_size, int dummy_cycles = 0); + void set_dummy_cycles(int dummy_cycles); + void build(int instruction, int address = QSPI_NONE, int alt = QSPI_NONE); qspi_command_t *get(); @@ -51,8 +53,10 @@ struct Qspi { #define MODE_1_1_1 QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_SINGLE #define MODE_1_1_2 QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_DUAL, QSPI_CFG_BUS_DUAL #define MODE_1_2_2 QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_DUAL, QSPI_CFG_BUS_DUAL, QSPI_CFG_BUS_DUAL -#define MODE_1_1_4 QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_QUAD, QSPI_CFG_BUS_SINGLE +#define MODE_2_2_2 QSPI_CFG_BUS_DUAL, QSPI_CFG_BUS_DUAL, QSPI_CFG_BUS_DUAL, QSPI_CFG_BUS_DUAL +#define MODE_1_1_4 QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_QUAD, QSPI_CFG_BUS_QUAD #define MODE_1_4_4 QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_QUAD, QSPI_CFG_BUS_QUAD, QSPI_CFG_BUS_QUAD +#define MODE_4_4_4 QSPI_CFG_BUS_QUAD, QSPI_CFG_BUS_QUAD, QSPI_CFG_BUS_QUAD, QSPI_CFG_BUS_QUAD #define WRITE_1_1_1 MODE_1_1_1, QSPI_CMD_WRITE_1IO #ifdef QSPI_CMD_WRITE_2IO @@ -61,6 +65,12 @@ struct Qspi { #ifdef QSPI_CMD_WRITE_4IO #define WRITE_1_4_4 MODE_1_4_4, QSPI_CMD_WRITE_4IO #endif +#ifdef QSPI_CMD_WRITE_DPI +#define WRITE_2_2_2 MODE_2_2_2, QSPI_CMD_WRITE_DPI +#endif +#ifdef QSPI_CMD_WRITE_QPI +#define WRITE_4_4_4 MODE_4_4_4, QSPI_CMD_WRITE_QPI +#endif #define READ_1_1_1 MODE_1_1_1, QSPI_CMD_READ_1IO, QSPI_READ_1IO_DUMMY_CYCLE @@ -68,7 +78,12 @@ struct Qspi { #define READ_1_2_2 MODE_1_2_2, QSPI_CMD_READ_2IO, QSPI_READ_2IO_DUMMY_CYCLE #define READ_1_1_4 MODE_1_1_4, QSPI_CMD_READ_1I4O, QSPI_READ_1I4O_DUMMY_CYCLE #define READ_1_4_4 MODE_1_4_4, QSPI_CMD_READ_4IO, QSPI_READ_4IO_DUMMY_CYCLE - +#ifdef QSPI_CMD_READ_DPI +#define READ_2_2_2 MODE_2_2_2, QSPI_CMD_READ_DPI, QSPI_READ_2IO_DUMMY_CYCLE +#endif +#ifdef QSPI_CMD_READ_QPI +#define READ_4_4_4 MODE_4_4_4, QSPI_CMD_READ_QPI, QSPI_READ_4IO_DUMMY_CYCLE +#endif #define ADDR_SIZE_8 QSPI_CFG_ADDR_SIZE_8 #define ADDR_SIZE_16 QSPI_CFG_ADDR_SIZE_16 @@ -120,26 +135,21 @@ QspiStatus flash_wait_for(uint32_t time_us, Qspi &qspi); void flash_init(Qspi &qspi); qspi_status_t write_enable(Qspi &qspi); - qspi_status_t write_disable(Qspi &qspi); void log_register(uint32_t cmd, uint32_t reg_size, Qspi &qspi, const char *str = NULL); -qspi_status_t dual_enable(Qspi &qspi); - -qspi_status_t dual_disable(Qspi &qspi); - -qspi_status_t quad_enable(Qspi &qspi); - -qspi_status_t quad_disable(Qspi &qspi); +qspi_status_t mode_enable(Qspi &qspi, qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width); +qspi_status_t mode_disable(Qspi &qspi, qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width); qspi_status_t fast_mode_enable(Qspi &qspi); +qspi_status_t fast_mode_disable(Qspi &qspi); qspi_status_t erase(uint32_t erase_cmd, uint32_t flash_addr, Qspi &qspi); -bool is_dual_cmd(qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width); - -bool is_quad_cmd(qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width); +bool is_extended_mode(qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width); +bool is_dual_mode(qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width); +bool is_quad_mode(qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width); #define WAIT_FOR(timeout, q) TEST_ASSERT_EQUAL_MESSAGE(sOK, flash_wait_for(timeout, q), "flash_wait_for failed!!!") diff --git a/TESTS/mbed_hal/sleep/main.cpp b/TESTS/mbed_hal/sleep/main.cpp index 46beb039b2..4d98274278 100644 --- a/TESTS/mbed_hal/sleep/main.cpp +++ b/TESTS/mbed_hal/sleep/main.cpp @@ -47,6 +47,8 @@ using namespace utest::v1; +static char info[512] = {0}; + /* The following ticker frequencies are possible: * high frequency ticker: 250 KHz (1 tick per 4 us) - 8 Mhz (1 tick per 1/8 us) * low power ticker: 8 KHz (1 tick per 125 us) - 64 KHz (1 tick per ~15.6 us) @@ -140,6 +142,11 @@ void sleep_usticker_test() const ticker_irq_handler_type us_ticker_irq_handler_org = set_us_ticker_irq_handler(us_ticker_isr); + /* Give some time Green Tea to finish UART transmission before entering + * sleep mode. + */ + busy_wait_ms(SERIAL_FLUSH_TIME_MS); + /* Test only sleep functionality. */ sleep_manager_lock_deep_sleep(); TEST_ASSERT_FALSE_MESSAGE(sleep_manager_can_deep_sleep(), "deep sleep should be locked"); @@ -147,7 +154,8 @@ void sleep_usticker_test() /* Testing wake-up time 10 us. */ for (timestamp_t i = 100; i < 1000; i += 100) { /* note: us_ticker_read() operates on ticks. */ - const timestamp_t next_match_timestamp = overflow_protect(us_ticker_read() + us_to_ticks(i, ticker_freq), + const timestamp_t start_timestamp = us_ticker_read(); + const timestamp_t next_match_timestamp = overflow_protect(start_timestamp + us_to_ticks(i, ticker_freq), ticker_width); us_ticker_set_interrupt(next_match_timestamp); @@ -156,9 +164,11 @@ void sleep_usticker_test() const unsigned int wakeup_timestamp = us_ticker_read(); - TEST_ASSERT( - compare_timestamps(us_to_ticks(sleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp, - wakeup_timestamp)); + sprintf(info, "Delta ticks: %u, Ticker width: %u, Expected wake up tick: %d, Actual wake up tick: %d, delay ticks: %d, wake up after ticks: %d", + us_to_ticks(sleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp, wakeup_timestamp, us_to_ticks(i, ticker_freq) , wakeup_timestamp - start_timestamp); + + TEST_ASSERT_MESSAGE(compare_timestamps(us_to_ticks(sleep_mode_delta_us, ticker_freq), + ticker_width, next_match_timestamp, wakeup_timestamp), info); } set_us_ticker_irq_handler(us_ticker_irq_handler_org); @@ -189,7 +199,8 @@ void deepsleep_lpticker_test() /* Testing wake-up time 10 ms. */ for (timestamp_t i = 20000; i < 200000; i += 20000) { /* note: lp_ticker_read() operates on ticks. */ - const timestamp_t next_match_timestamp = overflow_protect(lp_ticker_read() + us_to_ticks(i, ticker_freq), ticker_width); + const timestamp_t start_timestamp = lp_ticker_read(); + const timestamp_t next_match_timestamp = overflow_protect(start_timestamp + us_to_ticks(i, ticker_freq), ticker_width); lp_ticker_set_interrupt(next_match_timestamp); @@ -197,7 +208,11 @@ void deepsleep_lpticker_test() const timestamp_t wakeup_timestamp = lp_ticker_read(); - TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp, wakeup_timestamp)); + sprintf(info, "Delta ticks: %u, Ticker width: %u, Expected wake up tick: %d, Actual wake up tick: %d, delay ticks: %d, wake up after ticks: %d", + us_to_ticks(deepsleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp, wakeup_timestamp, us_to_ticks(i, ticker_freq) , wakeup_timestamp - start_timestamp); + + TEST_ASSERT_MESSAGE(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, ticker_freq), ticker_width, + next_match_timestamp, wakeup_timestamp), info); } set_lp_ticker_irq_handler(lp_ticker_irq_handler_org); @@ -240,8 +255,12 @@ void deepsleep_high_speed_clocks_turned_off_test() TEST_ASSERT_UINT32_WITHIN(1000, 0, ticks_to_us(us_ticks_diff, us_ticker_freq)); + sprintf(info, "Delta ticks: %u, Ticker width: %u, Expected wake up tick: %d, Actual wake up tick: %d", + us_to_ticks(deepsleep_mode_delta_us, lp_ticker_freq), lp_ticker_width, wakeup_time, lp_ticks_after_sleep); + /* Check if we have woken-up after expected time. */ - TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, lp_ticker_freq), lp_ticker_width, wakeup_time, lp_ticks_after_sleep)); + TEST_ASSERT_MESSAGE(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, lp_ticker_freq), lp_ticker_width, + wakeup_time, lp_ticks_after_sleep), info); } #endif diff --git a/TESTS/mbed_hal/trng/base64b/base64b.cpp b/TESTS/mbed_hal/trng/base64b/base64b.cpp new file mode 100644 index 0000000000..2623bfee6f --- /dev/null +++ b/TESTS/mbed_hal/trng/base64b/base64b.cpp @@ -0,0 +1,197 @@ +/* +* Copyright (c) 2018 ARM Limited. All rights reserved. +* SPDX-License-Identifier: Apache-2.0 +* Licensed under the Apache License, Version 2.0 (the License); you may +* not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an AS IS BASIS, WITHOUT +* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "base64b.h" + +using namespace std; + +static char IntToBase64Char(uint8_t intVal) +{ + const char *base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + return base64Digits[intVal & 0x3F]; +} + +#define BASE_64_PAD 0xFF +static base64_result_e Base64CharToInt(char base64, uint8_t *intVal) +{ + if (NULL == intVal) { + return BASE64_INVALID_PARAMETER; + } + + if ((base64 >= 'A') && (base64 <= 'Z')) { + *intVal = base64 - 'A' ; + } else if ((base64 >= 'a') && (base64 <= 'z')) { + *intVal = base64 - 'a' + 26; + } else if ((base64 >= '0') && (base64 <= '9')) { + *intVal = base64 - '0' + 52; + } else if (base64 == '+') { + *intVal = 62; + } else if (base64 == '/') { + *intVal = 63; + } else if (base64 == '=') { + *intVal = BASE_64_PAD; + } else { + return BASE64_ERROR; + } + + return BASE64_SUCCESS; +} + +base64_result_e trng_DecodeNBase64(const char *string, + uint32_t stringMaxSize, + void *buffer, + uint32_t bufferSize, + uint32_t *lengthWritten, + uint32_t *charsProcessed) +{ + base64_result_e result = BASE64_SUCCESS; + uint32_t bitOffset = 0; + uint8_t *writePtr = (uint8_t *)buffer; + uint8_t *bufferEnd = (uint8_t *)buffer + bufferSize; + uint8_t tempVal = 0; + uint32_t currPos = 0; + uint32_t localBytesWritten = 0; + uint32_t localCharsProcessed = 0; + bool isEndOfString = false; + + if ((NULL == string) || (NULL == buffer) || (bufferSize == 0)) { + return BASE64_INVALID_PARAMETER; + } + + *writePtr = 0; + while (( currPos < stringMaxSize ) && + ( string[currPos] != 0 ) && + ( writePtr < bufferEnd ) && + ( !isEndOfString )) { + uint8_t val; + + if (string[currPos] == 0) { + break; + } + + result = Base64CharToInt(string[currPos++], &val); + if (result != BASE64_SUCCESS) { + break; + } + + if (val != BASE_64_PAD) { + if (bitOffset <= 2) { + tempVal |= val << (2 - bitOffset); + if (bitOffset == 2) { + *writePtr++ = tempVal; + tempVal = 0; + } + } else { + *writePtr++ = (uint8_t)(tempVal | (val >> (bitOffset - 2))); + tempVal = (uint8_t)(val << (10 - bitOffset)); + } + } else { // found BASE_64_PAD + // At most two pad characters may occur at the end of the encoded stream + if (bitOffset == 2) { + isEndOfString = true; // The last padding byte has been processed. + } else if (bitOffset != 4) { + return BASE64_ERROR; // Incorrect padding + } + } + + bitOffset = (bitOffset + 6) & 0x7; + if (bitOffset == 0) { + localBytesWritten = (uint32_t)(writePtr - (uint8_t *)buffer); + localCharsProcessed = currPos; + } + } + if (charsProcessed == NULL) { + localBytesWritten = (uint32_t)(writePtr - (uint8_t *)buffer); + } else { + *charsProcessed = localCharsProcessed; + } + if (lengthWritten != NULL) { + *lengthWritten = localBytesWritten; + } else if (bufferSize != localBytesWritten) { + return BASE64_BUFFER_TOO_SMALL; + } + + // Check if additional bytes should have been processed but buffer isn't sufficient. + if (( result == BASE64_SUCCESS ) && + ( !isEndOfString ) && + ( currPos < stringMaxSize ) && + ( string[currPos] != 0 ) && + ( string[currPos] != '=' ) ) { + return BASE64_BUFFER_TOO_SMALL; + } + + if (result != BASE64_SUCCESS) { + return result; + } + + return BASE64_SUCCESS; +} + +base64_result_e trng_EncodeBase64(const void *buffer, uint32_t bufferSize, char *string, uint32_t stringSize) +{ + uint32_t bitOffset = 0; + + const uint8_t *readPtr = (const uint8_t *)buffer; + const uint8_t *bufferEnd = (const uint8_t *)buffer + bufferSize; + + char *writePtr = string; + char *stringEnd = string + stringSize - 1; + + if ((NULL == string) || (NULL == buffer) || (stringSize == 0)) { + return BASE64_INVALID_PARAMETER; + } + + stringSize--; + while (readPtr < bufferEnd && writePtr < stringEnd) { + uint8_t tempVal = 0; + switch (bitOffset) { + case 0: + *writePtr++ = IntToBase64Char(*readPtr >> 2); // take upper 6 bits + break; + case 6: + tempVal = *readPtr++ << 4; + if (readPtr < bufferEnd) { + tempVal |= *readPtr >> 4; + } + *writePtr++ = IntToBase64Char(tempVal); + break; + case 4: + tempVal = *readPtr++ << 2; + if (readPtr < bufferEnd) { + tempVal |= *readPtr >> 6; + } + *writePtr++ = IntToBase64Char(tempVal); + break; + case 2: + *writePtr++ = IntToBase64Char(*readPtr++); + break; + default: + return BASE64_ERROR; // we should never reach this code. + } + bitOffset = (bitOffset + 6) & 0x7; + } + while (bitOffset > 0 && writePtr < stringEnd) { + *writePtr++ = '='; + bitOffset = (bitOffset + 6) & 0x7; + } + *writePtr = 0; + + if ((readPtr < bufferEnd) || (bitOffset != 0)) { + return (BASE64_BUFFER_TOO_SMALL); + } + + return (BASE64_SUCCESS); +} diff --git a/TESTS/mbed_hal/trng/base64b/base64b.h b/TESTS/mbed_hal/trng/base64b/base64b.h new file mode 100644 index 0000000000..cbb6b85b56 --- /dev/null +++ b/TESTS/mbed_hal/trng/base64b/base64b.h @@ -0,0 +1,32 @@ +/* +* Copyright (c) 2018 ARM Limited. All rights reserved. +* SPDX-License-Identifier: Apache-2.0 +* Licensed under the Apache License, Version 2.0 (the License); you may +* not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an AS IS BASIS, WITHOUT +* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include +#include +#include + +typedef enum { + BASE64_SUCCESS = 0, + BASE64_INVALID_PARAMETER = 1, + BASE64_BUFFER_TOO_SMALL = 2, + BASE64_ERROR = 3, +} base64_result_e; + +base64_result_e trng_EncodeBase64(const void *buffer, uint32_t bufferSize, char *string, uint32_t stringSize); +base64_result_e trng_DecodeNBase64(const char *string, uint32_t stringMaxSize, void *buffer, uint32_t bufferSize, + uint32_t *lengthWritten, uint32_t *charsProcessed); + + diff --git a/TESTS/mbed_hal/trng/main.cpp b/TESTS/mbed_hal/trng/main.cpp new file mode 100644 index 0000000000..cfa0260d13 --- /dev/null +++ b/TESTS/mbed_hal/trng/main.cpp @@ -0,0 +1,247 @@ +/* +* Copyright (c) 2018 ARM Limited. All rights reserved. +* SPDX-License-Identifier: Apache-2.0 +* Licensed under the Apache License, Version 2.0 (the License); you may +* not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an AS IS BASIS, WITHOUT +* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* The test is based on the assumption that trng will generate random data, random so +* there will not be any similar patterns in it, that kind of data will be impossible to +* compress, if compression will occur the test will result in failure. +* +* The test is composed out of three parts: +* the first, generate a trng buffer and try to compress it, at the end of first part +* we will reset the device. +* In second part we will generate a trng buffer with a different buffer size and try to +* compress it. +* In the third part we will again generate a trng buffer to see that the same trng output +* is not generated as the stored trng buffer from part one (before reseting), the new trng data will +* be concatenated to the trng data from the first part and then try to compress it +* together, if there are similar patterns the compression will succeed. +* +* We need to store and load the first part data before and after reset, the mechanism +* we will use is the mbed greentea platform for sending and receving the data from the device +* to the host running the test and back, the problem with this mechanism is that it doesn't +* handle well certain characters, especially non ASCII ones, so we use the base64 algorithm +* to ensure all characters will be transmitted correctly. +*/ + +#include "greentea-client/test_env.h" +#include "unity/unity.h" +#include "utest/utest.h" +#include "hal/trng_api.h" +#include "base64b.h" +#include "pithy.h" +#include + +#if !DEVICE_TRNG +#error [NOT_SUPPORTED] TRNG API not supported for this target +#endif + +#define MSG_VALUE_DUMMY "0" +#define MSG_VALUE_LEN 64 +#define MSG_KEY_LEN 32 + +#define BUFFER_LEN (MSG_VALUE_LEN/2) + +#define MSG_TRNG_READY "ready" +#define MSG_TRNG_BUFFER "buffer" +#define MSG_TRNG_EXIT "exit" + +#define MSG_TRNG_TEST_STEP1 "check_step1" +#define MSG_TRNG_TEST_STEP2 "check_step2" +#define MSG_TRNG_TEST_SUITE_ENDED "Test_suite_ended" + +#define RESULT_SUCCESS 0 + +using namespace utest::v1; + +static int fill_buffer_trng(uint8_t *buffer, trng_t *trng_obj, size_t trng_len) +{ + size_t temp_size = 0, output_length = 0; + int trng_res = 0; + uint8_t *temp_in_buf = buffer; + + trng_init(trng_obj); + memset(buffer, 0, BUFFER_LEN); + + while (true) { + trng_res = trng_get_bytes(trng_obj, temp_in_buf, trng_len - temp_size, &output_length); + TEST_ASSERT_EQUAL_INT_MESSAGE(0, trng_res, "trng_get_bytes error!"); + temp_size += output_length; + temp_in_buf += output_length; + if (temp_size >= trng_len) { + break; + } + } + + temp_in_buf = NULL; + trng_free(trng_obj); + return 0; +} + +void print_array(uint8_t *buffer, size_t size) +{ + for (size_t i=0; i < size; i++) { + utest_printf("%02x", buffer[i]); + } + utest_printf("\n"); +} + +static void compress_and_compare(char *key, char *value) +{ + trng_t trng_obj; + uint8_t *out_comp_buf, *buffer; + uint8_t *input_buf, *temp_buf; + size_t comp_sz = 0; + unsigned int result = 0; + +#define OUT_COMP_BUF_SIZE ((BUFFER_LEN * 5) + 32) +#define TEMP_BUF_SIZE (BUFFER_LEN * 2) + + out_comp_buf = new uint8_t[OUT_COMP_BUF_SIZE]; + buffer = new uint8_t[BUFFER_LEN]; + temp_buf = new uint8_t[BUFFER_LEN * 2]; + input_buf = new uint8_t[BUFFER_LEN * 4]; + + /*At the begining of step 2 load trng buffer from step 1*/ + if (strcmp(key, MSG_TRNG_TEST_STEP2) == 0) { + /*Using base64 to decode data sent from host*/ + uint32_t lengthWritten = 0; + uint32_t charsProcessed = 0; + result = trng_DecodeNBase64((const char *)value, + MSG_VALUE_LEN, + buffer, + BUFFER_LEN, + &lengthWritten, + &charsProcessed); + TEST_ASSERT_EQUAL(0, result); + memcpy(input_buf, buffer, BUFFER_LEN); + } + + if (strcmp(key, MSG_TRNG_TEST_STEP1) == 0) { + /*Fill buffer with trng values*/ + result = fill_buffer_trng(buffer, &trng_obj, BUFFER_LEN); + TEST_ASSERT_EQUAL(0, result); + memcpy(input_buf, buffer, BUFFER_LEN); + } + /*pithy_Compress will try to compress the random data, if it succeeded it means the data is not really random*/ + else if (strcmp(key, MSG_TRNG_TEST_STEP2) == 0) { + + comp_sz = pithy_Compress((char *)buffer, + BUFFER_LEN, + (char *)out_comp_buf, + OUT_COMP_BUF_SIZE, + 9); + if (comp_sz <= BUFFER_LEN){ + print_array(buffer, BUFFER_LEN); + } + TEST_ASSERT_MESSAGE(comp_sz > BUFFER_LEN, + "TRNG_TEST_STEP1: trng_get_bytes was able to compress thus not random"); + + /*pithy_Compress will try to compress the random data with a different buffer size*/ + result = fill_buffer_trng(temp_buf, &trng_obj, TEMP_BUF_SIZE); + TEST_ASSERT_EQUAL(0, result); + + comp_sz = pithy_Compress((char *)temp_buf, + TEMP_BUF_SIZE, + (char *)out_comp_buf, + OUT_COMP_BUF_SIZE, + 9); + if (comp_sz <= TEMP_BUF_SIZE){ + print_array(temp_buf, TEMP_BUF_SIZE); + } + TEST_ASSERT_MESSAGE(comp_sz > TEMP_BUF_SIZE, + "TRNG_TEST_STEP2: trng_get_bytes was able to compress thus not random"); + + memcpy(input_buf + BUFFER_LEN, temp_buf, TEMP_BUF_SIZE); + /*pithy_Compress will try to compress the random data from before reset concatenated with new random data*/ + comp_sz = pithy_Compress((char *)input_buf, + TEMP_BUF_SIZE + BUFFER_LEN, + (char *)out_comp_buf, + OUT_COMP_BUF_SIZE, + 9); + if (comp_sz <= TEMP_BUF_SIZE + BUFFER_LEN){ + print_array(input_buf, TEMP_BUF_SIZE + BUFFER_LEN); + } + TEST_ASSERT_MESSAGE(comp_sz > TEMP_BUF_SIZE + BUFFER_LEN, + "TRNG_TEST_STEP3: concatenated buffer after reset was able to compress thus not random"); + + greentea_send_kv(MSG_TRNG_TEST_SUITE_ENDED, MSG_VALUE_DUMMY); + } + + /*At the end of step 1 store trng buffer and reset the device*/ + if (strcmp(key, MSG_TRNG_TEST_STEP1) == 0) { + int result = 0; + /*Using base64 to encode data sending from host*/ + result = trng_EncodeBase64(buffer, + BUFFER_LEN, + (char *)out_comp_buf, + OUT_COMP_BUF_SIZE); + TEST_ASSERT_EQUAL(RESULT_SUCCESS, result); + + greentea_send_kv(MSG_TRNG_BUFFER, (const char *)out_comp_buf); + } + + delete[] out_comp_buf; + delete[] buffer; + delete[] input_buf; + delete[] temp_buf; +} + +/*This method call first and second steps, it directs by the key received from the host*/ +void trng_test() +{ + greentea_send_kv(MSG_TRNG_READY, MSG_VALUE_DUMMY); + + char key[MSG_KEY_LEN + 1] = { }; + char *value = new char[MSG_VALUE_LEN + 1]; + do { + memset(key, 0, MSG_KEY_LEN + 1); + memset(value, 0, MSG_VALUE_LEN + 1); + + greentea_parse_kv(key, value, MSG_KEY_LEN, MSG_VALUE_LEN); + + if (strcmp(key, MSG_TRNG_TEST_STEP1) == 0) { + /*create trng data buffer and try to compress it, store it for later checks*/ + compress_and_compare(key, value); + } + + if (strcmp(key, MSG_TRNG_TEST_STEP2) == 0) { + /*create another trng data buffer and concatenate it to the stored trng data buffer + try to compress them both*/ + compress_and_compare(key, value); + } + } while (strcmp(key, MSG_TRNG_EXIT) != 0); + + delete[] value; +} + +Case cases[] = { + Case("TRNG: trng_test", trng_test), +}; + +utest::v1::status_t greentea_test_setup(const size_t number_of_cases) +{ + GREENTEA_SETUP(100, "trng_reset"); + return greentea_test_setup_handler(number_of_cases); +} + +Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); + +int main() +{ + bool ret = !Harness::run(specification); + + return ret; +} diff --git a/TESTS/mbed_hal/trng/pithy/pithy.c b/TESTS/mbed_hal/trng/pithy/pithy.c new file mode 100644 index 0000000000..a17091d85a --- /dev/null +++ b/TESTS/mbed_hal/trng/pithy/pithy.c @@ -0,0 +1,795 @@ +// +// pithy.c +// http://github.com/johnezang/pithy +// Licensed under the terms of the BSD License, as specified below. +// + +/* + Copyright (c) 2011, John Engelhart + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the Zang Industries nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include +#include +#include + +#if defined(__arm__) && defined(__ARM_NEON__) +#include +#endif + +#include "pithy.h" + +#define kBlockLog 20ul +#define kBlockSize ((size_t)(1 << kBlockLog)) + +// The maximum size that can be compressed while still allowing for the worst case compression expansion. +#define PITHY_UNCOMPRESSED_MAX_LENGTH 0xdb6db6bfu // 0xdb6db6bf == 3681400511, or 3510.857 Mbytes. + +typedef const char *pithy_hashOffset_t; + +enum { + PITHY_LITERAL = 0, + PITHY_COPY_1_BYTE_OFFSET = 1, + PITHY_COPY_2_BYTE_OFFSET = 2, + PITHY_COPY_3_BYTE_OFFSET = 3 +}; + + +#if defined (__GNUC__) && (__GNUC__ >= 3) +#define PITHY_ATTRIBUTES(attr, ...) __attribute__((attr, ##__VA_ARGS__)) +#define PITHY_EXPECTED(cond, expect) __builtin_expect((long)(cond), (expect)) +#define PITHY_EXPECT_T(cond) PITHY_EXPECTED(cond, 1u) +#define PITHY_EXPECT_F(cond) PITHY_EXPECTED(cond, 0u) +#define PITHY_PREFETCH(ptr) __builtin_prefetch(ptr) +#else // defined (__GNUC__) && (__GNUC__ >= 3) +#define PITHY_ATTRIBUTES(attr, ...) +#define PITHY_EXPECTED(cond, expect) (cond) +#define PITHY_EXPECT_T(cond) (cond) +#define PITHY_EXPECT_F(cond) (cond) +#define PITHY_PREFETCH(ptr) +#endif // defined (__GNUC__) && (__GNUC__ >= 3) + +#define PITHY_STATIC_INLINE static inline PITHY_ATTRIBUTES(always_inline) +#define PITHY_ALIGNED(x) PITHY_ATTRIBUTES(aligned(x)) + +#if defined(NS_BLOCK_ASSERTIONS) && !defined(NDEBUG) +#define NDEBUG +#endif + +#ifdef NDEBUG +#define DCHECK(condition) +#else +#define DCHECK(condition) do { \ + if(PITHY_EXPECT_F(!(condition))) { \ + fprintf(stderr, "%s / %s @ %ld: Invalid parameter not satisfying: %s", \ + __FILE__, __PRETTY_FUNCTION__, (long)__LINE__, #condition); fflush(stderr); \ + abort(); \ + } \ + } while(0) +#endif + +PITHY_STATIC_INLINE const char *pithy_Parse32WithLimit(const char *p, const char *l, size_t *OUTPUT); +PITHY_STATIC_INLINE char *pithy_Encode32(char *ptr, uint32_t v); + +PITHY_STATIC_INLINE uint32_t pithy_GetUint32AtOffset(uint64_t v, uint32_t offset); +PITHY_STATIC_INLINE uint32_t pithy_HashBytes(uint32_t bytes, uint32_t shift); +PITHY_STATIC_INLINE size_t pithy_FindMatchLength(const char *s1, const char *s2, const char *s2_limit); +PITHY_STATIC_INLINE char *pithy_EmitLiteral(char *op, const char *literal, size_t len, int allow_fast_path); +PITHY_STATIC_INLINE char *pithy_EmitCopyGreaterThan63(char *op, size_t offset, size_t len); +PITHY_STATIC_INLINE char *pithy_EmitCopyLessThan63(char *op, size_t offset, size_t len); +PITHY_STATIC_INLINE char *pithy_EmitCopy(char *op, size_t offset, size_t len); + +PITHY_STATIC_INLINE uint16_t pithy_Load16(const void *p) { uint16_t t; memcpy(&t, p, sizeof(t)); return (t); } +PITHY_STATIC_INLINE uint32_t pithy_Load32(const void *p) { uint32_t t; memcpy(&t, p, sizeof(t)); return (t); } +PITHY_STATIC_INLINE uint64_t pithy_Load64(const void *p) { uint64_t t; memcpy(&t, p, sizeof(t)); return (t); } +PITHY_STATIC_INLINE void pithy_Store16(void *p, uint16_t v) { memcpy(p, &v, sizeof(v)); } +PITHY_STATIC_INLINE void pithy_Store32(void *p, uint32_t v) { memcpy(p, &v, sizeof(v)); } +PITHY_STATIC_INLINE void pithy_Store64(void *p, uint64_t v) { memcpy(p, &v, sizeof(v)); } + +#define pithy_Move64(dst,src) pithy_Store64(dst, pithy_Load64(src)); +#define pithy_Move128(dst,src) pithy_Move64(dst, src); pithy_Move64(dst + 8ul, src + 8ul); + +#ifdef __BIG_ENDIAN__ + +#ifdef _MSC_VER +#include +#define pithy_bswap_16(x) _byteswap_ushort(x) +#define pithy_bswap_32(x) _byteswap_ulong(x) +#define pithy_bswap_64(x) _byteswap_uint64(x) + +#elif defined(__APPLE__) + +// Mac OS X / Darwin features +#include +#define pithy_bswap_16(x) OSSwapInt16(x) +#define pithy_bswap_32(x) OSSwapInt32(x) +#define pithy_bswap_64(x) OSSwapInt64(x) +#else +#include +#endif + +#endif // __BIG_ENDIAN__ + +// Conversion functions. +#ifdef __BIG_ENDIAN__ +#define pithy_FromHost16(x) ((uint16_t)pithy_bswap_16(x)) +#define pithy_ToHost16(x) ((uint16_t)pithy_bswap_16(x)) +#define pithy_FromHost32(x) ((uint32_t)pithy_bswap_32(x)) +#define pithy_ToHost32(x) ((uint32_t)pithy_bswap_32(x)) +#define pithy_IsLittleEndian() (0) + +#else // !defined(__BIG_ENDIAN__) +#define pithy_FromHost16(x) ((uint16_t)(x)) +#define pithy_ToHost16(x) ((uint16_t)(x)) +#define pithy_FromHost32(x) ((uint32_t)(x)) +#define pithy_ToHost32(x) ((uint32_t)(x)) +#define pithy_IsLittleEndian() (1) + +#endif // !defined(__BIG_ENDIAN__) + +#define pithy_LoadHost16(p) pithy_ToHost16(pithy_Load16((const void *)(p))) +#define pithy_StoreHost16(p, v) pithy_Store16((void *)(p), pithy_FromHost16(v)) +#define pithy_LoadHost32(p) pithy_ToHost32(pithy_Load32((p))) +#define pithy_StoreHost32(p, v) pithy_Store32((p), pithy_FromHost32(v)) + +PITHY_STATIC_INLINE void pithy_StoreHost24(char *p, uint32_t v) +{ + *p++ = (v & 0xffu); + *p++ = ((v >> 8) & 0xffu); + *p++ = ((v >> 16) & 0xffu); +} + +#if defined (__GNUC__) && (__GNUC__ >= 3) + +#define pithy_Log2Floor(n) ({typeof(n) _n = (n); _n == 0 ? (int)-1 : (int)(31 ^ __builtin_clz(_n));}) +#define pithy_FindLSBSetNonZero32(n) ((int)__builtin_ctz((uint32_t)(n))) +#define pithy_FindLSBSetNonZero64(n) ((int)__builtin_ctzll((uint64_t)(n))) +#define pithy_FindMSBSetNonZero32(n) ((int)__builtin_clz((uint32_t)(n))) +#define pithy_FindMSBSetNonZero64(n) ((int)__builtin_clzll((uint64_t)(n))) + +#else // Portable versions, !GNUC || GNUC < 3 + +PITHY_STATIC_INLINE int pithy_Log2Floor(uint32_t n) +{ + if (n == 0u) { + return (-1); + } + int i = 0, log = 0; + uint32_t value = n; + for (i = 4; i >= 0; --i) { + int shift = (1 << i); + uint32_t x = value >> shift; + if (x != 0u) { + value = x; + log += shift; + } + } + DCHECK(value == 1); + return (log); +} + +PITHY_STATIC_INLINE int pithy_FindLSBSetNonZero32(uint32_t n) +{ + int i = 0, rc = 31, shift = 0; + for (i = 4, shift = 1 << 4; i >= 0; --i) { + const uint32_t x = n << shift; + if (x != 0u) { + n = x; + rc -= shift; + } + shift >>= 1; + } + return (rc); +} + +PITHY_STATIC_INLINE int pithy_FindLSBSetNonZero64(uint64_t n) +{ + const uint32_t bottomBits = n; + if (bottomBits == 0u) { + return (32 + pithy_FindLSBSetNonZero32((n >> 32))); + } else { + return (pithy_FindLSBSetNonZero32(bottomBits)); + } +} + +PITHY_STATIC_INLINE int pithy_FindMSBSetNonZero32(uint32_t n) +{ + int i; + uint32_t x, rc = 32, shift = 1 << 4; + for (i = 3; i >= 0; --i) { + x = n >> shift; + if (x != 0) { + rc -= shift; + n = x; + } + shift >>= 1; + } + x = n >> shift; + return (rc - ((x != 0) ? 2 : n)); +} + +PITHY_STATIC_INLINE int pithy_FindMSBSetNonZero64(uint64_t n) +{ + const uint32_t upperBits = n >> 32; + if (upperBits == 0u) { + return (32 + pithy_FindMSBSetNonZero32((n))); + } else { + return (pithy_FindMSBSetNonZero32(upperBits)); + } +} + +#endif // End portable versions. + +PITHY_STATIC_INLINE const char *pithy_Parse32WithLimit(const char *p, const char *l, size_t *resultOut) +{ + const unsigned char *ptr = (const unsigned char *)p, *limit = (const unsigned char *)l; + size_t resultShift = 0ul, result = 0ul; + uint32_t encodedByte = 0u; + + for (resultShift = 0ul; resultShift <= 28ul; resultShift += 7ul) { + if (ptr >= limit) { + return (NULL); + } + encodedByte = *(ptr++); + result |= (encodedByte & 127u) << resultShift; + if (encodedByte < ((resultShift == 28ul) ? 16u : 128u)) { + goto done; + } + } + return (NULL); +done: + *resultOut = result; + return ((const char *)ptr); +} + +PITHY_STATIC_INLINE char *pithy_Encode32(char *sptr, uint32_t v) +{ + unsigned char *ptr = (unsigned char *)sptr; + if (v < (1u << 7)) { + *(ptr++) = v; + } else if (v < (1u << 14)) { + *(ptr++) = v | 0x80u; + *(ptr++) = (v >> 7); + } else if (v < (1u << 21)) { + *(ptr++) = v | 0x80u; + *(ptr++) = (v >> 7) | 0x80u; + *(ptr++) = (v >> 14); + } else if (v < (1u << 28)) { + *(ptr++) = v | 0x80u; + *(ptr++) = (v >> 7) | 0x80u; + *(ptr++) = (v >> 14) | 0x80u; + *(ptr++) = (v >> 21); + } else { + *(ptr++) = v | 0x80u; + *(ptr++) = (v >> 7) | 0x80u; + *(ptr++) = (v >> 14) | 0x80u; + *(ptr++) = (v >> 21) | 0x80u; + *(ptr++) = (v >> 28); + } + return ((char *)ptr); +} + + +PITHY_STATIC_INLINE uint32_t pithy_GetUint32AtOffset(uint64_t v, uint32_t offset) +{ + DCHECK(offset <= 4); + return (v >> (pithy_IsLittleEndian() ? (8u * offset) : (32u - (8u * offset)))); +} + + +PITHY_STATIC_INLINE uint32_t pithy_HashBytes(uint32_t bytes, uint32_t shift) +{ + uint32_t kMul = 0x1e35a7bdU; + return ((bytes * kMul) >> shift); +} + + +PITHY_STATIC_INLINE size_t pithy_FindMatchLength(const char *s1, const char *s2, const char *s2_limit) +{ + DCHECK(s2_limit >= s2); + const char *ms1 = s1, *ms2 = s2; + +#if defined(__LP64__) + while (PITHY_EXPECT_T(ms2 < (s2_limit - 8ul))) { + uint64_t x = pithy_Load64(ms1) ^ pithy_Load64(ms2); + if (PITHY_EXPECT_F(x == 0ul)) { + ms1 += 8ul; + ms2 += 8ul; + } else { + return ((ms1 - s1) + ((unsigned int)(pithy_IsLittleEndian() ? (pithy_FindLSBSetNonZero64(x) >> 3) : + (pithy_FindMSBSetNonZero64(x) >> 3)))); + } + } +#else + while (PITHY_EXPECT_T(ms2 < (s2_limit - 4u ))) { + uint32_t x = pithy_Load32(ms1) ^ pithy_Load32(ms2); + if (PITHY_EXPECT_F(x == 0u)) { + ms1 += 4u; + ms2 += 4u; + } else { + return ((ms1 - s1) + ((unsigned int)(pithy_IsLittleEndian() ? + (pithy_FindLSBSetNonZero32(x) >> 3) : (pithy_FindMSBSetNonZero32(x) >> 3)))); + } + } +#endif + while (PITHY_EXPECT_T(ms2 < s2_limit)) { + if (PITHY_EXPECT_T(*ms1 == *ms2)) { + ms1++; + ms2++; + } else { + return (ms1 - s1); + } + } + return (ms1 - s1); +} + + +PITHY_STATIC_INLINE char *pithy_EmitLiteral(char *op, const char *literal, size_t len, int allow_fast_path) +{ + int n = len - 1l; + if (PITHY_EXPECT_T(n < 60l)) { + *op++ = PITHY_LITERAL | (n << 2); + if (PITHY_EXPECT_T(allow_fast_path) && PITHY_EXPECT_T(len <= 16ul)) { + pithy_Move128(op, literal); + return (op + len); + } + } else { + char *base = op; + int count = 0; + op++; + while (n > 0l) { + *op++ = n & 0xff; + n >>= 8; + count++; + } + DCHECK((count >= 1) && (count <= 4)); + *base = PITHY_LITERAL | ((59 + count) << 2); + } + memcpy(op, literal, len); + return (op + len); +} + +PITHY_STATIC_INLINE char *pithy_EmitCopyGreaterThan63(char *op, size_t offset, size_t len) +{ + DCHECK((len < 65536ul) && (len >= 63ul) && (offset < kBlockSize)); + if (PITHY_EXPECT_T(offset < 65536ul)) { + if (PITHY_EXPECT_T(len < (256ul + 63ul))) { + *op++ = PITHY_COPY_2_BYTE_OFFSET | (62 << 2); + pithy_StoreHost16(op, offset); + op += 2ul; + *op++ = (len - 63ul); + } else { + *op++ = PITHY_COPY_2_BYTE_OFFSET | (63 << 2); + pithy_StoreHost16(op, offset); + op += 2ul; + pithy_StoreHost16(op, len); + op += 2ul; + } + } else { + if (PITHY_EXPECT_T(len < (256ul + 63ul))) { + *op++ = PITHY_COPY_3_BYTE_OFFSET | (62 << 2); + pithy_StoreHost24(op, offset); + op += 3ul; + *op++ = (len - 63ul); + } else { + *op++ = PITHY_COPY_3_BYTE_OFFSET | (63 << 2); + pithy_StoreHost24(op, offset); + op += 3ul; + pithy_StoreHost16(op, len); + op += 2ul; + } + } + return (op); +} + +PITHY_STATIC_INLINE char *pithy_EmitCopyLessThan63(char *op, size_t offset, size_t len) +{ + DCHECK((len < 63ul) && (len >= 4ul) && (offset < kBlockSize)); + if (PITHY_EXPECT_T(len < 12ul) && PITHY_EXPECT_T(offset < 2048ul)) { + int lenMinus4 = len - 4l; + DCHECK(lenMinus4 < 8l); + *op++ = PITHY_COPY_1_BYTE_OFFSET | (lenMinus4 << 2) | ((offset >> 8) << 5); + *op++ = offset & 0xff; + } else { + if (PITHY_EXPECT_T(offset < 65536ul)) { + *op++ = PITHY_COPY_2_BYTE_OFFSET | ((len - 1ul) << 2); + pithy_StoreHost16(op, offset); + op += 2ul; + } else { + *op++ = PITHY_COPY_3_BYTE_OFFSET | ((len - 1ul) << 2); + pithy_StoreHost24(op, offset); + op += 3ul; + } + } + return (op); +} + +PITHY_STATIC_INLINE char *pithy_EmitCopy(char *op, size_t offset, size_t len) +{ + while (PITHY_EXPECT_F(len >= 63ul)) { + op = pithy_EmitCopyGreaterThan63(op, offset, (len >= 65539ul) ? 65535ul : len); + len -= (len >= 65539ul) ? 65535ul : len; + } + DCHECK((len > 0ul) ? ((len >= 4ul) && (len < 63ul)) : 1); + if ( PITHY_EXPECT_T(len > 0ul)) { + op = pithy_EmitCopyLessThan63(op, offset, len); + len -= len; + } + return (op); +} + +size_t pithy_MaxCompressedLength(size_t inputLength) +{ + return ((inputLength >= PITHY_UNCOMPRESSED_MAX_LENGTH) ? 0ul : 32ul + inputLength + (inputLength / 6ul)); +} + +size_t pithy_Compress(const char *uncompressed, + size_t uncompressedLength, + char *compressedOut, + size_t compressedOutLength, + int compressionLevel) +{ + + if ((pithy_MaxCompressedLength(uncompressedLength) > compressedOutLength) || + (uncompressedLength >= PITHY_UNCOMPRESSED_MAX_LENGTH) || + (uncompressedLength == 0ul)) { + return (0ul); + } + + char *compressedPtr = compressedOut; + + size_t hashTableSize = 0x100ul, maxHashTableSize = 1 << (12ul + (((compressionLevel < 0) ? 0 : + (compressionLevel > 9) ? 9 : compressionLevel) / 2ul)); + while ((hashTableSize < maxHashTableSize) && (hashTableSize < uncompressedLength)) { + hashTableSize <<= 1; + } + pithy_hashOffset_t stackHashTable[hashTableSize], *heapHashTable = NULL, *hashTable = stackHashTable; + if ((sizeof(pithy_hashOffset_t) * hashTableSize) >= (1024ul * 128ul)) { + if ((heapHashTable = malloc(sizeof(pithy_hashOffset_t) * hashTableSize)) == NULL) { + return (0ul); + } + hashTable = heapHashTable; + } + size_t x = 0ul; + for (x = 0ul; x < hashTableSize; x++) { + hashTable[x] = uncompressed; + } + +#ifndef NDEBUG + char *const compressedOutEnd = compressedOut + compressedOutLength; +#endif + compressedPtr = pithy_Encode32(compressedPtr, uncompressedLength); + DCHECK(compressedPtr <= compressedOutEnd); + { + const char *uncompressedPtr = uncompressed; + const char *uncompressedEnd = uncompressed + uncompressedLength; + const char *nextEmitUncompressedPtr = uncompressedPtr; + DCHECK((hashTableSize & (hashTableSize - 1l)) == 0); + const int shift = 32 - pithy_Log2Floor(hashTableSize); + DCHECK((UINT32_MAX >> shift) == (hashTableSize - 1l)); + size_t skip = 32ul; + + if (PITHY_EXPECT_T(uncompressedLength >= 15ul)) { + const char *uncompressedEndLimit = uncompressed + uncompressedLength - 15ul; + uint32_t uncompressedBytes; + uint32_t nextUncompressedBytes = pithy_Load32(++uncompressedPtr); + uint32_t nextUncompressedBytesHash = pithy_HashBytes(nextUncompressedBytes, shift); + + while (1) { + DCHECK(nextEmitUncompressedPtr < uncompressedPtr); + const char *nextUncompressedPtr = uncompressedPtr, *matchCandidatePtr = NULL; + + skip = (((skip - 32ul) * 184ul) >> 8) + 32ul; + + do { + uncompressedPtr = nextUncompressedPtr; + uncompressedBytes = nextUncompressedBytes; + uint32_t uncompressedBytesHash = nextUncompressedBytesHash; + DCHECK(uncompressedBytesHash == pithy_HashBytes(uncompressedBytes, shift)); + size_t skipBytesBetweenHashLookups = skip >> 5; + skip += ((skip * 7ul) >> 11) + 1ul; + nextUncompressedPtr = uncompressedPtr + skipBytesBetweenHashLookups; + if (PITHY_EXPECT_F(nextUncompressedPtr > uncompressedEndLimit)) { + goto emit_remainder; + } + nextUncompressedBytes = pithy_Load32(nextUncompressedPtr); + nextUncompressedBytesHash = pithy_HashBytes(nextUncompressedBytes, shift); + matchCandidatePtr = hashTable[uncompressedBytesHash]; + DCHECK((matchCandidatePtr >= uncompressed) && (matchCandidatePtr < uncompressedPtr)); + hashTable[uncompressedBytesHash] = uncompressedPtr; + } while ((PITHY_EXPECT_T(uncompressedBytes != pithy_Load32(matchCandidatePtr))) || + PITHY_EXPECT_F((uncompressedPtr - matchCandidatePtr) >= ((int)(kBlockSize - 2ul)))); + + DCHECK((nextEmitUncompressedPtr + 16ul) <= uncompressedEnd); + compressedPtr = pithy_EmitLiteral(compressedPtr, + nextEmitUncompressedPtr, + uncompressedPtr - nextEmitUncompressedPtr, + 1); + DCHECK(compressedPtr <= compressedOutEnd); + uint64_t uncompressedBytes64 = 0ul; + + do { + if (compressionLevel > 2) { + DCHECK((uncompressedPtr + 5ul) <= uncompressedEnd); + uncompressedBytes64 = pithy_Load64((uint64_t*)uncompressedPtr + 1ul); + hashTable[pithy_HashBytes(pithy_GetUint32AtOffset(uncompressedBytes64, 0u), shift)] = + uncompressedPtr + 1ul; + if (compressionLevel > 4) { + hashTable[pithy_HashBytes(pithy_GetUint32AtOffset(uncompressedBytes64, 1u), shift)] = + uncompressedPtr + 2ul; + } + } + + DCHECK((matchCandidatePtr >= uncompressed) && + (matchCandidatePtr <= uncompressedPtr) && + ((matchCandidatePtr + 4ul) <= uncompressedEnd) && + ((uncompressedPtr + 4ul) <= uncompressedEnd)); + + size_t matchCandidateLength = 4ul + pithy_FindMatchLength(matchCandidatePtr + 4ul, + uncompressedPtr + 4ul, + uncompressedEnd); + DCHECK(((matchCandidatePtr + matchCandidateLength) >= uncompressed) && + ((matchCandidatePtr + matchCandidateLength) <= uncompressedEnd)); + DCHECK(0 == memcmp(uncompressedPtr, matchCandidatePtr, matchCandidateLength)); + compressedPtr = pithy_EmitCopy(compressedPtr, + uncompressedPtr - matchCandidatePtr, + matchCandidateLength); + DCHECK(compressedPtr <= compressedOutEnd); + uncompressedPtr += matchCandidateLength; + DCHECK(uncompressedPtr <= uncompressedEnd); + nextEmitUncompressedPtr = uncompressedPtr; + if (PITHY_EXPECT_F(uncompressedPtr >= uncompressedEndLimit)) { + goto emit_remainder; + } + + DCHECK(((uncompressedPtr - 3ul) >= uncompressed) && (uncompressedPtr <= uncompressedEnd)); + + uncompressedBytes64 = pithy_Load64((uint64_t*)uncompressedPtr - 3ul); + + if (compressionLevel > 0) { + if (compressionLevel > 8) { + hashTable[pithy_HashBytes(pithy_GetUint32AtOffset(uncompressedBytes64, 0u), shift)] = + uncompressedPtr - 3ul; + } + if (compressionLevel > 6) { + hashTable[pithy_HashBytes(pithy_GetUint32AtOffset(uncompressedBytes64, 1u), shift)] = + uncompressedPtr - 2ul; + } + hashTable[pithy_HashBytes(pithy_GetUint32AtOffset(uncompressedBytes64, 2u), shift)] = + uncompressedPtr - 1ul; + } + + uncompressedBytes = pithy_GetUint32AtOffset(uncompressedBytes64, 3u); + uint32_t uncompressedBytesHash = pithy_HashBytes(uncompressedBytes, shift); + matchCandidatePtr = hashTable[uncompressedBytesHash]; + DCHECK((matchCandidatePtr >= uncompressed) && (matchCandidatePtr < uncompressedPtr)); + hashTable[uncompressedBytesHash] = uncompressedPtr; + } while (PITHY_EXPECT_F(uncompressedBytes == pithy_Load32(matchCandidatePtr)) && + PITHY_EXPECT_T((uncompressedPtr - matchCandidatePtr) < ((int)(kBlockSize - 2ul)))); + + nextUncompressedBytes = pithy_GetUint32AtOffset(uncompressedBytes64, 4u); + nextUncompressedBytesHash = pithy_HashBytes(nextUncompressedBytes, shift); + uncompressedPtr++; + } + } + +emit_remainder: + if (nextEmitUncompressedPtr < uncompressedEnd) { + compressedPtr = pithy_EmitLiteral(compressedPtr, + nextEmitUncompressedPtr, + uncompressedEnd - nextEmitUncompressedPtr, + 0); + } + } + + pithy_Store32(compressedPtr, 0); + compressedPtr += 4; + + DCHECK((size_t)(compressedPtr - compressedOut) <= compressedOutLength); + if (heapHashTable != NULL) { + free(heapHashTable); + heapHashTable = NULL; + hashTable = NULL; + } + return (compressedPtr - compressedOut); +} + + +static const uint32_t pithy_wordmask[] = { + 0u, 0xffu, 0xffffu, 0xffffffu, 0xffffffffu +}; + + +static const uint16_t pithy_charTable[256] = { + 0x0001, 0x0804, 0x1001, 0x1801, 0x0002, 0x0805, 0x1002, 0x1802, + 0x0003, 0x0806, 0x1003, 0x1803, 0x0004, 0x0807, 0x1004, 0x1804, + 0x0005, 0x0808, 0x1005, 0x1805, 0x0006, 0x0809, 0x1006, 0x1806, + 0x0007, 0x080a, 0x1007, 0x1807, 0x0008, 0x080b, 0x1008, 0x1808, + 0x0009, 0x0904, 0x1009, 0x1809, 0x000a, 0x0905, 0x100a, 0x180a, + 0x000b, 0x0906, 0x100b, 0x180b, 0x000c, 0x0907, 0x100c, 0x180c, + 0x000d, 0x0908, 0x100d, 0x180d, 0x000e, 0x0909, 0x100e, 0x180e, + 0x000f, 0x090a, 0x100f, 0x180f, 0x0010, 0x090b, 0x1010, 0x1810, + 0x0011, 0x0a04, 0x1011, 0x1811, 0x0012, 0x0a05, 0x1012, 0x1812, + 0x0013, 0x0a06, 0x1013, 0x1813, 0x0014, 0x0a07, 0x1014, 0x1814, + 0x0015, 0x0a08, 0x1015, 0x1815, 0x0016, 0x0a09, 0x1016, 0x1816, + 0x0017, 0x0a0a, 0x1017, 0x1817, 0x0018, 0x0a0b, 0x1018, 0x1818, + 0x0019, 0x0b04, 0x1019, 0x1819, 0x001a, 0x0b05, 0x101a, 0x181a, + 0x001b, 0x0b06, 0x101b, 0x181b, 0x001c, 0x0b07, 0x101c, 0x181c, + 0x001d, 0x0b08, 0x101d, 0x181d, 0x001e, 0x0b09, 0x101e, 0x181e, + 0x001f, 0x0b0a, 0x101f, 0x181f, 0x0020, 0x0b0b, 0x1020, 0x1820, + 0x0021, 0x0c04, 0x1021, 0x1821, 0x0022, 0x0c05, 0x1022, 0x1822, + 0x0023, 0x0c06, 0x1023, 0x1823, 0x0024, 0x0c07, 0x1024, 0x1824, + 0x0025, 0x0c08, 0x1025, 0x1825, 0x0026, 0x0c09, 0x1026, 0x1826, + 0x0027, 0x0c0a, 0x1027, 0x1827, 0x0028, 0x0c0b, 0x1028, 0x1828, + 0x0029, 0x0d04, 0x1029, 0x1829, 0x002a, 0x0d05, 0x102a, 0x182a, + 0x002b, 0x0d06, 0x102b, 0x182b, 0x002c, 0x0d07, 0x102c, 0x182c, + 0x002d, 0x0d08, 0x102d, 0x182d, 0x002e, 0x0d09, 0x102e, 0x182e, + 0x002f, 0x0d0a, 0x102f, 0x182f, 0x0030, 0x0d0b, 0x1030, 0x1830, + 0x0031, 0x0e04, 0x1031, 0x1831, 0x0032, 0x0e05, 0x1032, 0x1832, + 0x0033, 0x0e06, 0x1033, 0x1833, 0x0034, 0x0e07, 0x1034, 0x1834, + 0x0035, 0x0e08, 0x1035, 0x1835, 0x0036, 0x0e09, 0x1036, 0x1836, + 0x0037, 0x0e0a, 0x1037, 0x1837, 0x0038, 0x0e0b, 0x1038, 0x1838, + 0x0039, 0x0f04, 0x1039, 0x1839, 0x003a, 0x0f05, 0x103a, 0x183a, + 0x003b, 0x0f06, 0x103b, 0x183b, 0x003c, 0x0f07, 0x103c, 0x183c, + 0x0801, 0x0f08, 0x103d, 0x183d, 0x1001, 0x0f09, 0x103e, 0x183e, + 0x1801, 0x0f0a, 0x103f, 0x183f, 0x2001, 0x0f0b, 0x1040, 0x1840 +}; + + +int pithy_GetDecompressedLength(const char *compressed, size_t compressedLength, size_t *decompressedOutLengthResult) +{ + const char *compressedEnd = compressed + compressedLength; + size_t decompressedLength = 0ul; + if (pithy_Parse32WithLimit(compressed, compressedEnd, &decompressedLength) != NULL) { + *decompressedOutLengthResult = decompressedLength; + return (1); + } else { + return (0); + } +} + + +int pithy_Decompress(const char *compressed, size_t compressedLength, char *decompressedOut, + size_t decompressedOutLength) +{ + const char *nextCompressedPtr = NULL, *compressedEnd = (compressed + compressedLength); + size_t parsedDecompressedLength = 0ul; + if (((nextCompressedPtr = pithy_Parse32WithLimit(compressed, compressedEnd, &parsedDecompressedLength)) == NULL) || + (parsedDecompressedLength > decompressedOutLength)) { + return (0); + } + + char *decompressedPtr = decompressedOut, *decompressedEnd = decompressedOut + parsedDecompressedLength; + + while (1) { + const char *compressedPtr = nextCompressedPtr; + DCHECK(compressedPtr <= compressedEnd); + if (PITHY_EXPECT_F(compressedPtr >= compressedEnd)) { + break; + } + + const unsigned char c = *((const unsigned char *)(compressedPtr++)); + const unsigned char cLowerBits = (c & 0x3u); + const int spaceLeft = (decompressedEnd - decompressedPtr); + + if ((cLowerBits == PITHY_LITERAL)) { + size_t literalLength = (c >> 2) + 1; + if (PITHY_EXPECT_T(literalLength <= 16ul) && PITHY_EXPECT_T((compressedEnd - compressedPtr) >= 16l) && + PITHY_EXPECT_T(spaceLeft >= 16l)) { + pithy_Move128(decompressedPtr, compressedPtr); + } else { + if (PITHY_EXPECT_F(literalLength > 60)) { + if (PITHY_EXPECT_F((compressedPtr + 4) > compressedEnd)) { + break; + } + size_t literalLengthBytes = literalLength - 60; + literalLength = (pithy_LoadHost32(compressedPtr) & pithy_wordmask[literalLengthBytes]) + 1; + compressedPtr += literalLengthBytes; + } + if (PITHY_EXPECT_F(spaceLeft < (int)literalLength) || + PITHY_EXPECT_F((compressedPtr + literalLength) > compressedEnd)) { + break; + } + memcpy(decompressedPtr, compressedPtr, literalLength); + } + nextCompressedPtr = compressedPtr + literalLength; + decompressedPtr += literalLength; + } else { + const uint32_t entry = pithy_charTable[c]; + const size_t trailer = pithy_LoadHost32(compressedPtr) & pithy_wordmask[cLowerBits]; + size_t length = entry & 0xffu; + const size_t copyOffset = ((entry & 0x700u) + trailer); + + compressedPtr += cLowerBits; + + DCHECK((compressedPtr <= compressedEnd) && (copyOffset > 0ul) && (spaceLeft > 0l) && (length > 0ul)); + + if (PITHY_EXPECT_F((decompressedPtr - decompressedOut) <= ((int)copyOffset - 1l))) { + break; + } + if (PITHY_EXPECT_T(length <= 16ul) && + PITHY_EXPECT_T(copyOffset >= 16ul) && + PITHY_EXPECT_T(spaceLeft >= 16l)) { + pithy_Move128(decompressedPtr, decompressedPtr - copyOffset); + } else { + if (PITHY_EXPECT_F(length >= 63ul)) { + if (PITHY_EXPECT_T(length == 63ul)) { + if (PITHY_EXPECT_F((compressedPtr + 1) > compressedEnd)) { + break; + } + length = (*((unsigned char *)compressedPtr++)) + 63ul; + } else { + if (PITHY_EXPECT_F((compressedPtr + 2) > compressedEnd)) { + break; + } + length = pithy_LoadHost16(compressedPtr); + compressedPtr += 2ul; + } + } + + char *copyFrom = decompressedPtr - copyOffset, *copyTo = decompressedPtr; + int copyLength = (int)length; + + if (PITHY_EXPECT_F(copyLength > 256l) && PITHY_EXPECT_T(copyOffset > (size_t)copyLength)) { + if (PITHY_EXPECT_F(spaceLeft < copyLength)) { + break; + } + memcpy(copyTo, copyFrom, copyLength); + } else { + if (PITHY_EXPECT_T(spaceLeft >= (copyLength + 24)) && PITHY_EXPECT_T(copyLength > 0l)) { + while ((copyTo - copyFrom) < 16l) { + pithy_Move128(copyTo, copyFrom); + copyLength -= copyTo - copyFrom; + copyTo += copyTo - copyFrom; + } + while (copyLength > 0l) { + pithy_Move128(copyTo, copyFrom); + copyFrom += 16l; + copyTo += 16l; + copyLength -= 16l; + } + } else { + if (PITHY_EXPECT_F(spaceLeft < copyLength) || PITHY_EXPECT_F(copyLength <= 0l)) { + break; + } + do { + *copyTo++ = *copyFrom++; + } while (--copyLength > 0l); + } + } + } + nextCompressedPtr = compressedPtr; + decompressedPtr += length; + } + } + + return (decompressedPtr == decompressedEnd); +} diff --git a/TESTS/mbed_hal/trng/pithy/pithy.h b/TESTS/mbed_hal/trng/pithy/pithy.h new file mode 100644 index 0000000000..57fff97088 --- /dev/null +++ b/TESTS/mbed_hal/trng/pithy/pithy.h @@ -0,0 +1,63 @@ +// +// pithy.h +// http://github.com/johnezang/pithy +// Licensed under the terms of the BSD License, as specified below. +// + +/* + Copyright (c) 2011, John Engelhart + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the Zang Industries nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef _PITHY_H_ +#define _PITHY_H_ + +// compressionLevel >= 0 && compressionLevel <= 9. Values out side this range will be clamped to this range. +size_t pithy_Compress (const char *uncompressed, size_t uncompressedLength, char *compressedOut, + size_t compressedOutLength, int compressionLevel); +int pithy_Decompress(const char *compressed, size_t compressedLength, char *decompressedOut, + size_t decompressedOutLength); + +size_t pithy_MaxCompressedLength(size_t inputLength); +int pithy_GetDecompressedLength(const char *compressed, size_t compressedLength, + size_t *decompressedOutLengthResult); + +#endif // _PITHY_H_ + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/TESTS/mbed_platform/stats_heap/main.cpp b/TESTS/mbed_platform/stats_heap/main.cpp index 2d7d6b27e9..837b240362 100644 --- a/TESTS/mbed_platform/stats_heap/main.cpp +++ b/TESTS/mbed_platform/stats_heap/main.cpp @@ -66,11 +66,13 @@ void test_case_malloc_free_size() TEST_ASSERT_EQUAL_UINT32(stats_start.total_size + ALLOCATION_SIZE_DEFAULT * (i + 1), stats_current.total_size); TEST_ASSERT_EQUAL_UINT32(stats_start.alloc_cnt + 1, stats_current.alloc_cnt); TEST_ASSERT_EQUAL_UINT32(stats_start.alloc_fail_cnt, stats_current.alloc_fail_cnt); - + // Library header 0x4-0x8, stats header 0x8 and alignment addition 0x4 + TEST_ASSERT_INT_WITHIN(0x8, stats_start.overhead_size + 0xC , stats_current.overhead_size); // Free memory and assert back to starting size free(data); mbed_stats_heap_get(&stats_current); TEST_ASSERT_EQUAL_UINT32(stats_start.current_size, stats_current.current_size); + TEST_ASSERT_EQUAL_UINT32(stats_start.overhead_size, stats_current.overhead_size); TEST_ASSERT_EQUAL_UINT32(stats_start.alloc_cnt, stats_current.alloc_cnt); TEST_ASSERT_EQUAL_UINT32(stats_start.alloc_fail_cnt, stats_current.alloc_fail_cnt); } @@ -93,10 +95,14 @@ void test_case_allocate_zero() TEST_ASSERT_EQUAL_UINT32(stats_start.current_size, stats_current.current_size); TEST_ASSERT_EQUAL_UINT32(stats_start.total_size, stats_current.total_size); TEST_ASSERT_EQUAL_UINT32(stats_start.alloc_fail_cnt, stats_current.alloc_fail_cnt); - + // Library header 0x4-0x8, stats header 0x8 and alignment addition 0x4 + if (NULL != data) { + TEST_ASSERT_INT_WITHIN(0x8, stats_start.overhead_size + 0xC , stats_current.overhead_size); + } // Free memory and assert back to starting size free(data); mbed_stats_heap_get(&stats_current); + TEST_ASSERT_EQUAL_UINT32(stats_start.overhead_size, stats_current.overhead_size); TEST_ASSERT_EQUAL_UINT32(stats_start.current_size, stats_current.current_size); TEST_ASSERT_EQUAL_UINT32(stats_start.alloc_cnt, stats_current.alloc_cnt); TEST_ASSERT_EQUAL_UINT32(stats_start.alloc_fail_cnt, stats_current.alloc_fail_cnt); @@ -121,6 +127,7 @@ void test_case_allocate_fail() TEST_ASSERT_EQUAL_UINT32(stats_start.total_size, stats_current.total_size); TEST_ASSERT_EQUAL_UINT32(stats_start.alloc_cnt, stats_current.alloc_cnt); TEST_ASSERT_EQUAL_UINT32(stats_start.alloc_fail_cnt + i + 1, stats_current.alloc_fail_cnt); + TEST_ASSERT_EQUAL_UINT32(stats_start.overhead_size, stats_current.overhead_size); } } diff --git a/TESTS/mbed_platform/system_reset/main.cpp b/TESTS/mbed_platform/system_reset/main.cpp index 637735e472..e611ebf0eb 100644 --- a/TESTS/mbed_platform/system_reset/main.cpp +++ b/TESTS/mbed_platform/system_reset/main.cpp @@ -43,9 +43,9 @@ void test_system_reset() int main(void) { - GREENTEA_SETUP(2, "system_reset"); + GREENTEA_SETUP(30, "system_reset"); test_system_reset(); GREENTEA_TESTSUITE_RESULT(0); // Fail on any error. return 0; -} \ No newline at end of file +} diff --git a/TESTS/mbedtls/multi/main.cpp b/TESTS/mbedtls/multi/main.cpp index e84ad489ef..76d5ff1b8f 100644 --- a/TESTS/mbedtls/multi/main.cpp +++ b/TESTS/mbedtls/multi/main.cpp @@ -188,15 +188,14 @@ int main() { int ret = 0; #if defined(MBEDTLS_PLATFORM_C) - mbedtls_platform_context platform_ctx; - if ((ret = mbedtls_platform_setup(&platform_ctx)) != 0) { + if ((ret = mbedtls_platform_setup(NULL)) != 0) { mbedtls_printf("Mbed TLS multitest failed! mbedtls_platform_setup returned %d\n", ret); return 1; } #endif ret = (Harness::run(specification) ? 0 : 1); #if defined(MBEDTLS_PLATFORM_C) - mbedtls_platform_teardown(&platform_ctx); + mbedtls_platform_teardown(NULL); #endif return ret; } diff --git a/TESTS/mbedtls/selftest/main.cpp b/TESTS/mbedtls/selftest/main.cpp index f2ef3582c2..3704f65123 100644 --- a/TESTS/mbedtls/selftest/main.cpp +++ b/TESTS/mbedtls/selftest/main.cpp @@ -96,15 +96,14 @@ int main() { int ret = 0; #if defined(MBEDTLS_PLATFORM_C) - mbedtls_platform_context platform_ctx; - if ((ret = mbedtls_platform_setup(&platform_ctx)) != 0) { + if ((ret = mbedtls_platform_setup(NULL)) != 0) { mbedtls_printf("Mbed TLS selftest failed! mbedtls_platform_setup returned %d\n", ret); return 1; } #endif ret = (Harness::run(specification) ? 0 : 1); #if defined(MBEDTLS_PLATFORM_C) - mbedtls_platform_teardown(&platform_ctx); + mbedtls_platform_teardown(NULL); #endif return ret; } diff --git a/TESTS/netsocket/README.md b/TESTS/netsocket/README.md index 7922826ac7..689c711495 100644 --- a/TESTS/netsocket/README.md +++ b/TESTS/netsocket/README.md @@ -234,6 +234,16 @@ content at minimum: ``` { + "config": { + "echo-server-addr" : { + "help" : "IP address of echo server", + "value" : "\"echo.mbedcloudtesting.com\"" + }, + "echo-server-port" : { + "help" : "Port of echo server", + "value" : "7" + } + }, "macros": ["MBED_EXTENDED_TESTS"] } ``` @@ -257,7 +267,7 @@ the `mbed_app.json` might look like this: "value": "\"password\"" }, "wifi-secure-protocol": { - "help": "WiFi security protocol, valid values are WEP, WPA, WPA2, WPA/WPA2", + "help": "WiFi security protocol, valid values are WEP, WPA, WPA2, WPA_WPA2", "value": "\"WPA2\"" }, "wifi-ch-secure": { @@ -280,17 +290,6 @@ the `mbed_app.json` might look like this: "help": "How many networks may appear in Wifi scan result", "value": 30 }, - "header-file": { - "help" : "String for including your driver header file", - "value" : "\"MyWifiInterface.h\"" - }, - "object-construction" : { - "value" : "new MyWifiInterface()" - }, - "connect-statement" : { - "help" : "Must use 'net' variable name", - "value" : "net->wifiInterface()->connect(MBED_CONF_APP_WIFI_SECURE_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2)" - }, "echo-server-addr" : { "help" : "IP address of echo server", "value" : "\"echo.mbedcloudtesting.com\"" @@ -300,9 +299,18 @@ the `mbed_app.json` might look like this: "value" : "7" } }, - "macros": ["MBED_EXTENDED_TESTS"] + "macros": ["MBED_EXTENDED_TESTS"], + "target_overrides": { + "*": { + "target.network-default-interface-type": "WIFI", + "nsapi.default-wifi-ssid": "\"WIFI_SSID\"", + "nsapi.default-wifi-password": "\"WIFI_PASSWORD\"", + "nsapi.default-wifi-security": "WPA_WPA2" + } + } } ``` +See `mbed-os/tools/test_configs` folder for examples. Now build test binaries: diff --git a/TESTS/netsocket/dns/main.cpp b/TESTS/netsocket/dns/main.cpp index 70f70c20c1..e8ae973532 100644 --- a/TESTS/netsocket/dns/main.cpp +++ b/TESTS/netsocket/dns/main.cpp @@ -178,9 +178,6 @@ Case cases[] = { #endif Case("SYNCHRONOUS_DNS", SYNCHRONOUS_DNS), Case("SYNCHRONOUS_DNS_MULTIPLE", SYNCHRONOUS_DNS_MULTIPLE), -#ifdef MBED_EXTENDED_TESTS - Case("SYNCHRONOUS_DNS_CACHE", SYNCHRONOUS_DNS_CACHE), -#endif Case("SYNCHRONOUS_DNS_INVALID", SYNCHRONOUS_DNS_INVALID), }; diff --git a/TESTS/netsocket/tcp/tcp_tests.h b/TESTS/netsocket/tcp/tcp_tests.h index 871eab9c9b..c2e34e4bc4 100644 --- a/TESTS/netsocket/tcp/tcp_tests.h +++ b/TESTS/netsocket/tcp/tcp_tests.h @@ -30,8 +30,8 @@ nsapi_error_t tcpsocket_connect_to_discard_srv(TCPSocket &sock); int split2half_rmng_tcp_test_time(); // [s] namespace tcp_global { -static const int TESTS_TIMEOUT = 480; -static const int TCP_OS_STACK_SIZE = 1024; +static const int TESTS_TIMEOUT = 960; +static const int TCP_OS_STACK_SIZE = 2048; static const int RX_BUFF_SIZE = 1220; static const int TX_BUFF_SIZE = 1220; diff --git a/TESTS/netsocket/tcp/tcpsocket_thread_per_socket_safety.cpp b/TESTS/netsocket/tcp/tcpsocket_thread_per_socket_safety.cpp index 04172ef3d3..b508949179 100644 --- a/TESTS/netsocket/tcp/tcpsocket_thread_per_socket_safety.cpp +++ b/TESTS/netsocket/tcp/tcpsocket_thread_per_socket_safety.cpp @@ -29,7 +29,7 @@ static const int SIGNAL_SIGIO1 = 0x1; static const int SIGNAL_SIGIO2 = 0x2; static const int SIGIO_TIMEOUT = 5000; //[ms] -Thread thread; +Thread thread(osPriorityNormal, tcp_global::TCP_OS_STACK_SIZE); volatile bool running = true; } @@ -50,8 +50,8 @@ static void check_const_len_rand_sequence() sock.sigio(callback(_sigio_handler1, Thread::gettid())); static const int BUFF_SIZE = 10; - char rx_buff[BUFF_SIZE] = {0}; - char tx_buff[BUFF_SIZE] = {0}; + static char rx_buff[BUFF_SIZE] = {0}; + static char tx_buff[BUFF_SIZE] = {0}; int bytes2process; @@ -107,8 +107,8 @@ static void check_var_len_rand_sequence() sock.sigio(callback(_sigio_handler2, Thread::gettid())); static const int BUFF_SIZE = 1001; - char rx_buff[BUFF_SIZE]; - char tx_buff[BUFF_SIZE]; + static char rx_buff[BUFF_SIZE]; + static char tx_buff[BUFF_SIZE]; static const int pkt_size_diff = 100; int bytes2process; diff --git a/TESTS/network/interface/main.cpp b/TESTS/network/interface/main.cpp new file mode 100644 index 0000000000..995bec86ff --- /dev/null +++ b/TESTS/network/interface/main.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define WIFI 2 +#if !defined(MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE) || \ + (MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE == WIFI && !defined(MBED_CONF_NSAPI_DEFAULT_WIFI_SSID)) +#error [NOT_SUPPORTED] No network configuration found for this target. +#endif + +#include "mbed.h" +#include "greentea-client/test_env.h" +#include "unity/unity.h" +#include "utest.h" +#include "utest/utest_stack_trace.h" +#include "networkinterface_tests.h" + +using namespace utest::v1; + +// Test setup +utest::v1::status_t test_setup(const size_t number_of_cases) +{ + GREENTEA_SETUP(480, "default_auto"); + return verbose_test_setup_handler(number_of_cases); +} + +Case cases[] = { + Case("NETWORKINTERFACE_STATUS", NETWORKINTERFACE_STATUS), + Case("NETWORKINTERFACE_STATUS_NONBLOCK", NETWORKINTERFACE_STATUS_NONBLOCK), + Case("NETWORKINTERFACE_STATUS_GET", NETWORKINTERFACE_STATUS_GET), + Case("NETWORKINTERFACE_CONN_DISC_REPEAT", NETWORKINTERFACE_CONN_DISC_REPEAT), +}; + +Specification specification(test_setup, cases); + +int main() +{ + return !Harness::run(specification); +} diff --git a/TESTS/network/interface/networkinterface_conn_disc_repeat.cpp b/TESTS/network/interface/networkinterface_conn_disc_repeat.cpp new file mode 100644 index 0000000000..9582c7c82b --- /dev/null +++ b/TESTS/network/interface/networkinterface_conn_disc_repeat.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mbed.h" +#include "greentea-client/test_env.h" +#include "networkinterface_tests.h" +#include "unity/unity.h" +#include "utest.h" + +using namespace utest::v1; + +namespace +{ + NetworkInterface* net; + const int repeats = 5; +} + +void NETWORKINTERFACE_CONN_DISC_REPEAT() +{ + net = NetworkInterface::get_default_instance(); + + for (int i = 0; i < repeats; i++) { + nsapi_error_t err = net->connect(); + TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, err); + + err = net->disconnect(); + TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, err); + } +} diff --git a/TESTS/network/interface/networkinterface_status.cpp b/TESTS/network/interface/networkinterface_status.cpp new file mode 100644 index 0000000000..8da8b139bc --- /dev/null +++ b/TESTS/network/interface/networkinterface_status.cpp @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mbed.h" +#include "greentea-client/test_env.h" +#include "networkinterface_tests.h" +#include "unity/unity.h" +#include "utest.h" + +using namespace utest::v1; + +namespace +{ + NetworkInterface* net; + rtos::Semaphore status_semaphore; + int status_write_counter = 0; + int status_read_counter = 0; + const int repeats = 5; + const int status_buffer_size = 100; + nsapi_connection_status_t current_status = NSAPI_STATUS_ERROR_UNSUPPORTED; + nsapi_connection_status_t statuses[status_buffer_size]; +} + +void status_cb(nsapi_event_t event, intptr_t value) +{ + TEST_ASSERT_EQUAL(NSAPI_EVENT_CONNECTION_STATUS_CHANGE, event); + + statuses[status_write_counter] = static_cast(value); + status_write_counter++; + if (status_write_counter >= status_buffer_size) { + TEST_ASSERT(0); + } + + status_semaphore.release(); +} + +nsapi_connection_status_t wait_status_callback() +{ + nsapi_connection_status_t status; + + while (true) { + status_semaphore.wait(); + + status = statuses[status_read_counter]; + status_read_counter++; + + if (status != current_status) { + current_status = status; + return status; + } + } +} + +void NETWORKINTERFACE_STATUS() +{ + nsapi_connection_status_t status; + + status_write_counter = 0; + status_read_counter = 0; + current_status = NSAPI_STATUS_ERROR_UNSUPPORTED; + + net = NetworkInterface::get_default_instance(); + net->attach(status_cb); + net->set_blocking(true); + + for (int i = 0; i < repeats; i++) { + nsapi_error_t err = net->connect(); + TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, err); + + status = wait_status_callback(); + TEST_ASSERT_EQUAL(NSAPI_STATUS_CONNECTING, status); + + status = wait_status_callback(); + if (status == NSAPI_STATUS_LOCAL_UP) { + status = wait_status_callback(); + } + TEST_ASSERT_EQUAL(NSAPI_STATUS_GLOBAL_UP, status); + + net->disconnect(); + + status = wait_status_callback(); + TEST_ASSERT_EQUAL(NSAPI_STATUS_DISCONNECTED, status); + } + + net->attach(NULL); +} + +void NETWORKINTERFACE_STATUS_NONBLOCK() +{ + nsapi_connection_status_t status; + + status_write_counter = 0; + status_read_counter = 0; + current_status = NSAPI_STATUS_ERROR_UNSUPPORTED; + + net = NetworkInterface::get_default_instance(); + net->attach(status_cb); + net->set_blocking(false); + + for (int i = 0; i < repeats; i++) { + nsapi_error_t err = net->connect(); + TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, err); + + status = wait_status_callback(); + TEST_ASSERT_EQUAL(NSAPI_STATUS_CONNECTING, status); + + status = wait_status_callback(); + if (status == NSAPI_STATUS_LOCAL_UP) { + status = wait_status_callback(); + } + TEST_ASSERT_EQUAL(NSAPI_STATUS_GLOBAL_UP, status); + + net->disconnect(); + + status = wait_status_callback(); + TEST_ASSERT_EQUAL(NSAPI_STATUS_DISCONNECTED, status); + } + + net->attach(NULL); + net->set_blocking(true); +} + +void NETWORKINTERFACE_STATUS_GET() +{ + nsapi_connection_status_t status; + + net = NetworkInterface::get_default_instance(); + net->set_blocking(true); + + TEST_ASSERT_EQUAL(NSAPI_STATUS_DISCONNECTED, net->get_connection_status()); + + for (int i = 0; i < repeats; i++) { + nsapi_error_t err = net->connect(); + TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, err); + + while (net->get_connection_status() != NSAPI_STATUS_GLOBAL_UP) { + wait(0.5); + } + + net->disconnect(); + + TEST_ASSERT_EQUAL(NSAPI_STATUS_DISCONNECTED, net->get_connection_status()); + } + + net->attach(NULL); +} diff --git a/TESTS/network/interface/networkinterface_tests.h b/TESTS/network/interface/networkinterface_tests.h new file mode 100644 index 0000000000..d3d0293d2e --- /dev/null +++ b/TESTS/network/interface/networkinterface_tests.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETWORKINTERFACE_TESTS_H +#define NETWORKINTERFACE_TESTS_H + +/* + * Test cases + */ +void NETWORKINTERFACE_STATUS(); +void NETWORKINTERFACE_STATUS_NONBLOCK(); +void NETWORKINTERFACE_STATUS_GET(); +void NETWORKINTERFACE_CONN_DISC_REPEAT(); + +#endif //NETWORKINTERFACE_TESTS_H diff --git a/TEST_APPS/device/nanostack_mac_tester/README.md b/TEST_APPS/device/nanostack_mac_tester/README.md new file mode 100644 index 0000000000..0a42a2d2f8 --- /dev/null +++ b/TEST_APPS/device/nanostack_mac_tester/README.md @@ -0,0 +1,88 @@ +# Nanostack MAC test application + +You can use this application to test the Nanostack RF driver implementations that follow the [Nanostack RF driver porting instructions](https://os.mbed.com/docs/v5.6/reference/contributing-connectivity.html#porting-new-rf-driver-for-6lowpan-stack). The application has a command-line interface that is used to send commands to Nanostack's MAC layer, for example starting PANs, scanning or sending data. The provided tests do not test performance or stability and only indirectly test RF functionalities. + +## Table of contents + +* [Prerequisites](#prerequisites) +* [Setting up the application](#setting-up-the-application) +* [Application usage](#application-usage) + * [Interactive mode](#interactive-mode) + * [Automated mode](#automated-mode) + * [Testcases](#testcases) + * [Considerations](#considerations) + +## Prerequisites + +* [Mbed CLI](https://github.com/ARMmbed/mbed-cli). +* Mbed OS target board with build in radio, OR RF shield with Mbed OS driver + +## Setting up the application + +### Add your RF driver + +When using RF shield, you need to configure it to be a default RF driver and instruct Mbed OS that RF driver is present. For example, configuring Atmel RF driver to provide default driver: + +``` + "target_overrides": { + "*": { + "target.device_has_add": ["802_15_4_RF_PHY"], + "atmel-rf.provide-default": true +``` + +### Checking platform support + +Check that your choice of platform is supported by your choice of toolchain: + +``` +mbed compile --supported +``` + +**Note:** Targets are often abbreviated from the full model names. In the case of `FRDM-K64F` the target is `K64F`. + +## Run tests + +You can use this application in interactive or automated mode. + +### Interactive mode + +To set the application to interactive mode: + +1. Build the application. +``` +mbed test --compile --icetea -t TOOLCHAIN -m TARGET_PLATFORM -DICETEA_MAC_TESTER_ENABLED --test-config NANOSTACK_MAC_TESTER -n address_read_and_write,send_data,send_data_indirect,send_large_payloads,create_and_join_PAN,ED_scan +``` +2. Connect your board and copy the compiled application binary from the `BUILD/tests/TARGET_PLATFORM/TOOLCHAIN/TEST_APPS/device/nanostack_mac_tester/` folder to the board. +3. Wait for the device to flash the binary. +4. Open a serial connection with a program such as PuTTY, screen or minicom. The default baudrate is 115200. +5. Press the reset button on the board. The Arm Mbed logo and trace appears in the terminal window. + +If the driver registration and SW MAC creation was successful, the application is ready to receive commands. + +To start off, type `help` to list all commands available and furthermore `help ` to print detailed information about a specific command. + +### Automated mode + +``` +mbed test --clean --compile --run --icetea -t TOOLCHAIN -m TARGET_PLATFORM -DICETEA_MAC_TESTER_ENABLED --test-config NANOSTACK_MAC_TESTER -n address_read_and_write,send_data,send_data_indirect,send_large_payloads,create_and_join_PAN,ED_scan +``` + +Many of the provided testcases have a `self.channel` variable in the `setUp()` function for setting the RF channel. The default channel is 11. If you wish to run a test on another channel, you will need to change it manually in TEST_APPS/testcases/nanostack_mac_tester/. + +Some testcases also use a secondary channel for transmitting and will use the next higher channel for that purpose. If the given channel is 26, the secondary channel will default to 25. + +### Test cases + +The automated test set runs the following testcases included in the repository under `TEST_APPS/testcases/nanostack_mac_tester/`. +* Create and join PAN +* Direct data transmission(Transmission between two devices) +* Indirect data transmission(Transmission between two devices with one device acting as intermediary) +* ED scan(Energy Density scanning) +* Address read and write +* Large data transmission + +### Considerations + +* Devices need to be power cycled if they are unresponsive to test framework commands even after resetting. +* Devices can be enclosed in an RF isolation box to improve the consistency of test results. +* Some boards and radio modules come with a PCB trace antenna, instead of an SMD antenna, and need to be spaced further apart to decrease interference. \ No newline at end of file diff --git a/TEST_APPS/device/nanostack_mac_tester/main.cpp b/TEST_APPS/device/nanostack_mac_tester/main.cpp new file mode 100644 index 0000000000..32d49d485c --- /dev/null +++ b/TEST_APPS/device/nanostack_mac_tester/main.cpp @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2017, Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "mbed.h" +#include "rtos.h" +#include "sw_mac.h" +#include "ns_hal_init.h" +#define MBED_CMDLINE_MAX_LINE_LENGTH 250 +#include "ns_cmdline.h" + +#include "mac_commands.h" + +#define HEAP_FOR_MAC_TESTER_SIZE 10000 +#define RX_BUFFER_SIZE 512 + +#define ATMEL 1 +#define MCR20 2 +#define OTHER 3 + +#define TRACE_GROUP "Main" +#include "mbed-trace/mbed_trace.h" + +#include "NanostackRfPhy.h" + +#if !DEVICE_802_15_4_PHY +#error [NOT_SUPPORTED] No 802.15.4 RF driver found for this target +#endif + +#ifndef ICETEA_MAC_TESTER_ENABLED +#error [NOT_SUPPORTED] Skipping Nanostack MAC tester application. +#endif + +extern mac_api_s *mac_interface; +RawSerial pc(USBTX, USBRX); +osThreadId main_thread; +static CircularBuffer rx_buffer; +static uint8_t ns_heap[HEAP_FOR_MAC_TESTER_SIZE]; + +static void app_heap_error_handler(heap_fail_t event) +{ + tr_error("Heap error (%d), app_heap_error_handler()", event); + switch (event) { + case NS_DYN_MEM_NULL_FREE: + case NS_DYN_MEM_DOUBLE_FREE: + case NS_DYN_MEM_ALLOCATE_SIZE_NOT_VALID: + case NS_DYN_MEM_POINTER_NOT_VALID: + case NS_DYN_MEM_HEAP_SECTOR_CORRUPTED: + case NS_DYN_MEM_HEAP_SECTOR_UNITIALIZED: + break; + default: + break; + } + while (1); +} + +static void rx_interrupt(void) +{ + uint8_t c = pc.getc(); + rx_buffer.push(c); + if (main_thread != NULL) { + osSignalSet(main_thread, 1); + } +} + +static void handle_rx_data(void) +{ + bool exit = false; + uint8_t data; + + while (1) { + exit = !rx_buffer.pop(data); + if (exit) { + break; + } + cmd_char_input(data); + } +} + + +static int mac_prepare(void) +{ + NanostackRfPhy &rf_phy = NanostackRfPhy::get_default_instance(); + int8_t rf_driver_id = rf_phy.rf_register(); + uint8_t rf_eui64[8]; + + if (rf_driver_id < 0) { + tr_error("Failed to register RF driver."); + return -1; + } + rf_phy.get_mac_address(rf_eui64); + mac_description_storage_size_t mac_description; + mac_description.device_decription_table_size = DEVICE_DESCRIPTOR_TABLE_SIZE; /** MAC Device description list size */ + mac_description.key_description_table_size = KEY_DESCRIPTOR_TABLE_SIZE; /** MAC Key description list size */ + mac_description.key_lookup_size = LOOKUP_DESCRIPTOR_TABLE_SIZE; /** Key description key lookup list size */ + mac_description.key_usage_size = USAGE_DESCRIPTOR_TABLE_SIZE; /** Key description key usage list size */ + tr_info("Registered RF driver with id: %hhu, EUI64: %s", rf_driver_id, mbed_trace_array(rf_eui64, 8)); + mac_interface = ns_sw_mac_create(rf_driver_id, &mac_description); + if (!mac_interface) { + tr_error("Failed to create SW MAC."); + return -2; + } + + return mac_interface->mac_initialize(mac_interface, mac_data_confirm_handler, + mac_data_indication_handler, mac_purge_confirm_handler, mac_mlme_confirm_handler, + mac_mlme_indication_handler, rf_driver_id); +} + +static void cmd_ready_cb(int retcode) +{ + cmd_next(retcode); +} + +static void trace_printer(const char *str) +{ + printf("%s\n", str); + cmd_output(); + fflush(stdout); +} + +int main(void) +{ + main_thread = osThreadGetId(); + pc.baud(MBED_CONF_PLATFORM_STDIO_BAUD_RATE); + pc.attach(rx_interrupt); + ns_hal_init(ns_heap, HEAP_FOR_MAC_TESTER_SIZE, app_heap_error_handler, NULL); + mbed_trace_init(); + mbed_trace_print_function_set(trace_printer); + cmd_init(&default_cmd_response_out); + cmd_set_ready_cb(cmd_ready_cb); + mac_commands_init(); + + if (mac_prepare() != 0) { + return -1; + } + tr_info("Created driver & SW MAC"); + + while (true) { + osEvent os_event = Thread::signal_wait(1); + if (os_event.status != osEventSignal) { + osThreadYield(); + } else { + handle_rx_data(); + } + } + return 0; +} diff --git a/TEST_APPS/device/nanostack_mac_tester/mbed_app.json b/TEST_APPS/device/nanostack_mac_tester/mbed_app.json new file mode 100644 index 0000000000..d86bfd2dc7 --- /dev/null +++ b/TEST_APPS/device/nanostack_mac_tester/mbed_app.json @@ -0,0 +1,16 @@ +{ + "macros": ["MBED_TRACE_LINE_LENGTH=200", "OS_TASKCNT=4", "OS_IDLESTKSIZE=32"], + "target_overrides": { + "*": { + "nanostack.configuration": "lowpan_host", + "platform.stdio-convert-newlines": true, + "platform.stdio-baud-rate": 115200, + "mbed-mesh-api.heap-size": 6000, + "nanostack-hal.event_loop_thread_stack_size": 2000, + "mbed-trace.enable": true, + "nsapi.default-stack": "LWIP", + "target.device_has_add": ["802_15_4_PHY"], + "atmel-rf.provide-default": true + } + } +} diff --git a/TEST_APPS/device/nanostack_mac_tester/source/mac_commands.cpp b/TEST_APPS/device/nanostack_mac_tester/source/mac_commands.cpp new file mode 100644 index 0000000000..2cde6ee88c --- /dev/null +++ b/TEST_APPS/device/nanostack_mac_tester/source/mac_commands.cpp @@ -0,0 +1,1644 @@ +/* + * Copyright (c) 2017, Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "mac_commands.h" + +//Need to disable filtering until mac_filter_api.h in mbed-os is updated +#define DISABLE_FILTERING + +#define TRACE_GROUP "MAC" + +#define MAN_MAC_START "start --- Starts a PAN\n"\ + " --pan_id PAN id in hex, default: 0x1234\n"\ + " --logical_channel Operated logical channel, default: 11 (0-26)\n"\ + " --channel_page Operated channel page, default: 0 (0-2)\n"\ + " --start_time Time at which to start sending beacons\n"\ + " default: 0\n"\ + " --beacon_order How often are beacons transmitted\n"\ + " default: 15 (0-15, 15 = never)\n"\ + " --super_frame_order Length of the superframe's active portion\n"\ + " if beacon_order is 15, this option is ignored\n"\ + " default: 15 (0-15)\n"\ + " --pan_coordinator Is this device the PAN coordinator?\n"\ + " default: true\n"\ + " --battery_life_extension Disable beaconing device periodically\n"\ + " to save power? default: false\n"\ + " --coord_realignment If true, coordinator realignment command\n"\ + " is sent prior to changing\n"\ + " the superframe configuration default: false\n" + +#define MAN_MAC_SCAN "scan --- Perform a scan\n"\ + " --scan_type What type of scan to perform, 0=ED, 1=active\n"\ + " 2=passive, 3=orphan, default: 1\n"\ + " --channel_page_enum default: 0 (0-10)\n"\ + " --channel_mask Bitmap of the channels on which to perform\n"\ + " the scan, lower 27-bits are used\n"\ + " bit 0 corresponds to channel 0 and so forth\n"\ + " default: 0x07FFF800 (channels 11-26)\n"\ + " --scan_duration How long to spend in each channel,\n"\ + " aBaseSuperFrameDuration * (2^n + 1) symbols\n"\ + " default: 5 (0-14)\n"\ + " --channel_page The channel page on which to perform the scan\n"\ + " default: 0 (0-31)\n"\ + MAN_MAC_SECURITY + +#define MAN_MAC_DATA "data --- Send arbitrary data\n"\ + " --src_addr_mode Source addressing mode, 0=no address, 1=reserved\n"\ + " 2=16-bit address, 3=64-bit address\n"\ + " default: 3 (0-3)\n"\ + " --dst_addr_mode Destination addressing mode, same as above\n"\ + " default: 3 (0-3)\n"\ + " --dst_pan_id Destination PAN id in hex\n"\ + " default: 0x1234 (0x0-0xFFFF)\n"\ + " --dst_addr Destination address, default: 00:00:00:...\n"\ + " --msdu_length Length of the data to send, default: 0 (0-255)\n"\ + " --msdu Data to transmit, default: \n"\ + " --msdu_handle Handle of this MSDU, default: 0 (0-255)\n"\ + " --tx_ack_req Is ack required for this transmission?\n"\ + " default: true\n"\ + " --indirect_tx Transmit indirectly? default: false\n"\ + " --pending_bit Specifies whether more fragments (higher layer)\n"\ + " are to be sent, default: false\n"\ + " --wait_for_confirm Should we block further commands until we have\n"\ + " received a data confirmation, default: true\n"\ + MAN_MAC_SECURITY + +#define MAN_MAC_POLL "poll --- Poll the coordinator for data\n"\ + " --coord_addr_mode Coordinator addressing mode, 2=16-bit address\n"\ + " 3=64-bit address, default: 3 (2-3)\n"\ + " --coord_pan_id Coordinator PAN id in hex\n"\ + " default: 0x1234 (0x0-0xFFFF)\n"\ + " --coord_address Coordinator address, default 00:00:00:...\n"\ + MAN_MAC_SECURITY + +#define MAN_MAC_PURGE "purge --- Remove a transmission from the queue\n"\ + " --msdu_handle Handle of the MSDU to be removed\n"\ + " default: 0 (0-255)\n"\ + +#define MAN_MAC_SET "mlme-set --- Set a specified PIB attribute\n"\ + " --attr ID of the attribute to set in hex (0x0-0xFF)\n"\ + " --attr_index <0-255> Index of the attribute, default: 0 (0-255)\n"\ + " --value_ascii Specify the set value as an ASCII string\n"\ + " --value_bytes Value as a string of bytes\n"\ + " --value_uint8/16/32 Value as a uint8, uint16, or uint32\n"\ + " Max value for uint32 is the max value for int32\n"\ + " --value_size Size of the value in bytes (0-255)\n" + +#define MAN_MAC_GET "mlme-get --- Get a specified PIB attribute\n"\ + " --attr ID of the attribute we want to get in hex (0x0-0xFF)\n"\ + " --attr_index Index of the attribute, default: 0 (0-255)\n" + +#define MAN_MAC_RESET "mlme-reset --- Reset the MAC sublayer\n"\ + " --set_default_pib When set to true, PIB attributes are set to\n"\ + " their default values\n"\ + " If set to false, PIB attributes retain\n"\ + " their values, default: true\n" + +#define MAN_MAC_ADDR "addr --- Configure 16/64-bit MAC addresses\n"\ + " having no options will display the addresses\n"\ + " --16-bit 16-bit MAC address in hex (0x0-0xFFFF)\n"\ + " --64-bit 64-bit MAC address\n" + +#define MAN_MAC_SECURITY " --security_level 0=no security, 1=MIC32, 2=MIC64, 3=MIC128,\n"\ + " 4=ENC, 5=ENC+MIC32, 6=ENC+MIC64, 7=ENC+MIC128\n"\ + " default: 0\n"\ + " --key_id_mode 0=implicit, 1=default key source\n"\ + " 2=2-byte key source\n"\ + " 3=8-byte key source, default: 0 (0-3)\n"\ + " --key_index Which key to use, default: 0 (0-255)\n"\ + " --key_source The originator of the key to be used\n" + +#define MAN_MAC_KEY "key --- Configure or add key descriptors\n"\ + "config --- Configure parameters for key descriptor\n"\ + " --key Actual security key, 16 bytes\n"\ + " default: C0:C1:C2:...:CF\n"\ + " --key_id_lookup_list_entries Amount of entries in the key's lookup\n"\ + " --key_device_list_entries ...device...\n"\ + " --key_usage_list_entries and usage list, default: 2 (0-255)\n"\ + " --lookup_index Which entry of the lookup list\n"\ + " are we accessing? default: 0 (0-255)\n"\ + " --lookup_data The lookup data for this key\n"\ + " length is 9 bytes regardless of\n"\ + " the next option\n"\ + " --lookup_data_size How large is the lookup data? (0-1)\n"\ + " 0=5 bytes, 1=9 bytes\n"\ + " --device_list_index Which entry of the device list\n"\ + " are we accessing, default: 0 (0-255)\n"\ + " --device_descriptor_handle Which entry in our neighbour table\n"\ + " do we want to use this key with\n"\ + " default: 0 (0-255)\n"\ + " --unique_device Is the device unique to the key?\n"\ + " --blacklisted Is the device blacklisted?\n"\ + " --usage_list_index Which entry of the usage list\n"\ + " are we accessing, default: 0 (0-255)\n"\ + " --frame_type What type of frame do we want to\n"\ + " use this key with? (0-3)\n"\ + " 0=beacon, 1=data, 2=ACK, 3=command\n"\ + " --command_frame_identifier Type of the command frame (1-9)\n"\ + " 1=association request\n"\ + " 2=association response\n"\ + " 3=disassociation notification\n"\ + " 4=data request\n"\ + " 5=PAN id conflict notification\n"\ + " 6=orphan notification\n"\ + " 7=beacon request\n"\ + " 8=coordinator realigment\n"\ + " 9=GTS request\n"\ + "add --- Add the key into the key descriptor table\n"\ + " --index Index in the key table (0-255)\n" + +#define MAN_MAC_ADD_NEIGHBOUR "add-neigh --- Add an entry to the neighbour table\n"\ + " --frame_ctr Frame counter for this neighbour\n"\ + " --mac16 16-bit MAC address in hex (0x0-0xFFFF)\n"\ + " --mac64 64-bit MAC address\n"\ + " --pan_id PAN id (0x0-0xFFFF)\n"\ + " --index Index in the neighbour table (0-255)\n" + +#define MAN_MAC_FILTER "filter --- Configure MAC layer filtering\n"\ + "start --- Start a generic filter in blacklist, whitelist or fixed mode\n"\ + " --mode Set the filtering mode, values: allow|block|fixed\n"\ + " --lqi_m LQI multiplier (fixed mode only)\n"\ + " --dbm_m dBm multiplier (fixed mode only)\n"\ + "add --- Add a filter by manually supplying values, or using a preset mode\n"\ + " --lqi_m LQI multiplier\n"\ + " --lqi_add Value added to the LQI\n"\ + " --dbm_m dBm multiplier\n"\ + " --dbm_add Value added to the dBm\n"\ + " --mode Filtering mode, values: allow|block|fixed\n"\ + " --short 16-bit address in hex to filter (0x0-0xFFFF)\n"\ + " --long 64-bit address as bytes to filter\n"\ + "remove --- Remove a filter\n"\ + " --short 16-bit address to remove from filter (0x0-0xFFFF)\n"\ + " --long 64-bit address to remove from filter\n"\ + "clear --- Clear all filters excluding the default one\n"\ + "stop --- Stop filtering completely\n"\ + +#define MAN_MAC_CONFIG_STATUS "config-status --- Configure expected status codes\n"\ + " having no options will display configured statuses\n"\ + " default: 0 (MLME_SUCCESS) for all\n"\ + " --data_conf MCPS-DATA.confirm (0-255)\n"\ + " --data_ind MCPS-DATA.indication (0-255)\n"\ + " --get MLME-GET.confirm (0-255)\n"\ + " --scan MLME-SCAN.confirm (0-255)\n"\ + " --poll MLME-POLL.confirm (0-255)\n"\ + " --purge MCPS-PURGE.confirm (0-255)\n"\ + " --comm_status MLME-COMM-STATUS.indication (0-255)\n"\ + " --list List all statuses\n"\ + " --reset Reset all statuses to default values\n" + +#define MAN_MAC_FIND_BEACON "find-beacon --- Search for a PAN in the\n"\ + " results of the last scan\n"\ + " --data Beacon data transmitted in the beacon\n" + +#define MAN_MAC_WAIT "wait --- Wait for data sent directly for a\n"\ + " specified amount of milliseconds\n"\ + " --timeout Milliseconds to wait, default: 1000\n" + +#define MAN_MAC_ED_ANALYZE "analyze-ed Channel to analyze (11-26)\n"\ + " --above Check if the ED value is above a given value\n"\ + " --below Check if the ED value is below a given value\n" + +#define MAN_RESET "reset --- Reset MCPS and MLME structures to default values\n" + +#define MAN_SILENT "silent-mode --- When enabled, doesn't print extended information\n"\ + " of MCPS/MLME primitives\n" + +mac_api_s *mac_interface = NULL; +static bool wait_for_confirm = true; +static bool silent_mode = false; +static volatile unsigned int data_count = 0; + +static mlme_start_t start_req = { + 0x1234, /*PANId*/ + 11, /*LogicalChannel*/ + 0, /*ChannelPage*/ + 0, /*StartTime*/ + 15, /*BeaconOrder*/ + 15, /*SuperframeOrder*/ + true, /*PANCoordinator*/ + false, /*BatteryLifeExtension*/ + false, /*CoordRealignment*/ +}; + +static mlme_scan_t scan_req = { + MAC_ACTIVE_SCAN, /*ScanType*/ + { + CHANNEL_PAGE_0, /*channel_page (enum)*/ + 0x07FFF800 /*channel_mask*/ + }, + 5, /*ScanDuration*/ + 0, /*ChannelPage*/ + { + 0, /*SecurityLevel*/ + 0, /*KeyIdMode*/ + 0, /*KeyIndex*/ + {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} /*Keysource*/ + } +}; + +static mcps_data_req_t data_req = { + 3, /*SrcAddrMode*/ + 3, /*DstAddrMode*/ + 0x1234, /*DstPANId*/ + {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /*DstAddr*/ + 0, /*msduLength*/ + NULL, /*msdu*/ + 0, /*msduHandle*/ + true, /*TxAckReq*/ + false, /*IndirectTx*/ + false, /*PendingBit*/ + false, /*SeqNumSuppressed*/ + false, /*PanIdSuppressed*/ + { + 0, /*SecurityLevel*/ + 0, /*KeyIdMode*/ + 0, /*KeyIndex*/ + {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} /*Keysource*/ + } +}; + +static mlme_poll_t poll_req = { + 3, /*CoordAddrMode*/ + 0x1234, /*CoordPANId*/ + {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /*CoordAddress*/ + { + 0, /*SecurityLevel*/ + 0, /*KeyIdMode*/ + 0, /*KeyIndex*/ + {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} /*Keysource*/ + } +}; + +static mcps_purge_t purge_req = { + 0 /*msduHandle*/ +}; + +static mlme_set_t set_req = { + (mlme_attr_t)0x39, /*attr*/ + 0, /*attr_index*/ + NULL, /*value_pointer*/ + 0 /*value_size*/ +}; + +static mlme_get_t get_req = { + (mlme_attr_t)0x39, /*attr*/ + 0 /*attr_index*/ +}; + +static mlme_reset_t reset_req = { + true /*SetDefaultPIB*/ +}; + +static mlme_key_id_lookup_descriptor_t lookup_descriptors[LOOKUP_DESCRIPTOR_TABLE_SIZE]; +static mlme_key_device_descriptor_t device_descriptors[DEVICE_DESCRIPTOR_TABLE_SIZE]; +static mlme_key_usage_descriptor_t usage_descriptors[USAGE_DESCRIPTOR_TABLE_SIZE]; +static mlme_key_descriptor_entry_t key_descriptor = { + lookup_descriptors, /*KeyIdLookupList*/ + LOOKUP_DESCRIPTOR_TABLE_SIZE, /*KeyIdLookupListEntries*/ + device_descriptors, /*KeyDeviceList*/ + DEVICE_DESCRIPTOR_TABLE_SIZE, /*KeyDeviceListEntries*/ + usage_descriptors, /*KeyUsageList*/ + USAGE_DESCRIPTOR_TABLE_SIZE, /*KeyUsageListEntries*/ + {0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF} /*Key*/ +}; + +struct status_list_t { + uint8_t data_conf; + uint8_t get_conf; + uint8_t scan_conf; + uint8_t poll_conf; + uint8_t purge_conf; + uint8_t comm_status_ind; + uint8_t data_ind_len; + uint8_t *data_ind; +}; + +static struct status_list_t expected_statuses = { + MLME_SUCCESS, + MLME_SUCCESS, + MLME_SUCCESS, + MLME_SUCCESS, + MLME_SUCCESS, + MLME_SUCCESS, + 0, + NULL +}; + +struct beacon_list_t { + size_t count; + char *beacons[MLME_MAC_RES_SIZE_MAX]; + uint8_t beacon_lengths[MLME_MAC_RES_SIZE_MAX]; +}; + +static struct beacon_list_t received_beacons = {}; + +struct ed_scan_result_list_t { + uint8_t count; + uint8_t channel[MLME_MAC_RES_SIZE_MAX]; + uint8_t ED_values[MLME_MAC_RES_SIZE_MAX]; +}; + +static struct ed_scan_result_list_t last_ed_results; + +static void print_security(const mlme_security_t *key) +{ + if (key->SecurityLevel > 0) { + cmd_printf("Key.SecurityLevel: %u\n", key->SecurityLevel); + cmd_printf("Key.KeyIdMode: %u\n", key->KeyIdMode); + cmd_printf("Key.KeyIndex: %hhu\n", key->KeyIndex); + cmd_printf("Key.Keysource %s\n", trace_array(key->Keysource, 8)); + } +} + +static void print_PAN_descriptor(const mlme_pan_descriptor_t *desc) +{ + cmd_printf("PANDescriptor.CoordAddrMode: %u\n", desc->CoordAddrMode); + cmd_printf("PANDescriptor.CoordPANId: 0x%04X\n", desc->CoordPANId); + cmd_printf("PANDescriptor.CoordAddress: %s\n", trace_array(desc->CoordAddress, 8)); + cmd_printf("PANDescriptor.LogicalChannel: %hhu\n", desc->LogicalChannel); + cmd_printf("PANDescriptor.ChannelPage: %hhu\n", desc->ChannelPage); + cmd_printf("PANDescriptor.SuperframeSpec: %02x:%02x\n", desc->SuperframeSpec[0], desc->SuperframeSpec[1]); + cmd_printf("PANDescriptor.GTSPermit: %s\n", desc->GTSPermit ? "true" : "false"); + cmd_printf("PANDescriptor.LinkQuality: %hhu\n", desc->LinkQuality); + cmd_printf("PANDescriptor.Timestamp: %lu\n", desc->Timestamp); + cmd_printf("PANDescriptor.SecurityFailure: %hhu\n", desc->SecurityFailure); + print_security(&desc->Key); +} + +static int handle_security_args(int argc, char *argv[], mlme_security_t *key) +{ + char *str; + int32_t val; + + if (cmd_parameter_int(argc, argv, "--security_level", &val)) { + if (val >= 0 && val <= 7) { + key->SecurityLevel = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--key_id_mode", &val)) { + if (val >= 0 && val <= 3) { + key->KeyIdMode = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--key_index", &val)) { + if (val >= 0 && val <= 255) { + key->KeyIndex = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_val(argc, argv, "--key_source", &str)) { + if (strlen(str) == 2*8+7) { + if (string_to_bytes(str, key->Keysource, 8) != 0) { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + return CMDLINE_RETCODE_SUCCESS; +} + +static void add_beacon(const uint8_t *beacon, uint8_t len) +{ + if (received_beacons.count >= MLME_MAC_RES_SIZE_MAX) { + tr_warn("List of received beacons is full. Discarding %s <%.*s>", trace_array(beacon, len), len, beacon); + return; + } + unsigned int cur_beacon = received_beacons.count; + received_beacons.beacon_lengths[cur_beacon] = len; + received_beacons.beacons[cur_beacon] = (char*)ns_dyn_mem_temporary_alloc(len <= 75 ? 75:len); + if (len != 0) { + std::memcpy(received_beacons.beacons[cur_beacon], beacon, len); + } + ++received_beacons.count; +} + +static void clear_beacons(void) +{ + for (unsigned int i = 0; i < received_beacons.count; ++i) { + ns_dyn_mem_free(received_beacons.beacons[i]); + received_beacons.beacons[i] = NULL; + received_beacons.beacon_lengths[i] = 0; + } + received_beacons.count = 0; +} + +void mac_commands_init(void) +{ + cmd_add("start", mac_start_command, "Start a PAN", MAN_MAC_START); + cmd_add("scan", mac_scan_command, "Perform a scan", MAN_MAC_SCAN); + cmd_add("data", mac_data_command, "Send data", MAN_MAC_DATA); + cmd_add("poll", mac_poll_command, "Poll for data", MAN_MAC_POLL); + cmd_add("purge", mac_purge_command, "Purge data from the transmission queue", MAN_MAC_PURGE); + cmd_add("mlme-set", mac_set_command, "Writes a given value to the PIB attribute", MAN_MAC_SET); + cmd_add("mlme-get", mac_get_command, "Gets the value of a given PIB attribute", MAN_MAC_GET); + cmd_add("mlme-reset", mac_reset_command, "Resets the MAC sublayer to default values", MAN_MAC_RESET); + cmd_add("addr", mac_address_command, "Configure MAC addresses", MAN_MAC_ADDR); + cmd_add("key", mac_key_command, "Configure or add security keys", MAN_MAC_KEY); + cmd_add("add-neigh", mac_add_neighbour_command, "Add a device to the neighbour table", MAN_MAC_ADD_NEIGHBOUR); + cmd_add("filter", mac_filter_command, "Add or remove filters based on MAC addresses", MAN_MAC_FILTER); + cmd_add("config-status", mac_config_status_command, "Set expected return statuses for confirmations and indications", MAN_MAC_CONFIG_STATUS); + cmd_add("find-beacon", mac_find_beacon_command, "Find a PAN by beacon data", MAN_MAC_FIND_BEACON); + cmd_add("wait", mac_wait_command, "Wait for data", MAN_MAC_WAIT); + cmd_add("analyze-ed", mac_analyze_ed_command, "Analyze the results of the last ED scan", MAN_MAC_ED_ANALYZE); + cmd_add("reset", reset_command, "Reset MCPS/MLME structures to default values", MAN_RESET); + cmd_add("silent-mode", silent_mode_command, "Stop printing fields of MCPS/MLME structures", MAN_SILENT); +} + +void mac_data_confirm_handler(const mac_api_t *api, const mcps_data_conf_t *data) +{ + cmd_printf("MCPS-DATA.confirm\n"); + if (!silent_mode) { + cmd_printf("msduHandle: %hhu\n", data->msduHandle); + cmd_printf("status: %hhu (%s)\n", data->status, mlme_status_string(data->status)); + cmd_printf("timestamp: %lu\n", data->timestamp); + cmd_printf("cca_retries:%hhu\n", data->cca_retries); + cmd_printf("tx_retries: %hhu\n", data->tx_retries); + } + if (data->status == expected_statuses.data_conf) { + cmd_ready(CMDLINE_RETCODE_SUCCESS); + } else { + cmd_ready(CMDLINE_RETCODE_FAIL); + } +} + +void mac_data_indication_handler(const mac_api_t *api, const mcps_data_ind_t *data) +{ + cmd_printf("MCPS-DATA.indication\n"); + if (!silent_mode) { + cmd_printf("SrcAddrMode: %u\n", data->SrcAddrMode); + cmd_printf("SrcPANId: 0x%04X\n", data->SrcPANId); + cmd_printf("SrcAddr: %s\n", trace_array(data->SrcAddr, 8)); + cmd_printf("DstAddrMode: %u\n", data->DstAddrMode); + cmd_printf("DstPANId: 0x%04X\n", data->DstPANId); + cmd_printf("DstAddr: %s\n", trace_array(data->DstAddr, 8)); + cmd_printf("mpduLinkQuality:%hhu\n", data->mpduLinkQuality); + cmd_printf("signal_dbm: %hhi\n", data->signal_dbm); + cmd_printf("timestamp: %lu\n", data->timestamp); + cmd_printf("DSN: %hhi\n", data->DSN); + print_security(&data->Key); + cmd_printf("msduLength %hu\n", data->msduLength); + cmd_printf("msdu_ptr: %s <%.*s>\n", trace_array(data->msdu_ptr, data->msduLength), data->msduLength, data->msdu_ptr); + } + if (data->msdu_ptr && expected_statuses.data_ind) { + if (data->msduLength != expected_statuses.data_ind_len) { + return; + } + if (strncmp((const char*)data->msdu_ptr, (const char*)expected_statuses.data_ind, expected_statuses.data_ind_len) == 0) { + ++data_count; + } else { + tr_warn("Received unexpected data!"); + } + } +} + +void mac_purge_confirm_handler(const mac_api_t *api, mcps_purge_conf_t *data) +{ + cmd_printf("MCPS-PURGE.confirm\n"); + if (!silent_mode) { + cmd_printf("msduHandle: %hhu\n", data->msduHandle); + cmd_printf("status: %hhu (%s)\n", data->status, mlme_status_string(data->status)); + } + if (data->status == expected_statuses.purge_conf) { + cmd_ready(CMDLINE_RETCODE_SUCCESS); + } else { + cmd_ready(CMDLINE_RETCODE_FAIL); + } +} + +void mac_mlme_confirm_handler(const mac_api_t *api, mlme_primitive id, const void *data) +{ + switch (id) { + case MLME_ASSOCIATE: { + break; + } + case MLME_DISASSOCIATE: { + break; + } + case MLME_GET: { + mlme_get_conf_t *get_data = (mlme_get_conf_t*)data; + cmd_printf("MLME-GET.confirm\n"); + if (!silent_mode) { + cmd_printf("status: %hhu (%s)\n", get_data->status, mlme_status_string(get_data->status)); + cmd_printf("attr: %hhu\n", get_data->attr); + cmd_printf("attr_index: %hhu\n", get_data->attr_index); + cmd_printf("value_pointer: %s\n", trace_array((uint8_t*)get_data->value_pointer, get_data->value_size)); + cmd_printf("value_size: %hhu\n", get_data->value_size); + } + if (get_data->status == expected_statuses.get_conf) { + cmd_ready(CMDLINE_RETCODE_SUCCESS); + } else { + cmd_ready(CMDLINE_RETCODE_FAIL); + } + break; + } + case MLME_GTS: { + break; + } + case MLME_RESET: { + break; + } + case MLME_RX_ENABLE: { + break; + } + case MLME_SCAN: { + mlme_scan_conf_t *scan_data = (mlme_scan_conf_t*)data; + cmd_printf("MLME-SCAN.confirm\n"); + if (!silent_mode) { + cmd_printf("status: %hhu (%s)\n", scan_data->status, mlme_status_string(scan_data->status)); + cmd_printf("ScanType: %u\n", scan_data->ScanType); + cmd_printf("ChannelPage: %hhu\n", scan_data->ChannelPage); + cmd_printf("UnscannedChannels: 0x%08lX\n", scan_data->UnscannedChannels.channel_mask[0]); + cmd_printf("ResultListSize: %hhu\n", scan_data->ResultListSize); + } + for (unsigned int i = 0; i < scan_data->ResultListSize; ++i) { + if (scan_data->ScanType == MAC_ED_SCAN_TYPE) { + cmd_printf("Channel %d ED value: %hhu\n", channel_from_mask(scan_req.ScanChannels.channel_mask[0], i), scan_data->ED_values[i]); + memcpy(last_ed_results.ED_values, scan_data->ED_values, scan_data->ResultListSize); + last_ed_results.count = scan_data->ResultListSize; + for (int i = 0; i < scan_data->ResultListSize; ++i) { + last_ed_results.channel[i] = channel_from_mask(scan_req.ScanChannels.channel_mask[0], i); + } + } else if (scan_data->ScanType == MAC_PASSIVE_SCAN) { + print_PAN_descriptor(scan_data->PAN_values[i]); + } + } + if (scan_data->status == expected_statuses.scan_conf || scan_data->status == MLME_LIMIT_REACHED) { + cmd_ready(CMDLINE_RETCODE_SUCCESS); + } else { + cmd_ready(CMDLINE_RETCODE_FAIL); + } + break; + } + case MLME_SET: { + break; + } + case MLME_START: { + break; + } + case MLME_POLL: { + mlme_poll_conf_t *poll_data = (mlme_poll_conf_t*)data; + cmd_printf("MLME-POLL.confirm\n"); + if (!silent_mode) { + cmd_printf("status: %hhu (%s)\n", poll_data->status, mlme_status_string(poll_data->status)); + cmd_printf("data_count %u\n", data_count); + } + if (expected_statuses.poll_conf == MLME_SUCCESS) { + if (data_count == 1 && poll_data->status == MLME_SUCCESS) { + cmd_ready(CMDLINE_RETCODE_SUCCESS); + } else { + cmd_ready(CMDLINE_RETCODE_FAIL); + } + } else if (expected_statuses.poll_conf == poll_data->status) { + cmd_ready(CMDLINE_RETCODE_SUCCESS); + } else { + cmd_ready(CMDLINE_RETCODE_FAIL); + } + break; + } + default: { + cmd_ready(CMDLINE_RETCODE_COMMAND_NOT_IMPLEMENTED); + break; + } + } +} + +void mac_mlme_indication_handler(const mac_api_t *api, mlme_primitive id, const void *data) +{ + switch (id) { + case MLME_ASSOCIATE: { + break; + } + case MLME_DISASSOCIATE: { + break; + } + case MLME_BEACON_NOTIFY: { + const mlme_beacon_ind_t *beacon_ind = (mlme_beacon_ind_t*)data; + cmd_printf("MLME-BEACON-NOTIFY.indication\n"); + if (!silent_mode) { + cmd_printf("BSN: %hhu\n", beacon_ind->BSN); + print_PAN_descriptor(&beacon_ind->PANDescriptor); + cmd_printf("PendAddrSpec.short_address_count %u\n", beacon_ind->PendAddrSpec.short_address_count); + cmd_printf("PendAddrSpec.extended_address_count %u\n", beacon_ind->PendAddrSpec.extended_address_count); + cmd_printf("AddrList %s\n", trace_array(beacon_ind->AddrList, beacon_ind->PendAddrSpec.short_address_count * 2 + + beacon_ind->PendAddrSpec.extended_address_count * 8)); + cmd_printf("beacon_data_length %hu\n", beacon_ind->beacon_data_length); + cmd_printf("beacon_data %s\n", trace_array(beacon_ind->beacon_data, beacon_ind->beacon_data_length)); + } + add_beacon(beacon_ind->beacon_data, beacon_ind->beacon_data_length); + break; + } + case MLME_GTS: { + break; + } + case MLME_ORPHAN: { + break; + } + case MLME_COMM_STATUS: { + cmd_printf("MLME-COMM-STATUS.indication\n"); + const mlme_comm_status_t *comm_status_ind_data = (mlme_comm_status_t*)data; + if (!silent_mode) { + cmd_printf("PANId: 0x%04X\n", comm_status_ind_data->PANId); + cmd_printf("SrcAddrMode: %u\n", comm_status_ind_data->SrcAddrMode); + cmd_printf("SrcAddr: %s\n", trace_array(comm_status_ind_data->SrcAddr, 8)); + cmd_printf("DstAddrMode: %u\n", comm_status_ind_data->DstAddrMode); + cmd_printf("DstAddr: %s\n", trace_array(comm_status_ind_data->DstAddr, 8)); + cmd_printf("status: %hhu (%s)\n", comm_status_ind_data->status, mlme_status_string(comm_status_ind_data->status)); + print_security(&comm_status_ind_data->Key); + } + break; + } + case MLME_SYNC_LOSS: { + break; + } + default: + break; + } +} + +int mac_start_command(int argc, char *argv[]) +{ + char *str; + int32_t val; + bool boolean; + + cmd_printf("MLME-START.request\n"); + if (cmd_parameter_val(argc, argv, "--pan_id", &str)) { + uint32_t pan_id = strtoul(str, NULL, 16); + if (pan_id <= 0xFFFF) { + start_req.PANId = pan_id; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--logical_channel", &val)) { + if (val >= 0 && val <= 26) { + start_req.LogicalChannel = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--channel_page", &val)) { + if (val >= 0 && val <= 2) { + start_req.ChannelPage = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--start_time", &val)) { + start_req.StartTime = val; + } + if (cmd_parameter_int(argc, argv, "--beacon_order", &val)) { + if (val >= 0 && val <= 15) { + start_req.BeaconOrder = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--super_frame_order", &val)) { + if (val >= 0 && val <= 15) { + start_req.SuperframeOrder = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_bool(argc, argv, "--pan_coordinator", &boolean)) { + start_req.PANCoordinator = boolean; + } + if (cmd_parameter_bool(argc, argv, "--battery_life_extension", &boolean)) { + start_req.BatteryLifeExtension = boolean; + } + if (cmd_parameter_bool(argc, argv, "--coord_realignment", &boolean)) { + start_req.CoordRealignment = boolean; + } + mac_interface->mlme_req(mac_interface, MLME_START, &start_req); + return CMDLINE_RETCODE_SUCCESS; +} + +int mac_scan_command(int argc, char *argv[]) +{ + char *str; + int32_t val; + + cmd_printf("MLME-SCAN.request\n"); + if (cmd_parameter_int(argc, argv, "--scan_type", &val)) { + if (val >= 0 && val <= 3) { + scan_req.ScanType = (mac_scan_type_t)val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--channel_page_enum", &val)) { + if (val >= 0 && val <= 10) { + scan_req.ScanChannels.channel_page = (channel_page_e)val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_val(argc, argv, "--channel_mask", &str)) { + scan_req.ScanChannels.channel_mask[0] = strtoul(str, NULL, 16); + } + if (cmd_parameter_int(argc, argv, "--scan_duration", &val)) { + if (val >= 0 && val <= 14) { + scan_req.ScanDuration = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--channel_page", &val)) { + if (val >= 0 && val <= 2) { + scan_req.ChannelPage = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (handle_security_args(argc, argv, &scan_req.Key) != CMDLINE_RETCODE_SUCCESS) { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + clear_beacons(); + mac_interface->mlme_req(mac_interface, MLME_SCAN, &scan_req); + return CMDLINE_RETCODE_EXCUTING_CONTINUE; +} + +int mac_data_command(int argc, char *argv[]) +{ + char *str; + int32_t val; + bool boolean; + + cmd_printf("MCPS-DATA.request\n"); + if (cmd_parameter_int(argc, argv, "--src_addr_mode", &val)) { + if (val == 0 || val == 2 || val == 3) { + data_req.SrcAddrMode = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--dst_addr_mode", &val)) { + if (val == 0 || val == 2 || val == 3) { + data_req.DstAddrMode = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_val(argc, argv, "--dst_pan_id", &str)) { + uint32_t pan_id = strtoul(str, NULL, 16); + if (pan_id <= 0xFFFF) { + data_req.DstPANId = pan_id; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_val(argc, argv, "--dst_addr", &str)) { + int len = (data_req.DstAddrMode == 2 ? 2 : 8); + if (string_to_bytes(str, data_req.DstAddr, len) != 0) { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--msdu_length", &val)) { + data_req.msduLength = val; + } + if (cmd_parameter_val(argc, argv, "--msdu", &str)) { + ns_dyn_mem_free(data_req.msdu); + if (strlen(str) != data_req.msduLength) { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + data_req.msdu = (uint8_t*)ns_dyn_mem_temporary_alloc(data_req.msduLength); + if (data_req.msdu == NULL) { + tr_error("Failed to allocate memory for the msdu"); + return CMDLINE_RETCODE_FAIL; + } + std::memcpy(data_req.msdu, str, data_req.msduLength); + } + if (cmd_parameter_int(argc, argv, "--msdu_handle", &val)) { + if (val >= 0 && val <= 255) { + data_req.msduHandle = val; + } + } + if (cmd_parameter_bool(argc, argv, "--tx_ack_req", &boolean)) { + data_req.TxAckReq = boolean; + } + if (cmd_parameter_bool(argc, argv, "--indirect_tx", &boolean)) { + data_req.InDirectTx = boolean; + } + if (cmd_parameter_bool(argc, argv, "--pending_bit", &boolean)) { + data_req.PendingBit = boolean; + } + if (cmd_parameter_bool(argc, argv, "--wait_for_confirm", &boolean)) { + wait_for_confirm = boolean; + } + if (handle_security_args(argc, argv, &data_req.Key) != CMDLINE_RETCODE_SUCCESS) { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + mac_interface->mcps_data_req(mac_interface, &data_req); + if (wait_for_confirm) { + return CMDLINE_RETCODE_EXCUTING_CONTINUE; + } + return CMDLINE_RETCODE_SUCCESS; +} + +int mac_poll_command(int argc, char *argv[]) +{ + char *str; + int32_t val; + + cmd_printf("MLME-POLL.request\n"); + data_count = 0; + if (cmd_parameter_int(argc, argv, "--coord_addr_mode", &val)) { + if (val == 2 || val == 3) { + poll_req.CoordAddrMode = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_val(argc, argv, "--coord_pan_id", &str)) { + unsigned long pan_id = strtoul(str, NULL, 16); + if (pan_id <= 0xFFFF) { + poll_req.CoordPANId = pan_id; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_val(argc, argv, "--coord_address", &str)) { + int len = (poll_req.CoordAddrMode == 2 ? 2: 8); + if (string_to_bytes(str, poll_req.CoordAddress, len) != 0) { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (handle_security_args(argc, argv, &poll_req.Key) != CMDLINE_RETCODE_SUCCESS) { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + mac_interface->mlme_req(mac_interface, MLME_POLL, &poll_req); + return CMDLINE_RETCODE_EXCUTING_CONTINUE; +} + +int mac_purge_command(int argc, char *argv[]) +{ + int32_t val; + + cmd_printf("MCPS-PURGE.request\n"); + if (cmd_parameter_int(argc, argv, "--msdu_handle", &val)) { + if (val >= 0 && val <= 255) { + purge_req.msduHandle = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + mac_interface->mcps_purge_req(mac_interface, &purge_req); + return CMDLINE_RETCODE_EXCUTING_CONTINUE; +} + +int mac_set_command(int argc, char *argv[]) +{ + char *str; + int32_t val; + uint8_t val_uint8 = 0; + uint16_t val_uint16 = 0; + uint32_t val_uint32 = 0; + uint8_t *val_ptr_array = NULL; + + cmd_printf("MLME-SET.request\n"); + if (cmd_parameter_val(argc, argv, "--attr", &str)) { + uint32_t attribute = strtoul(str, NULL, 16); + if (attribute <= 255) { + set_req.attr = (mlme_attr_t)attribute; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--attr_index", &val)) { + if (val >= 0 && val <= 255) { + set_req.attr_index = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_val(argc, argv, "--value_ascii", &str)) { + val_ptr_array = (uint8_t*)ns_dyn_mem_temporary_alloc(strlen(str)); + if (val_ptr_array == NULL) { + tr_error("Failed to allocate memory for MLME-SET.request"); + return CMDLINE_RETCODE_FAIL; + } + std::memcpy(val_ptr_array, str, strlen(str)); + set_req.value_pointer = val_ptr_array; + } else if (cmd_parameter_val(argc, argv, "--value_bytes", &str)) { + size_t bytes = (strlen(str) + 1) / 3; + val_ptr_array = (uint8_t*)ns_dyn_mem_temporary_alloc(bytes); + if (val_ptr_array == NULL) { + tr_error("Failed to allocate memory for MLME-SET.request"); + return CMDLINE_RETCODE_FAIL; + } + if (string_to_bytes(str, val_ptr_array, bytes) != 0) { + ns_dyn_mem_free(val_ptr_array); + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + set_req.value_pointer = val_ptr_array; + } else if (cmd_parameter_int(argc, argv, "--value_uint8", &val)) { + if (val >= 0 && val <= 0xFF) { + val_uint8 = val; + set_req.value_pointer = &val_uint8; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } else if (cmd_parameter_int(argc, argv, "--value_uint16", &val)) { + if (val >= 0 && val <= 0xFFFF) { + val_uint16 = val; + set_req.value_pointer = &val_uint16; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } else if (cmd_parameter_int(argc, argv, "--value_uint32", &val)) { + if (val >= 0 && val <= 0x7FFFFFFF) { + val_uint32 = val; + set_req.value_pointer = &val_uint32; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--value_size", &val)) { + if (val >= 0 && val <= 255) { + set_req.value_size = val; + } + } + + mac_interface->mlme_req(mac_interface, MLME_SET, &set_req); + ns_dyn_mem_free(val_ptr_array); + set_req.value_pointer = NULL; + return CMDLINE_RETCODE_SUCCESS; +} + +int mac_get_command(int argc, char *argv[]) +{ + char *str; + int32_t val; + + cmd_printf("MLME-GET.request\n"); + if (cmd_parameter_val(argc, argv, "--attr", &str)) { + uint32_t attribute = strtoul(str, NULL, 16); + if (attribute <= 255) { + get_req.attr = (mlme_attr_t)attribute; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--attr_index", &val)) { + if (val >= 0 && val <= 255) { + get_req.attr_index = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + mac_interface->mlme_req(mac_interface, MLME_GET, &get_req); + return CMDLINE_RETCODE_SUCCESS; +} + +int mac_reset_command(int argc, char *argv[]) +{ + bool boolean; + + cmd_printf("MLME-RESET.request\n"); + if (cmd_parameter_bool(argc, argv, "--set_default_pib", &boolean)) { + reset_req.SetDefaultPIB = boolean; + } + mac_interface->mlme_req(mac_interface, MLME_RESET, &reset_req); + return CMDLINE_RETCODE_SUCCESS; +} + +int mac_address_command(int argc, char *argv[]) +{ + char *str; + uint8_t ext_addr[8]; + + if (cmd_parameter_val(argc, argv, "--64-bit", &str)) { + if (string_to_bytes(str, ext_addr, 8) != 0) { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + mac_interface->mac64_set(mac_interface, ext_addr); + cmd_printf("64-bit MAC address set to: %s\n", trace_array(ext_addr, 8)); + } else if (cmd_parameter_val(argc, argv, "--16-bit", &str)) { + uint32_t short_addr_32 = strtoul(str, NULL, 16); + if (short_addr_32 <= 0xFFFF) { + uint16_t short_addr = short_addr_32; + mlme_set_t set_req; + set_req.attr = macShortAddress; + set_req.value_pointer = &short_addr; + set_req.value_size = 2; + mac_interface->mlme_req(mac_interface, MLME_SET, &set_req); + cmd_printf("16-bit MAC address set to: 0x%04X\n", short_addr); + } else { + tr_warn("Invalid 16-bit MAC address given: %lu", short_addr_32); + } + } else if (argc == 1) { + if (mac_interface->mac64_get(mac_interface, MAC_EXTENDED_READ_ONLY, ext_addr) == 0) { + cmd_printf("EUI64: %s\n", trace_array(ext_addr, 8)); + } else { + tr_warn("Failed to read EUI64"); + return CMDLINE_RETCODE_FAIL; + } + if (mac_interface->mac64_get(mac_interface, MAC_EXTENDED_DYNAMIC, ext_addr) == 0) { + cmd_printf("MAC64: %s\n", trace_array(ext_addr, 8)); + } else { + tr_warn("Failed to read MAC64"); + return CMDLINE_RETCODE_FAIL; + } + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + return CMDLINE_RETCODE_SUCCESS; +} + +static int key_config_command(int argc, char *argv[]) +{ + char *str; + int32_t val; + bool boolean; + int lookup_index = 0, device_index = 0, usage_index = 0; + + if (cmd_parameter_val(argc, argv, "--key", &str)) { + if (strlen(str) == 2*16+15) { + if (string_to_bytes(str, key_descriptor.Key, 16) != 0) { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--key_id_lookup_list_entries", &val)) { + if (val >= 0 && val < LOOKUP_DESCRIPTOR_TABLE_SIZE) { + key_descriptor.KeyIdLookupListEntries = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--key_device_list_entries", &val)) { + if (val >= 0 && val < DEVICE_DESCRIPTOR_TABLE_SIZE) { + key_descriptor.KeyDeviceListEntries = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--key_usage_list_entries", &val)) { + if (val >= 0 && val < USAGE_DESCRIPTOR_TABLE_SIZE) { + key_descriptor.KeyUsageListEntries = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--lookup_index", &val)) { + if (val >= 0 && val < LOOKUP_DESCRIPTOR_TABLE_SIZE) { + lookup_index = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_val(argc, argv, "--lookup_data", &str)) { + if (strlen(str) == 2*9+8) { + if (string_to_bytes(str, key_descriptor.KeyIdLookupList[lookup_index].LookupData, 9) != 0) { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--lookup_data_size", &val)) { + if (val == 0 || val == 1) { + key_descriptor.KeyIdLookupList[lookup_index].LookupDataSize = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--device_list_index", &val)) { + if (val >= 0 && val < DEVICE_DESCRIPTOR_TABLE_SIZE) { + device_index = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--device_descriptor_handle", &val)) { + if (val >= 0 && val <= 255) { + key_descriptor.KeyDeviceList[device_index].DeviceDescriptorHandle = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_bool(argc, argv, "--unique_device", &boolean)) { + key_descriptor.KeyDeviceList[device_index].UniqueDevice = boolean; + } + if (cmd_parameter_bool(argc, argv, "--blacklisted", &boolean)) { + key_descriptor.KeyDeviceList[device_index].Blacklisted = boolean; + } + if (cmd_parameter_int(argc, argv, "--usage_index", &val)) { + if (val >= 0 && val <= USAGE_DESCRIPTOR_TABLE_SIZE) { + usage_index = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--frame_type", &val)) { + if (val >= 0 && val <= 3) { + key_descriptor.KeyUsageList[usage_index].FrameType = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (key_descriptor.KeyUsageList[usage_index].FrameType == 3) { + if (cmd_parameter_int(argc, argv, "--command_frame_identifier", &val)) { + if (val >= 1 && val <= 9) { + key_descriptor.KeyUsageList[usage_index].CommandFrameIdentifier = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + } + return CMDLINE_RETCODE_SUCCESS; +} + +static int key_add_command(int argc, char *argv[]) +{ + mlme_set_t set_req; + int32_t val; + int key_index = 0; + + if (cmd_parameter_int(argc, argv, "--index", &val)) { + if (val >= 0 && val <= 255) { + key_index = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + + set_req.attr = macKeyTable; + set_req.attr_index = key_index; + set_req.value_pointer = &key_descriptor; + set_req.value_size = sizeof(mlme_key_descriptor_entry_t); + mac_interface->mlme_req(mac_interface, MLME_SET, &set_req); + return CMDLINE_RETCODE_SUCCESS; +} + +int mac_key_command(int argc, char *argv[]) +{ + char *cmd = argv[1]; + + if (strcmp(cmd, "config") == 0) { + return key_config_command(argc, argv); + } else if (strcmp(cmd, "add") == 0) { + return key_add_command(argc, argv); + } + return CMDLINE_RETCODE_INVALID_PARAMETERS; +} + +int mac_add_neighbour_command(int argc, char *argv[]) +{ + char *str; + int32_t val; + mlme_device_descriptor_t neighbour; + mlme_set_t set_req; + + neighbour.Exempt = false; + if (cmd_parameter_int(argc, argv, "--frame_ctr", &val)) { + neighbour.FrameCounter = val; + } + if (cmd_parameter_val(argc, argv, "--mac16", &str)) { + uint32_t short_addr = strtoul(str, NULL, 16); + if (short_addr <= 0xFFFF) { + neighbour.ShortAddress = short_addr; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_val(argc, argv, "--mac64", &str)) { + if (strlen(str) == 2*8+7) { + if (string_to_bytes(str, neighbour.ExtAddress, 8) != 0) { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_val(argc, argv, "--pan_id", &str)) { + uint32_t pan_id = strtoul(str, NULL, 16); + if (pan_id <= 0xFFFF) { + neighbour.PANId = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + if (cmd_parameter_int(argc, argv, "--index", &val)) { + if (val >= 0 && val <= 255) { + set_req.attr_index = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + + set_req.attr = macDeviceTable; + set_req.value_pointer = &neighbour; + set_req.value_size = sizeof(mlme_device_descriptor_t); + mac_interface->mlme_req(mac_interface, MLME_SET, &set_req); + return CMDLINE_RETCODE_SUCCESS; +} + +#ifndef DISABLE_FILTERING +static int filter_start(int argc, char *argv[]) +{ + char *str; + + if (cmd_parameter_val(argc, argv, "--mode", &str)) { + if (strcmp(str, "allow") == 0) { + return mac_filter_start(mac_interface->parent_id, MAC_FILTER_ALLOWED) < 0 ? CMDLINE_RETCODE_FAIL : CMDLINE_RETCODE_SUCCESS; + } else if (strcmp(str, "block") == 0) { + return mac_filter_start(mac_interface->parent_id, MAC_FILTER_BLOCKED) < 0 ? CMDLINE_RETCODE_FAIL : CMDLINE_RETCODE_SUCCESS;; + } else if (strcmp(str, "fixed") == 0) { + int32_t lqi, dbm; + if (cmd_parameter_int(argc, argv, "--lqi_m", &lqi) && + cmd_parameter_int(argc, argv, "--dbm_m", &dbm)) { + return mac_filter_start(mac_interface->parent_id, MAC_FILTER_FIXED(lqi, dbm)) < 0 ? CMDLINE_RETCODE_FAIL : CMDLINE_RETCODE_SUCCESS; + } + } + } + return CMDLINE_RETCODE_INVALID_PARAMETERS; +} + +static int filter_add(int argc, char *argv[]) +{ + char *str; + uint32_t short_addr; + uint8_t long_addr[8]; + int32_t lqi_m, lqi_add, dbm_m, dbm_add; + + if (cmd_parameter_int(argc, argv, "--lqi_m", &lqi_m) && + cmd_parameter_int(argc, argv, "--lqi_add", &lqi_add) && + cmd_parameter_int(argc, argv, "--dbm_m", &dbm_m) && + cmd_parameter_int(argc, argv, "--dbm_add", &dbm_add)) { + } else if (cmd_parameter_val(argc, argv, "--mode", &str)) { + if (strcmp(str, "allow")) { + lqi_m = dbm_m = 256; + lqi_add = dbm_add = 0; + } else if (strcmp(str, "block")) { + lqi_m = lqi_add = dbm_m = dbm_add = 0; + } else if (strcmp(str, "fixed")) { + lqi_add = dbm_add = 0; + if (cmd_parameter_int(argc, argv, "--lqi_m", &lqi_m) && + cmd_parameter_int(argc, argv, "--dbm_m", &dbm_m)) { + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + + if (cmd_parameter_val(argc, argv, "--short", &str)) { + short_addr = strtoul(str, NULL, 16); + if (short_addr <= 0xFFFF) { + return mac_filter_add_short(mac_interface->parent_id, short_addr, lqi_m, lqi_add, dbm_m, dbm_add) < 0 ? CMDLINE_RETCODE_FAIL : CMDLINE_RETCODE_SUCCESS; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } else if (cmd_parameter_val(argc, argv, "--long", &str)) { + if (string_to_bytes(str, long_addr, 8) != 0) { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + return mac_filter_add_long(mac_interface->parent_id, long_addr, lqi_m, lqi_add, dbm_m, dbm_add) < 0 ? CMDLINE_RETCODE_FAIL : CMDLINE_RETCODE_SUCCESS; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } +} + +static int filter_remove(int argc, char *argv[]) +{ + char *str; + uint32_t short_addr; + uint8_t long_addr[8]; + + if (cmd_parameter_val(argc, argv, "--short", &str)) { + short_addr = strtoul(str, NULL, 16); + if (short_addr <= 0xFFFF) { + return mac_filter_delete_short(mac_interface->parent_id, short_addr) < 0 ? CMDLINE_RETCODE_FAIL : CMDLINE_RETCODE_SUCCESS; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } else if (cmd_parameter_val(argc, argv, "--long", &str)) { + if (string_to_bytes(str, long_addr, 8) != 0) { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + return mac_filter_delete_long(mac_interface->parent_id, long_addr) < 0 ? CMDLINE_RETCODE_FAIL : CMDLINE_RETCODE_SUCCESS; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } +} + +static int filter_clear(int argc, char *argv[]) +{ + return mac_filter_clear(mac_interface->parent_id) < 0 ? CMDLINE_RETCODE_FAIL : CMDLINE_RETCODE_SUCCESS; +} + +static int filter_stop(int argc, char *argv[]) +{ + mac_filter_stop(mac_interface->parent_id); + return CMDLINE_RETCODE_SUCCESS; +} +#else +static int filter_start(int argc, char *argv[]) +{ + (void)argc; + (void)argv; + return 0; +} + +static int filter_add(int argc, char *argv[]) +{ + (void)argc; + (void)argv; + return 0; +} +static int filter_remove(int argc, char *argv[]) +{ + (void)argc; + (void)argv; + return 0; +} +static int filter_clear(int argc, char *argv[]) +{ + (void)argc; + (void)argv; + return 0; +} +static int filter_stop(int argc, char *argv[]) +{ + (void)argc; + (void)argv; + return 0; +} +#endif +int mac_filter_command(int argc, char *argv[]) +{ + char *cmd = argv[1]; + + if (strcmp(cmd, "start") == 0) { + return filter_start(argc, argv); + } else if (strcmp(cmd, "add") == 0) { + return filter_add(argc, argv); + } else if (strcmp(cmd, "remove") == 0) { + return filter_remove(argc, argv); + } else if (strcmp(cmd, "clear") == 0) { + return filter_clear(argc, argv); + } else if (strcmp(cmd, "stop") == 0) { + return filter_stop(argc, argv); + } + return CMDLINE_RETCODE_INVALID_PARAMETERS; +} + +int mac_config_status_command(int argc, char *argv[]) +{ + int32_t val; + char *str; + + if (cmd_parameter_int(argc, argv, "--data_conf", &val)) { + if (val >= 0 && val <= 255) { + expected_statuses.data_conf = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } else if (cmd_parameter_val(argc, argv, "--data_ind", &str)) { + size_t len = strlen(str); + ns_dyn_mem_free(expected_statuses.data_ind); + expected_statuses.data_ind = (uint8_t*)ns_dyn_mem_temporary_alloc(len); + expected_statuses.data_ind_len = len; + std::memcpy(expected_statuses.data_ind, str, len); + } else if (cmd_parameter_int(argc, argv, "--get", &val)) { + if (val >= 0 && val <= 255) { + expected_statuses.get_conf = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } else if (cmd_parameter_int(argc, argv, "--scan", &val)) { + if (val >= 0 && val <= 255) { + expected_statuses.scan_conf = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } else if (cmd_parameter_int(argc, argv, "--poll", &val)) { + if (val >= 0 && val <= 255) { + expected_statuses.poll_conf = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } else if (cmd_parameter_int(argc, argv, "--purge", &val)) { + if (val >= 0 && val <= 255) { + expected_statuses.purge_conf = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } else if (cmd_parameter_int(argc, argv, "--comm_status", &val)) { + if (val >= 0 && val <= 255) { + expected_statuses.comm_status_ind = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } else if (cmd_parameter_index(argc, argv, "--list") != -1) { + for (unsigned int i = 0; i < 256; ++i) { + const char *status = mlme_status_string(i); + if (status) { + cmd_printf("%hhu\t%s\n", i, status); + } + } + } else if (cmd_parameter_index(argc, argv, "--reset") != -1) { + expected_statuses.data_conf = MLME_SUCCESS; + expected_statuses.get_conf = MLME_SUCCESS; + expected_statuses.scan_conf = MLME_SUCCESS; + expected_statuses.poll_conf = MLME_SUCCESS; + expected_statuses.purge_conf = MLME_SUCCESS; + expected_statuses.comm_status_ind = MLME_SUCCESS; + expected_statuses.data_ind_len = 0; + expected_statuses.data_ind = NULL; + } else if (argc == 1) { + cmd_printf("MCPS-DATA.confirm: %d (%s)\n", expected_statuses.data_conf, mlme_status_string(expected_statuses.data_conf)); + cmd_printf("MLME-GET.confirm: %d (%s)\n", expected_statuses.get_conf, mlme_status_string(expected_statuses.get_conf)); + cmd_printf("MLME-SCAN.confirm: %d (%s)\n", expected_statuses.scan_conf, mlme_status_string(expected_statuses.scan_conf)); + cmd_printf("MLME-POLL.confirm: %d (%s)\n", expected_statuses.poll_conf, mlme_status_string(expected_statuses.poll_conf)); + cmd_printf("MCPS.PURGE.confirm. %d (%s)\n", expected_statuses.purge_conf, mlme_status_string(expected_statuses.purge_conf)); + cmd_printf("MLME-COMM-STATUS.indication: %d (%s)\n", expected_statuses.comm_status_ind, mlme_status_string(expected_statuses.comm_status_ind)); + cmd_printf("MCPS-DATA.indication: %s <%.*s>\n", trace_array(expected_statuses.data_ind, expected_statuses.data_ind_len), expected_statuses.data_ind_len, expected_statuses.data_ind); + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + return CMDLINE_RETCODE_SUCCESS; +} + +int mac_find_beacon_command(int argc, char *argv[]) +{ + char *str; + + if (cmd_parameter_val(argc, argv, "--data", &str)) { + for (int i = 0; i < MLME_MAC_RES_SIZE_MAX; ++i) { + if (received_beacons.beacons[i] == NULL) { + continue; + } + if (strncmp(received_beacons.beacons[i], str, received_beacons.beacon_lengths[i]) == 0) { + return CMDLINE_RETCODE_SUCCESS; + } + } + return CMDLINE_RETCODE_FAIL; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } +} + +int mac_wait_command(int argc, char *argv[]) +{ + int32_t val; + static uint32_t timeout_ms = 1000; + int remaining_ms = timeout_ms; + if (cmd_parameter_int(argc, argv, "--timeout", &val)) { + if (val >= 0) { + timeout_ms = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } + while (data_count < 1) { + ThisThread::sleep_for(10); + remaining_ms -= 10; + if (remaining_ms <= 0) { + return CMDLINE_RETCODE_FAIL; + } + } + data_count = 0; + return CMDLINE_RETCODE_SUCCESS; +} + +int mac_analyze_ed_command(int argc, char *argv[]) +{ + int32_t val; + int channel; + + if (cmd_parameter_int(argc, argv, "--channel", &val)) { + if (val >= 0 && val <= 26) { + channel = val; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + + if (cmd_parameter_int(argc, argv, "--above", &val)) { + for (int i = 0; i < last_ed_results.count; ++i) { + if (last_ed_results.channel[i] == channel) { + return last_ed_results.ED_values[i] >= val ? CMDLINE_RETCODE_SUCCESS : CMDLINE_RETCODE_FAIL; + } + } + } else if (cmd_parameter_int(argc, argv, "--below", &val)) { + for (int i = 0; i < last_ed_results.count; ++i) { + if (last_ed_results.channel[i] == channel) { + return last_ed_results.ED_values[i] <= val ? CMDLINE_RETCODE_SUCCESS : CMDLINE_RETCODE_FAIL; + } + } + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } + return CMDLINE_RETCODE_FAIL; +} + +static void reset_security(mlme_security_t *sec) +{ + sec->SecurityLevel = 0; + sec->KeyIdMode = 0; + sec->KeyIndex = 0; + memset(sec->Keysource, 0, 8); +} + +int reset_command(int argc, char *argv[]) +{ + wait_for_confirm = true; + silent_mode = false; + data_count = 0; + + start_req.PANId = 0x1234; + start_req.LogicalChannel = 11; + start_req.ChannelPage = 0; + start_req.StartTime = 0; + start_req.BeaconOrder = 15; + start_req.SuperframeOrder = 15; + start_req.PANCoordinator = true; + start_req.BatteryLifeExtension = false; + start_req.CoordRealignment = false; + reset_security(&start_req.CoordRealignKey); + reset_security(&start_req.BeaconRealignKey); + + scan_req.ScanType = MAC_ACTIVE_SCAN; + scan_req.ScanChannels.channel_page = CHANNEL_PAGE_0; + scan_req.ScanChannels.channel_mask[0] = 0x07FFF800; + reset_security(&scan_req.Key); + + data_req.SrcAddrMode = 3; + data_req.DstAddrMode = 3; + data_req.DstPANId = 0x1234; + memset(data_req.DstAddr, 0, 8); + data_req.msduLength = 0; + data_req.msdu = NULL; + data_req.msduHandle = 0; + data_req.TxAckReq = true; + data_req.InDirectTx = false; + data_req.PendingBit = false; + reset_security(&data_req.Key); + + poll_req.CoordAddrMode = 3; + poll_req.CoordPANId = 0x1234; + memset(poll_req.CoordAddress, 0, 8); + reset_security(&poll_req.Key); + + purge_req.msduHandle = 0; + + set_req.attr = (mlme_attr_t)0x39; + set_req.attr_index = 0; + set_req.value_pointer = NULL; + set_req.value_size = 0; + + get_req.attr = (mlme_attr_t)0x39; + get_req.attr_index = 0; + + reset_req.SetDefaultPIB = true; + + return CMDLINE_RETCODE_SUCCESS; +} + +int silent_mode_command(int argc, char *argv[]) +{ + char *cmd; + if (argc < 2) { + return CMDLINE_RETCODE_FAIL; + } + cmd = argv[1]; + if (strcmp(cmd, "on") == 0) { + silent_mode = true; + return CMDLINE_RETCODE_SUCCESS; + } else if (strcmp(cmd, "off") == 0) { + silent_mode = false; + return CMDLINE_RETCODE_SUCCESS; + } else { + return CMDLINE_RETCODE_INVALID_PARAMETERS; + } +} diff --git a/TEST_APPS/device/nanostack_mac_tester/source/mac_commands.h b/TEST_APPS/device/nanostack_mac_tester/source/mac_commands.h new file mode 100644 index 0000000000..a57e97fc31 --- /dev/null +++ b/TEST_APPS/device/nanostack_mac_tester/source/mac_commands.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2017, Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef MAC_COMMANDS_H_ +#define MAC_COMMANDS_H_ + +#include +#include + +#include "ns_cmdline.h" +#include "nsdynmemLIB.h" +#include "mbed_trace.h" +#include "mac_api.h" +#include "mlme.h" +#include "mac_mcps.h" +#include "mac_common_defines.h" +#include "mac_filter_api.h" +#include "util.h" + +#define LOOKUP_DESCRIPTOR_TABLE_SIZE 2 +#define DEVICE_DESCRIPTOR_TABLE_SIZE 2 +#define USAGE_DESCRIPTOR_TABLE_SIZE 2 +#define KEY_DESCRIPTOR_TABLE_SIZE 2 + +void mac_commands_init(void); + +void mac_data_confirm_handler(const mac_api_t *api, const mcps_data_conf_t *data); +void mac_data_indication_handler(const mac_api_t *api, const mcps_data_ind_t *data); +void mac_purge_confirm_handler(const mac_api_t *api, mcps_purge_conf_t *data); +void mac_mlme_confirm_handler(const mac_api_t *api, mlme_primitive id, const void *data); +void mac_mlme_indication_handler(const mac_api_t *api, mlme_primitive id, const void *data); + +int mac_start_command(int argc, char *argv[]); +int mac_scan_command(int argc, char *argv[]); +int mac_data_command(int argc, char *argv[]); +int mac_poll_command(int argc, char *argv[]); +int mac_purge_command(int argc, char *argv[]); +int mac_set_command(int argc, char *argv[]); +int mac_get_command(int argc, char *argv[]); +int mac_reset_command(int argc, char *argv[]); +int mac_address_command(int argc, char *argv[]); +int mac_key_command(int argc, char *argv[]); +int mac_add_neighbour_command(int argc, char *argv[]); +int mac_filter_command(int argc, char *argv[]); +int mac_config_status_command(int argc, char *argv[]); +int mac_find_beacon_command(int argc, char *argv[]); +int mac_wait_command(int argc, char *argv[]); +int mac_analyze_ed_command(int argc, char *argv[]); +int reset_command(int argc, char *argv[]); +int silent_mode_command(int argc, char *argv[]); + +#endif diff --git a/TEST_APPS/device/nanostack_mac_tester/source/util.cpp b/TEST_APPS/device/nanostack_mac_tester/source/util.cpp new file mode 100644 index 0000000000..286c6d68ca --- /dev/null +++ b/TEST_APPS/device/nanostack_mac_tester/source/util.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2017, Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + #include "util.h" + +int string_to_bytes(const char *str, uint8_t *buf, int bytes) +{ + int len = strlen(str); + + if (len <= (3 * bytes - 1)) { + int i; + + for (i = 0; i < bytes; ++i) { + if (i * 3 < len) { + buf[i] = (uint8_t)strtoul(str + i * 3, NULL, 16); + } else { + buf[i] = 0; + } + } + return 0; + } + return -1; +} + +const char *mlme_status_string(uint8_t status) +{ + switch (status) { + case MLME_SUCCESS: return "MLME_SUCCESS"; + case MLME_BUSY_CHAN: return "MLME_BUSY_CHAN"; + case MLME_BUSY_RX: return "MLME_BUSY_RX"; + case MLME_BUSY_TX: return "MLME_BUSY_TX"; + case MLME_FORCE_TRX_OFF: return "MLME_FORCE_TRX_OFF"; + case MLME_IDLE: return "MLME_IDLE"; + case MLME_RX_ON: return "MLME_RX_ON"; + case MLME_TRX_OFF: return "MLME_TRX_OFF"; + case MLME_TX_ON: return "MLME_TX_ON"; + case MLME_COUNTER_ERROR: return "MLME_COUNTER_ERROR"; + case MLME_IMPROPER_KEY_TYPE: return "MLME_IMPROPER_KEY_TYPE"; + case MLME_IMPROPER_SECURITY_LEVEL: return "MLME_IMPROPER_SECURITY_LEVEL"; + case MLME_UNSUPPORTED_LEGACY: return "MLME_UNSUPPORTED_LEGACY"; + case MLME_UNSUPPORTED_SECURITY: return "MLME_UNSUPPORTED_SECURITY"; + case MLME_SECURITY_FAIL: return "MLME_SECURITY_FAIL"; + case MLME_FRAME_TOO_LONG: return "MLME_FRAME_TOO_LONG"; + case MLME_INVALID_HANDLE: return "MLME_INVALID_HANDLE"; + case MLME_INVALID_PARAMETER: return "MLME_INVALID_PARAMETER"; + case MLME_TX_NO_ACK: return "MLME_TX_NO_ACK"; + case MLME_NO_BEACON: return "MLME_NO_BEACON"; + case MLME_NO_DATA: return "MLME_NO_DATA"; + case MLME_NO_SHORT_ADDRESS: return "MLME_NO_SHORT_ADDRESS"; + case MLME_PAN_ID_CONFLICT: return "MLME_PAN_ID_CONFLICT"; + case MLME_TRANSACTION_EXPIRED: return "MLME_TRANSACTION_EXPIRED"; + case MLME_TRANSACTION_OVERFLOW: return "MLME_TRANSACTION_OVERFLOW"; + case MLME_UNAVAILABLE_KEY: return "MLME_UNAVAILABLE_KEY"; + case MLME_UNSUPPORTED_ATTRIBUTE: return "MLME_UNSUPPORTED_ATTRIBUTE"; + case MLME_INVALID_ADDRESS: return "MLME_INVALID_ADDRESS"; + case MLME_INVALID_INDEX: return "MLME_INVALID_INDEX"; + case MLME_LIMIT_REACHED: return "MLME_LIMIT_REACHED"; + case MLME_READ_ONLY: return "MLME_READ_ONLY"; + case MLME_SCAN_IN_PROGRESS: return "MLME_SCAN_IN_PROGRESS"; + case MLME_DATA_POLL_NOTIFICATION: return "MLME_DATA_POLL_NOTIFICATION"; + default: return NULL; + } +} + +int channel_from_mask(uint32_t channel_mask, int index) +{ + int expected_index = 0; + for (int i = 0; i < 27; ++i) { + if ((channel_mask >> i) & 1) { + if (expected_index == index) { + return i; + } + ++expected_index; + } + } + return -1; +} diff --git a/TEST_APPS/device/nanostack_mac_tester/source/util.h b/TEST_APPS/device/nanostack_mac_tester/source/util.h new file mode 100644 index 0000000000..a792731427 --- /dev/null +++ b/TEST_APPS/device/nanostack_mac_tester/source/util.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2017, Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef UTIL_H_ +#define UTIL_H_ + +#include +#include + +#include "mbed.h" +#include "mlme.h" + +int string_to_bytes(const char *str, uint8_t *buf, int bytes); +const char *mlme_status_string(uint8_t status); +int channel_from_mask(uint32_t channel_mask, int index); + +#endif diff --git a/TEST_APPS/readme.md b/TEST_APPS/readme.md index 814e768df2..2d5f50bfac 100644 --- a/TEST_APPS/readme.md +++ b/TEST_APPS/readme.md @@ -2,57 +2,66 @@ ### Structure -mbed-os has a folder called TEST_APPS that contains everything related to Icetea testing. -There are currently 3 folders: +Mbed OS has a folder called `TEST_APPS` that contains everything related to Icetea testing. -- device - contains all the different test applications you can flash to your board -- icetea-plugins - contains plugins that are being used by some of the testcases, needed for the test execution -- testcases - contains Icetea testcases written in Python +There are currently three folders: -The testcases depends on test applications +- `device` - contains all the different test applications you can flash to your board. +- `icetea_plugins` - contains plugins that are being used by some of the testcases, needed for the test execution. +- `testcases` - contains Icetea testcases written in Python. + +The testcases depend on test applications. ### Preparing your work environment -#### Prerequisities +#### Prerequisites -You need Icetea and mbed-cli that supports Icetea, installed. +You need Icetea and version 1.8.0 or higher of Mbed CLI installed. #### Selecting the network interface to use -Depending on a device, there might be a default network interface type defined in the mbed-os/targets/targets.json, which is used to locate a test-config file by default. -If there is not, or you want to use a different interface than the default, you need to provide a relevant test-config -file to the mbed test with --test-config option. -The test-config file contains the necessary information for the test application, there are some test-config files located under mbed-os/tools/test_configs. -Devices which have their network drivers residing inside mbed-os can use generic test_configs like HeapBlockDeviceAndEthernetInterface.json and HeapBlockDeviceAndWifiInterface.json. Otherwise you need to use a device specific test-config. +Depending on the device, there might be a default network interface type defined in `mbed-os/targets/targets.json`, which you can use to locate a default test-config file. + +If the default network interface type is not defined or you want to use a different interface than the default, you need to provide a test-config file to the mbed test with `--test-config` option. + +The test-config file contains the necessary information for the test application. There are some test-config files located under `mbed-os/tools/test_configs`. + +Devices that have their network drivers residing inside `mbed-os` can use generic `test_configs`, such as `HeapBlockDeviceAndEthernetInterface.json` and `HeapBlockDeviceAndWifiInterface.json`. Otherwise, you need to use a device-specific test-config. ### Running the tests -Now that the interface has been selected you can run the icetea tests from the mbed-os root on your command line by +Now that you have selected the interface, you can run the Icetea tests from the `mbed-os` root on your command-line by running the following command: -`>mbed test -m -t --icetea` +`mbed test -m -t --icetea` -This command will compile the mbed-os, then compiles the test applications, creates a test suite and then starts running the tests. +This command compiles the OS, compiles the test applications, creates a test suite and then starts running the tests. -If you want only to run some specific tests, you can use the -n -option. You can list multiple tests by separating them by comma (,). +If you only want to run some specific tests, you can use the `-n` option. You can choose multiple tests by separating them with a comma (`,`): -`>mbed test -m -t --icetea -n test1,test2` +`mbed test -m -t --icetea -n test1,test2` -#### Running the tests with specifig test-config +#### Running the tests with a specific test-config + +Some devices may offer multiple network interfaces to operate with. For example, `UBLOX_EVK_ODIN_W2` offers ethernet and Wi-Fi capabilities. -Some devices may offer multiple network interfaces to operate with. For example, UBLOX_EVK_ODIN_W2 offers ethernet and Wi-Fi capabilities. The tests can be run for either one of those using already existing test-config -files. -To run the tests with Wi-Fi interface: -`>mbed test -m UBLOX_EVK_ODIN_W2 -t --icetea --test-config tools/test_configs/HeapBlockDeviceAndWifiInterface.json` +To run the tests with the Wi-Fi interface: -To run the tests with ethernet interface: -`>mbed test -m UBLOX_EVK_ODIN_W2 -t --icetea --test-config tools/test_configs/HeapBlockDeviceAndEthernetInterface.json` +`mbed test -m UBLOX_EVK_ODIN_W2 -t --icetea --test-config tools/test_configs/HeapBlockDeviceAndWifiInterface.json` + +To run the tests with the ethernet interface: + +`mbed test -m UBLOX_EVK_ODIN_W2 -t --icetea --test-config tools/test_configs/HeapBlockDeviceAndEthernetInterface.json` #### Providing Wi-Fi access point information -If you are using Wi-Fi interface for running the tests, you need to provide also information about the used access point. +If you are using the Wi-Fi interface for running the tests, you need to also provide information about the used access point. + The information can be provided in the used test-config file. Example of access point information: + ``` "target_overrides": { "*": { @@ -66,7 +75,7 @@ Example of access point information: ### Test results -Icetea prints the results from the test run to the command line, and the final result looks similar to this. +Icetea prints the results from the test run to the command-line, and the final result looks similar to this: ``` +--------------------------------+---------+-------------+-------------+-----------+----------+ @@ -89,5 +98,6 @@ Icetea prints the results from the test run to the command line, and the final r +---------------+----------------+ ``` -The results from the tests can also be found in the mbed-os/log folder. -You probably want to add the log folder to your .mbedignore file to prevent issues with build commands becoming too long over the time. +You can also find the results from the tests in the `mbed-os/log` folder. + +You probably want to add the log folder to your `.mbedignore` file to prevent issues with build commands becoming too long over the time. diff --git a/TEST_APPS/testcases/README.md b/TEST_APPS/testcases/README.md new file mode 100644 index 0000000000..3ceb8b881b --- /dev/null +++ b/TEST_APPS/testcases/README.md @@ -0,0 +1,14 @@ +Icetea tests +============ + +This folder contains all the test cases done with Icetea residing in `mbed-os`. +The tests are divided in to subfolders and each subfolder contains a set of testcases. +The subfolder has a description of all the testcases it contains. + +Testcases +--------- + +Current testcases: + +- [netsocket](https://github.com/ARMmbed/mbed-os/blob/master/TEST_APPS/testcases/netsocket) +- [example](https://github.com/ARMmbed/mbed-os/blob/master/TEST_APPS/testcases/example) diff --git a/TEST_APPS/testcases/example/README.md b/TEST_APPS/testcases/example/README.md new file mode 100644 index 0000000000..7bf8901ccd --- /dev/null +++ b/TEST_APPS/testcases/example/README.md @@ -0,0 +1,24 @@ +Example tests +============= + +This folder contains example tests for Icetea +The test located under this folder is dependent of the application [exampleapp](https://github.com/ARMmbed/mbed-os/blob/master/TEST_APPS/device/exampleapp) +The exampleapp is disabled by default, to be able to run the test_cmdline with the exampleapp, either remove the preprocessor macro from exampleapp.cpp or add `-DICETEA_EXAMPLE_ENABLED` to the mbed test command + +Testcases +--------- + +### test_cmdline + +**Description:** +Send command line commands to target over serial interface. +This test introduces the Icetea testcase structure to the user. + +**Test steps:** +Send "echo hello world" to the target. +Target sends "hello world" back to the host machine. +Send help to the target. +Target prints out the command line commands the application supports. + +**Expected result:** +The test exits without timeouts. diff --git a/TEST_APPS/testcases/nanostack_mac_tester/ED_scan.py b/TEST_APPS/testcases/nanostack_mac_tester/ED_scan.py new file mode 100644 index 0000000000..1eac278fba --- /dev/null +++ b/TEST_APPS/testcases/nanostack_mac_tester/ED_scan.py @@ -0,0 +1,107 @@ +""" +Copyright (c) 2017, Arm Limited and affiliates. +SPDX-License-Identifier: Apache-2.0 + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import threading +import os,sys +from icetea_lib.bench import Bench + +class Testcase(Bench): + def __init__(self): + Bench.__init__(self, name = "ED_scan", + title = "ED scan test", + status = "development", + type = "smoke", + subtype = "", + execution = { + "skip": { + "value": False, + "reason": "" + } + }, + author = "Valtteri Erkkila", + purpose = "Tests reading the ED values from channels 11-16", + feature = ["MLME-SCAN (ED)"], + component = ["MAC"], + requirements = { + "duts": { + '*': { + "count":3, + "type": "hardware", + "allowed_platforms": ["K64F", "K66F", "NUCLEO_F429ZI", "KW24D", "UBLOX_EVK_ODIN_W2"], + "application": { + "name": "TEST_APPS-device-nanostack_mac_tester" + } + }, + "1":{"nick": "First"}, + "2":{"nick": "Second"}, + "3":{"nick": "Third"} + }} + ) + + def setUp(self): + self.channel = 11 + self.command("First", "addr --64-bit 01:02:03:00:00:00:00:01") + self.command("Second", "addr --64-bit 01:02:03:00:00:00:00:02") + self.command("Third", "addr --64-bit 01:02:03:00:00:00:00:03") + + def spam_channel(self, event): + while not event.wait(0.1): + self.lock_th.acquire() + self.command("First", "data --dst_addr 01:02:03:00:00:00:00:03 --msdu {} --msdu_length {} --wait_for_confirm false".format(self.payload, len(self.payload))) + self.command("Third", "data --dst_addr 01:02:03:00:00:00:00:01 --msdu {} --msdu_length {} --wait_for_confirm false".format(self.payload, len(self.payload))) + self.lock_th.release() + + def mask_from_channel_list(self, channels): + res = 0 + for ch in channels: + res = res | ( 1 << ch) + return hex(res) + + def case(self): + self.lock_th = threading.Lock() + self.payload = "01234567890123456789012345678901234567890123456789" + + self.command("First", "start --pan_coordinator true --logical_channel {}".format(self.channel)) + self.command("Second", "start --pan_coordinator false --logical_channel {}".format(self.channel)) + self.command("Third", "start --pan_coordinator false --logical_channel {}".format(self.channel)) + + #No reason to print their spamming + self.command("First", "silent-mode on") + self.command("Third", "silent-mode on") + + self.stop_event = threading.Event() + self.th = threading.Thread(target=self.spam_channel, args=(self.stop_event,)) + self.th.start() + self.stopped = True + channels = range(11,27) + for i in range(0, 3): + self.lock_th.acquire() + self.command("First", "mlme-reset") + self.command("First", "start --pan_coordinator true --logical_channel {}".format(self.channel)) + self.command("Third", "mlme-reset") + self.command("Third", "start --pan_coordinator false --logical_channel {}".format(self.channel)) + self.lock_th.release() + self.command("Second", "scan --scan_type 0 --scan_duration 7 --channel_mask {}".format(self.mask_from_channel_list(channels))) + self.command("Second", "analyze-ed --channel {} --above 100".format(self.channel)) + + def tearDown(self): + self.command("First", "silent-mode off") + self.command("Third", "silent-mode off") + self.stop_event.set() + self.th.join() + del self.th + self.reset_dut() diff --git a/TEST_APPS/testcases/nanostack_mac_tester/__init__.py b/TEST_APPS/testcases/nanostack_mac_tester/__init__.py new file mode 100644 index 0000000000..4265cc3e6c --- /dev/null +++ b/TEST_APPS/testcases/nanostack_mac_tester/__init__.py @@ -0,0 +1 @@ +#!/usr/bin/env python diff --git a/TEST_APPS/testcases/nanostack_mac_tester/address_read_and_write.py b/TEST_APPS/testcases/nanostack_mac_tester/address_read_and_write.py new file mode 100644 index 0000000000..d05efa4ed2 --- /dev/null +++ b/TEST_APPS/testcases/nanostack_mac_tester/address_read_and_write.py @@ -0,0 +1,65 @@ +""" +Copyright (c) 2017, Arm Limited and affiliates. +SPDX-License-Identifier: Apache-2.0 + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import os,sys +from icetea_lib.bench import Bench + +class Testcase(Bench): + def __init__(self): + Bench.__init__(self, name = "address_read_and_write", + title = "MAC address and PAN id read/write test", + status = "development", + type = "smoke", + subtype = "", + execution = { + "skip": { + "value": False, + "reason": "" + } + }, + author = "Valtteri Erkkila", + purpose = "Tests reading a MAC address from the driver, and writing to the modifiable MAC address", + feature = ["MLME-SET"], + component = ["MAC"], + requirements = { + "duts": { + '*': { + "count":1, + "type": "hardware", + "allowed_platforms": ["K64F", "K66F", "NUCLEO_F429ZI", "KW24D", "UBLOX_EVK_ODIN_W2"], + "application": { + "name": "TEST_APPS-device-nanostack_mac_tester" + } + }, + "1":{"nick": "First"} + }} + ) + + def setUp(self): + pass + + def case(self): + self.command("First", "addr") + self.command("First", "addr --64-bit 01:02:03:00:00:00:00:01") + self.command("First", "addr --16-bit 0xABCD") + #macPANId + self.command("First", "mlme-set --attr 0x50 --value_bytes CD:CD --value_size 2") + self.command("First", "addr") + self.verify_trace(1, "MAC64: 01:02:03:00:00:00:00:01") + + def tearDown(self): + self.reset_dut() diff --git a/TEST_APPS/testcases/nanostack_mac_tester/create_and_join_PAN.py b/TEST_APPS/testcases/nanostack_mac_tester/create_and_join_PAN.py new file mode 100644 index 0000000000..c141df269a --- /dev/null +++ b/TEST_APPS/testcases/nanostack_mac_tester/create_and_join_PAN.py @@ -0,0 +1,86 @@ +""" +Copyright (c) 2017, Arm Limited and affiliates. +SPDX-License-Identifier: Apache-2.0 + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import os,sys +from icetea_lib.bench import Bench + +class Testcase(Bench): + def __init__(self): + Bench.__init__(self, name = "create_and_join_PAN", + title = "Create a PAN and have a device join it", + status = "development", + type = "smoke", + subtype = "", + execution = { + "skip": { + "value": False, + "reason": "" + } + }, + author = "Valtteri Erkkila", + purpose = "", + feature = ["MLME-START", "MLME-SCAN (active)"], + component = ["MAC"], + requirements = { + "duts": { + '*': { + "count":3, + "type": "hardware", + "allowed_platforms": ["K64F", "K66F", "NUCLEO_F429ZI", "KW24D", "UBLOX_EVK_ODIN_W2"], + "application": { + "name": "TEST_APPS-device-nanostack_mac_tester" + } + }, + "1":{"nick": "First"}, + "2":{"nick": "Second"}, + "3":{"nick": "Third"} + }} + ) + + def mask_from_channel_list(self, channels): + res = 0 + for ch in channels: + res = res | ( 1 << ch) + return hex(res) + + def setUp(self): + self.channel = 11 + + def case(self): + #Beacon payload & length + self.command("First", "mlme-set --attr 0x45 --value_ascii mac-tester --value_size 10") + self.command("First", "mlme-set --attr 0x46 --value_uint8 10 --value_size 1") + + self.command("Second", "mlme-set --attr 0x45 --value_ascii second-mac-tester --value_size 17") + self.command("Second", "mlme-set --attr 0x46 --value_uint8 17 --value_size 1") + + self.command("First", "start --pan_coordinator true --logical_channel {}".format(self.channel)) + self.command("Second", "start --pan_coordinator true --logical_channel {}".format(int(self.channel)+1)) + self.delay(3) + if self.channel == 11: + channels = [11,12] + elif self.channel == 26: + channels = [25,26] + else: + channels = [self.channel, self.channel+1] + self.command("Third", "scan --channel_mask {}".format(self.mask_from_channel_list(channels))) + self.delay(0.2) + self.command("Third", "find-beacon --data mac-tester") + self.command("Third", "find-beacon --data second-mac-tester") + + def tearDown(self): + self.reset_dut() diff --git a/TEST_APPS/testcases/nanostack_mac_tester/send_data.py b/TEST_APPS/testcases/nanostack_mac_tester/send_data.py new file mode 100644 index 0000000000..575b00c545 --- /dev/null +++ b/TEST_APPS/testcases/nanostack_mac_tester/send_data.py @@ -0,0 +1,66 @@ +""" +Copyright (c) 2017, Arm Limited and affiliates. +SPDX-License-Identifier: Apache-2.0 + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import os,sys +from icetea_lib.bench import Bench + +class Testcase(Bench): + def __init__(self): + Bench.__init__(self, name = "send_data", + title = "Simple data transmission test", + status = "development", + type = "smoke", + subtype = "", + execution = { + "skip": { + "value": False, + "reason": "" + } + }, + author = "Valtteri Erkkila", + purpose = "Tests that sending data works", + feature = ["MCPS-DATA"], + component = ["MAC"], + requirements = { + "duts": { + '*': { + "count":2, + "type": "hardware", + "allowed_platforms": ["K64F", "K66F", "NUCLEO_F429ZI", "KW24D", "UBLOX_EVK_ODIN_W2"], + "application": { + "name": "TEST_APPS-device-nanostack_mac_tester" + } + }, + "1":{"nick": "First"}, + "2":{"nick": "Second"} + }} + ) + + def setUp(self): + self.channel = 11 + self.command("First", "addr --64-bit 01:02:03:00:00:00:00:01") + self.command("Second", "addr --64-bit 01:02:03:00:00:00:00:02") + + def case(self): + self.command("First", "start --pan_coordinator true --logical_channel {}".format(self.channel)) + self.command("Second", "start --pan_coordinator false --logical_channel {}".format(self.channel)) + + self.command("First", "data --dst_addr 01:02:03:00:00:00:00:02 --msdu_length 5 --msdu abcde") + self.command("Second", "data --dst_addr 01:02:03:00:00:00:00:01 --msdu_length 5 --msdu 12345") + + def tearDown(self): + self.reset_dut() diff --git a/TEST_APPS/testcases/nanostack_mac_tester/send_data_indirect.py b/TEST_APPS/testcases/nanostack_mac_tester/send_data_indirect.py new file mode 100644 index 0000000000..241db37b4b --- /dev/null +++ b/TEST_APPS/testcases/nanostack_mac_tester/send_data_indirect.py @@ -0,0 +1,96 @@ +""" +Copyright (c) 2017, Arm Limited and affiliates. +SPDX-License-Identifier: Apache-2.0 + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import os,sys +from icetea_lib.bench import Bench + +class Testcase(Bench): + def __init__(self): + Bench.__init__(self, name = "send_data_indirect", + title = "Indirect data transmission test", + status = "development", + type = "smoke", + subtype = "", + execution = { + "skip": { + "value": False, + "reason": "" + } + }, + author = "Valtteri Erkkila", + purpose = "Tests sending data indirectly, i.e polling the coordinator for data", + feature = ["MCPS-DATA", "MLME-POLL"], + component = ["MAC"], + requirements = { + "duts": { + '*': { + "count":3, + "type": "hardware", + "allowed_platforms": ["K64F", "K66F", "NUCLEO_F429ZI", "KW24D", "UBLOX_EVK_ODIN_W2"], + "application": { + "name": "TEST_APPS-device-nanostack_mac_tester" + } + }, + "1":{"nick": "First"}, + "2":{"nick": "Second"}, + "3":{"nick": "Third"} + }} + ) + + def setUp(self): + self.channel = 11 + self.command("First", "addr --64-bit 01:02:03:00:00:00:00:01") + self.command("Second", "addr --64-bit 01:02:03:00:00:00:00:02") + self.command("Third", "addr --64-bit 01:02:03:00:00:00:00:03") + + def case(self): + self.command("First", "start --pan_coordinator true --logical_channel {}".format(self.channel)) + self.command("Second", "start --pan_coordinator false --logical_channel {}".format(self.channel)) + self.command("Third", "start --pan_coordinator false --logical_channel {}".format(self.channel)) + + #macRxOnWhenIdle + self.command("Second", "mlme-set --attr 0x52 --value_uint8 0 --value_size 1") + self.command("Third", "mlme-set --attr 0x52 --value_uint8 0 --value_size 1") + + self.command("First", "add-neigh --frame_ctr 0 --mac16 0xFFFF --mac64 01:02:03:00:00:00:00:02 --pan_id 0x1234 --index 0") + self.command("First", "add-neigh --frame_ctr 0 --mac16 0xFFFF --mac64 01:02:03:00:00:00:00:03 --pan_id 0x1234 --index 1") + self.command("Second", "add-neigh --frame_ctr 0 --mac16 0xFFFF --mac64 01:02:03:00:00:00:00:01 --pan_id 0x1234 --index 0") + self.command("Third", "add-neigh --frame_ctr 0 --mac16 0xFFFF --mac64 01:02:03:00:00:00:00:01 --pan_id 0x1234 --index 0") + + self.command("Second", "config-status --data_ind abcde") + self.command("Third", "config-status --data_ind 12345") + + #Runs into timing issues if extensive printing is enabled + self.command("*", "silent-mode on") + self.command("First", "data --dst_addr 01:02:03:00:00:00:00:02 --msdu_length 5 --msdu abcde --indirect_tx true --wait_for_confirm false") + self.command("Second", "poll --coord_address 01:02:03:00:00:00:00:01") + + self.command("First", "data") + self.command("First", "data") + self.command("Second", "poll") + self.command("Second", "poll") + self.command("Second", "config-status --poll 235") + self.command("Second", "poll") + + self.command("Second", "config-status --poll 235") + self.command("First", "data --dst_addr 01:02:03:00:00:00:00:03 --msdu 12345") + self.command("Second", "poll") + self.command("Third", "poll --coord_address 01:02:03:00:00:00:00:01") + self.command("*", "silent-mode off") + + def tearDown(self): + self.reset_dut() diff --git a/TEST_APPS/testcases/nanostack_mac_tester/send_large_payloads.py b/TEST_APPS/testcases/nanostack_mac_tester/send_large_payloads.py new file mode 100644 index 0000000000..32121f2493 --- /dev/null +++ b/TEST_APPS/testcases/nanostack_mac_tester/send_large_payloads.py @@ -0,0 +1,79 @@ +""" +Copyright (c) 2017, Arm Limited and affiliates. +SPDX-License-Identifier: Apache-2.0 + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import os,sys +from icetea_lib.bench import Bench + +class Testcase(Bench): + def __init__(self): + Bench.__init__(self, name = "send_large_payloads", + title = "Data transmission test with large packets", + status = "development", + type = "reliability", + subtype = "", + execution = { + "skip": { + "value": False, + "reason": "" + } + }, + author = "Valtteri Erkkila", + purpose = "Repeatedly sends long packets, checking that the payload is correct in each one", + feature = ["MCPS-DATA"], + component = ["MAC"], + requirements = { + "duts": { + '*': { + "count":2, + "type": "hardware", + "allowed_platforms": ["K64F", "K66F", "NUCLEO_F429ZI", "KW24D", "UBLOX_EVK_ODIN_W2"], + "application": { + "name": "TEST_APPS-device-nanostack_mac_tester" + } + }, + "1":{"nick": "First"}, + "2":{"nick": "Second"} + }} + ) + + def setUp(self): + self.channel = 11 + self.command("First", "addr --64-bit 01:02:03:00:00:00:00:01") + self.command("Second", "addr --64-bit 01:02:03:00:00:00:00:02") + + def case(self): + #104 characters, headers are 2+1+2+8+8+2=23 bytes, resulting in a packet size of 127 (max) + large_payload = "0123456789abcdefghjiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZZZZZZZZZ0123456789012345678901234567891234" + self.command("First", "start --pan_coordinator true --logical_channel {}".format(self.channel)) + self.command("Second", "start --pan_coordinator false --logical_channel {}".format(self.channel)) + + self.command("First", "config-status --data_ind {}".format(large_payload)) + self.command("Second", "config-status --data_ind {}".format(large_payload)) + + self.command("First", "data --dst_addr 01:02:03:00:00:00:00:02 --msdu_length {} --msdu {}".format(len(large_payload), large_payload)) + self.command("Second", "wait --timeout 500") + + self.command("Second", "data --dst_addr 01:02:03:00:00:00:00:01 --msdu_length {} --msdu {}".format(len(large_payload), large_payload)) + self.command("First", "wait --timeout 500") + for i in range(0, 25): + self.command("First", "data") + self.command("Second", "wait") + self.command("Second", "data") + self.command("First", "wait") + + def tearDown(self): + self.reset_dut() diff --git a/TEST_APPS/testcases/nanostack_mac_tester/template b/TEST_APPS/testcases/nanostack_mac_tester/template new file mode 100644 index 0000000000..4335851efd --- /dev/null +++ b/TEST_APPS/testcases/nanostack_mac_tester/template @@ -0,0 +1,65 @@ +""" +Copyright (c) 2017, Arm Limited and affiliates. +SPDX-License-Identifier: Apache-2.0 + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" +import os,sys +# ensure that test/ directory is first choice for imports +test_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +if not test_dir in sys.path: + sys.path.insert(0, test_dir) +from GenericTestcase import Bench +from Error import TestStepFail + +class Testcase(Bench): + def __init__(self): + Bench.__init__(self, name = "template", # Name should be the same as the filename + title = "TITLE", + status = "development", + type = "TYPE", + subtype = "", + execution = { + "skip": { + "value": False, + "reason": "" + } + }, + author = "Valtteri Erkkila", + purpose = "", + feature = [""], + component = ["MAC"], + requirements = { + "duts": { + '*': { + "count":2, # Count must reflect the amount of specified devices below + "type": "hardware", + "application":{ "name":"generalTestApplication", "version": "1.0"}, + "rf_channel": 11 + }, + "1":{"nick": "First"}, + "2":{"nick": "Second"} + }} + ) + + def setUp(self): + pass + + def case(self): + pass + + def tearDown(self): + pass + +if __name__=='__main__': + sys.exit( Testcase().run() ) diff --git a/TEST_APPS/testcases/netsocket/README.md b/TEST_APPS/testcases/netsocket/README.md new file mode 100644 index 0000000000..30c66ee337 --- /dev/null +++ b/TEST_APPS/testcases/netsocket/README.md @@ -0,0 +1,7 @@ +Netsocket tests +=============== + +This folder contains netsocket tests for Icetea +The tests located under this folder are dependent of the application [socket_app](https://github.com/ARMmbed/mbed-os/blob/master/TEST_APPS/device/socket_app) + +The test cases under this folder are defined in [Network Socket test plan](https://github.com/ARMmbed/mbed-os/blob/master/TESTS/netsocket/README.md) diff --git a/UNITTESTS/CMakeLists.txt b/UNITTESTS/CMakeLists.txt index 5b28cd46b6..15dcb0681e 100644 --- a/UNITTESTS/CMakeLists.txt +++ b/UNITTESTS/CMakeLists.txt @@ -90,17 +90,42 @@ endif(COVERAGE) set(unittest-includes-base "${PROJECT_SOURCE_DIR}/target_h" "${PROJECT_SOURCE_DIR}/target_h/events" + "${PROJECT_SOURCE_DIR}/target_h/events/equeue" + "${PROJECT_SOURCE_DIR}/target_h/platform" "${PROJECT_SOURCE_DIR}/stubs" "${PROJECT_SOURCE_DIR}/.." "${PROJECT_SOURCE_DIR}/../features" + "${PROJECT_SOURCE_DIR}/../features/netsocket" "${PROJECT_SOURCE_DIR}/../platform" "${PROJECT_SOURCE_DIR}/../drivers" "${PROJECT_SOURCE_DIR}/../hal" "${PROJECT_SOURCE_DIR}/../events" + "${PROJECT_SOURCE_DIR}/../events/equeue" + "${PROJECT_SOURCE_DIR}/../rtos" "${PROJECT_SOURCE_DIR}/../rtos/TARGET_CORTEX" "${PROJECT_SOURCE_DIR}/../rtos/TARGET_CORTEX/rtx5/Include" "${PROJECT_SOURCE_DIR}/../cmsis" - "${PROJECT_SOURCE_DIR}/../features/frameworks/nanostack-libservice/mbed-client-libservice/" + "${PROJECT_SOURCE_DIR}/../features/frameworks" + "${PROJECT_SOURCE_DIR}/../features/frameworks/mbed-trace" + "${PROJECT_SOURCE_DIR}/../features/frameworks/nanostack-libservice" + "${PROJECT_SOURCE_DIR}/../features/frameworks/nanostack-libservice/mbed-client-libservice" + "${PROJECT_SOURCE_DIR}/../features/filesystem/fat" + "${PROJECT_SOURCE_DIR}/../features/filesystem/fat/ChaN" + "${PROJECT_SOURCE_DIR}/../features/filesystem/bd" + "${PROJECT_SOURCE_DIR}/../features/filesystem/" + "${PROJECT_SOURCE_DIR}/../features/filesystem/littlefs" + "${PROJECT_SOURCE_DIR}/../features/filesystem/littlefs/littlefs" + "${PROJECT_SOURCE_DIR}/../features/cellular/framework/API" + "${PROJECT_SOURCE_DIR}/../features/cellular/framework/AT" + "${PROJECT_SOURCE_DIR}/../features/cellular/framework" + "${PROJECT_SOURCE_DIR}/../features/cellular/framework/common" + "${PROJECT_SOURCE_DIR}/../features/lorawan" + "${PROJECT_SOURCE_DIR}/../features/lorawan/lorastack" + "${PROJECT_SOURCE_DIR}/../features/lorawan/lorastack/mac" + "${PROJECT_SOURCE_DIR}/../features/lorawan/lorastack/phy" + "${PROJECT_SOURCE_DIR}/../features/lorawan/system" + "${PROJECT_SOURCE_DIR}/../features/mbedtls" + "${PROJECT_SOURCE_DIR}/../features/mbedtls/inc" ) # Create a list for test suites. @@ -129,11 +154,17 @@ foreach(testfile ${unittest-file-list}) # Get source files include("${testfile}") - if(TEST_SUITE_NAME) - set(TEST_SUITES ${TEST_SUITES} ${TEST_SUITE_NAME}) - else() - message(FATAL_ERROR "No TEST_SUITE_NAME found in test file. Add it to ${testfile}.") - endif() + get_filename_component(TEST_SUITE_DIR ${testfile} DIRECTORY) + + file(RELATIVE_PATH + TEST_SUITE_NAME # output + ${PROJECT_SOURCE_DIR} # root + ${TEST_SUITE_DIR} #abs dirpath + ) + + string(REGEX REPLACE "/|\\\\" "-" TEST_SUITE_NAME ${TEST_SUITE_NAME}) + + set(TEST_SUITES ${TEST_SUITES} ${TEST_SUITE_NAME}) set(LIBS_TO_BE_LINKED gmock_main) @@ -160,7 +191,7 @@ foreach(testfile ${unittest-file-list}) # Link the executable with the libraries. target_link_libraries(${TEST_SUITE_NAME} ${LIBS_TO_BE_LINKED}) - add_test(NAME "${TEST_SUITE_NAME}UnitTests" COMMAND ${TEST_SUITE_NAME}) + add_test(NAME "${TEST_SUITE_NAME}" COMMAND ${TEST_SUITE_NAME}) # Append test build directory to list list(APPEND BUILD_DIRECTORIES "./CMakeFiles/${TEST_SUITE_NAME}.dir") @@ -168,3 +199,4 @@ foreach(testfile ${unittest-file-list}) message(WARNING "No test source files found for ${TEST_SUITE_NAME}.\n") endif(unittest-test-sources) endforeach(testfile) + diff --git a/UNITTESTS/README.md b/UNITTESTS/README.md index 0ae44996f1..4d40a7120e 100644 --- a/UNITTESTS/README.md +++ b/UNITTESTS/README.md @@ -1,242 +1,107 @@ -# Unit testing Mbed OS +## Unit testing -This document describes how to run and write unit tests for Mbed OS. +This document describes how to write and test unit tests for Mbed OS. To prevent and solve problems, please see the [troubleshooting](#troubleshooting) section. -## Prerequisites +### Introduction -* GNU toolchains installed. - * GCC 6 or later - * MinGW-W64 GCC-6.4.0 or MinGW-W64 GCC-7.3.0 (Windows) -* CMake 3.0+ installed. -* Python 2.7.x or >3.5 and pip 10.0 (or newer) installed. -* gcovr >=4.1 +Unit tests test code in small sections on a host machine. Unlike other testing tools, unit testing doesn't require embedded hardware, and it doesn't need to build the full operating system. Because of this, unit testing can result in faster tests than other testing tools. Unit testing takes place in a build environment where we test each C or C++ class or module in isolation. This means we build test suites into separate test binaries and stub all access outside to remove dependencies on any specific embedded hardware or software combination. This allows us to complete the testing using native compilers on the build machine. -### Installing dependencies on Debian/Ubuntu +### Prerequisites + +Please install the following dependencies to use Mbed OS unit testing. + +- GNU toolchains. + - GCC 6 or later. We recommend you use MinGW-W64 on Windows, but any Windows port of the above GCC versions works. +- CMake 3.0 or newer. +- Python 2.7.x, 3.5 or newer. +- Pip 10.0 or newer. +- Gcovr 4.1 or newer. +- Mbed CLI 1.8.0 or newer. + +Detailed instructions for supported operating systems are below. + +#### Installing dependencies on Debian or Ubuntu 1. `sudo apt-get -y install build-essential cmake` -2. Install python and pip: -``` -sudo apt-get -y install python python-setuptools -sudo easy_install pip -``` -3. Install [gcovr](#installing-covr). -4. (Optional) Install [Mbed CLI](https://os.mbed.com/docs/latest/tools/arm-mbed-cli.html). +1. Install Python and Pip with: -### Installing dependencies on Mac OS + ``` + sudo apt-get -y install python python-setuptools + sudo easy_install pip + ``` + +1. Install Gcovr and [Mbed CLI](https://os.mbed.com/docs/latest/tools/arm-mbed-cli.html) with `pip install "gcovr>=4.1" mbed-cli`. + +#### Installing dependencies on macOS 1. Install [Homebrew](https://brew.sh/). -2. Install gcc compilers and cmake with: `brew install gcc cmake` -3. Install python and pip: -``` -brew install python -sudo easy_install pip -``` -3. Install [gcovr](#installing-covr). -4. (Optional) Install [Mbed CLI](https://os.mbed.com/docs/latest/tools/arm-mbed-cli.html). +1. Install GCC compilers and CMake with: `brew install gcc cmake`. +1. Install Python and Pip: -### Installing dependencies on Windows + ``` + brew install python + sudo easy_install pip + ``` + +1. Install Gcovr and [Mbed CLI](https://os.mbed.com/docs/latest/tools/arm-mbed-cli.html) with `pip install "gcovr>=4.1" mbed-cli`. + +#### Installing dependencies on Windows 1. Download and install [MinGW-W64](http://mingw-w64.org/). -2. Download CMake binaries from https://cmake.org/download/ and run the installer. -3. Download Python2.7 or Python3 from https://www.python.org/getit/ and run the installer. -4. Add MinGW, CMake and Python into PATH. -5. Install [gcovr](#installing-covr). -6. (Optional) Install [Mbed CLI](https://os.mbed.com/docs/latest/tools/arm-mbed-cli.html). +1. Download CMake binaries from https://cmake.org/download/, and run the installer. +1. Download Python 2.7 or Python 3 from https://www.python.org/getit/, and run the installer. +1. Add MinGW, CMake and Python into system PATH. +1. Install Gcovr and [Mbed CLI](https://os.mbed.com/docs/latest/tools/arm-mbed-cli.html) with `pip install "gcovr>=4.1" mbed-cli`. -### Installing covr +### Test code structure -Install gcovr code coverage tool globally with `pip install "gcovr>=4.1"` or using virtualenv: +Unit tests are located in the Mbed OS repository under the `UNITTESTS` folder. We recommend unit test files use an identical directory path to the file under test. This makes it easier to find unit tests for a particular class or a module. For example, if the file under test is `some/example/path/ClassName.cpp`, then all the test files are in the `UNITTESTS/some/example/path/ClassName` directory. Each test suite needs to have its own `unittest.cmake` file for test configuration. -#### virtualenv +#### Test discovery -1. Install virtualenv if not installed with `pip install virtualenv` -2. Install gcovr with: +Registering unit tests for running is automatic, and the test runner handles registration. However, test files are not automatically assigned to be built. We build unit tests by using a separate build system, which searches for unit tests under the `UNITTESTS` directory. -**[Debian/Linux/Mac OS]** -``` -virtualenv pyenv -. pyenv/bin/activate -pip install 'gcovr>=4.1' -``` -**[Windows]** -``` -virtualenv pyenv -pyenv\\Scripts\\activate -pip install "gcovr>=4.1" -``` +For the build system to find and build any test suite automatically, you must include a unit test configuration file named `unittest.cmake` for each unit test suite. This configuration file contains all the source files required for the build. -## Building and running unit tests +#### Test names -> In case of running into problems see [troubleshooting](#troubleshooting) section. +The build system automatically generates names of test suites. The name is constructed by taking a relative file path from the UNITTESTS directory to the test directory and replacing path separators with dashes. For example, the test suite name for `some/example/path/ClassName.cpp` is `some-example-path-ClassName`. Suite names are used when deciding which test suites to run. -`UNITTESTS/mbed_unittest.py` contains testing scripts for Mbed OS unit testing. Mbed CLI supports unit testing through `mbed test --unittests` command with the same arguments. +### Unit testing with Mbed CLI -### Testing with Mbed CLI +Mbed CLI supports unit tests through `mbed test --unittests` command. For information on using Mbed CLI, please see the [CLI documentation in handbook](https://os.mbed.com/docs/latest/tools/arm-mbed-cli.html). -``` -mbed test --unittests -``` +### Writing unit tests -A subset of tests can be run by providing `-r` flag for the tool which runs tests matching a regular expression. +Create two files in the test directory for each test suite: -e.g. `mbed test --unittests --run -r features-netsocket` +- Unit test source file (`test_ClassName.cpp`). +- Unit test configuration file (`unittest.cmake`). -### Build manually without Python tools +List all the files required for the build in the `unittest.cmake` file. We recommend you list the file paths relative to the `UNITTESTS` folder. Use the following variables to list the source files and include paths: -1. Create a build directory e.g. `mkdir UNITTESTS/build`. -2. Move to the build directory `cd UNITTESTS/build`. -3. Run CMake with `cmake [RELATIVE PATH TO UNITTESTS DIR] [OPTIONAL ARGUMENTS]` e.g. `cmake ..`: - * Add `-g [generator]` argument if target other than Unix Makefiles e.g. MinGW `-g "MinGW Makefiles"` -4. Run make program (make, gmake, mingw32-make, etc). +- **unittest-includes** - List of header include paths. You can use this to extend or overwrite default paths listed in CMakeLists.txt. +- **unittest-sources** - List of files under test. +- **unittest-test-sources** - List of test sources and stubs. -##### Run CMake and build Unix Makefiles (GNU make) - -``` -cmake .. -make -``` - -##### Run CMake and build MinGW Makefiles (mingw32-make) - -``` -cmake -G "MinGW Makefiles" .. -mingw32-make -``` - -#### Custom CMake variables - -Usage: -`cmake [RELATIVE PATH TO UNITTESTS DIR] [OPTIONS]` - -Keyword variables (usage `cmake -D(:)=`: - -| Variable | Type | Accepted values | Description | -| -------- | ---- | --------------- | ----------- | -| COVERAGE | STRING | merged
separate | Generate merged or individual reports | - -### Run in terminal - -Unit tests can be run separately from each executable or by using ctest test runner. Run ctest with make program using target test. Options can be passed to ctest using ARGS argument. See [ctest manual](https://cmake.org/cmake/help/v3.0/manual/ctest.1.html) for more information. - -Run ctest on test suite level: -``` -{MAKE_PROGRAM} test -C [RELATIVE PATH TO BUILD DIRECTORY] -``` -e.g. `make test -C UNITTESTS/build` or `mingw32-make test -C UNITTESTS/build` - -Run ctest verbose (show each test case): -``` -{MAKE_PROGRAM} test -C UNITTESTS/build ARGS="-V" -``` - -Run ctest dashboard test and create test results: -``` -{MAKE_PROGRAM} test --C UNITTESTS/build ARGS="-D ExperimentalTest" -``` - -### Run with GUI test runner - -1. Build and/or install *gtest-runner* using the documentation: https://github.com/nholthaus/gtest-runner - -2. Run the application, add built test executables into the list and run it. - -### Get code coverage - -Python tools use gcovr to build code coverage reports. Generate html report `UNITTESTS/build/coverage/index.html` with: -``` -mbed test --unittests --coverage html -``` - -To get coverage for a single test suite, run gcovr separately for suite coverage data directory. See [gcovr documentation](https://gcovr.com/guide.html#filter-options) for more information. - -e.g. for features/netsocket/InternetSocket coverage: - -Debian/Ubuntu/Mac OS: -``` -mkdir UNITTESTS/build -cd UNITTESTS/build -cmake -DCMAKE_BUILD_TYPE=Debug -DCOVERAGE:STRING=html .. -make -./features-netsocket-InternetSocket -gcovr -r ../.. --html --html-detail -o ./index.html ./CMakeFiles/features-netsocket-InternetSocket.MbedOS.dir/ -``` -Windows: -``` -mkdir UNITTESTS/build -cd UNITTESTS/build -cmake -DCMAKE_BUILD_TYPE=Debug -DCOVERAGE:STRING=html -g "MinGW Makefiles" .. -mingw32-make -features-netsocket-InternetSocket.exe -gcovr -r ..\.. --html --html-detail -o .\index.html .\CMakeFiles\features-netsocket-InternetSocket.MbedOS.dir\ -``` - -## The structure of unit tests - -The structure of the unit tests directory looks like this: -``` -UNITTESTS - ├── mbed_unittest.py Python tool for unit testing - ├── unit_test Python tool modules - ├── CMakeLists.txt CMake project definition file - ├── CMakeSettings.json CMake configurations for Visual Studio 2017 - ├── README.md - ├── googletest-CMakeLists.txt.in CMake project definition file for Google Test - │ - ├── features - │ └── netsocket Directory tree that mirrors Mbed OS root - │ ├── NetworkInterface Name of the class to be tested - │ │ ├── test_NetworkInterface.cpp - │ │ └── unittest.cmake CMake module for unit test - │ └── Socket - │ - ├── stubs Shared stubs which can be used for tests. - ├── target_h Shared headers which can be used for tests. - └── template Templates for creating new unittests -``` -Each unit test has an identical directory tree as seen in the Mbed OS root folder. This is not a mandatory requirement but helps to maintain tests. Each class to be tested have their own `unittest.cmake` which is found by `CMakeLists.txt`. - -## Creating a unit test - -Each class to be tested requires two files for unit testing: -1. C++ unit test source file (e.g. `test_NetworkInterface.cpp`) -2. CMake module file for unit test definition (`unittest.cmake`) - -A unit test definition file `unittest.cmake` requires variables to be set for a test to be configured. File source paths in `unittest.cmake` files need to be relative to the unit test folder and `CMakeLists.txt`. - -* **TEST_SUITE_NAME** - Identifier for the test suite. Use naming convention *PATH_TO_THE_TESTABLE_FILE* e.g. *features-netsocket-InternetSocket* -* **unittest-includes** - Include paths for headers needed to build the tests in addition to the base include paths listed in [CMakeLists.txt](CMakeLists.txt). Optional. -* **unittest-sources** - Mbed OS source files and stubs included for the build. -* **unittest-test-sources** - Unit test source files. - -#### Creating unit tests files with Mbed CLI - -``` -mbed test --unittests --new -``` - -E.g. `mbed test --unittests --new rtos/Semaphore.cpp` - -The generator script only creates the files required for a unit test. It does not write unit tests automatically nor does it handle source dependencies. - -#### Create files manually - -For example to create a unit test for `rtos/Semaphore.cpp`: +With the following steps, you can write a simple unit test. In this example, `rtos/Semaphore.cpp` is a class under test. 1. Create a directory for unit test files in `UNITTESTS/rtos/Semaphore`. -2. Create a test definition file `UNITTESTS/rtos/Semaphore/unittest.cmake` with the following content: -``` -set(TEST_SUITE_NAME "rtos-Semaphore") +1. Create a test configuration file `UNITTESTS/rtos/Semaphore/unittest.cmake` with the following content: -set(unittest-sources - stubs/mbed_assert.c - ../rtos/Semaphore.cpp -) + ``` + set(unittest-sources + ../rtos/Semaphore.cpp + ) + + set(unittest-test-sources + stubs/mbed_assert.c + rtos/Semaphore/test_Semaphore.cpp + ) + ``` + +1. Create a test source file `UNITTESTS/rtos/Semaphore/test_Semaphore.cpp` with the following content: -set(unittest-test-sources - rtos/Semaphore/test_Semaphore.cpp -) -``` -3. Create a test source file `UNITTESTS/rtos/Semaphore/test_Semaphore.cpp` with the following content: ``` #include "gtest/gtest.h" #include "rtos/Semaphore.h" @@ -287,8 +152,39 @@ TEST_F(TestSemaphore, constructor) } ``` -## Troubleshooting +### Building and running unit tests -**Problem:** virus protection identifies files generated by CMake as malicious and quarantines the files on Windows. +Use Mbed CLI to build and run unit tests. For advanced use, you can run CMake and a make program directly. -* **Solution**: restore the false positive files from the quarantine. +#### Build tests directly with CMake + +1. Create a build directory `mkdir UNITTESTS/build`. +1. Move to the build directory `cd UNITTESTS/build`. +1. Run CMake using a relative path to `UNITTESTS` folder as the argument. So from `UNITTESTS/build` use `cmake ..`: + - Add `-g [generator]` if generating other than Unix Makefiles such in case of MinGW use `-g "MinGW Makefiles"`. + - Add `-DCOVERAGE:True` to add coverage compiler flags. + - See the [CMake manual](https://cmake.org/cmake/help/v3.0/manual/cmake.1.html) for more information. +1. Run a make program (Make, Gmake, Mingw32-make and so on) to build the tests. + +#### Run tests directly with CTest + +Run a test binary in the build directory to run a unit test suite. To run multiple test suites at once, use CTest test runner. Run CTest with `ctest`. Add `-v` to get results for each test case. See the [CTest manual](https://cmake.org/cmake/help/v3.0/manual/ctest.1.html) for more information. + +#### Run tests with GUI test runner + +1. Install *gtest-runner* using the [documentation](https://github.com/nholthaus/gtest-runner). +1. Run *gtest-runner* +1. Add test executables into the list. +1. Run them. + +### Get code coverage + +Use Mbed CLI to generate code coverage reports. For advanced use, you can run Gcovr or any other code coverage tool directly in the build directory. + +### Troubleshooting + +**Problem:** Generic problems with CMake or with the build process. +* **Solution**: Delete the build directory. Make sure that CMake, g++, gcc and a make program can be found in the path and are correct versions. + +**Problem:** Virus protection identifies files generated by CMake as malicious and quarantines the files on Windows. +* **Solution**: Restore the false positive files from the quarantine. diff --git a/UNITTESTS/features/cellular/framework/AT/AT_CellularBase/test_at_cellularbase.cpp b/UNITTESTS/features/cellular/framework/AT/AT_CellularBase/test_at_cellularbase.cpp deleted file mode 100644 index 11d28a225c..0000000000 --- a/UNITTESTS/features/cellular/framework/AT/AT_CellularBase/test_at_cellularbase.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2018, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "gtest/gtest.h" -#include "test_at_cellularbase.h" -#include "EventQueue.h" -#include "AT_CellularBase.h" -#include "ATHandler_stub.h" -#include "FileHandle_stub.h" -#include - -using namespace mbed; -using namespace events; - -Test_AT_CellularBase::Test_AT_CellularBase() -{ - -} - -Test_AT_CellularBase::~Test_AT_CellularBase() -{ -} - -void Test_AT_CellularBase::test_AT_CellularBase_get_at_handler() -{ - EventQueue eq; - FileHandle_stub fh; - ATHandler ah(&fh, eq, 100, ","); - AT_CellularBase at(ah); - - EXPECT_EQ(&ah, &at.get_at_handler()); -} - -void Test_AT_CellularBase::test_AT_CellularBase_get_device_error() -{ - EventQueue eq; - FileHandle_stub fh; - ATHandler ah(&fh, eq, 0, ","); - AT_CellularBase at(ah); - - ATHandler_stub::device_err_value.errCode = 8; - - EXPECT_EQ(8, at.get_device_error().errCode); - - ATHandler_stub::device_err_value.errCode = 0; -} diff --git a/features/cellular/UNITTESTS/at/at_cellularbase/test_at_cellularbase.cpp b/UNITTESTS/features/cellular/framework/AT/at_cellularbase/at_cellularbasetest.cpp similarity index 71% rename from features/cellular/UNITTESTS/at/at_cellularbase/test_at_cellularbase.cpp rename to UNITTESTS/features/cellular/framework/AT/at_cellularbase/at_cellularbasetest.cpp index e69af7f28f..3537aa9c8a 100644 --- a/features/cellular/UNITTESTS/at/at_cellularbase/test_at_cellularbase.cpp +++ b/UNITTESTS/features/cellular/framework/AT/at_cellularbase/at_cellularbasetest.cpp @@ -14,8 +14,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "CppUTest/TestHarness.h" -#include "test_at_cellularbase.h" + +#include "gtest/gtest.h" +#include "AT_CellularBase.h" #include "EventQueue.h" #include "AT_CellularBase.h" #include "ATHandler_stub.h" @@ -57,26 +58,44 @@ public: } }; -Test_AT_CellularBase::Test_AT_CellularBase() -{ +// AStyle ignored as the definition is not clear due to preprocessor usage +// *INDENT-OFF* +class TestAT_CellularBase : public testing::Test { +protected: + void SetUp() + { + } + + void TearDown() + { + } +}; +// *INDENT-ON* + +TEST_F(TestAT_CellularBase, Create) +{ + EventQueue eq; + FileHandle_stub fh; + ATHandler ah(&fh, eq, 100, ","); + AT_CellularBase *unit = new AT_CellularBase(ah); + + EXPECT_TRUE(unit != NULL); + + delete unit; } -Test_AT_CellularBase::~Test_AT_CellularBase() -{ -} - -void Test_AT_CellularBase::test_AT_CellularBase_get_at_handler() +TEST_F(TestAT_CellularBase, test_AT_CellularBase_get_at_handler) { EventQueue eq; FileHandle_stub fh; ATHandler ah(&fh, eq, 100, ","); AT_CellularBase at(ah); - CHECK(&ah == &at.get_at_handler()); + EXPECT_TRUE(&ah == &at.get_at_handler()); } -void Test_AT_CellularBase::test_AT_CellularBase_get_device_error() +TEST_F(TestAT_CellularBase, test_AT_CellularBase_get_device_error) { EventQueue eq; FileHandle_stub fh; @@ -85,12 +104,12 @@ void Test_AT_CellularBase::test_AT_CellularBase_get_device_error() ATHandler_stub::device_err_value.errCode = 8; - CHECK_EQUAL(8, at.get_device_error().errCode); + EXPECT_EQ(8, at.get_device_error().errCode); ATHandler_stub::device_err_value.errCode = 0; } -void Test_AT_CellularBase::test_AT_CellularBase_set_unsupported_features() +TEST_F(TestAT_CellularBase, test_AT_CellularBase_set_unsupported_features) { EventQueue eq; FileHandle_stub fh; @@ -105,15 +124,14 @@ void Test_AT_CellularBase::test_AT_CellularBase_set_unsupported_features() at.set_unsupported_features(unsupported_features); } -void Test_AT_CellularBase::test_AT_CellularBase_is_supported() +TEST_F(TestAT_CellularBase, test_AT_CellularBase_is_supported) { EventQueue eq; FileHandle_stub fh; ATHandler ah(&fh, eq, 0, ","); my_base my_at(ah); - CHECK(true == my_at.check_supported()); - CHECK(true == my_at.check_supported_not_found()); - CHECK(false == my_at.check_not_supported()); - + EXPECT_TRUE(true == my_at.check_supported()); + EXPECT_TRUE(true == my_at.check_supported_not_found()); + EXPECT_TRUE(false == my_at.check_not_supported()); } diff --git a/UNITTESTS/features/cellular/framework/AT/AT_CellularBase/unittest.cmake b/UNITTESTS/features/cellular/framework/AT/at_cellularbase/unittest.cmake similarity index 74% rename from UNITTESTS/features/cellular/framework/AT/AT_CellularBase/unittest.cmake rename to UNITTESTS/features/cellular/framework/AT/at_cellularbase/unittest.cmake index 8229144a79..eab77c34eb 100644 --- a/UNITTESTS/features/cellular/framework/AT/AT_CellularBase/unittest.cmake +++ b/UNITTESTS/features/cellular/framework/AT/at_cellularbase/unittest.cmake @@ -3,9 +3,6 @@ # UNIT TESTS #################### -# Unit test suite name -set(TEST_SUITE_NAME "cellular-framework-AT-AT_CellularBase") - # Add test specific include paths set(unittest-includes ${unittest-includes} features/cellular/framework/AT/AT_CellularBase @@ -23,10 +20,9 @@ set(unittest-sources # Test files set(unittest-test-sources + features/cellular/framework/AT/at_cellularbase/at_cellularbasetest.cpp stubs/mbed_assert_stub.c stubs/ATHandler_stub.cpp stubs/EventQueue_stub.cpp stubs/FileHandle_stub.cpp - features/cellular/framework/AT/AT_CellularBase/test_at_cellularbase.cpp - features/cellular/framework/AT/AT_CellularBase/at_cellularbasetest.cpp ) diff --git a/UNITTESTS/features/cellular/framework/AT/at_cellulardevice/at_cellulardevicetest.cpp b/UNITTESTS/features/cellular/framework/AT/at_cellulardevice/at_cellulardevicetest.cpp new file mode 100644 index 0000000000..7ab8f742f3 --- /dev/null +++ b/UNITTESTS/features/cellular/framework/AT/at_cellulardevice/at_cellulardevicetest.cpp @@ -0,0 +1,277 @@ +/* + * Copyright (c) 2018, Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "gtest/gtest.h" +#include "AT_CellularDevice.h" +#include "ATHandler_stub.h" +#include "AT_CellularBase_stub.h" +#include + +using namespace mbed; +using namespace events; + +class TestAT_CellularDevice : public testing::Test { +protected: + + void SetUp() { + } + + void TearDown() { + } +}; + +TEST_F(TestAT_CellularDevice, Create) +{ + EventQueue que; + AT_CellularDevice dev(que); + + CellularDevice *dev2 = new AT_CellularDevice(que); + + EXPECT_TRUE(dev2 != NULL); + delete dev2; +} + +TEST_F(TestAT_CellularDevice, test_AT_CellularDevice_get_at_handler) +{ + EventQueue que; + AT_CellularDevice dev(que); + FileHandle_stub fh1; + FileHandle_stub fh2; + FileHandle_stub fh3; + + EXPECT_TRUE(dev.open_network(&fh1)); + EXPECT_TRUE(dev.open_sms(&fh2)); + AT_CellularBase_stub::handler_value = AT_CellularBase_stub::handler_at_constructor_value; + EXPECT_TRUE(dev.open_sim(&fh3)); + ATHandler_stub::fh_value = &fh1; + EXPECT_TRUE(dev.open_power(&fh1)); + + ATHandler_stub::fh_value = NULL; +} + +TEST_F(TestAT_CellularDevice, test_AT_CellularDevice_open_network) +{ + EventQueue que; + AT_CellularDevice dev(que); + FileHandle_stub fh1; + + EXPECT_TRUE(!dev.open_network(NULL)); + EXPECT_TRUE(dev.open_network(&fh1)); +} + +TEST_F(TestAT_CellularDevice, test_AT_CellularDevice_open_sms) +{ + EventQueue que; + AT_CellularDevice dev(que); + FileHandle_stub fh1; + + EXPECT_TRUE(!dev.open_sms(NULL)); + EXPECT_TRUE(dev.open_sms(&fh1)); +} + +TEST_F(TestAT_CellularDevice, test_AT_CellularDevice_open_power) +{ + EventQueue que; + AT_CellularDevice dev(que); + FileHandle_stub fh1; + + EXPECT_TRUE(!dev.open_power(NULL)); + EXPECT_TRUE(dev.open_power(&fh1)); +} + +TEST_F(TestAT_CellularDevice, test_AT_CellularDevice_open_sim) +{ + EventQueue que; + AT_CellularDevice dev(que); + FileHandle_stub fh1; + + EXPECT_TRUE(! dev.open_sim(NULL)); + EXPECT_TRUE(dev.open_sim(&fh1)); +} + +TEST_F(TestAT_CellularDevice, test_AT_CellularDevice_open_information) +{ + EventQueue que; + AT_CellularDevice dev(que); + FileHandle_stub fh1; + + EXPECT_TRUE(!dev.open_information(NULL)); + EXPECT_TRUE(dev.open_information(&fh1)); +} + +TEST_F(TestAT_CellularDevice, test_AT_CellularDevice_close_network) +{ + EventQueue que; + AT_CellularDevice dev(que); + FileHandle_stub fh1; + ATHandler_stub::ref_count = 0; + + EXPECT_TRUE(dev.open_network(&fh1)); + AT_CellularBase_stub::handler_value = AT_CellularBase_stub::handler_at_constructor_value; + EXPECT_TRUE(ATHandler_stub::ref_count == 1); + + dev.close_network(); + EXPECT_TRUE(ATHandler_stub::ref_count == kATHandler_destructor_ref_ount); +} + +TEST_F(TestAT_CellularDevice, test_AT_CellularDevice_close_sms) +{ + EventQueue que; + AT_CellularDevice dev(que); + FileHandle_stub fh1; + ATHandler_stub::ref_count = 0; + + EXPECT_TRUE(dev.open_sms(&fh1)); + AT_CellularBase_stub::handler_value = AT_CellularBase_stub::handler_at_constructor_value; + EXPECT_TRUE(ATHandler_stub::ref_count == 1); + + dev.close_sms(); + EXPECT_TRUE(ATHandler_stub::ref_count == kATHandler_destructor_ref_ount); +} + +TEST_F(TestAT_CellularDevice, test_AT_CellularDevice_close_power) +{ + EventQueue que; + AT_CellularDevice dev(que); + FileHandle_stub fh1; + ATHandler_stub::ref_count = 0; + + EXPECT_TRUE(dev.open_power(&fh1)); + AT_CellularBase_stub::handler_value = AT_CellularBase_stub::handler_at_constructor_value; + EXPECT_TRUE(ATHandler_stub::ref_count == 1); + + dev.close_power(); + EXPECT_TRUE(ATHandler_stub::ref_count == kATHandler_destructor_ref_ount); +} + +TEST_F(TestAT_CellularDevice, test_AT_CellularDevice_close_sim) +{ + EventQueue que; + AT_CellularDevice dev(que); + FileHandle_stub fh1; + ATHandler_stub::ref_count = 0; + int ana = 0; + + EXPECT_TRUE(dev.open_sim(&fh1)); + AT_CellularBase_stub::handler_value = AT_CellularBase_stub::handler_at_constructor_value; + + ana = ATHandler_stub::ref_count; + + dev.close_sms(); // this should not affect to refcount as it's not opened + EXPECT_TRUE(ATHandler_stub::ref_count == 1); + ana = ATHandler_stub::ref_count; + + dev.close_sim(); + EXPECT_TRUE(ATHandler_stub::ref_count == kATHandler_destructor_ref_ount); +} + +TEST_F(TestAT_CellularDevice, test_AT_CellularDevice_close_information) +{ + EventQueue que; + AT_CellularDevice dev(que); + FileHandle_stub fh1; + ATHandler_stub::int_value = 0; + + EXPECT_TRUE(dev.open_information(&fh1)); + + ATHandler_stub::fh_value = NULL; + AT_CellularBase_stub::handler_value = NULL; + dev.close_information(); + + ATHandler_stub::fh_value = &fh1; + ATHandler at(&fh1, que, 0, ","); + AT_CellularBase_stub::handler_value = &at; + + EXPECT_TRUE(dev.open_information(&fh1)); + AT_CellularBase_stub::handler_value = AT_CellularBase_stub::handler_at_constructor_value; + + dev.close_information(); + EXPECT_TRUE(ATHandler_stub::ref_count == 1); + + ATHandler_stub::fh_value = NULL; +} + +TEST_F(TestAT_CellularDevice, test_AT_CellularDevice_set_timeout) +{ + EventQueue que; + AT_CellularDevice dev(que); + FileHandle_stub fh1; + ATHandler_stub::timeout = 0; + ATHandler_stub::default_timeout = false; + + // no interfaces open so settings timeout should not change anything + dev.set_timeout(5000); + EXPECT_TRUE(ATHandler_stub::timeout == 0); + EXPECT_TRUE(ATHandler_stub::default_timeout == false); + + EXPECT_TRUE(dev.open_sim(&fh1)); + EXPECT_TRUE(ATHandler_stub::ref_count == 1); + + dev.set_timeout(5000); + EXPECT_TRUE(ATHandler_stub::timeout == 5000); + EXPECT_TRUE(ATHandler_stub::default_timeout == true); + + dev.close_sim(); +} + +TEST_F(TestAT_CellularDevice, test_AT_CellularDevice_modem_debug_on) +{ + EventQueue que; + AT_CellularDevice dev(que); + FileHandle_stub fh1; + ATHandler_stub::debug_on = false; + + // no interfaces open so debug toggling should not affect + dev.modem_debug_on(true); + EXPECT_TRUE(ATHandler_stub::debug_on == false); + + EXPECT_TRUE(dev.open_sim(&fh1)); + EXPECT_TRUE(ATHandler_stub::ref_count == 1); + + dev.modem_debug_on(true); + EXPECT_TRUE(ATHandler_stub::debug_on == true); + + dev.close_sim(); +} + +TEST_F(TestAT_CellularDevice, test_AT_CellularDevice_get_stack) +{ + EventQueue que; + AT_CellularDevice dev(que); + FileHandle_stub fh1; + + NetworkStack *stack = dev.get_stack(); + EXPECT_TRUE(stack == NULL); + + EXPECT_TRUE(dev.open_network(&fh1)); + + stack = dev.get_stack(); + EXPECT_TRUE(stack == NULL); // Not in PPP so also null but this is got from the network class +} + +TEST_F(TestAT_CellularDevice, test_AT_CellularDevice_get_send_delay) +{ + EventQueue que; + AT_CellularDevice dev(que); + EXPECT_TRUE(0 == dev.get_send_delay()); +} + +TEST_F(TestAT_CellularDevice, test_AT_CellularDevice_init_module) +{ + EventQueue que; + AT_CellularDevice dev(que); + EXPECT_TRUE(NSAPI_ERROR_OK == dev.init_module(NULL)); +} diff --git a/UNITTESTS/features/cellular/framework/AT/at_cellulardevice/unittest.cmake b/UNITTESTS/features/cellular/framework/AT/at_cellulardevice/unittest.cmake new file mode 100644 index 0000000000..ca2c9c87be --- /dev/null +++ b/UNITTESTS/features/cellular/framework/AT/at_cellulardevice/unittest.cmake @@ -0,0 +1,35 @@ + +#################### +# UNIT TESTS +#################### + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + features/cellular/framework/common/util + ../features/cellular/framework/common + ../features/cellular/framework/AT + ../features/frameworks/mbed-client-randlib/mbed-client-randlib +) + +# Source files +set(unittest-sources + stubs/randLIB_stub.c + ../features/cellular/framework/AT/AT_CellularDevice.cpp +) + +# Test files +set(unittest-test-sources + features/cellular/framework/AT/at_cellulardevice/at_cellulardevicetest.cpp + stubs/AT_CellularNetwork_stub.cpp + stubs/ATHandler_stub.cpp + stubs/AT_CellularSMS_stub.cpp + stubs/AT_CellularSIM_stub.cpp + stubs/AT_CellularPower_stub.cpp + stubs/AT_CellularInformation_stub.cpp + stubs/CellularUtil_stub.cpp + stubs/AT_CellularBase_stub.cpp + stubs/NetworkInterface_stub.cpp + stubs/EventQueue_stub.cpp + stubs/FileHandle_stub.cpp + stubs/mbed_assert_stub.c +) diff --git a/features/cellular/UNITTESTS/at/at_cellularinformation/test_at_cellularinformation.cpp b/UNITTESTS/features/cellular/framework/AT/at_cellularinformation/at_cellularinformationtest.cpp similarity index 53% rename from features/cellular/UNITTESTS/at/at_cellularinformation/test_at_cellularinformation.cpp rename to UNITTESTS/features/cellular/framework/AT/at_cellularinformation/at_cellularinformationtest.cpp index 221ee054f9..0a6d649e74 100644 --- a/features/cellular/UNITTESTS/at/at_cellularinformation/test_at_cellularinformation.cpp +++ b/UNITTESTS/features/cellular/framework/AT/at_cellularinformation/at_cellularinformationtest.cpp @@ -14,8 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "CppUTest/TestHarness.h" -#include "test_at_cellularinformation.h" +#include "gtest/gtest.h" #include #include "ATHandler_stub.h" #include "EventQueue.h" @@ -28,16 +27,32 @@ using namespace mbed; using namespace events; -Test_AT_CellularInformation::Test_AT_CellularInformation() -{ +// AStyle ignored as the definition is not clear due to preprocessor usage +// *INDENT-OFF* +class TestAT_CellularInformation : public testing::Test { +protected: + void SetUp() + { + } + + void TearDown() + { + } +}; +// *INDENT-ON* + +TEST_F(TestAT_CellularInformation, Create) +{ + EventQueue eq; + FileHandle_stub fh; + ATHandler ah(&fh, eq, 0, ","); + AT_CellularInformation *unit = new AT_CellularInformation(ah); + EXPECT_TRUE(unit != NULL); + delete unit; } -Test_AT_CellularInformation::~Test_AT_CellularInformation() -{ -} - -void Test_AT_CellularInformation::test_AT_CellularInformation_get_manufacturer() +TEST_F(TestAT_CellularInformation, test_AT_CellularInformation_get_manufacturer) { EventQueue eq; FileHandle_stub fh; @@ -45,21 +60,21 @@ void Test_AT_CellularInformation::test_AT_CellularInformation_get_manufacturer() AT_CellularInformation aci(ah); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::read_string_value = "some"; + ATHandler_stub::read_string_value = (char *)"some"; ATHandler_stub::ssize_value = 4; char buf[8]; - CHECK(NSAPI_ERROR_OK == aci.get_manufacturer(buf, 8)); - CHECK(strcmp("some", buf) == 0); + EXPECT_TRUE(NSAPI_ERROR_OK == aci.get_manufacturer(buf, 8)); + EXPECT_TRUE(strcmp("some", buf) == 0); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; ATHandler_stub::ssize_value = -1; buf[0] = 0; - CHECK(NSAPI_ERROR_DEVICE_ERROR == aci.get_manufacturer(buf, 8)); - CHECK(strlen(buf) == 0); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == aci.get_manufacturer(buf, 8)); + EXPECT_TRUE(strlen(buf) == 0); } -void Test_AT_CellularInformation::test_AT_CellularInformation_get_model() +TEST_F(TestAT_CellularInformation, test_AT_CellularInformation_get_model) { EventQueue eq; FileHandle_stub fh; @@ -67,20 +82,20 @@ void Test_AT_CellularInformation::test_AT_CellularInformation_get_model() AT_CellularInformation aci(ah); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::read_string_value = "model"; + ATHandler_stub::read_string_value = (char *)"model"; ATHandler_stub::ssize_value = 5; char buf[8]; - CHECK(NSAPI_ERROR_OK == aci.get_model(buf, 8)); - CHECK(strcmp("model", buf) == 0); + EXPECT_TRUE(NSAPI_ERROR_OK == aci.get_model(buf, 8)); + EXPECT_TRUE(strcmp("model", buf) == 0); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; ATHandler_stub::ssize_value = -1; buf[0] = 0; - CHECK(NSAPI_ERROR_DEVICE_ERROR == aci.get_model(buf, 8)); - CHECK(strlen(buf) == 0); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == aci.get_model(buf, 8)); + EXPECT_TRUE(strlen(buf) == 0); } -void Test_AT_CellularInformation::test_AT_CellularInformation_get_revision() +TEST_F(TestAT_CellularInformation, test_AT_CellularInformation_get_revision) { EventQueue eq; FileHandle_stub fh; @@ -90,23 +105,23 @@ void Test_AT_CellularInformation::test_AT_CellularInformation_get_revision() AT_CellularInformation *aci = new AT_CellularInformation(ah); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::read_string_value = "revision"; + ATHandler_stub::read_string_value = (char *)"revision"; ATHandler_stub::ssize_value = 8; char buf[9]; - CHECK(NSAPI_ERROR_OK == aci->get_revision(buf, 9)); - CHECK(strcmp("revision", buf) == 0); + EXPECT_TRUE(NSAPI_ERROR_OK == aci->get_revision(buf, 9)); + EXPECT_TRUE(strcmp("revision", buf) == 0); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; ATHandler_stub::ssize_value = -1; buf[0] = 0; - CHECK(NSAPI_ERROR_DEVICE_ERROR == aci->get_revision(buf, 8)); - CHECK(strlen(buf) == 0); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == aci->get_revision(buf, 8)); + EXPECT_TRUE(strlen(buf) == 0); delete aci; } -void Test_AT_CellularInformation::test_AT_CellularInformation_get_serial_number() +TEST_F(TestAT_CellularInformation, test_AT_CellularInformation_get_serial_number) { EventQueue eq; FileHandle_stub fh; @@ -114,28 +129,27 @@ void Test_AT_CellularInformation::test_AT_CellularInformation_get_serial_number( AT_CellularInformation aci(ah); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::read_string_value = "1234567"; + ATHandler_stub::read_string_value = (char *)"1234567"; ATHandler_stub::ssize_value = 7; char buf[8]; - CHECK(NSAPI_ERROR_OK == aci.get_serial_number(buf, 8, CellularInformation::SN)); - CHECK(strcmp("1234567", buf) == 0); + EXPECT_TRUE(NSAPI_ERROR_OK == aci.get_serial_number(buf, 8, CellularInformation::SN)); + EXPECT_TRUE(strcmp("1234567", buf) == 0); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; ATHandler_stub::ssize_value = -1; buf[0] = 0; - CHECK(NSAPI_ERROR_DEVICE_ERROR == aci.get_serial_number(buf, 8, CellularInformation::SN)); - CHECK(strlen(buf) == 0); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == aci.get_serial_number(buf, 8, CellularInformation::SN)); + EXPECT_TRUE(strlen(buf) == 0); AT_CellularBase_stub::supported_bool = false; - CHECK(NSAPI_ERROR_UNSUPPORTED == aci.get_serial_number(buf, 8, CellularInformation::IMEI)); - CHECK(strlen(buf) == 0); + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == aci.get_serial_number(buf, 8, CellularInformation::IMEI)); + EXPECT_TRUE(strlen(buf) == 0); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::read_string_value = "1234567"; + ATHandler_stub::read_string_value = (char *)"1234567"; ATHandler_stub::ssize_value = 7; AT_CellularBase_stub::supported_bool = true; - CHECK(NSAPI_ERROR_OK == aci.get_serial_number(buf, 8, CellularInformation::IMEI)); - CHECK(strcmp("1234567", buf) == 0); + EXPECT_TRUE(NSAPI_ERROR_OK == aci.get_serial_number(buf, 8, CellularInformation::IMEI)); + EXPECT_TRUE(strcmp("1234567", buf) == 0); } - diff --git a/UNITTESTS/features/cellular/framework/AT/at_cellularinformation/unittest.cmake b/UNITTESTS/features/cellular/framework/AT/at_cellularinformation/unittest.cmake new file mode 100644 index 0000000000..57748f5e83 --- /dev/null +++ b/UNITTESTS/features/cellular/framework/AT/at_cellularinformation/unittest.cmake @@ -0,0 +1,28 @@ + +#################### +# UNIT TESTS +#################### + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + features/cellular/framework/common/util + ../features/cellular/framework/common + ../features/cellular/framework/AT + ../features/frameworks/mbed-client-randlib/mbed-client-randlib +) + +# Source files +set(unittest-sources + stubs/randLIB_stub.c + ../features/cellular/framework/AT/AT_CellularInformation.cpp +) + +# Test files +set(unittest-test-sources + features/cellular/framework/AT//at_cellularinformation/at_cellularinformationtest.cpp + stubs/ATHandler_stub.cpp + stubs/AT_CellularBase_stub.cpp + stubs/EventQueue_stub.cpp + stubs/FileHandle_stub.cpp + stubs/mbed_assert_stub.c +) diff --git a/UNITTESTS/features/cellular/framework/AT/at_cellularnetwork/at_cellularnetworktest.cpp b/UNITTESTS/features/cellular/framework/AT/at_cellularnetwork/at_cellularnetworktest.cpp new file mode 100644 index 0000000000..a498db66f8 --- /dev/null +++ b/UNITTESTS/features/cellular/framework/AT/at_cellularnetwork/at_cellularnetworktest.cpp @@ -0,0 +1,1166 @@ +/* + * Copyright (c) 2018, Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "gtest/gtest.h" +#include +#include "AT_CellularNetwork.h" +#include "EventQueue.h" +#include "ATHandler.h" +#include "AT_CellularDevice.h" +#include "FileHandle_stub.h" +#include "CellularLog.h" +#include "ATHandler_stub.h" +#include "AT_CellularStack.h" + +using namespace mbed; +using namespace events; + +// AStyle ignored as the definition is not clear due to preprocessor usage +// *INDENT-OFF* +class TestAT_CellularNetwork : public testing::Test { +protected: + + void SetUp() + { + ATHandler_stub::int_count = kRead_int_table_size; + ATHandler_stub::read_string_index = kRead_string_table_size; + ATHandler_stub::resp_stop_success_count = kResp_stop_count_default; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::int_value = -1; + } + + void TearDown() + { + } +}; +// *INDENT-ON* +class my_stack : public AT_CellularStack { +public: + my_stack(ATHandler &atHandler) : AT_CellularStack(atHandler, 1, IPV4_STACK) {} + virtual int get_max_socket_count() + { + return 1; + } + virtual int get_max_packet_size() + { + return 200; + } + virtual bool is_protocol_supported(nsapi_protocol_t protocol) + { + return true; + } + virtual nsapi_error_t socket_close_impl(int sock_id) + { + return NSAPI_ERROR_OK; + } + virtual nsapi_error_t create_socket_impl(CellularSocket *socket) + { + return NSAPI_ERROR_OK; + } + virtual nsapi_size_or_error_t socket_sendto_impl(CellularSocket *socket, const SocketAddress &address, + const void *data, nsapi_size_t size) + { + return 100; + } + virtual nsapi_size_or_error_t socket_recvfrom_impl(CellularSocket *socket, SocketAddress *address, + void *buffer, nsapi_size_t size) + { + return 100; + } +}; + +class my_AT_CN : public AT_CellularNetwork { +public: + my_AT_CN(ATHandler &atHandler) : AT_CellularNetwork(atHandler) {} + virtual ~my_AT_CN() {} + NetworkStack *get_stack() + { + if (!_stack) { + return new my_stack(get_at_handler()); + } else { + return _stack; + } + } + virtual AT_CellularNetwork::RegistrationMode has_registration(RegistrationType reg_type) + { + if (reg_type == C_GREG) { + return RegistrationModeDisable; + } + return RegistrationModeEnable; + } + virtual nsapi_error_t set_access_technology_impl(RadioAccessTechnology op_rat) + { + return NSAPI_ERROR_OK; + } + virtual bool get_modem_stack_type(nsapi_ip_stack_t requested_stack) + { + if (requested_stack == IPV4_STACK || requested_stack == DEFAULT_STACK) { + return true; + } + return false; + } +}; + +class my_AT_CNipv6 : public AT_CellularNetwork { +public: + my_AT_CNipv6(ATHandler &atHandler) : AT_CellularNetwork(atHandler) {} + virtual ~my_AT_CNipv6() {} + NetworkStack *get_stack() + { + if (!_stack) { + return new my_stack(get_at_handler()); + } else { + return _stack; + } + } + virtual AT_CellularNetwork::RegistrationMode has_registration(RegistrationType reg_type) + { + if (reg_type == C_GREG) { + return RegistrationModeDisable; + } + return RegistrationModeEnable; + } + virtual nsapi_error_t set_access_technology_impl(RadioAccessTechnology op_rat) + { + return NSAPI_ERROR_OK; + } + virtual bool get_modem_stack_type(nsapi_ip_stack_t requested_stack) + { + if (requested_stack == IPV6_STACK || requested_stack == DEFAULT_STACK) { + return true; + } + return false; + } +}; + +static int network_cb_count; +static void network_cb(nsapi_event_t ev, intptr_t intptr) +{ + network_cb_count++; +} + +TEST_F(TestAT_CellularNetwork, Create) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork *cn = new AT_CellularNetwork(at); + EXPECT_TRUE(cn != NULL); + delete cn; +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_init) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + AT_CellularNetwork cn(at); + + EXPECT_TRUE(NSAPI_ERROR_OK == cn.init()); + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_NO_MEMORY; + EXPECT_TRUE(NSAPI_ERROR_NO_MEMORY == cn.init()); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_set_credentials) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork *cnn = new AT_CellularNetwork(at); + delete cnn; + + AT_CellularNetwork cn(at); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_credentials("apn")); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_credentials("apn", CellularNetwork::CHAP)); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_credentials("apn", CellularNetwork::CHAP, NULL)); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_credentials("apn", CellularNetwork::CHAP, NULL, NULL)); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_credentials("apn", CellularNetwork::CHAP, NULL, "passwd")); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_credentials("apn", CellularNetwork::CHAP, "user", NULL)); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_credentials("apn", CellularNetwork::CHAP, "user")); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_credentials("apn", CellularNetwork::CHAP, "user", "passwd")); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_credentials("apn", NULL)); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_credentials("apn", NULL, NULL)); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_credentials("apn", NULL, "passwd")); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_credentials("apn", "user", NULL)); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_credentials("apn", "user")); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_credentials("apn", "user", "passwd")); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_activate_context) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + my_AT_CN my_cn(at); + my_AT_CNipv6 my_cnipv6(at); + + // get_context return true and new context created. But now stack and so error. + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == cn.activate_context()); + + // get_context return true and new context created, also do_user_authentication called with success. + // But now stack and so error. + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_credentials("apn", CellularNetwork::CHAP, "user", "passwd")); + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == cn.activate_context()); + + // get_context return true and new context created, also do_user_authentication called with failure. + ATHandler_stub::resp_stop_success_count = 2; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.set_credentials("apn", CellularNetwork::CHAP, "user", "passwd")); + EXPECT_TRUE(NSAPI_ERROR_AUTH_FAILURE == my_cn.activate_context()); + + // get_context return true and new context created, also do_user_authentication called with success. + // Now there is stack. + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + ATHandler_stub::resp_stop_success_count = kResp_stop_count_default; + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.set_credentials("apn", CellularNetwork::CHAP, "user", "passwd")); + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.activate_context()); + + // get_context return true and new context created, test delete context + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + ATHandler_stub::resp_stop_success_count = kResp_stop_count_default; + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.set_credentials("apn", CellularNetwork::CHAP, "user", "passwd")); + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.activate_context()); + + + + // get_context pdp type gives zero len, fails with no stack + ATHandler_stub::resp_info_true_counter = 1; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + ATHandler_stub::read_string_index = 1; + ATHandler_stub::read_string_table[0] = (char *)""; + ATHandler_stub::int_value = 1; + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == cn.activate_context()); + + // get_context pdp type gives proper type, apn reading fails + ATHandler_stub::resp_info_true_counter = 1; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + ATHandler_stub::read_string_index = 1; + ATHandler_stub::read_string_table[0] = (char *)"IPV6"; + ATHandler_stub::int_value = 1; + EXPECT_TRUE(NSAPI_ERROR_NO_CONNECTION == cn.activate_context()); + + // get_context pdp type gives proper type, apn does not match, now other contexts so new one created + ATHandler_stub::resp_info_true_counter = 1; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + ATHandler_stub::read_string_index = 2; + ATHandler_stub::read_string_table[0] = (char *)"internet"; + ATHandler_stub::read_string_table[1] = (char *)"IP"; + ATHandler_stub::int_value = 1; + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.set_credentials("apn", CellularNetwork::CHAP, "user", "passwd")); + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.activate_context()); + + // get_context pdp type gives proper type, apn match + ATHandler_stub::resp_info_true_counter = 2; // set to 2 so cgact will give that this context is active + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + ATHandler_stub::read_string_index = 2; + ATHandler_stub::read_string_table[0] = (char *)"internet"; + ATHandler_stub::read_string_table[1] = (char *)"IPV4V6"; + ATHandler_stub::int_value = 1; + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.set_stack_type(IPV4_STACK)); + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.set_credentials("internet")); + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.activate_context()); + + // get_context pdp type gives proper type, apn match + ATHandler_stub::resp_info_true_counter = 1; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + ATHandler_stub::read_string_index = 2; + ATHandler_stub::read_string_table[0] = (char *)"internet"; + ATHandler_stub::read_string_table[1] = (char *)"IPV6"; + ATHandler_stub::int_value = 1; + EXPECT_TRUE(NSAPI_ERROR_OK == my_cnipv6.set_stack_type(IPV6_STACK)); + EXPECT_TRUE(NSAPI_ERROR_OK == my_cnipv6.set_credentials("internet")); + EXPECT_TRUE(NSAPI_ERROR_OK == my_cnipv6.activate_context()); + + // get_context pdp type gives proper type, apn match + ATHandler_stub::resp_info_true_counter = 1; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + ATHandler_stub::read_string_index = 2; + ATHandler_stub::read_string_table[0] = (char *)"internet"; + ATHandler_stub::read_string_table[1] = (char *)"IPV4V6"; + ATHandler_stub::int_value = 1; + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.set_stack_type(DEFAULT_STACK)); + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.set_credentials("internet")); + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.activate_context()); + + // get_context pdp type gives proper type, apn match + ATHandler_stub::resp_info_true_counter = 1; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + ATHandler_stub::read_string_index = 2; + ATHandler_stub::read_string_table[0] = (char *)"internet"; + ATHandler_stub::read_string_table[1] = (char *)"IPV4V6"; + ATHandler_stub::int_value = 1; + EXPECT_TRUE(NSAPI_ERROR_OK == my_cnipv6.set_stack_type(DEFAULT_STACK)); + EXPECT_TRUE(NSAPI_ERROR_OK == my_cnipv6.set_credentials("internet")); + EXPECT_TRUE(NSAPI_ERROR_OK == my_cnipv6.activate_context()); + + // get_context pdp type gives proper type, apn match + ATHandler_stub::resp_info_true_counter = 1; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + ATHandler_stub::read_string_index = 2; + ATHandler_stub::read_string_table[0] = (char *)"internet"; + ATHandler_stub::read_string_table[1] = (char *)"IPV6"; + ATHandler_stub::int_value = 1; + EXPECT_TRUE(NSAPI_ERROR_OK == my_cnipv6.set_stack_type(DEFAULT_STACK)); + EXPECT_TRUE(NSAPI_ERROR_OK == my_cnipv6.set_credentials("internet")); + EXPECT_TRUE(NSAPI_ERROR_OK == my_cnipv6.activate_context()); + + // get_context pdp type gives proper type, apn match + ATHandler_stub::resp_info_true_counter = 1; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + ATHandler_stub::read_string_index = 2; + ATHandler_stub::read_string_table[0] = (char *)"internet"; + ATHandler_stub::read_string_table[1] = (char *)"IP"; + ATHandler_stub::int_value = 1; + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.set_stack_type(DEFAULT_STACK)); + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.set_credentials("internet")); + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.activate_context()); + + // get_context pdp type gives proper type, apn match. Test Delete the created context. + ATHandler_stub::resp_info_true_counter = 0; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + ATHandler_stub::int_value = 1; + //ATHandler_stub::nsapi_error_ok_counter = 2; + ATHandler_stub::resp_stop_success_count = 2; + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.set_credentials(NULL, NULL, NULL)); + EXPECT_TRUE(NSAPI_ERROR_NO_CONNECTION == my_cn.activate_context()); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_connect) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + // no stack so will fail + cn.attach(&network_cb); + network_cb_count = 0; + + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == cn.connect("APN", "a", "b")); + EXPECT_TRUE(NSAPI_STATUS_DISCONNECTED == cn.get_connection_status()); + EXPECT_TRUE(network_cb_count == 2); + + network_cb_count = 0; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_NO_CONNECTION == cn.connect("APN")); + EXPECT_TRUE(network_cb_count == 2); + EXPECT_TRUE(NSAPI_STATUS_DISCONNECTED == cn.get_connection_status()); + + my_AT_CN my_cn(at); + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + cn.set_stack_type(IPV4_STACK); + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.connect()); + EXPECT_TRUE(network_cb_count == 2); + EXPECT_TRUE(NSAPI_STATUS_GLOBAL_UP == my_cn.get_connection_status()); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_disconnect) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.disconnect()); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_get_stack) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + my_AT_CN my_cn(at); + my_stack *mystack = (my_stack *)my_cn.get_stack(); + EXPECT_TRUE(mystack); + delete mystack; +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_set_registration) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.set_registration()); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_registration()); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.set_registration("12345")); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_registration("12345")); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_get_registration_status) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::int_value = 3; + CellularNetwork::RegistrationStatus stat = CellularNetwork::NotRegistered; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_registration_status(CellularNetwork::C_EREG, stat)); + EXPECT_TRUE(stat == CellularNetwork::RegistrationDenied); + stat = CellularNetwork::NotRegistered; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_registration_status(CellularNetwork::C_GREG, stat)); + EXPECT_TRUE(stat == CellularNetwork::RegistrationDenied); + + my_AT_CN nw(at); + stat = CellularNetwork::NotRegistered; + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == nw.get_registration_status(CellularNetwork::C_GREG, stat)); + EXPECT_TRUE(stat == CellularNetwork::NotRegistered); + EXPECT_TRUE(NSAPI_ERROR_OK == nw.get_registration_status(CellularNetwork::C_EREG, stat)); + EXPECT_TRUE(stat == CellularNetwork::RegistrationDenied); + + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + stat = CellularNetwork::NotRegistered; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.get_registration_status(CellularNetwork::C_EREG, stat)); + EXPECT_TRUE(stat == -1); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.get_registration_status(CellularNetwork::C_GREG, stat)); + EXPECT_TRUE(stat == -1); + + stat = CellularNetwork::NotRegistered; + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == nw.get_registration_status(CellularNetwork::C_GREG, stat)); + EXPECT_TRUE(stat == CellularNetwork::NotRegistered); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == nw.get_registration_status(CellularNetwork::C_EREG, stat)); + EXPECT_TRUE(stat == -1); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_get_network_registering_mode) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + + ATHandler_stub::int_value = 0; + CellularNetwork::NWRegisteringMode mode = CellularNetwork::NWModeManual; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_network_registering_mode(mode)); + EXPECT_TRUE(mode == CellularNetwork::NWModeAutomatic); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + mode = CellularNetwork::NWModeManual; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.get_network_registering_mode(mode)); + EXPECT_TRUE(mode == -1); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_set_registration_urc) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + + CellularNetwork::RegistrationType type = CellularNetwork::C_EREG; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_registration_urc(type, true)); + type = CellularNetwork::C_GREG; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_registration_urc(type, true)); + type = CellularNetwork::C_REG; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_registration_urc(type, true)); + + my_AT_CN nw(at); + type = CellularNetwork::C_EREG; + EXPECT_TRUE(NSAPI_ERROR_OK == nw.set_registration_urc(type, true)); + type = CellularNetwork::C_GREG; + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == nw.set_registration_urc(type, true)); + type = CellularNetwork::C_REG; + EXPECT_TRUE(NSAPI_ERROR_OK == nw.set_registration_urc(type, true)); + + type = CellularNetwork::C_EREG; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_registration_urc(type, false)); + type = CellularNetwork::C_GREG; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_registration_urc(type, false)); + type = CellularNetwork::C_REG; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_registration_urc(type, false)); + + type = CellularNetwork::C_EREG; + EXPECT_TRUE(NSAPI_ERROR_OK == nw.set_registration_urc(type, false)); + type = CellularNetwork::C_GREG; + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == nw.set_registration_urc(type, false)); + type = CellularNetwork::C_REG; + EXPECT_TRUE(NSAPI_ERROR_OK == nw.set_registration_urc(type, false)); + + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + type = CellularNetwork::C_EREG; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.set_registration_urc(type, true)); + type = CellularNetwork::C_GREG; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.set_registration_urc(type, true)); + type = CellularNetwork::C_REG; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.set_registration_urc(type, true)); + + type = CellularNetwork::C_EREG; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == nw.set_registration_urc(type, true)); + type = CellularNetwork::C_GREG; + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == nw.set_registration_urc(type, true)); + type = CellularNetwork::C_REG; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == nw.set_registration_urc(type, true)); + + type = CellularNetwork::C_EREG; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.set_registration_urc(type, false)); + type = CellularNetwork::C_GREG; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.set_registration_urc(type, false)); + type = CellularNetwork::C_REG; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.set_registration_urc(type, false)); + + type = CellularNetwork::C_EREG; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == nw.set_registration_urc(type, false)); + type = CellularNetwork::C_GREG; + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == nw.set_registration_urc(type, false)); + type = CellularNetwork::C_REG; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == nw.set_registration_urc(type, false)); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_set_attach) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + ATHandler_stub::int_value = 0; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_attach()); + ATHandler_stub::int_value = 1; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_attach()); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.set_attach()); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_get_attach) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + CellularNetwork::AttachStatus stat = CellularNetwork::Detached; + ATHandler_stub::int_value = 1; + ATHandler_stub::bool_value = true; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_attach(stat)); + EXPECT_TRUE(stat == CellularNetwork::Attached); + + ATHandler_stub::int_value = 0; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_attach(stat)); + EXPECT_TRUE(stat == CellularNetwork::Detached); + + stat = CellularNetwork::Attached; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.get_attach(stat)); + EXPECT_TRUE(stat == CellularNetwork::Detached); + + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_attach(stat)); + EXPECT_TRUE(stat == CellularNetwork::Detached); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + ATHandler_stub::bool_value = false; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.get_attach(stat)); + EXPECT_TRUE(stat == CellularNetwork::Detached); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_detach) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + my_AT_CN cn(at); + + EXPECT_TRUE(NSAPI_ERROR_OK == cn.detach()); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.detach()); + + // connect so we can test callback in detach + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + cn.set_stack_type(IPV4_STACK); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.connect()); + EXPECT_TRUE(NSAPI_STATUS_GLOBAL_UP == cn.get_connection_status()); + // attach callback + cn.attach(&network_cb); + network_cb_count = 0; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.detach()); + EXPECT_TRUE(network_cb_count == 1); + EXPECT_TRUE(NSAPI_STATUS_DISCONNECTED == cn.get_connection_status()); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_get_rate_control) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + int ur = -1; + CellularNetwork::RateControlExceptionReports reports = CellularNetwork::NotAllowedToBeSent; + CellularNetwork::RateControlUplinkTimeUnit timeUnit = CellularNetwork::Unrestricted; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.get_rate_control(reports, timeUnit, ur)); + EXPECT_TRUE(reports == CellularNetwork::NotAllowedToBeSent); + EXPECT_TRUE(timeUnit == CellularNetwork::Unrestricted); + EXPECT_TRUE(ur == -1); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::int_value = 1; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_rate_control(reports, timeUnit, ur)); + EXPECT_TRUE(reports == CellularNetwork::AllowedToBeSent); + EXPECT_TRUE(timeUnit == CellularNetwork::Minute); + EXPECT_TRUE(ur == 1); + + // test second if in get_rate_control + reports = CellularNetwork::NotAllowedToBeSent; + timeUnit = CellularNetwork::Unrestricted; + ur = -1; + + ATHandler_stub::int_count = 1; + ATHandler_stub::int_valid_count_table[0] = 1; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.get_rate_control(reports, timeUnit, ur)); + EXPECT_TRUE(reports == CellularNetwork::NotAllowedToBeSent); + EXPECT_TRUE(timeUnit == CellularNetwork::Unrestricted); + EXPECT_TRUE(ur == -1); + + // test second if in get_rate_control + ATHandler_stub::int_count = 2; + ATHandler_stub::int_valid_count_table[0] = 1; + ATHandler_stub::int_valid_count_table[1] = 1; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.get_rate_control(reports, timeUnit, ur)); + EXPECT_TRUE(reports == CellularNetwork::AllowedToBeSent); + EXPECT_TRUE(timeUnit == CellularNetwork::Unrestricted); + EXPECT_TRUE(ur == -1); + + // test third if in get_rate_control + ATHandler_stub::int_count = 3; + ATHandler_stub::int_valid_count_table[0] = 3; + ATHandler_stub::int_valid_count_table[1] = 1; + ATHandler_stub::int_valid_count_table[2] = 1; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.get_rate_control(reports, timeUnit, ur)); + EXPECT_TRUE(reports == CellularNetwork::AllowedToBeSent); + EXPECT_TRUE(timeUnit == CellularNetwork::Day); + EXPECT_TRUE(ur == -1); + + ATHandler_stub::int_count = 4; + ATHandler_stub::int_valid_count_table[0] = 5; + ATHandler_stub::int_valid_count_table[1] = 3; + ATHandler_stub::int_valid_count_table[2] = 1; + ATHandler_stub::int_valid_count_table[3] = 1; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_rate_control(reports, timeUnit, ur)); + EXPECT_TRUE(reports == CellularNetwork::AllowedToBeSent); + EXPECT_TRUE(timeUnit == CellularNetwork::Day); + EXPECT_TRUE(ur == 5); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_get_apn_backoff_timer) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + int time = -1; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_PARAMETER == cn.get_apn_backoff_timer(time)); + EXPECT_TRUE(time == -1); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_PARAMETER == cn.get_apn_backoff_timer(time)); + EXPECT_TRUE(time == -1); + + ATHandler_stub::resp_info_true_counter = 0; + ATHandler_stub::bool_value = false; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + cn.set_credentials("internet", NULL, NULL); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_apn_backoff_timer(time)); + EXPECT_TRUE(time == -1); + + ATHandler_stub::resp_info_true_counter = 0; + ATHandler_stub::bool_value = true; + ATHandler_stub::int_value = 55; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + cn.set_credentials("internet", NULL, NULL); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_apn_backoff_timer(time)); + EXPECT_TRUE(time == 55); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_get_ip_address) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + EXPECT_TRUE(!cn.get_ip_address()); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_set_access_technology) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == cn.set_access_technology(CellularNetwork::RAT_UNKNOWN)); + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == cn.set_access_technology(CellularNetwork::RAT_GSM_COMPACT)); + + my_AT_CN my_cn(at); + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.set_access_technology(CellularNetwork::RAT_GSM_COMPACT)); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_get_access_technology) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + CellularNetwork::RadioAccessTechnology rat; + + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_access_technology(rat)); + EXPECT_TRUE(CellularNetwork::RAT_UNKNOWN == rat); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_scan_plmn) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + int c = -1; + CellularNetwork::operList_t ops; + ATHandler_stub::bool_value = false; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.scan_plmn(ops, c)); + EXPECT_TRUE(c == 0); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.scan_plmn(ops, c)); + EXPECT_TRUE(c == 0); + + + ATHandler_stub::read_string_index = 3; + ATHandler_stub::read_string_table[0] = (char *)"44444"; + ATHandler_stub::read_string_table[1] = (char *)"33333"; + ATHandler_stub::read_string_table[2] = (char *)"12345"; + ATHandler_stub::int_value = 1; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::info_elem_true_counter = 1; + ATHandler_stub::bool_value = false; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.scan_plmn(ops, c)); + EXPECT_TRUE(c == 1); + EXPECT_TRUE(ops.get_head() != NULL); + CellularNetwork::operator_t *op = ops.get_head(); + EXPECT_TRUE(op->op_status == CellularNetwork::operator_t::Available); + EXPECT_TRUE(strcmp(op->op_long, "12345") == 0); + EXPECT_TRUE(strcmp(op->op_short, "33333") == 0); + EXPECT_TRUE(strcmp(op->op_num, "44444") == 0); + ops.delete_all(); + + ATHandler_stub::read_string_index = 3; + ATHandler_stub::int_value = 6; // RAT_HSDPA_HSUPA + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::info_elem_true_counter = 1; + ATHandler_stub::bool_value = false; + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == cn.set_access_technology(CellularNetwork::RAT_UTRAN)); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.scan_plmn(ops, c)); + EXPECT_TRUE(c == 0); + EXPECT_TRUE(ops.get_head() == NULL); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_set_ciot_optimization_config) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_ciot_optimization_config(CellularNetwork::SUPPORTED_UE_OPT_NO_SUPPORT, CellularNetwork::PREFERRED_UE_OPT_NO_PREFERENCE)); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.set_ciot_optimization_config(CellularNetwork::SUPPORTED_UE_OPT_NO_SUPPORT, CellularNetwork::PREFERRED_UE_OPT_NO_PREFERENCE)); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_get_ciot_optimization_config) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + CellularNetwork::Supported_UE_Opt sup = CellularNetwork::SUPPORTED_UE_OPT_NO_SUPPORT; + CellularNetwork::Preferred_UE_Opt pref = CellularNetwork::PREFERRED_UE_OPT_NO_PREFERENCE; + ATHandler_stub::int_value = 1; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_ciot_optimization_config(sup, pref)); + EXPECT_TRUE(sup == CellularNetwork::SUPPORTED_UE_OPT_CONTROL_PLANE); + EXPECT_TRUE(pref == CellularNetwork::PREFERRED_UE_OPT_CONTROL_PLANE); + + sup = CellularNetwork::SUPPORTED_UE_OPT_NO_SUPPORT; + pref = CellularNetwork::PREFERRED_UE_OPT_NO_PREFERENCE; + ATHandler_stub::int_value = 1; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.get_ciot_optimization_config(sup, pref)); + EXPECT_TRUE(sup == CellularNetwork::SUPPORTED_UE_OPT_NO_SUPPORT); + EXPECT_TRUE(pref == CellularNetwork::PREFERRED_UE_OPT_NO_PREFERENCE); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_set_stack_type) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + EXPECT_TRUE(NSAPI_ERROR_PARAMETER == cn.set_stack_type(IPV4_STACK)); + + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_stack_type(DEFAULT_STACK)); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_get_stack_type) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + EXPECT_TRUE(DEFAULT_STACK == cn.get_stack_type()); + + my_AT_CN my_cn(at); + EXPECT_TRUE(DEFAULT_STACK == my_cn.get_stack_type()); + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.set_stack_type(IPV4_STACK)); + EXPECT_TRUE(DEFAULT_STACK == my_cn.get_stack_type()); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_get_pdpcontext_params) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + CellularNetwork::pdpContextList_t list; + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.get_pdpcontext_params(list)); + + // don't got to while loop + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + ATHandler_stub::resp_info_true_counter = 0; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_pdpcontext_params(list)); + EXPECT_TRUE(NULL == list.get_head()); + + // go to while loop and check values + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::resp_info_true_counter = 1; + ATHandler_stub::int_count = 9; + ATHandler_stub::int_valid_count_table[8] = 1; + ATHandler_stub::int_valid_count_table[7] = 2; + ATHandler_stub::int_valid_count_table[6] = 3; + ATHandler_stub::int_valid_count_table[5] = 4; + ATHandler_stub::int_valid_count_table[4] = 5; + ATHandler_stub::int_valid_count_table[3] = 6; + ATHandler_stub::int_valid_count_table[2] = 7; + ATHandler_stub::int_valid_count_table[1] = 8; + ATHandler_stub::int_valid_count_table[0] = 9; + + ATHandler_stub::read_string_index = 7; + ATHandler_stub::read_string_table[6] = (char *)"internet"; + ATHandler_stub::read_string_table[5] = (char *)"1.2.3.4.5.6.7.8.9.10.11.112.13.14.15.16.1.2.3.44.55.6.7.8.9.10.11.12.13.14.15.16"; + ATHandler_stub::read_string_table[4] = (char *)"23.33.44.1.2.3.55.123.225.34.11.1.0.0.123.234"; + ATHandler_stub::read_string_table[3] = (char *)"1.2.3.4"; + ATHandler_stub::read_string_table[2] = (char *)"0.255.0.255"; + ATHandler_stub::read_string_table[1] = (char *)"25.66.77.88"; + ATHandler_stub::read_string_table[0] = (char *)"004.003.002.001"; + + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_pdpcontext_params(list)); + CellularNetwork::pdpcontext_params_t *params = list.get_head(); + EXPECT_TRUE(params != NULL); + EXPECT_TRUE(params->next == NULL); + EXPECT_TRUE(params->cid == 1); + EXPECT_TRUE(params->bearer_id == 2); + EXPECT_TRUE(params->im_signalling_flag == 3); + EXPECT_TRUE(params->lipa_indication == 4); + EXPECT_TRUE(params->ipv4_mtu == 5); + EXPECT_TRUE(params->wlan_offload == 6); + EXPECT_TRUE(params->local_addr_ind == 7); + EXPECT_TRUE(params->non_ip_mtu == 8); + EXPECT_TRUE(params->serving_plmn_rate_control_value == 9); + EXPECT_TRUE(strcmp(params->apn, "internet") == 0); + EXPECT_TRUE(strcmp(params->local_addr, "102:304:506:708:90A:B70:D0E:F10") == 0); + EXPECT_TRUE(strcmp(params->local_subnet_mask, "102:32C:3706:708:90A:B0C:D0E:F10") == 0); + EXPECT_TRUE(strcmp(params->gateway_addr, "1721:2C01:203:377B:E122:B01:000:7BEA") == 0); + EXPECT_TRUE(strcmp(params->dns_primary_addr, "1.2.3.4") == 0); + EXPECT_TRUE(strcmp(params->dns_secondary_addr, "0.255.0.255") == 0); + EXPECT_TRUE(strcmp(params->p_cscf_prim_addr, "25.66.77.88") == 0); + EXPECT_TRUE(strcmp(params->p_cscf_sec_addr, "004.003.002.001") == 0); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_get_extended_signal_quality) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + int rx = -1, be = -1, rs = -1, ec = -1, rsrq = -1, rsrp = -1; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.get_extended_signal_quality(rx, be, rs, ec, rsrq, rsrp)); + EXPECT_TRUE(rx == -1 && be == -1 && rs == -1 && ec == -1 && rsrq == -1 && rsrp == -1); + + ATHandler_stub::int_value = 5; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_extended_signal_quality(rx, be, rs, ec, rsrq, rsrp)); + EXPECT_TRUE(rx == 5 && be == 5 && rs == 5 && ec == 5 && rsrq == 5 && rsrp == 5); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_get_signal_quality) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + int rs = -1, ber = -1; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.get_signal_quality(rs, ber)); + EXPECT_TRUE(rs == -1 && ber == -1); + + ATHandler_stub::int_value = 1; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_signal_quality(rs, ber)); + EXPECT_TRUE(rs == 1 && ber == 1); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_get_cell_id) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + int id = 0; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_cell_id(id)); + EXPECT_TRUE(id == -1); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_cell_id(id)); + EXPECT_TRUE(id == -1); + + ATHandler_stub::read_string_index = 2; + ATHandler_stub::read_string_table[1] = (char *)"00C3"; + ATHandler_stub::read_string_table[0] = (char *)"1234FFC1"; //== cellid and in dec: 305463233 + ATHandler_stub::int_value = 1; + // Get registration status to modify cell_id + CellularNetwork::RegistrationType type; + CellularNetwork::RegistrationStatus status; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_registration_status(CellularNetwork::C_EREG, status)); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_cell_id(id)); + EXPECT_TRUE(id == 305463233); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_get_3gpp_error) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + ATHandler_stub::int_value = 8; + EXPECT_TRUE(8 == cn.get_3gpp_error()); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_get_operator_params) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + int format; + CellularNetwork::operator_t ops; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.get_operator_params(format, ops)); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::int_value = 0; + ATHandler_stub::read_string_index = 1; + ATHandler_stub::read_string_table[0] = (char *)"12345"; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_operator_params(format, ops)); + EXPECT_TRUE(format == 0); + EXPECT_TRUE(strcmp(ops.op_long, "12345") == 0); + EXPECT_TRUE(strlen(ops.op_short) == 0); + EXPECT_TRUE(strlen(ops.op_num) == 0); + EXPECT_TRUE(ops.op_rat == CellularNetwork::RAT_GSM); + + ops.op_long[0] = 0; + ATHandler_stub::int_value = 1; + ATHandler_stub::read_string_index = 1; + ATHandler_stub::read_string_table[0] = (char *)"12345"; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_operator_params(format, ops)); + EXPECT_TRUE(format == 1); + EXPECT_TRUE(strlen(ops.op_long) == 0); + EXPECT_TRUE(strcmp(ops.op_short, "12345") == 0); + EXPECT_TRUE(strlen(ops.op_num) == 0); + EXPECT_TRUE(ops.op_rat == CellularNetwork::RAT_GSM_COMPACT); + + ops.op_short[0] = 0; + ATHandler_stub::int_value = 2; + ATHandler_stub::read_string_index = 1; + ATHandler_stub::read_string_table[0] = (char *)"12345"; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_operator_params(format, ops)); + EXPECT_TRUE(format == 2); + EXPECT_TRUE(strlen(ops.op_long) == 0); + EXPECT_TRUE(strlen(ops.op_short) == 0); + EXPECT_TRUE(strcmp(ops.op_num, "12345") == 0); + EXPECT_TRUE(ops.op_rat == CellularNetwork::RAT_UTRAN); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_get_operator_names) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + CellularNetwork::operator_names_list name_list; + + ATHandler_stub::resp_info_true_counter = 0; + ATHandler_stub::bool_value = false; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_operator_names(name_list)); + EXPECT_TRUE(name_list.get_head() == NULL); + + ATHandler_stub::resp_info_true_counter = 1; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == cn.get_operator_names(name_list)); + EXPECT_TRUE(name_list.get_head() != NULL); + EXPECT_TRUE(name_list.get_head()->next == NULL); + + ATHandler_stub::resp_info_true_counter = 1; + ATHandler_stub::bool_value = false; + ATHandler_stub::read_string_index = 2; + ATHandler_stub::read_string_table[1] = (char *)"12345"; + ATHandler_stub::read_string_table[0] = (char *)"56789"; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + name_list.delete_all(); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.get_operator_names(name_list)); + CellularNetwork::operator_names_t *op_names = name_list.get_head(); + EXPECT_TRUE(op_names != NULL); + EXPECT_TRUE(op_names->next == NULL); + EXPECT_TRUE(strcmp(op_names->numeric, "12345") == 0); + EXPECT_TRUE(strcmp(op_names->alpha, "56789") == 0); +} + +TEST_F(TestAT_CellularNetwork, test_AT_CellularNetwork_attach) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + network_cb_count = 0; + cn.attach(&network_cb); + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == cn.connect()); + EXPECT_TRUE(network_cb_count == 2); // check that attached callback was called twice +} + +TEST_F(TestAT_CellularNetwork, test_get_connection_status) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + network_cb_count = 0; + cn.attach(&network_cb); + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == cn.connect()); + EXPECT_TRUE(network_cb_count == 2); // check that attached callback was called twice + EXPECT_TRUE(NSAPI_STATUS_DISCONNECTED == cn.get_connection_status()); + + my_AT_CN my_cn(at); + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::bool_value = false; + cn.set_stack_type(IPV4_STACK); + EXPECT_TRUE(NSAPI_ERROR_OK == my_cn.connect()); + EXPECT_TRUE(network_cb_count == 2); + EXPECT_TRUE(NSAPI_STATUS_GLOBAL_UP == my_cn.get_connection_status()); +} + +TEST_F(TestAT_CellularNetwork, test_set_blocking) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularNetwork cn(at); + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_blocking(false)); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_blocking(true)); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_blocking(false)); + EXPECT_TRUE(NSAPI_ERROR_OK == cn.set_blocking(true)); +} + diff --git a/UNITTESTS/features/cellular/framework/AT/at_cellularnetwork/unittest.cmake b/UNITTESTS/features/cellular/framework/AT/at_cellularnetwork/unittest.cmake new file mode 100644 index 0000000000..48f7eae3ca --- /dev/null +++ b/UNITTESTS/features/cellular/framework/AT/at_cellularnetwork/unittest.cmake @@ -0,0 +1,34 @@ + +#################### +# UNIT TESTS +#################### + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + features/cellular/framework/common/util + ../features/cellular/framework/common + ../features/cellular/framework/AT + ../features/frameworks/mbed-client-randlib/mbed-client-randlib +) + +# Source files +set(unittest-sources + ../features/cellular/framework/AT/AT_CellularNetwork.cpp + ../features/cellular/framework/AT/AT_CellularStack.cpp + ../features/cellular/framework/common/CellularUtil.cpp +) + +# Test files +set(unittest-test-sources + features/cellular/framework/AT/at_cellularnetwork/at_cellularnetworktest.cpp + stubs/ATHandler_stub.cpp + stubs/AT_CellularBase_stub.cpp + stubs/EventQueue_stub.cpp + stubs/FileHandle_stub.cpp + stubs/NetworkInterface_stub.cpp + stubs/NetworkStack_stub.cpp + stubs/us_ticker_stub.cpp + stubs/mbed_assert_stub.c + stubs/SocketAddress_stub.cpp + stubs/randLIB_stub.cpp +) diff --git a/features/cellular/UNITTESTS/at/at_cellularpower/test_at_cellularpower.cpp b/UNITTESTS/features/cellular/framework/AT/at_cellularpower/at_cellularpowertest.cpp similarity index 51% rename from features/cellular/UNITTESTS/at/at_cellularpower/test_at_cellularpower.cpp rename to UNITTESTS/features/cellular/framework/AT/at_cellularpower/at_cellularpowertest.cpp index 593f4c447b..48b67abd2f 100644 --- a/features/cellular/UNITTESTS/at/at_cellularpower/test_at_cellularpower.cpp +++ b/UNITTESTS/features/cellular/framework/AT/at_cellularpower/at_cellularpowertest.cpp @@ -14,8 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "CppUTest/TestHarness.h" -#include "test_at_cellularpower.h" +#include "gtest/gtest.h" #include #include "AT_CellularNetwork.h" #include "EventQueue.h" @@ -27,47 +26,60 @@ using namespace mbed; using namespace events; -Test_AT_CellularPower::Test_AT_CellularPower() -{ - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; -} +// AStyle ignored as the definition is not clear due to preprocessor usage +// *INDENT-OFF* +class TestAT_CellularPower : public testing::Test { +protected: -Test_AT_CellularPower::~Test_AT_CellularPower() + void SetUp() { + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + } + + void TearDown() { + } +}; +// *INDENT-ON* + + +static void device_ready_cb() { } -void Test_AT_CellularPower::test_AT_CellularPower_constructor() +TEST_F(TestAT_CellularPower, Create) { + EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); AT_CellularPower *pow = new AT_CellularPower(at); + EXPECT_TRUE(pow != NULL); + delete pow; } -void Test_AT_CellularPower::test_AT_CellularPower_on() +TEST_F(TestAT_CellularPower, test_AT_CellularPower_on) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); AT_CellularPower pow(at); - CHECK(NSAPI_ERROR_UNSUPPORTED == pow.on()); + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == pow.on()); } -void Test_AT_CellularPower::test_AT_CellularPower_off() +TEST_F(TestAT_CellularPower, test_AT_CellularPower_off) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); AT_CellularPower pow(at); - CHECK(NSAPI_ERROR_UNSUPPORTED == pow.off()); + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == pow.off()); } -void Test_AT_CellularPower::test_AT_CellularPower_set_at_mode() +TEST_F(TestAT_CellularPower, test_AT_CellularPower_set_at_mode) { EventQueue que; FileHandle_stub fh1; @@ -75,13 +87,13 @@ void Test_AT_CellularPower::test_AT_CellularPower_set_at_mode() AT_CellularPower pow(at); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == pow.set_at_mode()); + EXPECT_TRUE(NSAPI_ERROR_OK == pow.set_at_mode()); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == pow.set_at_mode()); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == pow.set_at_mode()); } -void Test_AT_CellularPower::test_AT_CellularPower_set_power_level() +TEST_F(TestAT_CellularPower, test_AT_CellularPower_set_power_level) { EventQueue que; FileHandle_stub fh1; @@ -89,15 +101,15 @@ void Test_AT_CellularPower::test_AT_CellularPower_set_power_level() AT_CellularPower pow(at); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == pow.set_power_level(6)); - CHECK(NSAPI_ERROR_OK == pow.set_power_level(1, 1)); - CHECK(NSAPI_ERROR_OK == pow.set_power_level(1, 0)); + EXPECT_TRUE(NSAPI_ERROR_OK == pow.set_power_level(6)); + EXPECT_TRUE(NSAPI_ERROR_OK == pow.set_power_level(1, 1)); + EXPECT_TRUE(NSAPI_ERROR_OK == pow.set_power_level(1, 0)); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == pow.set_power_level(6)); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == pow.set_power_level(6)); } -void Test_AT_CellularPower::test_AT_CellularPower_reset() +TEST_F(TestAT_CellularPower, test_AT_CellularPower_reset) { EventQueue que; FileHandle_stub fh1; @@ -105,13 +117,13 @@ void Test_AT_CellularPower::test_AT_CellularPower_reset() AT_CellularPower pow(at); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == pow.reset()); + EXPECT_TRUE(NSAPI_ERROR_OK == pow.reset()); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == pow.reset()); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == pow.reset()); } -void Test_AT_CellularPower::test_AT_CellularPower_opt_power_save_mode() +TEST_F(TestAT_CellularPower, test_AT_CellularPower_opt_power_save_mode) { EventQueue que; FileHandle_stub fh1; @@ -119,27 +131,27 @@ void Test_AT_CellularPower::test_AT_CellularPower_opt_power_save_mode() AT_CellularPower pow(at); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == pow.opt_power_save_mode(0, 0)); + EXPECT_TRUE(NSAPI_ERROR_OK == pow.opt_power_save_mode(0, 0)); - CHECK(NSAPI_ERROR_OK == pow.opt_power_save_mode(10, 0)); + EXPECT_TRUE(NSAPI_ERROR_OK == pow.opt_power_save_mode(10, 0)); - CHECK(NSAPI_ERROR_OK == pow.opt_power_save_mode(912, 0)); + EXPECT_TRUE(NSAPI_ERROR_OK == pow.opt_power_save_mode(912, 0)); - CHECK(NSAPI_ERROR_OK == pow.opt_power_save_mode(1834, 1834)); + EXPECT_TRUE(NSAPI_ERROR_OK == pow.opt_power_save_mode(1834, 1834)); - CHECK(NSAPI_ERROR_OK == pow.opt_power_save_mode(18345, 18345)); + EXPECT_TRUE(NSAPI_ERROR_OK == pow.opt_power_save_mode(18345, 18345)); - CHECK(NSAPI_ERROR_OK == pow.opt_power_save_mode(101234, 101234)); + EXPECT_TRUE(NSAPI_ERROR_OK == pow.opt_power_save_mode(101234, 101234)); - CHECK(NSAPI_ERROR_OK == pow.opt_power_save_mode(1012345, 1012345)); + EXPECT_TRUE(NSAPI_ERROR_OK == pow.opt_power_save_mode(1012345, 1012345)); - CHECK(NSAPI_ERROR_OK == pow.opt_power_save_mode(39612345, 39612345)); + EXPECT_TRUE(NSAPI_ERROR_OK == pow.opt_power_save_mode(39612345, 39612345)); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == pow.opt_power_save_mode(0, 0)); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == pow.opt_power_save_mode(0, 0)); } -void Test_AT_CellularPower::test_AT_CellularPower_opt_receive_period() +TEST_F(TestAT_CellularPower, test_AT_CellularPower_opt_receive_period) { EventQueue que; FileHandle_stub fh1; @@ -147,13 +159,13 @@ void Test_AT_CellularPower::test_AT_CellularPower_opt_receive_period() AT_CellularPower pow(at); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == pow.opt_receive_period(1, CellularPower::EDRXUTRAN_Iu_mode, 3)); + EXPECT_TRUE(NSAPI_ERROR_OK == pow.opt_receive_period(1, CellularPower::EDRXUTRAN_Iu_mode, 3)); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == pow.opt_receive_period(1, CellularPower::EDRXUTRAN_Iu_mode, 3)); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == pow.opt_receive_period(1, CellularPower::EDRXUTRAN_Iu_mode, 3)); } -void Test_AT_CellularPower::test_AT_CellularPower_is_device_ready() +TEST_F(TestAT_CellularPower, test_AT_CellularPower_is_device_ready) { EventQueue que; FileHandle_stub fh1; @@ -161,32 +173,28 @@ void Test_AT_CellularPower::test_AT_CellularPower_is_device_ready() AT_CellularPower pow(at); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_AUTH_FAILURE; - CHECK(NSAPI_ERROR_AUTH_FAILURE == pow.is_device_ready()); + EXPECT_TRUE(NSAPI_ERROR_AUTH_FAILURE == pow.is_device_ready()); } -static void device_ready_cb() -{ -} - -void Test_AT_CellularPower::test_AT_CellularPower_set_device_ready_urc_cb() +TEST_F(TestAT_CellularPower, test_AT_CellularPower_set_device_ready_urc_cb) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); AT_CellularPower pow(at); - CHECK(NSAPI_ERROR_UNSUPPORTED == pow.set_device_ready_urc_cb(&device_ready_cb)); - CHECK(NSAPI_ERROR_UNSUPPORTED == pow.set_device_ready_urc_cb(NULL)); + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == pow.set_device_ready_urc_cb(&device_ready_cb)); + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == pow.set_device_ready_urc_cb(NULL)); } -void Test_AT_CellularPower::test_AT_CellularPower_remove_device_ready_urc_cb() +TEST_F(TestAT_CellularPower, test_AT_CellularPower_remove_device_ready_urc_cb) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); AT_CellularPower pow(at); - CHECK(NSAPI_ERROR_UNSUPPORTED == pow.set_device_ready_urc_cb(&device_ready_cb)); + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == pow.set_device_ready_urc_cb(&device_ready_cb)); pow.remove_device_ready_urc_cb(NULL); pow.remove_device_ready_urc_cb(&device_ready_cb); diff --git a/UNITTESTS/features/cellular/framework/AT/at_cellularpower/unittest.cmake b/UNITTESTS/features/cellular/framework/AT/at_cellularpower/unittest.cmake new file mode 100644 index 0000000000..82dc0e9b38 --- /dev/null +++ b/UNITTESTS/features/cellular/framework/AT/at_cellularpower/unittest.cmake @@ -0,0 +1,28 @@ + +#################### +# UNIT TESTS +#################### + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + features/cellular/framework/common/util + ../features/cellular/framework/common + ../features/cellular/framework/AT + ../features/frameworks/mbed-client-randlib/mbed-client-randlib +) + +# Source files +set(unittest-sources + ../features/cellular/framework/AT/AT_CellularPower.cpp +) + +# Test files +set(unittest-test-sources + features/cellular/framework/AT/at_cellularpower/at_cellularpowertest.cpp + stubs/ATHandler_stub.cpp + stubs/AT_CellularBase_stub.cpp + stubs/EventQueue_stub.cpp + stubs/FileHandle_stub.cpp + stubs/CellularUtil_stub.cpp + stubs/mbed_assert_stub.c +) diff --git a/UNITTESTS/features/cellular/framework/AT/at_cellularsim/at_cellularsimtest.cpp b/UNITTESTS/features/cellular/framework/AT/at_cellularsim/at_cellularsimtest.cpp new file mode 100644 index 0000000000..e4fe6a1ce1 --- /dev/null +++ b/UNITTESTS/features/cellular/framework/AT/at_cellularsim/at_cellularsimtest.cpp @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2018, Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "gtest/gtest.h" +#include "ATHandler_stub.h" +#include +#include "AT_CellularNetwork.h" +#include "EventQueue.h" +#include "ATHandler.h" +#include "AT_CellularSIM.h" +#include "FileHandle_stub.h" +#include "CellularLog.h" +#include "ATHandler_stub.h" + +using namespace mbed; +using namespace events; + +// AStyle ignored as the definition is not clear due to preprocessor usage +// *INDENT-OFF* +class TestAT_CellularSIM : public testing::Test { +protected: + + void SetUp() + { + ATHandler_stub::read_string_index = kRead_string_table_size; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::read_string_value = NULL; + ATHandler_stub::ssize_value = 0; + } + + void TearDown() + { + } +}; +// *INDENT-ON* + +TEST_F(TestAT_CellularSIM, Create) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularSIM *sim = new AT_CellularSIM(at); + + EXPECT_TRUE(sim != NULL); + delete sim; +} + +TEST_F(TestAT_CellularSIM, test_AT_CellularSIM_set_pin) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularSIM sim(at); + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_OK == sim.set_pin("12")); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == sim.set_pin("12")); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::read_string_value = (char *)"READY"; + ATHandler_stub::ssize_value = 5; + EXPECT_TRUE(NSAPI_ERROR_OK == sim.set_pin("12")); + + EXPECT_TRUE(NSAPI_ERROR_OK == sim.set_pin(NULL)); +} + +TEST_F(TestAT_CellularSIM, test_AT_CellularSIM_change_pin) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularSIM sim(at); + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_OK == sim.change_pin("12", "34")); + EXPECT_TRUE(NSAPI_ERROR_OK == sim.change_pin(NULL, "34")); + EXPECT_TRUE(NSAPI_ERROR_OK == sim.change_pin("12", NULL)); + EXPECT_TRUE(NSAPI_ERROR_OK == sim.change_pin(NULL, NULL)); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == sim.change_pin("12", "34")); +} + +TEST_F(TestAT_CellularSIM, test_AT_CellularSIM_set_pin_query) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularSIM sim(at); + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_OK == sim.set_pin_query("12", true)); + EXPECT_TRUE(NSAPI_ERROR_OK == sim.set_pin_query(NULL, true)); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_OK == sim.set_pin_query("12", false)); + EXPECT_TRUE(NSAPI_ERROR_OK == sim.set_pin_query(NULL, false)); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == sim.set_pin_query("12", false)); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == sim.set_pin_query("12", true)); +} + +TEST_F(TestAT_CellularSIM, test_AT_CellularSIM_get_sim_state) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + AT_CellularSIM sim(at); + CellularSIM::SimState state; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::ssize_value = -1; + ATHandler_stub::read_string_value = NULL; + EXPECT_TRUE(NSAPI_ERROR_OK == sim.get_sim_state(state)); + EXPECT_TRUE(CellularSIM::SimStateUnknown == state); + + ATHandler_stub::read_string_value = (char *)"READY"; + ATHandler_stub::ssize_value = 5; + EXPECT_TRUE(NSAPI_ERROR_OK == sim.get_sim_state(state)); + EXPECT_TRUE(CellularSIM::SimStateReady == state); + + ATHandler_stub::read_string_value = (char *)"SIM PIN"; + ATHandler_stub::ssize_value = 7; + EXPECT_TRUE(NSAPI_ERROR_OK == sim.get_sim_state(state)); + EXPECT_TRUE(CellularSIM::SimStatePinNeeded == state); + + ATHandler_stub::read_string_value = (char *)"SIM PUK"; + ATHandler_stub::ssize_value = 7; + EXPECT_TRUE(NSAPI_ERROR_OK == sim.get_sim_state(state)); + EXPECT_TRUE(CellularSIM::SimStatePukNeeded == state); + + ATHandler_stub::read_string_value = (char *)"SOME CRAP"; + ATHandler_stub::ssize_value = 9; + EXPECT_TRUE(NSAPI_ERROR_OK == sim.get_sim_state(state)); + EXPECT_TRUE(CellularSIM::SimStateUnknown == state); +} + +TEST_F(TestAT_CellularSIM, test_AT_CellularSIM_get_imsi) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + char imsi[16]; + AT_CellularSIM sim(at); + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::read_string_value = (char *)"123456789012345"; + ATHandler_stub::ssize_value = 15; + EXPECT_TRUE(NSAPI_ERROR_OK == sim.get_imsi(imsi)); + EXPECT_TRUE(strcmp(ATHandler_stub::read_string_value, imsi) == 0); + + ATHandler_stub::read_string_value = NULL; + ATHandler_stub::ssize_value = -1; + ATHandler_stub::read_string_index = -1; + imsi[0] = 0; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == sim.get_imsi(imsi)); + EXPECT_TRUE(strlen(imsi) == 0); + + EXPECT_TRUE(NSAPI_ERROR_PARAMETER == sim.get_imsi(NULL)); + + // this would fail as get_imsi should take another param which is the size of the buffer which we could use for validation. + // Now we have improved documentation that that the given imsi buffer size must be over 15. + //char imsi2[5]; + //EXPECT_TRUE(NSAPI_ERROR_PARAMETER == sim.get_imsi(imsi2)); +} + +TEST_F(TestAT_CellularSIM, test_AT_CellularSIM_get_iccid) +{ + EventQueue que; + FileHandle_stub fh1; + ATHandler at(&fh1, que, 0, ","); + + char buf[16]; + AT_CellularSIM sim(at); + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::read_string_value = (char *)"123456789012345"; + ATHandler_stub::ssize_value = 15; + EXPECT_TRUE(NSAPI_ERROR_OK == sim.get_iccid(buf, 16)); + EXPECT_TRUE(strcmp(ATHandler_stub::read_string_value, buf) == 0); + + buf[0] = 0; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + ATHandler_stub::read_string_value = NULL; + ATHandler_stub::ssize_value = -1; + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == sim.get_iccid(buf, 16)); + EXPECT_TRUE(strlen(buf) == 0); +} diff --git a/UNITTESTS/features/cellular/framework/AT/at_cellularsim/unittest.cmake b/UNITTESTS/features/cellular/framework/AT/at_cellularsim/unittest.cmake new file mode 100644 index 0000000000..7adbfef871 --- /dev/null +++ b/UNITTESTS/features/cellular/framework/AT/at_cellularsim/unittest.cmake @@ -0,0 +1,29 @@ + +#################### +# UNIT TESTS +#################### + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + features/cellular/framework/common/util + ../features/cellular/framework/common + ../features/cellular/framework/AT + ../features/frameworks/mbed-client-randlib/mbed-client-randlib +) + +# Source files +set(unittest-sources + ../features/cellular/framework/AT/AT_CellularSIM.cpp +) + +# Test files +set(unittest-test-sources + features/cellular/framework/AT/at_cellularsim/at_cellularsimtest.cpp + stubs/ATHandler_stub.cpp + stubs/AT_CellularBase_stub.cpp + stubs/EventQueue_stub.cpp + stubs/FileHandle_stub.cpp + stubs/CellularUtil_stub.cpp + stubs/us_ticker_stub.cpp + stubs/mbed_assert_stub.c +) diff --git a/features/cellular/UNITTESTS/at/at_cellularsms/test_at_cellularsms.cpp b/UNITTESTS/features/cellular/framework/AT/at_cellularsms/at_cellularsmstest.cpp similarity index 60% rename from features/cellular/UNITTESTS/at/at_cellularsms/test_at_cellularsms.cpp rename to UNITTESTS/features/cellular/framework/AT/at_cellularsms/at_cellularsmstest.cpp index 94c5884a63..a21b7098de 100644 --- a/features/cellular/UNITTESTS/at/at_cellularsms/test_at_cellularsms.cpp +++ b/UNITTESTS/features/cellular/framework/AT/at_cellularsms/at_cellularsmstest.cpp @@ -14,8 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "CppUTest/TestHarness.h" -#include "test_at_cellularsms.h" +#include "gtest/gtest.h" #include #include "AT_CellularNetwork.h" #include "EventQueue.h" @@ -28,17 +27,24 @@ using namespace mbed; using namespace events; -Test_AT_CellularSMS::Test_AT_CellularSMS() -{ - ATHandler_stub::return_given_size = false; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; -} +// AStyle ignored as the definition is not clear due to preprocessor usage +// *INDENT-OFF* +class TestAT_CellularSMS : public testing::Test { +protected: -Test_AT_CellularSMS::~Test_AT_CellularSMS() -{ -} + void SetUp() + { + ATHandler_stub::return_given_size = false; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + } -void Test_AT_CellularSMS::test_AT_CellularSMS_constructor() + void TearDown() + { + } +}; +// *INDENT-ON* + +TEST_F(TestAT_CellularSMS, Create) { EventQueue que; FileHandle_stub fh1; @@ -46,50 +52,66 @@ void Test_AT_CellularSMS::test_AT_CellularSMS_constructor() AT_CellularSMS *sms = new AT_CellularSMS(at); + EXPECT_TRUE(sms != NULL); delete sms; } -void Test_AT_CellularSMS::test_AT_CellularSMS_initialize() +void my_callback() +{ + +} + +TEST_F(TestAT_CellularSMS, test_AT_CellularSMS_initialize) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); + ATHandler_stub::call_immediately = true; + AT_CellularSMS sms(at); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_AUTH_FAILURE; - CHECK(NSAPI_ERROR_NO_MEMORY == sms.initialize(CellularSMS::CellularSMSMmodeText)); + EXPECT_TRUE(NSAPI_ERROR_NO_MEMORY == sms.initialize(CellularSMS::CellularSMSMmodeText)); + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_OK == sms.initialize(CellularSMS::CellularSMSMmodeText)); + + sms.set_sms_callback(&my_callback); + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + EXPECT_TRUE(NSAPI_ERROR_OK == sms.initialize(CellularSMS::CellularSMSMmodeText)); + + ATHandler_stub::call_immediately = false; } - -void Test_AT_CellularSMS::test_AT_CellularSMS_send_sms() +TEST_F(TestAT_CellularSMS, test_AT_CellularSMS_send_sms) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); AT_CellularSMS sms(at); - LONGS_EQUAL(NSAPI_ERROR_PARAMETER, sms.send_sms(NULL, "2", 1)); + EXPECT_EQ(NSAPI_ERROR_PARAMETER, sms.send_sms(NULL, "2", 1)); sms.initialize(CellularSMS::CellularSMSMmodeText); ATHandler_stub::size_value = 1; - LONGS_EQUAL(1, sms.send_sms("1", "22", 2)); + EXPECT_EQ(1, sms.send_sms("1", "22", 2)); ATHandler_stub::size_value = 2; - LONGS_EQUAL(2, sms.send_sms("1", "22", 2)); + EXPECT_EQ(2, sms.send_sms("1", "22", 2)); ATHandler_stub::return_given_size = true; // PDU mode write is much longer than than msg len sms.initialize(CellularSMS::CellularSMSMmodePDU); - LONGS_EQUAL(2, sms.send_sms("1", "23", 2));; + EXPECT_EQ(2, sms.send_sms("1", "23", 2));; ATHandler_stub::nsapi_error_ok_counter = 1; ATHandler_stub::size_value = 32; ATHandler_stub::nsapi_error_value = NSAPI_ERROR_AUTH_FAILURE; - LONGS_EQUAL(NSAPI_ERROR_AUTH_FAILURE, sms.send_sms("1", "23232323", 8)); + EXPECT_EQ(NSAPI_ERROR_AUTH_FAILURE, sms.send_sms("1", "23232323", 8)); ATHandler_stub::nsapi_error_ok_counter = 2; ATHandler_stub::size_value = 32; ATHandler_stub::nsapi_error_value = NSAPI_ERROR_AUTH_FAILURE; - LONGS_EQUAL(NSAPI_ERROR_AUTH_FAILURE, sms.send_sms("1", "23232323", 8)); + EXPECT_EQ(NSAPI_ERROR_AUTH_FAILURE, sms.send_sms("1", "23232323", 8)); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; char table[] = "232323232323232323232323232323232323232323232323232323\ @@ -97,12 +119,11 @@ void Test_AT_CellularSMS::test_AT_CellularSMS_send_sms() 232323232323232323232323232323232323232323232323232323\ 23232323232323232323232323232323232323\0"; - LONGS_EQUAL(strlen(table), sms.send_sms("1", table, strlen(table))); - LONGS_EQUAL(strlen(table), sms.send_sms("12", table, strlen(table))); + EXPECT_EQ(strlen(table), sms.send_sms("1", table, strlen(table))); + EXPECT_EQ(strlen(table), sms.send_sms("12", table, strlen(table))); } - -void Test_AT_CellularSMS::test_AT_CellularSMS_get_sms() +TEST_F(TestAT_CellularSMS, test_AT_CellularSMS_get_sms) { EventQueue que; FileHandle_stub fh1; @@ -113,28 +134,27 @@ void Test_AT_CellularSMS::test_AT_CellularSMS_get_sms() char phone[21]; char stamp[21]; int size; - CHECK(NSAPI_ERROR_PARAMETER == sms.get_sms(NULL, 16, phone, 21, stamp, 21, &size)); + EXPECT_TRUE(NSAPI_ERROR_PARAMETER == sms.get_sms(NULL, 16, phone, 21, stamp, 21, &size)); ATHandler_stub::resp_info_true_counter = 1; ATHandler_stub::int_value = 0; - CHECK(-1 == sms.get_sms(buf, 16, phone, 21, stamp, 21, &size)); + EXPECT_TRUE(-1 == sms.get_sms(buf, 16, phone, 21, stamp, 21, &size)); ATHandler_stub::resp_info_true_counter = 2; ATHandler_stub::int_value = 11; - CHECK(0 == sms.get_sms(buf, 16, phone, 21, stamp, 21, &size)); + EXPECT_TRUE(0 == sms.get_sms(buf, 16, phone, 21, stamp, 21, &size)); //TODO: Should make add_info to happen, before calling get_sms! ATHandler_stub::resp_info_true_counter = 2; ATHandler_stub::int_value = 11; sms.initialize(CellularSMS::CellularSMSMmodePDU); - CHECK(0 == sms.get_sms(buf, 16, phone, 21, stamp, 21, &size)); + EXPECT_TRUE(0 == sms.get_sms(buf, 16, phone, 21, stamp, 21, &size)); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_AUTH_FAILURE; - CHECK(NSAPI_ERROR_AUTH_FAILURE == sms.get_sms(buf, 16, phone, 21, stamp, 21, &size)); + EXPECT_TRUE(NSAPI_ERROR_AUTH_FAILURE == sms.get_sms(buf, 16, phone, 21, stamp, 21, &size)); } - -void Test_AT_CellularSMS::test_AT_CellularSMS_set_sms_callback() +TEST_F(TestAT_CellularSMS, test_AT_CellularSMS_set_sms_callback) { EventQueue que; FileHandle_stub fh1; @@ -144,8 +164,7 @@ void Test_AT_CellularSMS::test_AT_CellularSMS_set_sms_callback() sms.set_sms_callback(NULL); } - -void Test_AT_CellularSMS::test_AT_CellularSMS_set_cpms() +TEST_F(TestAT_CellularSMS, test_AT_CellularSMS_set_cpms) { EventQueue que; FileHandle_stub fh1; @@ -153,11 +172,10 @@ void Test_AT_CellularSMS::test_AT_CellularSMS_set_cpms() AT_CellularSMS sms(at); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_AUTH_FAILURE; - CHECK(NSAPI_ERROR_AUTH_FAILURE == sms.set_cpms("2", "3", "4")); + EXPECT_TRUE(NSAPI_ERROR_AUTH_FAILURE == sms.set_cpms("2", "3", "4")); } - -void Test_AT_CellularSMS::test_AT_CellularSMS_set_csca() +TEST_F(TestAT_CellularSMS, test_AT_CellularSMS_set_csca) { EventQueue que; FileHandle_stub fh1; @@ -165,11 +183,10 @@ void Test_AT_CellularSMS::test_AT_CellularSMS_set_csca() AT_CellularSMS sms(at); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_AUTH_FAILURE; - CHECK(NSAPI_ERROR_AUTH_FAILURE == sms.set_csca("2", 1)); + EXPECT_TRUE(NSAPI_ERROR_AUTH_FAILURE == sms.set_csca("2", 1)); } - -void Test_AT_CellularSMS::test_AT_CellularSMS_set_cscs() +TEST_F(TestAT_CellularSMS, test_AT_CellularSMS_set_cscs) { EventQueue que; FileHandle_stub fh1; @@ -177,11 +194,10 @@ void Test_AT_CellularSMS::test_AT_CellularSMS_set_cscs() AT_CellularSMS sms(at); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_AUTH_FAILURE; - CHECK(NSAPI_ERROR_AUTH_FAILURE == sms.set_cscs("2")); + EXPECT_TRUE(NSAPI_ERROR_AUTH_FAILURE == sms.set_cscs("2")); } - -void Test_AT_CellularSMS::test_AT_CellularSMS_delete_all_messages() +TEST_F(TestAT_CellularSMS, test_AT_CellularSMS_delete_all_messages) { EventQueue que; FileHandle_stub fh1; @@ -189,11 +205,10 @@ void Test_AT_CellularSMS::test_AT_CellularSMS_delete_all_messages() AT_CellularSMS sms(at); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_AUTH_FAILURE; - CHECK(NSAPI_ERROR_AUTH_FAILURE == sms.delete_all_messages()); + EXPECT_TRUE(NSAPI_ERROR_AUTH_FAILURE == sms.delete_all_messages()); } - -void Test_AT_CellularSMS::test_AT_CellularSMS_set_extra_sim_wait_time() +TEST_F(TestAT_CellularSMS, test_AT_CellularSMS_set_extra_sim_wait_time) { EventQueue que; FileHandle_stub fh1; @@ -201,6 +216,4 @@ void Test_AT_CellularSMS::test_AT_CellularSMS_set_extra_sim_wait_time() AT_CellularSMS sms(at); sms.set_extra_sim_wait_time(56); - } - diff --git a/UNITTESTS/features/cellular/framework/AT/at_cellularsms/unittest.cmake b/UNITTESTS/features/cellular/framework/AT/at_cellularsms/unittest.cmake new file mode 100644 index 0000000000..616b49e49a --- /dev/null +++ b/UNITTESTS/features/cellular/framework/AT/at_cellularsms/unittest.cmake @@ -0,0 +1,30 @@ + +#################### +# UNIT TESTS +#################### + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + features/cellular/framework/common/util + ../features/cellular/framework/common + ../features/cellular/framework/AT + ../features/frameworks/mbed-client-randlib/mbed-client-randlib +) + +# Source files +set(unittest-sources + ../features/cellular/framework/AT/AT_CellularSMS.cpp +) + +# Test files +set(unittest-test-sources + features/cellular/framework/AT/at_cellularsms/at_cellularsmstest.cpp + stubs/ATHandler_stub.cpp + stubs/AT_CellularBase_stub.cpp + stubs/EventQueue_stub.cpp + stubs/FileHandle_stub.cpp + stubs/CellularUtil_stub.cpp + stubs/us_ticker_stub.cpp + stubs/mbed_assert_stub.c + stubs/mbed_wait_api_stub.cpp +) diff --git a/features/cellular/UNITTESTS/at/at_cellularstack/test_at_cellularstack.cpp b/UNITTESTS/features/cellular/framework/AT/at_cellularstack/at_cellularstacktest.cpp similarity index 70% rename from features/cellular/UNITTESTS/at/at_cellularstack/test_at_cellularstack.cpp rename to UNITTESTS/features/cellular/framework/AT/at_cellularstack/at_cellularstacktest.cpp index 0e4eefca2c..40e2aebe9c 100644 --- a/features/cellular/UNITTESTS/at/at_cellularstack/test_at_cellularstack.cpp +++ b/UNITTESTS/features/cellular/framework/AT/at_cellularstack/at_cellularstacktest.cpp @@ -14,8 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "CppUTest/TestHarness.h" -#include "test_at_cellularstack.h" +#include "gtest/gtest.h" +#include "AT_CellularStack.h" #include #include "AT_CellularNetwork.h" #include "EventQueue.h" @@ -136,18 +136,27 @@ public: } }; -Test_AT_CellularStack::Test_AT_CellularStack() -{ - ATHandler_stub::ssize_value = 0; - ATHandler_stub::bool_value = false; - ATHandler_stub::read_string_value = NULL; -} +// AStyle ignored as the definition is not clear due to preprocessor usage +// *INDENT-OFF* +class TestAT_CellularStack : public testing::Test { +protected: -Test_AT_CellularStack::~Test_AT_CellularStack() -{ -} + void SetUp() + { + ATHandler_stub::return_given_size = false; + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; + ATHandler_stub::ssize_value = 0; + ATHandler_stub::bool_value = false; + ATHandler_stub::read_string_value = NULL; + } -void Test_AT_CellularStack::test_AT_CellularStack_constructor() + void TearDown() + { + } +}; +// *INDENT-ON* + +TEST_F(TestAT_CellularStack, Create) { EventQueue que; FileHandle_stub fh1; @@ -155,31 +164,32 @@ void Test_AT_CellularStack::test_AT_CellularStack_constructor() MyStack *st = new MyStack(at, 0, IPV4_STACK); + EXPECT_TRUE(st != NULL); delete st; } -void Test_AT_CellularStack::test_AT_CellularStack_get_ip_address() +TEST_F(TestAT_CellularStack, test_AT_CellularStack_get_ip_address) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); MyStack st(at, 0, IPV6_STACK); - CHECK(0 == strlen(st.get_ip_address())); + EXPECT_TRUE(0 == strlen(st.get_ip_address())); char table[] = "1.2.3.4.5.65.7.8.9.10.11\0"; ATHandler_stub::ssize_value = -1; ATHandler_stub::bool_value = true; ATHandler_stub::read_string_value = table; - CHECK(NULL == st.get_ip_address()); + EXPECT_TRUE(NULL == st.get_ip_address()); ATHandler_stub::ssize_value = strlen(table); ATHandler_stub::bool_value = true; ATHandler_stub::read_string_value = table; - CHECK(st.get_ip_address()); + EXPECT_TRUE(st.get_ip_address()); } -void Test_AT_CellularStack::test_AT_CellularStack_socket_open() +TEST_F(TestAT_CellularStack, test_AT_CellularStack_socket_open) { EventQueue que; FileHandle_stub fh1; @@ -187,45 +197,45 @@ void Test_AT_CellularStack::test_AT_CellularStack_socket_open() MyStack st(at, 0, IPV6_STACK); st.bool_value = false; - CHECK(NSAPI_ERROR_UNSUPPORTED == st.socket_open(NULL, NSAPI_TCP)); + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == st.socket_open(NULL, NSAPI_TCP)); st.bool_value = true; st.max_sock_value = 0; nsapi_socket_t sock = &st.socket; - CHECK(NSAPI_ERROR_NO_SOCKET == st.socket_open(&sock, NSAPI_TCP)); + EXPECT_TRUE(NSAPI_ERROR_NO_SOCKET == st.socket_open(&sock, NSAPI_TCP)); MyStack st2(at, 0, IPV6_STACK); st2.bool_value = true; st2.max_sock_value = 1; sock = &st2.socket; - CHECK(NSAPI_ERROR_OK == st2.socket_open(&sock, NSAPI_TCP)); + EXPECT_TRUE(NSAPI_ERROR_OK == st2.socket_open(&sock, NSAPI_TCP)); } -void Test_AT_CellularStack::test_AT_CellularStack_socket_close() +TEST_F(TestAT_CellularStack, test_AT_CellularStack_socket_close) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); MyStack st(at, 0, IPV6_STACK); - CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_close(&st.socket)); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == st.socket_close(&st.socket)); nsapi_socket_t sock = &st.socket; st.bool_value = true; st.max_sock_value = 1; - CHECK(NSAPI_ERROR_OK == st.socket_open(&sock, NSAPI_TCP)); + EXPECT_TRUE(NSAPI_ERROR_OK == st.socket_open(&sock, NSAPI_TCP)); st.max_sock_value = 0; - CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_close(sock)); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == st.socket_close(sock)); MyStack st2(at, 0, IPV6_STACK); st2.max_sock_value = 1; st2.bool_value = true; sock = &st2.socket; - CHECK(NSAPI_ERROR_OK == st2.socket_open(&sock, NSAPI_TCP)); - CHECK(NSAPI_ERROR_OK == st2.socket_close(sock)); + EXPECT_TRUE(NSAPI_ERROR_OK == st2.socket_open(&sock, NSAPI_TCP)); + EXPECT_TRUE(NSAPI_ERROR_OK == st2.socket_close(sock)); } -void Test_AT_CellularStack::test_AT_CellularStack_socket_bind() +TEST_F(TestAT_CellularStack, test_AT_CellularStack_socket_bind) { EventQueue que; FileHandle_stub fh1; @@ -234,22 +244,22 @@ void Test_AT_CellularStack::test_AT_CellularStack_socket_bind() MyStack st(at, 0, IPV6_STACK); SocketAddress addr; ATHandler_stub::nsapi_error_value = NSAPI_ERROR_ALREADY; - CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_bind(NULL, addr)); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == st.socket_bind(NULL, addr)); - CHECK(NSAPI_ERROR_ALREADY == st.socket_bind(&st.socket, addr)); + EXPECT_TRUE(NSAPI_ERROR_ALREADY == st.socket_bind(&st.socket, addr)); } -void Test_AT_CellularStack::test_AT_CellularStack_socket_listen() +TEST_F(TestAT_CellularStack, test_AT_CellularStack_socket_listen) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); MyStack st(at, 0, IPV6_STACK); - CHECK(NSAPI_ERROR_UNSUPPORTED == st.socket_listen(&st.socket, 4)); + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == st.socket_listen(&st.socket, 4)); } -void Test_AT_CellularStack::test_AT_CellularStack_socket_connect() +TEST_F(TestAT_CellularStack, test_AT_CellularStack_socket_connect) { EventQueue que; FileHandle_stub fh1; @@ -257,12 +267,12 @@ void Test_AT_CellularStack::test_AT_CellularStack_socket_connect() MyStack st(at, 0, IPV6_STACK); SocketAddress addr; - CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_connect(NULL, addr)); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == st.socket_connect(NULL, addr)); - CHECK(NSAPI_ERROR_OK == st.socket_connect(&st.socket, addr)); + EXPECT_TRUE(NSAPI_ERROR_OK == st.socket_connect(&st.socket, addr)); } -void Test_AT_CellularStack::test_AT_CellularStack_socket_accept() +TEST_F(TestAT_CellularStack, test_AT_CellularStack_socket_accept) { EventQueue que; FileHandle_stub fh1; @@ -270,19 +280,19 @@ void Test_AT_CellularStack::test_AT_CellularStack_socket_accept() MyStack st(at, 0, IPV6_STACK); nsapi_socket_t sock = &st.socket; - CHECK(NSAPI_ERROR_UNSUPPORTED == st.socket_accept(NULL, &sock)); + EXPECT_TRUE(NSAPI_ERROR_UNSUPPORTED == st.socket_accept(NULL, &sock)); } -void Test_AT_CellularStack::test_AT_CellularStack_socket_send() +TEST_F(TestAT_CellularStack, test_AT_CellularStack_socket_send) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); MyStack st(at, 0, IPV6_STACK); - CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_send(NULL, "addr", 4)); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == st.socket_send(NULL, "addr", 4)); - CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_send(&st.socket, "addr", 4)); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == st.socket_send(&st.socket, "addr", 4)); SocketAddress addr; st.max_sock_value = 1; @@ -290,10 +300,10 @@ void Test_AT_CellularStack::test_AT_CellularStack_socket_send() nsapi_socket_t sock = &st.socket; st.socket_open(&sock, NSAPI_TCP); st.socket_connect(sock, addr); - CHECK(NSAPI_ERROR_OK == st.socket_send(sock, "addr", 4)); + EXPECT_TRUE(NSAPI_ERROR_OK == st.socket_send(sock, "addr", 4)); } -void Test_AT_CellularStack::test_AT_CellularStack_socket_sendto() +TEST_F(TestAT_CellularStack, test_AT_CellularStack_socket_sendto) { EventQueue que; FileHandle_stub fh1; @@ -302,7 +312,7 @@ void Test_AT_CellularStack::test_AT_CellularStack_socket_sendto() MyStack st(at, 0, IPV6_STACK); SocketAddress addr; - CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_sendto(NULL, addr, "addr", 4)); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == st.socket_sendto(NULL, addr, "addr", 4)); st.max_sock_value = 1; st.bool_value = true; @@ -310,13 +320,13 @@ void Test_AT_CellularStack::test_AT_CellularStack_socket_sendto() st.socket_open(&sock, NSAPI_TCP); st.socket_connect(sock, addr); st.create_error = NSAPI_ERROR_CONNECTION_LOST; - CHECK(NSAPI_ERROR_CONNECTION_LOST == st.socket_sendto(sock, addr, "addr", 4)); + EXPECT_TRUE(NSAPI_ERROR_CONNECTION_LOST == st.socket_sendto(sock, addr, "addr", 4)); st.create_error = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == st.socket_sendto(sock, addr, "addr", 4)); + EXPECT_TRUE(NSAPI_ERROR_OK == st.socket_sendto(sock, addr, "addr", 4)); } -void Test_AT_CellularStack::test_AT_CellularStack_socket_recv() +TEST_F(TestAT_CellularStack, test_AT_CellularStack_socket_recv) { EventQueue que; FileHandle_stub fh1; @@ -324,10 +334,10 @@ void Test_AT_CellularStack::test_AT_CellularStack_socket_recv() MyStack st(at, 0, IPV6_STACK); char table[4]; - CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_recv(NULL, table, 4)); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == st.socket_recv(NULL, table, 4)); } -void Test_AT_CellularStack::test_AT_CellularStack_socket_recvfrom() +TEST_F(TestAT_CellularStack, test_AT_CellularStack_socket_recvfrom) { EventQueue que; FileHandle_stub fh1; @@ -335,7 +345,7 @@ void Test_AT_CellularStack::test_AT_CellularStack_socket_recvfrom() MyStack st(at, 0, IPV6_STACK); char table[4]; - CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_recvfrom(NULL, NULL, table, 4)); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == st.socket_recvfrom(NULL, NULL, table, 4)); SocketAddress addr; st.max_sock_value = 1; @@ -344,13 +354,13 @@ void Test_AT_CellularStack::test_AT_CellularStack_socket_recvfrom() st.socket_open(&sock, NSAPI_TCP); st.socket_connect(sock, addr); st.create_error = NSAPI_ERROR_CONNECTION_LOST; - CHECK(NSAPI_ERROR_CONNECTION_LOST == st.socket_recvfrom(sock, &addr, table, 4)); + EXPECT_TRUE(NSAPI_ERROR_CONNECTION_LOST == st.socket_recvfrom(sock, &addr, table, 4)); st.create_error = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == st.socket_recvfrom(sock, &addr, table, 4)); + EXPECT_TRUE(NSAPI_ERROR_OK == st.socket_recvfrom(sock, &addr, table, 4)); } -void Test_AT_CellularStack::test_AT_CellularStack_socket_attach() +TEST_F(TestAT_CellularStack, test_AT_CellularStack_socket_attach) { EventQueue que; FileHandle_stub fh1; diff --git a/UNITTESTS/features/cellular/framework/AT/at_cellularstack/unittest.cmake b/UNITTESTS/features/cellular/framework/AT/at_cellularstack/unittest.cmake new file mode 100644 index 0000000000..2f1a243e02 --- /dev/null +++ b/UNITTESTS/features/cellular/framework/AT/at_cellularstack/unittest.cmake @@ -0,0 +1,31 @@ + +#################### +# UNIT TESTS +#################### + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + features/cellular/framework/common/util + ../features/cellular/framework/common + ../features/cellular/framework/AT + ../features/frameworks/mbed-client-randlib/mbed-client-randlib +) + +# Source files +set(unittest-sources + ../features/cellular/framework/AT/AT_CellularStack.cpp +) + +# Test files +set(unittest-test-sources + features/cellular/framework/AT/at_cellularstack/at_cellularstacktest.cpp + stubs/ATHandler_stub.cpp + stubs/AT_CellularBase_stub.cpp + stubs/EventQueue_stub.cpp + stubs/FileHandle_stub.cpp + stubs/CellularUtil_stub.cpp + stubs/us_ticker_stub.cpp + stubs/NetworkStack_stub.cpp + stubs/SocketAddress_stub.cpp + stubs/mbed_assert_stub.c +) diff --git a/features/cellular/UNITTESTS/at/athandler/test_athandler.cpp b/UNITTESTS/features/cellular/framework/AT/athandler/athandlertest.cpp similarity index 73% rename from features/cellular/UNITTESTS/at/athandler/test_athandler.cpp rename to UNITTESTS/features/cellular/framework/AT/athandler/athandlertest.cpp index 3d01ad0cad..7a49a70c42 100644 --- a/features/cellular/UNITTESTS/at/athandler/test_athandler.cpp +++ b/UNITTESTS/features/cellular/framework/AT/athandler/athandlertest.cpp @@ -14,8 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "CppUTest/TestHarness.h" -#include "test_athandler.h" +#include "gtest/gtest.h" #include #include "AT_CellularNetwork.h" #include "EventQueue.h" @@ -34,16 +33,26 @@ void urc_callback() { } -Test_ATHandler::Test_ATHandler() -{ - -} - -Test_ATHandler::~Test_ATHandler() +void urc2_callback() { } -void Test_ATHandler::test_ATHandler_constructor() +// AStyle ignored as the definition is not clear due to preprocessor usage +// *INDENT-OFF* +class TestATHandler : public testing::Test { +protected: + + void SetUp() + { + } + + void TearDown() + { + } +}; +// *INDENT-ON* + +TEST_F(TestATHandler, Create) { EventQueue que; FileHandle_stub fh1; @@ -54,19 +63,20 @@ void Test_ATHandler::test_ATHandler_constructor() at = new ATHandler(&fh1, que, 0, NULL); + EXPECT_TRUE(at != NULL); delete at; } -void Test_ATHandler::test_ATHandler_get_file_handle() +TEST_F(TestATHandler, test_ATHandler_get_file_handle) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); - CHECK_EQUAL(&fh1, at.get_file_handle()); + EXPECT_EQ(&fh1, at.get_file_handle()); } -void Test_ATHandler::test_ATHandler_set_file_handle() +TEST_F(TestATHandler, test_ATHandler_set_file_handle) { EventQueue que; FileHandle_stub fh1, fh2; @@ -76,7 +86,7 @@ void Test_ATHandler::test_ATHandler_set_file_handle() at.set_file_handle(&fh2); } -void Test_ATHandler::test_ATHandler_lock() +TEST_F(TestATHandler, test_ATHandler_lock) { EventQueue que; FileHandle_stub fh1; @@ -86,7 +96,7 @@ void Test_ATHandler::test_ATHandler_lock() at.lock(); } -void Test_ATHandler::test_ATHandler_unlock() +TEST_F(TestATHandler, test_ATHandler_unlock) { EventQueue que; FileHandle_stub fh1; @@ -97,44 +107,64 @@ void Test_ATHandler::test_ATHandler_unlock() at.unlock(); } -void Test_ATHandler::test_ATHandler_unlock_return_error() +TEST_F(TestATHandler, test_ATHandler_unlock_return_error) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); - CHECK(NSAPI_ERROR_OK == at.unlock_return_error()); + EXPECT_TRUE(NSAPI_ERROR_OK == at.unlock_return_error()); } -void Test_ATHandler::test_ATHandler_set_urc_handler() +TEST_F(TestATHandler, test_ATHandler_set_urc_handler) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); const char ch[] = "testtesttesttest"; - at.set_urc_handler(ch, &urc_callback); + + mbed::Callback cb(&urc_callback); + at.set_urc_handler(ch, cb); + + //THIS IS NOT same callback in find_urc_handler??? + EXPECT_TRUE(NSAPI_ERROR_OK == at.set_urc_handler(ch, cb)); } -void Test_ATHandler::test_ATHandler_get_last_error() +TEST_F(TestATHandler, test_ATHandler_remove_urc_handler) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); - CHECK(NSAPI_ERROR_OK == at.get_last_error()); + const char ch[] = "testtesttesttest"; + + mbed::Callback cb(&urc_callback); + at.set_urc_handler(ch, cb); + + //This does nothing!!! + at.remove_urc_handler(ch, cb); } -void Test_ATHandler::test_ATHandler_get_last_device_error() +TEST_F(TestATHandler, test_ATHandler_get_last_error) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); - CHECK(0 == at.get_last_device_error().errCode); + EXPECT_TRUE(NSAPI_ERROR_OK == at.get_last_error()); } -void Test_ATHandler::test_ATHandler_inc_ref_count() +TEST_F(TestATHandler, test_ATHandler_get_last_device_error) +{ + EventQueue que; + FileHandle_stub fh1; + + ATHandler at(&fh1, que, 0, ","); + EXPECT_TRUE(0 == at.get_last_device_error().errCode); +} + +TEST_F(TestATHandler, test_ATHandler_inc_ref_count) { EventQueue que; FileHandle_stub fh1; @@ -143,7 +173,7 @@ void Test_ATHandler::test_ATHandler_inc_ref_count() at.inc_ref_count(); } -void Test_ATHandler::test_ATHandler_dec_ref_count() +TEST_F(TestATHandler, test_ATHandler_dec_ref_count) { EventQueue que; FileHandle_stub fh1; @@ -152,26 +182,26 @@ void Test_ATHandler::test_ATHandler_dec_ref_count() at.dec_ref_count(); } -void Test_ATHandler::test_ATHandler_get_ref_count() +TEST_F(TestATHandler, test_ATHandler_get_ref_count) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); - CHECK(1 == at.get_ref_count()); + EXPECT_TRUE(1 == at.get_ref_count()); at.inc_ref_count(); - CHECK(2 == at.get_ref_count()); + EXPECT_TRUE(2 == at.get_ref_count()); at.inc_ref_count(); - CHECK(3 == at.get_ref_count()); + EXPECT_TRUE(3 == at.get_ref_count()); at.dec_ref_count(); at.dec_ref_count(); - CHECK(1 == at.get_ref_count()); + EXPECT_TRUE(1 == at.get_ref_count()); } -void Test_ATHandler::test_ATHandler_set_at_timeout() +TEST_F(TestATHandler, test_ATHandler_set_at_timeout) { EventQueue que; FileHandle_stub fh1; @@ -182,7 +212,7 @@ void Test_ATHandler::test_ATHandler_set_at_timeout() at.set_at_timeout(80, true); } -void Test_ATHandler::test_ATHandler_restore_at_timeout() +TEST_F(TestATHandler, test_ATHandler_restore_at_timeout) { EventQueue que; FileHandle_stub fh1; @@ -193,7 +223,7 @@ void Test_ATHandler::test_ATHandler_restore_at_timeout() at.restore_at_timeout(); } -void Test_ATHandler::test_ATHandler_clear_error() +TEST_F(TestATHandler, test_ATHandler_clear_error) { EventQueue que; FileHandle_stub fh1; @@ -202,12 +232,18 @@ void Test_ATHandler::test_ATHandler_clear_error() at.clear_error(); } -void Test_ATHandler::test_ATHandler_process_oob() +TEST_F(TestATHandler, test_ATHandler_process_oob) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); + at.set_at_timeout(10); + + at.set_is_filehandle_usable(false); + at.process_oob(); + at.set_is_filehandle_usable(true); + filehandle_stub_short_value_counter = 1; fh1.short_value = POLLIN; at.set_urc_handler("s", &urc_callback); @@ -222,6 +258,8 @@ void Test_ATHandler::test_ATHandler_process_oob() char table[] = "ssssssssssssssssssssssssssssssss\0"; filehandle_stub_table = table; filehandle_stub_table_pos = 0; + mbed_poll_stub::revents_value = POLLIN; + mbed_poll_stub::int_value = 1; at.read_bytes(buf, 5); filehandle_stub_short_value_counter = 2; @@ -235,31 +273,32 @@ void Test_ATHandler::test_ATHandler_process_oob() filehandle_stub_short_value_counter = 1; at.process_oob(); - char table2[4]; + char table2[5]; table2[0] = '\r'; table2[1] = '\r'; table2[2] = '\n'; - table2[3] = 0; + table2[3] = '\n'; + table2[4] = 0; filehandle_stub_table = table2; at.clear_error(); timer_stub_value = 0; filehandle_stub_table_pos = 0; + mbed_poll_stub::revents_value = POLLIN; + mbed_poll_stub::int_value = 1; at.read_bytes(buf, 1); filehandle_stub_short_value_counter = 1; at.process_oob(); - filehandle_stub_table = table; - filehandle_stub_short_value_counter = 0; filehandle_stub_table_pos = 0; filehandle_stub_table = NULL; } -void Test_ATHandler::test_ATHandler_set_filehandle_sigio() +TEST_F(TestATHandler, test_ATHandler_set_filehandle_sigio) { EventQueue que; FileHandle_stub fh1; @@ -268,7 +307,7 @@ void Test_ATHandler::test_ATHandler_set_filehandle_sigio() at.set_filehandle_sigio(); } -void Test_ATHandler::test_ATHandler_flush() +TEST_F(TestATHandler, test_ATHandler_flush) { EventQueue que; FileHandle_stub fh1; @@ -279,7 +318,7 @@ void Test_ATHandler::test_ATHandler_flush() at.flush(); } -void Test_ATHandler::test_ATHandler_cmd_start() +TEST_F(TestATHandler, test_ATHandler_cmd_start) { EventQueue que; FileHandle_stub fh1; @@ -297,7 +336,7 @@ void Test_ATHandler::test_ATHandler_cmd_start() at.cmd_start("s"); } -void Test_ATHandler::test_ATHandler_write_int() +TEST_F(TestATHandler, test_ATHandler_write_int) { EventQueue que; FileHandle_stub fh1; @@ -320,14 +359,15 @@ void Test_ATHandler::test_ATHandler_write_int() // at.write_int(4); } -void Test_ATHandler::test_ATHandler_write_string() +TEST_F(TestATHandler, test_ATHandler_write_string) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); + fh1.size_value = -1; at.write_string("help"); - CHECK(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); at.clear_error(); mbed_poll_stub::revents_value = POLLOUT; @@ -335,24 +375,24 @@ void Test_ATHandler::test_ATHandler_write_string() fh1.size_value = -1; at.cmd_start("s"); at.write_string("help", true); - CHECK(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); at.clear_error(); mbed_poll_stub::revents_value = POLLOUT; mbed_poll_stub::int_value = 1; fh1.size_value = -1; at.write_string("help", true); - CHECK(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); at.clear_error(); mbed_poll_stub::revents_value = POLLOUT; mbed_poll_stub::int_value = 1; fh1.size_value = 7; at.write_string("help", true); - CHECK(NSAPI_ERROR_OK == at.get_last_error()); + EXPECT_TRUE(NSAPI_ERROR_OK == at.get_last_error()); } -void Test_ATHandler::test_ATHandler_cmd_stop() +TEST_F(TestATHandler, test_ATHandler_cmd_stop) { EventQueue que; FileHandle_stub fh1; @@ -364,10 +404,10 @@ void Test_ATHandler::test_ATHandler_cmd_stop() at.write_string("help", true); at.cmd_stop(); - CHECK(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); } -void Test_ATHandler::test_ATHandler_write_bytes() +TEST_F(TestATHandler, test_ATHandler_write_bytes) { EventQueue que; FileHandle_stub fh1; @@ -378,10 +418,10 @@ void Test_ATHandler::test_ATHandler_write_bytes() at.write_bytes(data, 4); at.write_bytes(data, 4); - CHECK(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); } -void Test_ATHandler::test_ATHandler_set_stop_tag() +TEST_F(TestATHandler, test_ATHandler_set_stop_tag) { EventQueue que; FileHandle_stub fh1; @@ -390,7 +430,7 @@ void Test_ATHandler::test_ATHandler_set_stop_tag() at.set_stop_tag("s"); } -void Test_ATHandler::test_ATHandler_set_delimiter() +TEST_F(TestATHandler, test_ATHandler_set_delimiter) { EventQueue que; FileHandle_stub fh1; @@ -399,73 +439,83 @@ void Test_ATHandler::test_ATHandler_set_delimiter() at.set_delimiter('+'); } -void Test_ATHandler::test_ATHandler_skip_param() +TEST_F(TestATHandler, test_ATHandler_skip_param) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); + at.set_stop_tag("OK\r\n"); at.skip_param(); char table[] = "ssssssssssssssssssssssssssssOK\r\n\0"; filehandle_stub_table = table; - filehandle_stub_table_pos = 0; at.flush(); at.clear_error(); + filehandle_stub_table_pos = 0; + mbed_poll_stub::revents_value = POLLIN; + mbed_poll_stub::int_value = 1; + filehandle_stub_short_value_counter = 1; + fh1.short_value = POLLIN; at.resp_start(); at.skip_param(); - CHECK(at.get_last_error() == NSAPI_ERROR_DEVICE_ERROR); + EXPECT_TRUE(at.get_last_error() == NSAPI_ERROR_DEVICE_ERROR); char table1[] = "ss,sssssssssssss,sssssssssssOK\r\n\0"; filehandle_stub_table = table1; - filehandle_stub_table_pos = 0; at.flush(); at.clear_error(); + filehandle_stub_short_value_counter = 1; + filehandle_stub_table_pos = 0; at.resp_start(); at.skip_param(); char table2[] = "sssOK\r\n\0"; filehandle_stub_table = table2; - filehandle_stub_table_pos = 0; at.flush(); at.clear_error(); + filehandle_stub_short_value_counter = 1; + filehandle_stub_table_pos = 0; at.resp_start(); at.skip_param(); char table3[] = "sssssssOK\nssss\0"; filehandle_stub_table = table3; - filehandle_stub_table_pos = 0; //Need to create a new instance because stop tag already found ATHandler at2(&fh1, que, 0, ","); at2.flush(); at2.clear_error(); + filehandle_stub_short_value_counter = 1; + filehandle_stub_table_pos = 0; at2.resp_start(); at2.skip_param(); at2.skip_param(4, 3); filehandle_stub_table = table3; - filehandle_stub_table_pos = 0; at2.flush(); at2.clear_error(); + filehandle_stub_short_value_counter = 1; + filehandle_stub_table_pos = 0; at2.resp_start(); at2.skip_param(4, 3); filehandle_stub_table = table3; - filehandle_stub_table_pos = 0; at2.flush(); at2.clear_error(); + filehandle_stub_short_value_counter = 1; + filehandle_stub_table_pos = 0; at2.resp_start(); at2.skip_param(24, 17); } -void Test_ATHandler::test_ATHandler_read_bytes() +TEST_F(TestATHandler, test_ATHandler_read_bytes) { EventQueue que; FileHandle_stub fh1; @@ -477,10 +527,10 @@ void Test_ATHandler::test_ATHandler_read_bytes() // TEST EMPTY BUFFER // Shouldn't read any byte since buffer is empty - CHECK(-1 == at.read_bytes(buf, 1)); - CHECK(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); + EXPECT_TRUE(-1 == at.read_bytes(buf, 1)); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); // Return error due to error set to at handler by the above call on empty buffer - CHECK(-1 == at.read_bytes(buf, 1)); + EXPECT_TRUE(-1 == at.read_bytes(buf, 1)); // TEST DATA IN BUFFER at.clear_error(); @@ -491,18 +541,18 @@ void Test_ATHandler::test_ATHandler_read_bytes() mbed_poll_stub::int_value = 1;; // Read 5 bytes - CHECK(5 == at.read_bytes(buf, 5)); - CHECK(!memcmp(buf, table1, 5)); + EXPECT_TRUE(5 == at.read_bytes(buf, 5)); + EXPECT_TRUE(!memcmp(buf, table1, 5)); // get_char triggered above should have filled in the whole reading buffer(fill_buffer()) - CHECK(filehandle_stub_table_pos == (strlen(table1) - 1)); + EXPECT_TRUE(filehandle_stub_table_pos == (strlen(table1) - 1)); // Read another 8 bytes - CHECK(8 == at.read_bytes(buf, 8) && !memcmp(buf, table1 + 5, 8)); + EXPECT_TRUE(8 == at.read_bytes(buf, 8) && !memcmp(buf, table1 + 5, 8)); // Reading more than the 4 bytes left -> ERROR - CHECK(-1 == at.read_bytes(buf, 5)); - CHECK(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); + EXPECT_TRUE(-1 == at.read_bytes(buf, 5)); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); } -void Test_ATHandler::test_ATHandler_read_string() +TEST_F(TestATHandler, test_ATHandler_read_string) { EventQueue que; FileHandle_stub fh1; @@ -521,15 +571,15 @@ void Test_ATHandler::test_ATHandler_read_string() mbed_poll_stub::int_value = 1; char buf1[1]; // No _stop_tag set without resp_start - CHECK(-1 == at.read_string(buf1, 1)); + EXPECT_TRUE(-1 == at.read_string(buf1, 1)); at.clear_error(); // Set _stop_tag to resp_stop(OKCRLF) at.resp_start(); // Device error because buffer is empty - CHECK(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); at.clear_error(); // Device error because empty buffer and attempt to fill_buffer by consume_char('\"') - CHECK(-1 == at.read_string(buf1, 1)); + EXPECT_TRUE(-1 == at.read_string(buf1, 1)); // *** 1 BYTE *** at.clear_error(); @@ -543,9 +593,9 @@ void Test_ATHandler::test_ATHandler_read_string() // Set _stop_tag to resp_stop(OKCRLF) at.resp_start(); // Device error because no CRLF and no more data to read - CHECK(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); at.clear_error(); - CHECK(0 == at.read_string(buf2, 1)); + EXPECT_TRUE(0 == at.read_string(buf2, 1)); // *** CRLF *** at.clear_error(); @@ -559,15 +609,16 @@ void Test_ATHandler::test_ATHandler_read_string() // Set _stop_tag to resp_stop(OKCRLF) at.resp_start(); // OK because after CRLF matched there is more data to read ending in CRLF - CHECK(NSAPI_ERROR_OK == at.get_last_error()); + EXPECT_TRUE(NSAPI_ERROR_OK == at.get_last_error()); // To read 0 bytes from: s\r\n - CHECK(0 == at.read_string(buf3, 0 + 1/*for NULL*/)); + EXPECT_TRUE(0 == at.read_string(buf3, 0 + 1/*for NULL*/)); // To read 1 byte from: s\r\n -> read s - CHECK(1 == at.read_string(buf3, 1 + 1/*for NULL*/)); + EXPECT_TRUE(1 == at.read_string(buf3, 1 + 1/*for NULL*/)); // *** Reading more than available in buffer *** at.clear_error(); char table4[] = "\"s,\"OK\r\n\0"; + mbed_poll_stub::int_value = 0; at.flush(); filehandle_stub_table = table4; filehandle_stub_table_pos = 0; @@ -580,8 +631,8 @@ void Test_ATHandler::test_ATHandler_read_string() // TO read 5 bytes from: "s,"OK\r\n -> read "s,"O at.read_bytes(buf5, 5); // K\r\n left to be read -> reading more than 3 + 1(for NULL) -> ERROR - CHECK(-1 == at.read_string(buf4, 4 + 1/*for NULL*/)); - CHECK(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); + EXPECT_TRUE(-1 == at.read_string(buf4, 4 + 1/*for NULL*/)); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); // *** Encountering delimiter after reading 1 byte *** at.clear_error(); @@ -593,7 +644,7 @@ void Test_ATHandler::test_ATHandler_read_string() // TO read 1 byte from: "s,"OK\r\n -> read " at.read_bytes(buf5, 1); // TO read max 4 from: s,"OK\r\n -> read s and stop on , - CHECK(1 == at.read_string(buf4, 4 + 1/*for NULL*/)); + EXPECT_TRUE(1 == at.read_string(buf4, 4 + 1/*for NULL*/)); // *** Encountering delimiter as first char in buffer *** at.clear_error(); @@ -605,7 +656,7 @@ void Test_ATHandler::test_ATHandler_read_string() // TO read 2 bytes from: "s,"OK\r\n -> read "s at.read_bytes(buf5, 2); // TO read max 4 bytes from: ,"OK\r\n -> stop on , - CHECK(0 == at.read_string(buf4, 4 + 1/*for NULL*/)); + EXPECT_TRUE(0 == at.read_string(buf4, 4 + 1/*for NULL*/)); // *** Read as much as buffer size is without encountering any delimiter " or OKCRLF *** at.clear_error(); @@ -620,19 +671,19 @@ void Test_ATHandler::test_ATHandler_read_string() // TO read 1 byte from: "s"OK\r\n -> read " at.read_bytes(buf5, 1); // TO read max 1 byte from: s"OK\r\n -> read s - CHECK(1 == at.read_string(buf4, 1 + 1/*for NULL*/)); + EXPECT_TRUE(1 == at.read_string(buf4, 1 + 1/*for NULL*/)); // *** Consume " and run into OKCRLF *** // TO read max 1 byte from: "OK\r\n -> consume " and find stop tag OKCRLF - CHECK(0 == at.read_string(buf4, 1 + 1/*for NULL*/)); + EXPECT_TRUE(0 == at.read_string(buf4, 1 + 1/*for NULL*/)); // *** Try to read after stop tag was found *** // stop tag found do not read further - CHECK(-1 == at.read_string(buf4, 1 + 1/*for NULL*/)); + EXPECT_TRUE(-1 == at.read_string(buf4, 1 + 1/*for NULL*/)); // *** Try to read after stop tag was found when parameter allows it *** // stop tag found but flag indicates to read despite stop_tag found - CHECK(4 == at.read_string(buf4, 4 + 1/*for NULL*/, true)); + EXPECT_TRUE(4 == at.read_string(buf4, 4 + 1/*for NULL*/, true)); // *** Read as much as buffer size is without encountering any delimiter " or OKCRLF *** at.clear_error(); @@ -644,7 +695,7 @@ void Test_ATHandler::test_ATHandler_read_string() mbed_poll_stub::int_value = 1; at.resp_start("s"); // TO read from: ss\rsss -> read all 6 chars ss\rsss - CHECK(6 == at.read_string(buf4, 6 + 1/*for NULL*/)); + EXPECT_TRUE(6 == at.read_string(buf4, 6 + 1/*for NULL*/)); // *** Reading when buffer only has " *** at.clear_error(); @@ -656,8 +707,8 @@ void Test_ATHandler::test_ATHandler_read_string() mbed_poll_stub::int_value = 1; at.resp_start("s"); // TO read from buffer having only " -> consume " -> trying to read when nothing in buffer - CHECK(-1 == at.read_string(buf4, 5)); - CHECK(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); + EXPECT_TRUE(-1 == at.read_string(buf4, 5)); + EXPECT_TRUE(NSAPI_ERROR_DEVICE_ERROR == at.get_last_error()); // *** Reading through partially matching stop tag *** at.clear_error(); @@ -671,7 +722,7 @@ void Test_ATHandler::test_ATHandler_read_string() // NO prefix, NO OK, NO ERROR and NO URC match, CRLF found -> return so buffer could be read at.resp_start(); // TO read from - CHECK(8 == at.read_string(buf8, 8 + 1/*for NULL*/)); + EXPECT_TRUE(8 == at.read_string(buf8, 8 + 1/*for NULL*/)); // *** Reading through partially matching stop tag *** at.clear_error(); @@ -686,11 +737,12 @@ void Test_ATHandler::test_ATHandler_read_string() // NO prefix, NO OK, NO ERROR and NO URC match, CRLF found -> return so buffer could be read at.resp_start(); // TO read from - CHECK(6 == at.read_string(buf9, 6 + 1/*for NULL*/)); + EXPECT_TRUE(6 == at.read_string(buf9, 6 + 1/*for NULL*/)); // *** CRLF part of the string *** at.clear_error(); char table10[] = "\"s\"\r\nOK\r\n\0"; + mbed_poll_stub::int_value = 0; at.flush(); filehandle_stub_table = table10; filehandle_stub_table_pos = 0; @@ -701,10 +753,10 @@ void Test_ATHandler::test_ATHandler_read_string() // NO prefix, NO OK, NO ERROR and NO URC match, CRLF found -> return so buffer could be read at.resp_start(); // TO read from - CHECK(3 == at.read_string(buf10, 9 + 1/*for NULL*/)); + EXPECT_TRUE(3 == at.read_string(buf10, 9 + 1/*for NULL*/)); } -void Test_ATHandler::test_ATHandler_read_hex_string() +TEST_F(TestATHandler, test_ATHandler_read_hex_string) { EventQueue que; FileHandle_stub fh1; @@ -724,8 +776,8 @@ void Test_ATHandler::test_ATHandler_read_hex_string() char buf1[10]; // Set _stop_tag to resp_stop(OKCRLF) at.resp_start(); - CHECK(5 == at.read_hex_string(buf1, 5)); - CHECK(!strncmp(buf1, "hello", 5)); + EXPECT_TRUE(5 == at.read_hex_string(buf1, 5)); + EXPECT_TRUE(!strncmp(buf1, "hello", 5)); // *** Read up to delimiter, odd length *** at.clear_error(); @@ -738,8 +790,8 @@ void Test_ATHandler::test_ATHandler_read_hex_string() char buf2[10]; // Set _stop_tag to resp_stop(OKCRLF) at.resp_start(); - CHECK(5 == at.read_hex_string(buf2, 6)); - CHECK(!strncmp(buf2, "hello", 5)); + EXPECT_TRUE(5 == at.read_hex_string(buf2, 6)); + EXPECT_TRUE(!strncmp(buf2, "hello", 5)); // *** Read with stop tag, even length *** at.clear_error(); @@ -752,8 +804,8 @@ void Test_ATHandler::test_ATHandler_read_hex_string() char buf3[6]; // Set _stop_tag to resp_stop(OKCRLF) at.resp_start(); - CHECK(2 == at.read_hex_string(buf3, 2 + 1/*get to stop tag match*/)); - CHECK(!strncmp(buf3, "he", 2)); + EXPECT_TRUE(2 == at.read_hex_string(buf3, 2 + 1/*get to stop tag match*/)); + EXPECT_TRUE(!strncmp(buf3, "he", 2)); at.resp_stop(); // *** Read with stop tag, odd length *** @@ -767,11 +819,11 @@ void Test_ATHandler::test_ATHandler_read_hex_string() char buf4[6]; // Set _stop_tag to resp_stop(OKCRLF) at.resp_start(); - CHECK(1 == at.read_hex_string(buf4, 2 + 1/*get to stop tag match*/)); - CHECK(!strncmp(buf4, "h", 1)); + EXPECT_TRUE(1 == at.read_hex_string(buf4, 2 + 1/*get to stop tag match*/)); + EXPECT_TRUE(!strncmp(buf4, "h", 1)); } -void Test_ATHandler::test_ATHandler_read_int() +TEST_F(TestATHandler, test_ATHandler_read_int) { EventQueue que; FileHandle_stub fh1; @@ -781,7 +833,7 @@ void Test_ATHandler::test_ATHandler_read_int() ATHandler at(&fh1, que, 0, ","); int32_t ret = at.read_int(); - CHECK(-1 == ret); + EXPECT_TRUE(-1 == ret); at.clear_error(); char table[] = "\",\"OK\r\n\0"; @@ -793,7 +845,7 @@ void Test_ATHandler::test_ATHandler_read_int() at.resp_start(); ret = at.read_int(); - CHECK(-1 == ret); + EXPECT_TRUE(-1 == ret); at.flush(); at.clear_error(); @@ -806,11 +858,10 @@ void Test_ATHandler::test_ATHandler_read_int() at.resp_start(); ret = at.read_int(); - CHECK(2 == ret); - + EXPECT_TRUE(2 == ret); } -void Test_ATHandler::test_ATHandler_resp_start() +TEST_F(TestATHandler, test_ATHandler_resp_start) { EventQueue que; FileHandle_stub fh1; @@ -828,6 +879,7 @@ void Test_ATHandler::test_ATHandler_resp_start() at.flush(); at.clear_error(); + filehandle_stub_table_pos = 0; at.resp_start("ssssaaaassssaaaassss"); //too long prefix char table3[] = "+CME ERROR: 108\0"; @@ -836,20 +888,22 @@ void Test_ATHandler::test_ATHandler_resp_start() at.flush(); at.clear_error(); + filehandle_stub_table_pos = 0; at.resp_start(); - filehandle_stub_table_pos = 0; at.flush(); at.clear_error(); + filehandle_stub_table_pos = 0; at.resp_start(); char table4[] = "+CMS ERROR: 6\0"; filehandle_stub_table = table4; - filehandle_stub_table_pos = 0; + filehandle_stub_table_pos = 0; at.flush(); at.clear_error(); + filehandle_stub_table_pos = 0; at.resp_start(); char table5[] = "ERROR\r\n\0"; @@ -858,6 +912,7 @@ void Test_ATHandler::test_ATHandler_resp_start() at.flush(); at.clear_error(); + filehandle_stub_table_pos = 0; at.resp_start(); char table6[] = "OK\r\n\0"; @@ -866,6 +921,7 @@ void Test_ATHandler::test_ATHandler_resp_start() at.flush(); at.clear_error(); + filehandle_stub_table_pos = 0; at.resp_start(); char table7[] = "ssssss\0"; @@ -875,10 +931,11 @@ void Test_ATHandler::test_ATHandler_resp_start() at.flush(); at.clear_error(); at.set_urc_handler("ss", NULL); + filehandle_stub_table_pos = 0; at.resp_start(); } -void Test_ATHandler::test_ATHandler_resp_stop() +TEST_F(TestATHandler, test_ATHandler_resp_stop) { EventQueue que; FileHandle_stub fh1; @@ -899,6 +956,7 @@ void Test_ATHandler::test_ATHandler_resp_stop() at.flush(); at.clear_error(); + filehandle_stub_table_pos = 0; at.resp_start(); at.resp_stop(); @@ -909,11 +967,12 @@ void Test_ATHandler::test_ATHandler_resp_stop() at.flush(); at.clear_error(); + filehandle_stub_table_pos = 0; at.resp_start("ss", false); at.resp_stop(); } -void Test_ATHandler::test_ATHandler_info_resp() +TEST_F(TestATHandler, test_ATHandler_info_resp) { EventQueue que; FileHandle_stub fh1; @@ -921,10 +980,10 @@ void Test_ATHandler::test_ATHandler_info_resp() filehandle_stub_table = NULL; ATHandler at(&fh1, que, 0, ","); - CHECK(at.info_resp()); + EXPECT_TRUE(at.info_resp()); at.resp_start(); - CHECK(!at.info_resp()); + EXPECT_TRUE(!at.info_resp()); at.flush(); at.clear_error(); @@ -936,9 +995,9 @@ void Test_ATHandler::test_ATHandler_info_resp() mbed_poll_stub::int_value = strlen(table2); at.resp_start("21"); - CHECK(at.info_resp()); + EXPECT_TRUE(at.info_resp()); - CHECK(!at.info_resp()); + EXPECT_TRUE(!at.info_resp()); at.flush(); at.clear_error(); @@ -949,10 +1008,10 @@ void Test_ATHandler::test_ATHandler_info_resp() mbed_poll_stub::revents_value = POLLIN; mbed_poll_stub::int_value = strlen(table3); - CHECK(at.info_resp()); + EXPECT_TRUE(at.info_resp()); } -void Test_ATHandler::test_ATHandler_info_elem() +TEST_F(TestATHandler, test_ATHandler_info_elem) { EventQueue que; FileHandle_stub fh1; @@ -964,7 +1023,7 @@ void Test_ATHandler::test_ATHandler_info_elem() mbed_poll_stub::int_value = strlen(table); ATHandler at(&fh1, que, 0, ","); - CHECK(!at.info_elem('O')); + EXPECT_TRUE(!at.info_elem('O')); at.flush(); char table2[] = "21 OK\r\n\0"; @@ -975,7 +1034,7 @@ void Test_ATHandler::test_ATHandler_info_elem() at.clear_error(); at.resp_start("21"); - CHECK(at.info_elem('O')); + EXPECT_TRUE(at.info_elem('O')); at.flush(); filehandle_stub_table = NULL; @@ -983,19 +1042,19 @@ void Test_ATHandler::test_ATHandler_info_elem() at.clear_error(); at.resp_start("21"); - CHECK(!at.info_elem('2')); + EXPECT_TRUE(!at.info_elem('2')); } -void Test_ATHandler::test_ATHandler_consume_to_stop_tag() +TEST_F(TestATHandler, test_ATHandler_consume_to_stop_tag) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); - CHECK(at.consume_to_stop_tag()); + EXPECT_TRUE(at.consume_to_stop_tag()); } -void Test_ATHandler::test_ATHandler_set_debug() +TEST_F(TestATHandler, test_ATHandler_set_debug) { EventQueue que; FileHandle_stub fh1; @@ -1006,11 +1065,12 @@ void Test_ATHandler::test_ATHandler_set_debug() at.set_debug(false); } -void Test_ATHandler::test_ATHandler_get_3gpp_error() +TEST_F(TestATHandler, test_ATHandler_get_3gpp_error) { EventQueue que; FileHandle_stub fh1; ATHandler at(&fh1, que, 0, ","); - int ret = at.get_3gpp_error(); + at.get_3gpp_error(); } + diff --git a/UNITTESTS/features/cellular/framework/AT/athandler/unittest.cmake b/UNITTESTS/features/cellular/framework/AT/athandler/unittest.cmake new file mode 100644 index 0000000000..25f8f91944 --- /dev/null +++ b/UNITTESTS/features/cellular/framework/AT/athandler/unittest.cmake @@ -0,0 +1,38 @@ + +#################### +# UNIT TESTS +#################### + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + features/cellular/framework/common/util + ../features/cellular/framework/common + ../features/cellular/framework/AT + ../features/frameworks/mbed-client-randlib/mbed-client-randlib +) + +# Source files +set(unittest-sources + ../features/cellular/framework/AT/ATHandler.cpp + ../features/cellular/framework/common/CellularUtil.cpp +) + +# Test files +set(unittest-test-sources + features/cellular/framework/AT/athandler/athandlertest.cpp + stubs/AT_CellularBase_stub.cpp + stubs/EventQueue_stub.cpp + stubs/FileHandle_stub.cpp + stubs/us_ticker_stub.cpp + stubs/mbed_wait_api_stub.cpp + stubs/mbed_assert_stub.c + stubs/mbed_poll_stub.cpp + stubs/Timer_stub.cpp + stubs/equeue_stub.c + stubs/Kernel_stub.cpp + stubs/Thread_stub.cpp + stubs/randLIB_stub.cpp +) + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DMBED_CONF_CELLULAR_DEBUG_AT=true -DOS_STACK_SIZE=2048") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DMBED_CONF_CELLULAR_DEBUG_AT=true -DOS_STACK_SIZE=2048") diff --git a/UNITTESTS/features/cellular/framework/common/util/test_util.cpp b/UNITTESTS/features/cellular/framework/common/util/test_util.cpp deleted file mode 100644 index 49aebf90b0..0000000000 --- a/UNITTESTS/features/cellular/framework/common/util/test_util.cpp +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (c) 2018, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "gtest/gtest.h" -#include "test_util.h" -#include -#include "CellularUtil.h" -#include - -using namespace mbed_cellular_util; - -Test_util::Test_util() -{ - -} - -Test_util::~Test_util() -{ -} - -void Test_util::test_util_uint_to_binary_string() -{ - char str[33]; - uint_to_binary_str(15, str, 33, 32); - str[32] = '\0'; - // 15 is "1111" in binary but we ask all 32 bits so it should return "00000000000000000000000000001111" - EXPECT_STREQ("00000000000000000000000000001111", str); - - // test NULL pointer - uint_to_binary_str(15, NULL, 0, 32); - - // test give too small buffer - char too_small[5]; - uint_to_binary_str(15, too_small, 5, 6); -} - -void Test_util::test_util_char_str_to_hex() -{ - // basic conversion test, happy days - char hex_buf[50]; - uint16_t number_of_hex_chars = char_str_to_hex_str("1234", 4, hex_buf); - hex_buf[number_of_hex_chars] = '\0'; - EXPECT_STREQ("31323334", hex_buf); - EXPECT_EQ(8, number_of_hex_chars); - - number_of_hex_chars = char_str_to_hex_str("wuhuu", 5, hex_buf); - hex_buf[number_of_hex_chars] = '\0'; - EXPECT_STREQ("7775687575", hex_buf); - EXPECT_EQ(10, number_of_hex_chars); - - // First don't omit the leading zero and then omit and check that leading zero is missing - number_of_hex_chars = char_str_to_hex_str("\nwuhuu", 6, hex_buf); - hex_buf[number_of_hex_chars] = '\0'; - EXPECT_STREQ("0A7775687575", hex_buf); - EXPECT_EQ(12, number_of_hex_chars); - - number_of_hex_chars = char_str_to_hex_str("\nwuhuu", 6, hex_buf, true); - hex_buf[number_of_hex_chars] = '\0'; - EXPECT_STREQ("A7775687575", hex_buf); - EXPECT_EQ(11, number_of_hex_chars); - - // test giving a null pointer - number_of_hex_chars = char_str_to_hex_str(NULL, 4, hex_buf); - EXPECT_EQ(0, number_of_hex_chars); - number_of_hex_chars = char_str_to_hex_str("1234", 4, NULL); - EXPECT_EQ(0, number_of_hex_chars); -} - -void Test_util::test_util_convert_ipv6() -{ - // leading zeros omitted - char ipv6[64]; - strncpy(ipv6, "1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1", 64); - convert_ipv6(ipv6); - EXPECT_STREQ("101:101:101:101:101:101:101:101", ipv6); - EXPECT_EQ(31, strlen(ipv6)); - - // some omitted and some not so much - strncpy(ipv6, "255.1.120.2.244.12.55.45.201.110.11.2.233.154.85.96", 64); - convert_ipv6(ipv6); - EXPECT_STREQ("FF01:7802:F40C:372D:C96E:B02:E99A:5560", ipv6); - EXPECT_EQ(38, strlen(ipv6)); - - // test giving a null pointer - convert_ipv6(NULL); -} - -void Test_util::test_util_prefer_ipv6() -{ - char tt[20] = "62.241.198.246"; - char temp[64] = "2001:14B8:1000:000:000:000:000:002"; - - // not enough space to swap, arrays should stay the same - prefer_ipv6(tt, sizeof(tt), temp, sizeof(temp)); - EXPECT_STREQ("62.241.198.246", tt); - EXPECT_STREQ("2001:14B8:1000:000:000:000:000:002", temp); - - // should swap as first one was ip4 and later was ipv6 and enough space - char tt2[64] = "62.241.198.246"; - prefer_ipv6(tt2, sizeof(tt2), temp, sizeof(temp)); - EXPECT_STREQ("62.241.198.246", temp); - EXPECT_STREQ("2001:14B8:1000:000:000:000:000:002", tt2); -} - -void Test_util::test_util_separate_ip_addresses() -{ - char *s = (char *)calloc(128, 1); - - char ip[64] = {0}; - char subnet[64] = {0}; - - strncpy(s, "32.1.20.187.1.112.139.245.251.136.232.110.123.51.230.138.0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15", 94); - separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); - EXPECT_STREQ("2001:14BB:170:8BF5:FB88:E86E:7B33:E68A", ip); - EXPECT_STREQ("001:203:405:607:809:A0B:C0D:E0F", subnet); - - strncpy(s, "32:1:20:187:1:112:139:245:251:136:232:110:123:51:230:138 0:1:2:3:4:5:6:7:8:9:10:11:12:13:14:15", 94); - separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); - EXPECT_STREQ("32:1:20:187:1:112:139:245:251:136:232:110:123:51:230:138", ip); - EXPECT_STREQ("0:1:2:3:4:5:6:7:8:9:10:11:12:13:14:15", subnet); - - ip[0] = '\0'; - subnet[0] = '\0'; - strncpy(s, "1.2.3.4\0", 8); - separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); - EXPECT_STREQ("1.2.3.4", ip); - EXPECT_STREQ("", subnet); - - ip[0] = '\0'; - subnet[0] = '\0'; - strncpy(s, "1.2.3.4.5.6.7.8\0", 16); - separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); - EXPECT_STREQ("1.2.3.4", ip); - EXPECT_STREQ("5.6.7.8", subnet); - - ip[0] = '\0'; - subnet[0] = '\0'; - strncpy(s, "1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16\0", 39); - separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); - EXPECT_STREQ("102:304:506:708:90A:B0C:D0E:F10", ip); - EXPECT_STREQ("", subnet); - - ip[0] = '\0'; - subnet[0] = '\0'; - strncpy(s, "32:1:20:187:1:112:139:245:251:136:232:110:123:51:230:138\0", 57); - separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); - EXPECT_STREQ("32:1:20:187:1:112:139:245:251:136:232:110:123:51:230:138", ip); - EXPECT_STREQ("", subnet); - - ip[0] = '\0'; - subnet[0] = '\0'; - strncpy(s, "1.2.3.4 32:1:20:187:1:112:139:245:251:136:232:110:123:51:230:138\0", 65); - separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); - EXPECT_STREQ("1.2.3.4", ip); - EXPECT_STREQ("32:1:20:187:1:112:139:245:251:136:232:110:123:51:230:138", subnet); - - ip[0] = '\0'; - subnet[0] = '\0'; - strncpy(s, "1.2.3.4 5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20\0", 51); - separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); - EXPECT_STREQ("1.2.3.4", ip); - EXPECT_STREQ("506:708:90A:B0C:D0E:F10:1112:1314", subnet); - EXPECT_STREQ("1.2.3.4 5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20", s); - - free(s); -} diff --git a/UNITTESTS/features/cellular/framework/common/util/unittest.cmake b/UNITTESTS/features/cellular/framework/common/util/unittest.cmake index b1d43bac34..5a51c7f42c 100644 --- a/UNITTESTS/features/cellular/framework/common/util/unittest.cmake +++ b/UNITTESTS/features/cellular/framework/common/util/unittest.cmake @@ -3,9 +3,6 @@ # UNIT TESTS #################### -# Unit test suite name -set(TEST_SUITE_NAME "cellular-framework-common-util") - # Add test specific include paths set(unittest-includes ${unittest-includes} features/cellular/framework/common/util @@ -20,7 +17,6 @@ set(unittest-sources # Test files set(unittest-test-sources - stubs/randLIB_stub.c - features/cellular/framework/common/util/test_util.cpp features/cellular/framework/common/util/utiltest.cpp + stubs/randLIB_stub.cpp ) diff --git a/UNITTESTS/features/cellular/framework/common/util/utiltest.cpp b/UNITTESTS/features/cellular/framework/common/util/utiltest.cpp index deaa0c5690..4c00da93c2 100644 --- a/UNITTESTS/features/cellular/framework/common/util/utiltest.cpp +++ b/UNITTESTS/features/cellular/framework/common/util/utiltest.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Arm Limited and affiliates + * Copyright (c) 2018, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,49 +15,187 @@ * limitations under the License. */ #include "gtest/gtest.h" -#include "test_util.h" +#include +#include "CellularUtil.h" -class TestUtil : public testing::Test { +using namespace mbed_cellular_util; + +// AStyle ignored as the definition is not clear due to preprocessor usage +// *INDENT-OFF* +class Testutil : public testing::Test { protected: - Test_util *unit; - virtual void SetUp() + void SetUp() { - unit = new Test_util(); } - virtual void TearDown() + void TearDown() { - delete unit; } }; +// *INDENT-ON* -TEST_F(TestUtil, Create) +TEST_F(Testutil, test_util_uint_to_binary_string) { - EXPECT_TRUE(unit); + char str[33]; + uint_to_binary_str(15, str, 33, 32); + str[32] = '\0'; + // 15 is "1111" in binary but we ask all 32 bits so it should return "00000000000000000000000000001111" + EXPECT_STREQ("00000000000000000000000000001111", str); + + // test NULL pointer + uint_to_binary_str(15, NULL, 0, 32); + + // test give too small buffer + char too_small[5]; + uint_to_binary_str(15, too_small, 5, 6); } -TEST_F(TestUtil, test_util_uint_to_binary_string) +TEST_F(Testutil, char_str_to_hex) { - unit->test_util_uint_to_binary_string(); + // basic conversion test, happy days + char hex_buf[50]; + uint16_t number_of_hex_chars = char_str_to_hex_str("1234", 4, hex_buf); + hex_buf[number_of_hex_chars] = '\0'; + EXPECT_STREQ("31323334", hex_buf); + EXPECT_EQ(8, number_of_hex_chars); + + number_of_hex_chars = char_str_to_hex_str("wuhuu", 5, hex_buf); + hex_buf[number_of_hex_chars] = '\0'; + EXPECT_STREQ("7775687575", hex_buf); + EXPECT_EQ(10, number_of_hex_chars); + + // First don't omit the leading zero and then omit and check that leading zero is missing + number_of_hex_chars = char_str_to_hex_str("\nwuhuu", 6, hex_buf); + hex_buf[number_of_hex_chars] = '\0'; + EXPECT_STREQ("0A7775687575", hex_buf); + EXPECT_EQ(12, number_of_hex_chars); + + number_of_hex_chars = char_str_to_hex_str("\nwuhuu", 6, hex_buf, true); + hex_buf[number_of_hex_chars] = '\0'; + EXPECT_STREQ("A7775687575", hex_buf); + EXPECT_EQ(11, number_of_hex_chars); + + // test giving a null pointer + number_of_hex_chars = char_str_to_hex_str(NULL, 4, hex_buf); + EXPECT_EQ(0, number_of_hex_chars); + number_of_hex_chars = char_str_to_hex_str("1234", 4, NULL); + EXPECT_EQ(0, number_of_hex_chars); } -TEST_F(TestUtil, char_str_to_hex) +TEST_F(Testutil, convert_ipv6) { - unit->test_util_char_str_to_hex(); + // leading zeros omitted + char ipv6[64]; + strncpy(ipv6, "1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1", 64); + convert_ipv6(ipv6); + EXPECT_STREQ("101:101:101:101:101:101:101:101", ipv6); + EXPECT_EQ(31, strlen(ipv6)); + + // some omitted and some not so much + strncpy(ipv6, "255.1.120.2.244.12.55.45.201.110.11.2.233.154.85.96", 64); + convert_ipv6(ipv6); + EXPECT_STREQ("FF01:7802:F40C:372D:C96E:B02:E99A:5560", ipv6); + EXPECT_EQ(38, strlen(ipv6)); + + // test giving a null pointer + convert_ipv6(NULL); } -TEST_F(TestUtil, convert_ipv6) +TEST_F(Testutil, prefer_ipv6) { - unit->test_util_convert_ipv6(); + char tt[20] = "62.241.198.246"; + char temp[64] = "2001:14B8:1000:000:000:000:000:002"; + + // not enough space to swap, arrays should stay the same + prefer_ipv6(tt, sizeof(tt), temp, sizeof(temp)); + EXPECT_STREQ("62.241.198.246", tt); + EXPECT_STREQ("2001:14B8:1000:000:000:000:000:002", temp); + + // should swap as first one was ip4 and later was ipv6 and enough space + char tt2[64] = "62.241.198.246"; + prefer_ipv6(tt2, sizeof(tt2), temp, sizeof(temp)); + EXPECT_STREQ("62.241.198.246", temp); + EXPECT_STREQ("2001:14B8:1000:000:000:000:000:002", tt2); } -TEST_F(TestUtil, prefer_ipv6) +TEST_F(Testutil, separate_ip_addresses) { - unit->test_util_prefer_ipv6(); + char *s = (char *)malloc(128); + + char ip[64] = {0}; + char subnet[64] = {0}; + + strncpy(s, "32.1.20.187.1.112.139.245.251.136.232.110.123.51.230.138.0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15\0", 95); + separate_ip_addresses(NULL, ip, sizeof(ip), subnet, sizeof(subnet)); + + separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); + EXPECT_STREQ("2001:14BB:170:8BF5:FB88:E86E:7B33:E68A", ip); + EXPECT_STREQ("001:203:405:607:809:A0B:C0D:E0F", subnet); + + strncpy(s, "32:1:20:187:1:112:139:245:251:136:232:110:123:51:230:138 0:1:2:3:4:5:6:7:8:9:10:11:12:13:14:15\0", 95); + separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); + EXPECT_STREQ("32:1:20:187:1:112:139:245:251:136:232:110:123:51:230:138", ip); + EXPECT_STREQ("0:1:2:3:4:5:6:7:8:9:10:11:12:13:14:15", subnet); + + ip[0] = '\0'; + subnet[0] = '\0'; + strncpy(s, "1.2.3.4\0", 8); + separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); + EXPECT_STREQ("1.2.3.4", ip); + EXPECT_STREQ("", subnet); + + ip[0] = '\0'; + subnet[0] = '\0'; + strncpy(s, "1.2.3.4.5.6.7.8\0", 16); + separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); + EXPECT_STREQ("1.2.3.4", ip); + EXPECT_STREQ("5.6.7.8", subnet); + + ip[0] = '\0'; + subnet[0] = '\0'; + strncpy(s, "1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16\0", 39); + separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); + EXPECT_STREQ("102:304:506:708:90A:B0C:D0E:F10", ip); + EXPECT_STREQ("", subnet); + + ip[0] = '\0'; + subnet[0] = '\0'; + strncpy(s, "32:1:20:187:1:112:139:245:251:136:232:110:123:51:230:138\0", 57); + separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); + EXPECT_STREQ("32:1:20:187:1:112:139:245:251:136:232:110:123:51:230:138", ip); + EXPECT_STREQ("", subnet); + + ip[0] = '\0'; + subnet[0] = '\0'; + strncpy(s, "1.2.3.4 32:1:20:187:1:112:139:245:251:136:232:110:123:51:230:138\0", 65); + separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); + EXPECT_STREQ("1.2.3.4", ip); + EXPECT_STREQ("32:1:20:187:1:112:139:245:251:136:232:110:123:51:230:138", subnet); + + ip[0] = '\0'; + subnet[0] = '\0'; + strncpy(s, "1.2.3.4 5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20\0", 51); + separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); + EXPECT_STREQ("1.2.3.4", ip); + EXPECT_STREQ("506:708:90A:B0C:D0E:F10:1112:1314", subnet); + EXPECT_STREQ("1.2.3.4 5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20", s); } -TEST_F(TestUtil, separate_ip_addresses) +TEST_F(Testutil, get_dynamic_ip_port) { - unit->test_util_separate_ip_addresses(); + uint16_t port = get_dynamic_ip_port(); + uint16_t port2 = get_dynamic_ip_port(); + + EXPECT_TRUE(port != port2); } + +TEST_F(Testutil, int_to_hex_str) +{ + char buf[2]; + int_to_hex_str(100, (char*)buf); + + EXPECT_TRUE(buf[0] == '6'); + EXPECT_TRUE(buf[1] == '4'); +} + diff --git a/UNITTESTS/features/lorawan/loramac/Test_LoRaMac.cpp b/UNITTESTS/features/lorawan/loramac/Test_LoRaMac.cpp new file mode 100644 index 0000000000..4999da0f1d --- /dev/null +++ b/UNITTESTS/features/lorawan/loramac/Test_LoRaMac.cpp @@ -0,0 +1,560 @@ +/* + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "gtest/gtest.h" +#include "LoRaMac.h" +#include "LoRaPHY_stub.h" +#include "LoRaMacCrypto_stub.h" +#include "LoRaMacCommand_stub.h" +#include "LoRaWANTimer_stub.h" +#include "EventQueue_stub.h" + +using namespace events; + +class my_phy : public LoRaPHY +{ +public: + my_phy(){}; + + virtual ~my_phy(){}; +}; + +class Test_LoRaMac : public testing::Test { +protected: + LoRaMac *object; + + virtual void SetUp() + { + object = new LoRaMac(); + } + + virtual void TearDown() + { + delete object; + } +}; + +TEST_F(Test_LoRaMac, constructor) +{ + EXPECT_TRUE(object); +} + +void my_cb() +{ + +} + +TEST_F(Test_LoRaMac, initialize) +{ + my_phy phy; + object->bind_phy(phy); + + lorawan_connect_t conn; + uint8_t key[16]; + conn.connection_u.otaa.app_key = key; + conn.connection_u.otaa.app_eui = key; + conn.connection_u.otaa.dev_eui = key; + conn.connection_u.otaa.nb_trials = 2; + object->prepare_join(&conn, true); + + LoRaWANTimer_stub::call_cb_immediately = true; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize(NULL, my_cb)); +} + +TEST_F(Test_LoRaMac, disconnect) +{ + object->disconnect(); +} + +TEST_F(Test_LoRaMac, nwk_joined) +{ + EXPECT_EQ(false, object->nwk_joined()); +} + +TEST_F(Test_LoRaMac, add_channel_plan) +{ + lorawan_channelplan_t plan; + EXPECT_EQ(LORAWAN_STATUS_OK, object->add_channel_plan(plan)); + + object->set_tx_ongoing(true); + EXPECT_EQ(LORAWAN_STATUS_BUSY, object->add_channel_plan(plan)); +} + +TEST_F(Test_LoRaMac, remove_channel_plan) +{ + EXPECT_EQ(LORAWAN_STATUS_OK, object->remove_channel_plan()); + + object->set_tx_ongoing(true); + EXPECT_EQ(LORAWAN_STATUS_BUSY, object->remove_channel_plan()); +} + +TEST_F(Test_LoRaMac, get_channel_plan) +{ + lorawan_channelplan_t plan; + EXPECT_EQ(LORAWAN_STATUS_OK, object->get_channel_plan(plan)); +} + +TEST_F(Test_LoRaMac, remove_single_channel) +{ + EXPECT_EQ(LORAWAN_STATUS_OK, object->remove_single_channel(1)); + + object->set_tx_ongoing(true); + EXPECT_EQ(LORAWAN_STATUS_BUSY, object->remove_single_channel(1)); +} + +TEST_F(Test_LoRaMac, multicast_channel_link) +{ + multicast_params_t p; + + EXPECT_EQ(LORAWAN_STATUS_PARAMETER_INVALID, object->multicast_channel_link(NULL)); + + object->set_tx_ongoing(true); + EXPECT_EQ(LORAWAN_STATUS_BUSY, object->multicast_channel_link(&p)); + + object->set_tx_ongoing(false); + EXPECT_EQ(LORAWAN_STATUS_OK, object->multicast_channel_link(&p)); +} + +TEST_F(Test_LoRaMac, multicast_channel_unlink) +{ + multicast_params_t p; + + EXPECT_EQ(LORAWAN_STATUS_PARAMETER_INVALID, object->multicast_channel_unlink(NULL)); + + object->set_tx_ongoing(true); + EXPECT_EQ(LORAWAN_STATUS_BUSY, object->multicast_channel_unlink(&p)); + + object->set_tx_ongoing(false); + EXPECT_EQ(LORAWAN_STATUS_OK, object->multicast_channel_unlink(&p)); +} + +TEST_F(Test_LoRaMac, send) +{ + loramac_mhdr_t mac_hdr; + uint8_t buf[15]; + mac_hdr.bits.mtype = FRAME_TYPE_DATA_CONFIRMED_UP; + object->send(&mac_hdr, 1, buf, 15); +} + +TEST_F(Test_LoRaMac, get_default_tx_datarate) +{ + object->get_default_tx_datarate(); +} + +TEST_F(Test_LoRaMac, enable_adaptive_datarate) +{ + object->enable_adaptive_datarate(true); +} + +TEST_F(Test_LoRaMac, set_channel_data_rate) +{ + object->set_channel_data_rate(8); +} + +TEST_F(Test_LoRaMac, tx_ongoing) +{ + object->tx_ongoing(); +} + +TEST_F(Test_LoRaMac, set_tx_ongoing) +{ + object->set_tx_ongoing(true); +} + +TEST_F(Test_LoRaMac, reset_ongoing_tx) +{ + object->reset_ongoing_tx(true); +} + +TEST_F(Test_LoRaMac, prepare_ongoing_tx) +{ + uint8_t buf[16]; + object->prepare_ongoing_tx(1, buf, 16, 1, 0); +} + +TEST_F(Test_LoRaMac, send_ongoing_tx) +{ + object->send_ongoing_tx(); +} + +TEST_F(Test_LoRaMac, get_device_class) +{ + object->get_device_class(); +} + +void exp_cb() +{ + +} + +TEST_F(Test_LoRaMac, set_device_class) +{ + object->set_device_class(CLASS_B, exp_cb); +} + +TEST_F(Test_LoRaMac, setup_link_check_request) +{ + object->setup_link_check_request(); +} + +TEST_F(Test_LoRaMac, prepare_join) +{ + lorawan_connect_t conn; + object->prepare_join(&conn, false); + + my_phy phy; + object->bind_phy(phy); + EXPECT_EQ(LORAWAN_STATUS_OK, object->join(false)); + + uint8_t key[16]; + conn.connection_u.otaa.app_key = NULL; + conn.connection_u.otaa.app_eui = NULL; + conn.connection_u.otaa.dev_eui = NULL; + conn.connection_u.otaa.nb_trials = 0; + EXPECT_EQ(LORAWAN_STATUS_PARAMETER_INVALID, object->prepare_join(&conn, true)); + + conn.connection_u.otaa.app_key = key; + conn.connection_u.otaa.app_eui = NULL; + conn.connection_u.otaa.dev_eui = NULL; + conn.connection_u.otaa.nb_trials = 0; + EXPECT_EQ(LORAWAN_STATUS_PARAMETER_INVALID, object->prepare_join(&conn, true)); + + conn.connection_u.otaa.app_key = key; + conn.connection_u.otaa.app_eui = key; + conn.connection_u.otaa.dev_eui = NULL; + conn.connection_u.otaa.nb_trials = 0; + EXPECT_EQ(LORAWAN_STATUS_PARAMETER_INVALID, object->prepare_join(&conn, true)); + + conn.connection_u.otaa.app_key = key; + conn.connection_u.otaa.app_eui = key; + conn.connection_u.otaa.dev_eui = key; + conn.connection_u.otaa.nb_trials = 0; + EXPECT_EQ(LORAWAN_STATUS_PARAMETER_INVALID, object->prepare_join(&conn, true)); + + LoRaPHY_stub::bool_table[0] = false; + LoRaPHY_stub::bool_counter = 0; + conn.connection_u.otaa.app_key = key; + conn.connection_u.otaa.app_eui = key; + conn.connection_u.otaa.dev_eui = key; + conn.connection_u.otaa.nb_trials = 2; + EXPECT_EQ(LORAWAN_STATUS_OK, object->prepare_join(&conn, true)); + + conn.connection_u.abp.dev_addr = 0; + conn.connection_u.abp.nwk_id = 0; + conn.connection_u.abp.nwk_skey = NULL; + conn.connection_u.abp.app_skey = NULL; + EXPECT_EQ(LORAWAN_STATUS_PARAMETER_INVALID, object->prepare_join(&conn, false)); + + conn.connection_u.abp.dev_addr = 1; + conn.connection_u.abp.nwk_id = 0; + conn.connection_u.abp.nwk_skey = NULL; + conn.connection_u.abp.app_skey = NULL; + EXPECT_EQ(LORAWAN_STATUS_PARAMETER_INVALID, object->prepare_join(&conn, false)); + + conn.connection_u.abp.dev_addr = 1; + conn.connection_u.abp.nwk_id = 2; + conn.connection_u.abp.nwk_skey = NULL; + conn.connection_u.abp.app_skey = NULL; + EXPECT_EQ(LORAWAN_STATUS_PARAMETER_INVALID, object->prepare_join(&conn, false)); + + conn.connection_u.abp.dev_addr = 1; + conn.connection_u.abp.nwk_id = 2; + conn.connection_u.abp.nwk_skey = key; + conn.connection_u.abp.app_skey = NULL; + EXPECT_EQ(LORAWAN_STATUS_PARAMETER_INVALID, object->prepare_join(&conn, false)); + + conn.connection_u.abp.dev_addr = 1; + conn.connection_u.abp.nwk_id = 2; + conn.connection_u.abp.nwk_skey = key; + conn.connection_u.abp.app_skey = key; + EXPECT_EQ(LORAWAN_STATUS_OK, object->prepare_join(&conn, false)); + + EXPECT_EQ(LORAWAN_STATUS_OK, object->prepare_join(NULL, false)); +} + +TEST_F(Test_LoRaMac, join) +{ + my_phy phy; + object->bind_phy(phy); + EXPECT_EQ(LORAWAN_STATUS_OK, object->join(false)); + + lorawan_connect_t conn; + uint8_t key[16]; + conn.connection_u.otaa.app_key = key; + conn.connection_u.otaa.app_eui = key; + conn.connection_u.otaa.dev_eui = key; + conn.connection_u.otaa.nb_trials = 2; + object->prepare_join(&conn, true); + EXPECT_EQ(LORAWAN_STATUS_CONNECT_IN_PROGRESS, object->join(true)); +} + +TEST_F(Test_LoRaMac, on_radio_tx_done) +{ + my_phy phy; + object->bind_phy(phy); + object->on_radio_tx_done(100); +} + +TEST_F(Test_LoRaMac, on_radio_rx_done) +{ + uint8_t buf[16]; + object->on_radio_rx_done(buf, 16, 0, 0); +} + +TEST_F(Test_LoRaMac, on_radio_tx_timeout) +{ + object->on_radio_tx_timeout(); +} + +TEST_F(Test_LoRaMac, on_radio_rx_timeout) +{ + object->on_radio_rx_timeout(true); +} + +TEST_F(Test_LoRaMac, continue_joining_process) +{ + my_phy phy; + object->bind_phy(phy); + lorawan_connect_t conn; + uint8_t key[16]; + conn.connection_u.otaa.app_key = key; + conn.connection_u.otaa.app_eui = key; + conn.connection_u.otaa.dev_eui = key; + conn.connection_u.otaa.nb_trials = 2; + object->prepare_join(&conn, true); + object->continue_joining_process(); +} + +TEST_F(Test_LoRaMac, continue_sending_process) +{ + my_phy phy; + object->bind_phy(phy); + object->continue_sending_process(); +} + +TEST_F(Test_LoRaMac, get_mcps_confirmation) +{ + object->get_mcps_confirmation(); +} + +TEST_F(Test_LoRaMac, get_mcps_indication) +{ + object->get_mcps_indication(); +} + +TEST_F(Test_LoRaMac, get_mlme_confirmation) +{ + object->get_mlme_confirmation(); +} + +TEST_F(Test_LoRaMac, get_mlme_indication) +{ + object->get_mlme_indication(); +} + +TEST_F(Test_LoRaMac, post_process_mcps_req) +{ + uint8_t data[16]; + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = true; + + my_phy phy; + object->bind_phy(phy); + object->join(false); + + object->prepare_ongoing_tx(1, data, 15, 0x01, 2); + object->send_ongoing_tx(); + object->post_process_mcps_req(); + + LoRaPHY_stub::bool_counter = 0; + object->prepare_ongoing_tx(1, data, 15, 0x02, 2); + object->send_ongoing_tx(); + object->post_process_mcps_req(); + + //_mcps_confirmation.ack_received missing here + uint8_t payload[16] = {}; + LoRaPHY_stub::uint16_value = 5; + payload[0] = FRAME_TYPE_DATA_CONFIRMED_DOWN << 5; + payload[5] = 1 << 5; + + //address != _params.dev_addr + payload[2] = 2; + object->on_radio_rx_done(payload, 16, 0, 0); + object->post_process_mcps_req(); + + payload[2] = 0; + //mic failure + payload[13] = 2; + object->on_radio_rx_done(payload, 16, 0, 0); + object->post_process_mcps_req(); + + payload[13] = 0; + //crypto failure + LoRaMacCrypto_stub::int_table_idx_value = 0; + LoRaMacCrypto_stub::int_table[0] = 4; + LoRaMacCrypto_stub::int_table[1] = 4; +// LoRaPHY_stub::uint16_value = 0; + object->on_radio_rx_done(payload, 16, 0, 0); + object->post_process_mcps_req(); + + //process_mac_commands failure + LoRaMacCommand_stub::status_value = LORAWAN_STATUS_BUSY; + LoRaMacCrypto_stub::int_table[0] = 0; + LoRaMacCrypto_stub::int_table[1] = 0; + payload[7] = 1; + object->on_radio_rx_done(payload, 16, 0, 0); + object->post_process_mcps_req(); + + //FOpts_len != 0 + payload[5] = (1 << 5) + 1; + payload[7] = 0; + LoRaMacCommand_stub::status_value = LORAWAN_STATUS_OK; + payload[0] = FRAME_TYPE_DATA_UNCONFIRMED_DOWN << 5; + + object->on_radio_rx_done(payload, 13, 0, 0); + + //_mac_commands.process_mac_commands fails + LoRaMacCommand_stub::status_value = LORAWAN_STATUS_DATARATE_INVALID; + object->on_radio_rx_done(payload, 13, 0, 0); + + object->post_process_mcps_req(); + + payload[9] = 1; + LoRaMacCommand_stub::status_value = LORAWAN_STATUS_OK; + payload[0] = FRAME_TYPE_PROPRIETARY << 5; + object->on_radio_rx_done(payload, 16, 0, 0); + object->post_process_mcps_req(); + + payload[9] = 0; + payload[5] = 1 << 5; + LoRaMacCommand_stub::status_value = LORAWAN_STATUS_OK; + object->on_radio_rx_done(payload, 16, 0, 0); + object->post_process_mcps_req(); + + LoRaPHY_stub::bool_counter = 0; + object->prepare_ongoing_tx(1, data, 15, 0x04, 2); + object->send_ongoing_tx(); + object->post_process_mcps_req(); + + LoRaPHY_stub::bool_counter = 0; + object->prepare_ongoing_tx(1, data, 15, 0x08, 2); + object->send_ongoing_tx(); + object->post_process_mcps_req(); +} + +TEST_F(Test_LoRaMac, handle_join_accept_frame) +{ + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = true; + + my_phy phy; + object->bind_phy(phy); + + uint8_t payload[16] = {}; + LoRaPHY_stub::uint16_value = 5; + payload[0] = FRAME_TYPE_JOIN_ACCEPT << 5; + payload[5] = 1 << 5; + + LoRaMacCrypto_stub::int_table_idx_value = 0; + LoRaMacCrypto_stub::int_table[0] = 4; + LoRaMacCrypto_stub::int_table[1] = 4; + LoRaMacCrypto_stub::int_table[2] = 4; + LoRaMacCrypto_stub::int_table[3] = 4; + object->on_radio_rx_done(payload, 16, 0, 0); + + LoRaMacCrypto_stub::int_table_idx_value = 0; + LoRaMacCrypto_stub::int_table[0] = 0; + object->on_radio_rx_done(payload, 16, 0, 0); + + LoRaMacCrypto_stub::int_table_idx_value = 0; + LoRaMacCrypto_stub::int_table[1] = 0; + object->on_radio_rx_done(payload, 16, 0, 0); + + //mic failure case + payload[13] = 17; + LoRaMacCrypto_stub::int_table_idx_value = 0; + object->on_radio_rx_done(payload, 16, 0, 0); + + payload[13] = 0; + LoRaMacCrypto_stub::int_table_idx_value = 0; + LoRaMacCrypto_stub::int_table[2] = 0; + object->on_radio_rx_done(payload, 16, 0, 0); +} + +TEST_F(Test_LoRaMac, post_process_mcps_ind) +{ + object->post_process_mcps_ind(); +} + +TEST_F(Test_LoRaMac, post_process_mlme_request) +{ + object->post_process_mlme_request(); +} + +TEST_F(Test_LoRaMac, post_process_mlme_ind) +{ + object->post_process_mlme_ind(); +} + +uint8_t batt_cb() +{ + +} + +TEST_F(Test_LoRaMac, set_batterylevel_callback) +{ + object->set_batterylevel_callback(batt_cb); +} + +TEST_F(Test_LoRaMac, get_backoff_timer_event_id) +{ + object->get_backoff_timer_event_id(); +} + +TEST_F(Test_LoRaMac, clear_tx_pipe) +{ + EXPECT_EQ(LORAWAN_STATUS_OK, object->clear_tx_pipe()); //timer id == 0 + + my_phy phy; + object->bind_phy(phy); + + lorawan_connect_t conn; + uint8_t key[16]; + conn.connection_u.otaa.app_key = key; + conn.connection_u.otaa.app_eui = key; + conn.connection_u.otaa.dev_eui = key; + conn.connection_u.otaa.nb_trials = 2; + object->prepare_join(&conn, true); + + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize(NULL, my_cb)); + EventQueue_stub::int_value = 0; + EXPECT_EQ(LORAWAN_STATUS_BUSY, object->clear_tx_pipe()); + + EventQueue_stub::int_value = 1; + EXPECT_EQ(LORAWAN_STATUS_OK, object->clear_tx_pipe()); +} + +TEST_F(Test_LoRaMac, get_current_time) +{ + object->get_current_time(); +} + +TEST_F(Test_LoRaMac, get_current_slot) +{ + object->get_current_slot(); +} + diff --git a/UNITTESTS/features/lorawan/loramac/unittest.cmake b/UNITTESTS/features/lorawan/loramac/unittest.cmake new file mode 100644 index 0000000000..aff97c0412 --- /dev/null +++ b/UNITTESTS/features/lorawan/loramac/unittest.cmake @@ -0,0 +1,58 @@ +#[[ + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +]] + +# Unit test suite name +set(TEST_SUITE_NAME "lorawan_LoRaMac") + +# Source files +set(unittest-sources + ../features/lorawan/lorastack/mac/LoRaMac.cpp +) + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + target_h + ../features/lorawan/lorastack/mac +) + +# Test & stub files +set(unittest-test-sources + features/lorawan/loramac/Test_LoRaMac.cpp + stubs/LoRaPHY_stub.cpp + stubs/LoRaWANStack_stub.cpp + stubs/mbed_assert_stub.c + stubs/LoRaMacCrypto_stub.cpp + stubs/LoRaMacChannelPlan_stub.cpp + stubs/LoRaWANTimer_stub.cpp + stubs/LoRaMacCommand_stub.cpp + stubs/EventQueue_stub.cpp + +) + +# defines +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DMBED_CONF_LORA_ADR_ON=true -DMBED_CONF_LORA_PUBLIC_NETWORK=true -DMBED_CONF_LORA_NB_TRIALS=2 -DMBED_CONF_LORA_DOWNLINK_PREAMBLE_LENGTH=5") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DMBED_CONF_LORA_ADR_ON=true -DMBED_CONF_LORA_PUBLIC_NETWORK=true -DMBED_CONF_LORA_NB_TRIALS=2 -DMBED_CONF_LORA_DOWNLINK_PREAMBLE_LENGTH=5") + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DMBED_CONF_LORA_DUTY_CYCLE_ON=true -DMBED_CONF_LORA_MAX_SYS_RX_ERROR=10 -DMBED_CONF_LORA_NWKSKEY=\"{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}\"") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DMBED_CONF_LORA_DUTY_CYCLE_ON=true -DMBED_CONF_LORA_MAX_SYS_RX_ERROR=10 -DMBED_CONF_LORA_NWKSKEY=\"{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}\"") + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DMBED_CONF_LORA_APPSKEY=\"{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}\"") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DMBED_CONF_LORA_APPSKEY=\"{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}\"") + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DMBED_CONF_LORA_DEVICE_ADDRESS=\"0x00000000\"") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DMBED_CONF_LORA_DEVICE_ADDRESS=\"0x00000000\"") + diff --git a/UNITTESTS/features/lorawan/loramacchannelplan/Test_LoRaMacChannelPlan.cpp b/UNITTESTS/features/lorawan/loramacchannelplan/Test_LoRaMacChannelPlan.cpp new file mode 100644 index 0000000000..123d9830a8 --- /dev/null +++ b/UNITTESTS/features/lorawan/loramacchannelplan/Test_LoRaMacChannelPlan.cpp @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "gtest/gtest.h" +#include "LoRaMacChannelPlan.h" +#include "LoRaPHY_stub.h" +#include "LoRaPHY.h" + +class my_LoRaPHY : public LoRaPHY +{ +public: + my_LoRaPHY(){}; + + virtual ~my_LoRaPHY(){}; +}; + + +class Test_LoRaMacChannelPlan : public testing::Test { +protected: + LoRaMacChannelPlan *object; + my_LoRaPHY phy; + + virtual void SetUp() + { + object = new LoRaMacChannelPlan(); + object->activate_channelplan_subsystem(&phy); + + LoRaPHY_stub::uint8_value = 0; + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::lorawan_status_value = LORAWAN_STATUS_OK; + LoRaPHY_stub::uint16_value = 0; + memcpy(LoRaPHY_stub::bool_table, "0", 20); + } + + virtual void TearDown() + { + delete object; + } +}; + +TEST_F(Test_LoRaMacChannelPlan, constructor) +{ + EXPECT_TRUE(object); +} + +TEST_F(Test_LoRaMacChannelPlan, set_plan) +{ + lorawan_channelplan_t plan; + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = false; + EXPECT_TRUE(object->set_plan(plan) == LORAWAN_STATUS_SERVICE_UNKNOWN); + + plan.nb_channels = 1; + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = true; + LoRaPHY_stub::uint8_value = 0; + EXPECT_TRUE(object->set_plan(plan) == LORAWAN_STATUS_PARAMETER_INVALID); + + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = true; + LoRaPHY_stub::uint8_value = 10; + LoRaPHY_stub::lorawan_status_value = LORAWAN_STATUS_PARAMETER_INVALID; + EXPECT_TRUE(object->set_plan(plan) == LORAWAN_STATUS_PARAMETER_INVALID); + + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = true; + plan.nb_channels = 2; + LoRaPHY_stub::lorawan_status_value = LORAWAN_STATUS_OK; + EXPECT_TRUE(object->set_plan(plan) == LORAWAN_STATUS_OK); +} + +TEST_F(Test_LoRaMacChannelPlan, get_plan) +{ + lorawan_channelplan_t plan; + channel_params_t params; + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = false; + EXPECT_TRUE(object->get_plan(plan, ¶ms) == LORAWAN_STATUS_SERVICE_UNKNOWN); + + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = true; + LoRaPHY_stub::bool_table[1] = false; + + LoRaPHY_stub::uint8_value = 1; + LoRaPHY_stub::uint16_value = 0xABCD; + EXPECT_TRUE(object->get_plan(plan, ¶ms) == LORAWAN_STATUS_OK); + + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = true; + LoRaPHY_stub::bool_table[1] = true; + LoRaPHY_stub::bool_table[2] = false; + loramac_channel_t ch; + plan.channels = &ch; + EXPECT_TRUE(object->get_plan(plan, ¶ms) == LORAWAN_STATUS_OK); +} + +TEST_F(Test_LoRaMacChannelPlan, remove_plan) +{ + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = false; + EXPECT_TRUE(object->remove_plan() == LORAWAN_STATUS_SERVICE_UNKNOWN); + + LoRaPHY_stub::uint8_value = 4; + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = true; + LoRaPHY_stub::bool_table[1] = true; //first continue + LoRaPHY_stub::bool_table[2] = false; + LoRaPHY_stub::bool_table[3] = false;//second continue + LoRaPHY_stub::bool_table[4] = false; + LoRaPHY_stub::bool_table[5] = true; + LoRaPHY_stub::bool_table[6] = false;//false for remove_single_channel(i) + + EXPECT_TRUE(object->remove_plan() == LORAWAN_STATUS_SERVICE_UNKNOWN); + + LoRaPHY_stub::uint8_value = 3; + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = true; + LoRaPHY_stub::bool_table[1] = false; + LoRaPHY_stub::bool_table[2] = true; + LoRaPHY_stub::bool_table[3] = true; + LoRaPHY_stub::bool_table[4] = true; + LoRaPHY_stub::bool_table[5] = true; + LoRaPHY_stub::bool_table[7] = true; + LoRaPHY_stub::bool_table[8] = true; + LoRaPHY_stub::bool_table[9] = true; + LoRaPHY_stub::bool_table[10] = true; + + EXPECT_TRUE(object->remove_plan() == LORAWAN_STATUS_OK); + +} + +TEST_F(Test_LoRaMacChannelPlan, remove_single_channel) +{ + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = false; + EXPECT_TRUE(object->remove_single_channel(4) == LORAWAN_STATUS_SERVICE_UNKNOWN); + + LoRaPHY_stub::uint8_value = 2; + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = true; + + EXPECT_TRUE(object->remove_single_channel(4) == LORAWAN_STATUS_PARAMETER_INVALID); + + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = true; + LoRaPHY_stub::bool_table[1] = false; + EXPECT_TRUE(object->remove_single_channel(1) == LORAWAN_STATUS_PARAMETER_INVALID); + + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = true; + LoRaPHY_stub::bool_table[1] = true; + EXPECT_TRUE(object->remove_single_channel(1) == LORAWAN_STATUS_OK); +} + diff --git a/UNITTESTS/features/lorawan/loramacchannelplan/unittest.cmake b/UNITTESTS/features/lorawan/loramacchannelplan/unittest.cmake new file mode 100644 index 0000000000..1f15bf09ed --- /dev/null +++ b/UNITTESTS/features/lorawan/loramacchannelplan/unittest.cmake @@ -0,0 +1,39 @@ +#[[ + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +]] + +# Unit test suite name +set(TEST_SUITE_NAME "lorawan_LoRaMacChannelPlan") + +# Source files +set(unittest-sources + ../features/lorawan/lorastack/mac/LoRaMacChannelPlan.cpp +) + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + target_h + ../features/lorawan/lorastack/mac +) + +# Test & stub files +set(unittest-test-sources + features/lorawan/loramacchannelplan/Test_LoRaMacChannelPlan.cpp + stubs/LoRaPHY_stub.cpp +) + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DMBED_CONF_LORA_TX_MAX_SIZE=255") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DMBED_CONF_LORA_TX_MAX_SIZE=255") diff --git a/UNITTESTS/features/lorawan/loramaccommand/Test_LoRaMacCommand.cpp b/UNITTESTS/features/lorawan/loramaccommand/Test_LoRaMacCommand.cpp new file mode 100644 index 0000000000..3417a5eba3 --- /dev/null +++ b/UNITTESTS/features/lorawan/loramaccommand/Test_LoRaMacCommand.cpp @@ -0,0 +1,353 @@ +/* + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "gtest/gtest.h" +#include "LoRaMacCommand.h" + +#include "LoRaPHY_stub.h" + +class my_LoRaPHY : public LoRaPHY +{ +public: + my_LoRaPHY(){}; + + virtual ~my_LoRaPHY(){}; +}; + +uint8_t my_cb() +{ + return 1; +} + +class Test_LoRaMacCommand : public testing::Test { +protected: + LoRaMacCommand *object; + + virtual void SetUp() + { + object = new LoRaMacCommand(); + } + + virtual void TearDown() + { + delete object; + } +}; + +TEST_F(Test_LoRaMacCommand, constructor) +{ + EXPECT_TRUE(object); +} + +TEST_F(Test_LoRaMacCommand, get_mac_cmd_length) +{ + object->add_link_check_req(); + EXPECT_TRUE(object->get_mac_cmd_length() == 1); + object->clear_command_buffer(); + EXPECT_TRUE(object->get_mac_cmd_length() == 0); +} + +TEST_F(Test_LoRaMacCommand, parse_mac_commands_to_repeat) +{ + loramac_mlme_confirm_t mlme; + lora_mac_system_params_t params; + my_LoRaPHY phy; + uint8_t buf[20]; + + object->parse_mac_commands_to_repeat(); + + buf[0] = 2; + buf[1] = 16; + buf[2] = 32; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 3, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + buf[0] = 3; + LoRaPHY_stub::uint8_value = 7; + LoRaPHY_stub::linkAdrNbBytesParsed = 5; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 5, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + buf[0] = 4; + buf[1] = 2; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 1, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + buf[0] = 5; + buf[1] = 2; + buf[2] = 2; + buf[3] = 2; + buf[4] = 2; + buf[5] = 2; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 5, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + buf[0] = 6; + object->set_batterylevel_callback(my_cb); + EXPECT_TRUE(object->process_mac_commands(buf, 0, 1, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + buf[0] = 7; + buf[1] = 2; + buf[2] = 2; + buf[3] = 2; + buf[4] = 2; + buf[5] = 2; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 6, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + buf[0] = 8; + buf[1] = 0; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 2, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + buf[0] = 9; + buf[1] = 48; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 2, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + buf[0] = 10; + buf[1] = 2; + buf[1] = 3; + buf[1] = 4; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 4, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + object->parse_mac_commands_to_repeat(); +} + +TEST_F(Test_LoRaMacCommand, clear_repeat_buffer) +{ + object->clear_repeat_buffer(); +} + +TEST_F(Test_LoRaMacCommand, copy_repeat_commands_to_buffer) +{ + loramac_mlme_confirm_t mlme; + lora_mac_system_params_t params; + my_LoRaPHY phy; + uint8_t buf[20]; + + object->clear_command_buffer(); + buf[0] = 5; + buf[1] = 2; + buf[2] = 2; + buf[3] = 2; + buf[4] = 2; + buf[5] = 2; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 5, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + object->parse_mac_commands_to_repeat(); + + object->clear_command_buffer(); + EXPECT_TRUE(object->get_mac_cmd_length() == 0); + + object->copy_repeat_commands_to_buffer(); + + EXPECT_TRUE(object->get_mac_cmd_length() != 0); +} + +TEST_F(Test_LoRaMacCommand, get_repeat_commands_length) +{ + EXPECT_TRUE(object->get_repeat_commands_length() == 0 ); +} + +TEST_F(Test_LoRaMacCommand, clear_sticky_mac_cmd) +{ + loramac_mlme_confirm_t mlme; + lora_mac_system_params_t params; + my_LoRaPHY phy; + uint8_t buf[20]; + + EXPECT_TRUE(object->has_sticky_mac_cmd() == false); + + object->clear_command_buffer(); + buf[0] = 5; + buf[1] = 2; + buf[2] = 2; + buf[3] = 2; + buf[4] = 2; + buf[5] = 2; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 5, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + EXPECT_TRUE(object->has_sticky_mac_cmd() == true); + + object->clear_sticky_mac_cmd(); + EXPECT_TRUE(object->has_sticky_mac_cmd() == false); +} + +TEST_F(Test_LoRaMacCommand, has_sticky_mac_cmd) +{ + loramac_mlme_confirm_t mlme; + lora_mac_system_params_t params; + my_LoRaPHY phy; + uint8_t buf[20]; + + EXPECT_TRUE(object->has_sticky_mac_cmd() == false); + + object->clear_command_buffer(); + buf[0] = 5; + buf[1] = 2; + buf[2] = 2; + buf[3] = 2; + buf[4] = 2; + buf[5] = 2; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 5, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + EXPECT_TRUE(object->has_sticky_mac_cmd() == true); +} + +TEST_F(Test_LoRaMacCommand, process_mac_commands) +{ + loramac_mlme_confirm_t mlme; + lora_mac_system_params_t params; + my_LoRaPHY phy; + uint8_t buf[20]; + EXPECT_TRUE(object->process_mac_commands(NULL, 0, 0, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + buf[0] = 2; + buf[1] = 16; + buf[2] = 32; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 3, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + buf[0] = 3; + LoRaPHY_stub::uint8_value = 7; + LoRaPHY_stub::linkAdrNbBytesParsed = 5; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 5, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + //Overflow add_link_adr_ans function here + object->clear_command_buffer(); + buf[0] = 3; + for (int i=0; i < 64; i++) { + EXPECT_TRUE(object->process_mac_commands(buf, 0, 5, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + } + EXPECT_TRUE(object->process_mac_commands(buf, 0, 5, 0, mlme, params, phy) == LORAWAN_STATUS_LENGTH_ERROR); + + object->clear_command_buffer(); + buf[0] = 4; + buf[1] = 2; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 1, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + //Overflow add_duty_cycle_ans() + object->clear_command_buffer(); + for (int i=0; i < 128; i++) { + EXPECT_TRUE(object->process_mac_commands(buf, 0, 1, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + } + EXPECT_TRUE(object->process_mac_commands(buf, 0, 1, 0, mlme, params, phy) == LORAWAN_STATUS_LENGTH_ERROR); + + object->clear_command_buffer(); + buf[0] = 5; + buf[1] = 2; + buf[2] = 2; + buf[3] = 2; + buf[4] = 2; + buf[5] = 2; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 5, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + //Overflow add_rx_param_setup_ans + object->clear_command_buffer(); + LoRaPHY_stub::uint8_value = 7; + for (int i=0; i < 64; i++) { + EXPECT_TRUE(object->process_mac_commands(buf, 0, 5, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + } + EXPECT_TRUE(object->process_mac_commands(buf, 0, 5, 0, mlme, params, phy) == LORAWAN_STATUS_LENGTH_ERROR); + + object->clear_command_buffer(); + buf[0] = 6; + object->set_batterylevel_callback(my_cb); + EXPECT_TRUE(object->process_mac_commands(buf, 0, 1, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + //overflow add_dev_status_ans + object->clear_command_buffer(); + for (int i=0; i < 42; i++) { + EXPECT_TRUE(object->process_mac_commands(buf, 0, 1, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + } + EXPECT_TRUE(object->process_mac_commands(buf, 0, 1, 0, mlme, params, phy) == LORAWAN_STATUS_LENGTH_ERROR); + + object->clear_command_buffer(); + buf[0] = 7; + buf[1] = 2; + buf[2] = 2; + buf[3] = 2; + buf[4] = 2; + buf[5] = 2; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 6, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + //Overflow add_new_channel_ans + object->clear_command_buffer(); + LoRaPHY_stub::uint8_value = 7; + for (int i=0; i < 64; i++) { + EXPECT_TRUE(object->process_mac_commands(buf, 0, 6, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + } + EXPECT_TRUE(object->process_mac_commands(buf, 0, 6, 0, mlme, params, phy) == LORAWAN_STATUS_LENGTH_ERROR); + + object->clear_command_buffer(); + buf[0] = 8; + buf[1] = 0; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 2, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + //Overflow add_rx_timing_setup_ans + object->clear_command_buffer(); + LoRaPHY_stub::uint8_value = 7; + for (int i=0; i < 128; i++) { + EXPECT_TRUE(object->process_mac_commands(buf, 0, 2, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + } + EXPECT_TRUE(object->process_mac_commands(buf, 0, 2, 0, mlme, params, phy) == LORAWAN_STATUS_LENGTH_ERROR); + + object->clear_command_buffer(); + buf[0] = 9; + buf[1] = 48; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 2, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + //Overflow add_tx_param_setup_ans + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = true; + object->clear_command_buffer(); + LoRaPHY_stub::uint8_value = 7; + for (int i=0; i < 128; i++) { + EXPECT_TRUE(object->process_mac_commands(buf, 0, 2, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + LoRaPHY_stub::bool_counter = 0; + } + EXPECT_TRUE(object->process_mac_commands(buf, 0, 2, 0, mlme, params, phy) == LORAWAN_STATUS_LENGTH_ERROR); + + object->clear_command_buffer(); + buf[0] = 10; + buf[1] = 2; + buf[1] = 3; + buf[1] = 4; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 4, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + + //Overflow add_tx_param_setup_ans + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = true; + object->clear_command_buffer(); + LoRaPHY_stub::uint8_value = 7; + for (int i=0; i < 64; i++) { + EXPECT_TRUE(object->process_mac_commands(buf, 0, 4, 0, mlme, params, phy) == LORAWAN_STATUS_OK); + LoRaPHY_stub::bool_counter = 0; + } + EXPECT_TRUE(object->process_mac_commands(buf, 0, 4, 0, mlme, params, phy) == LORAWAN_STATUS_LENGTH_ERROR); + + object->clear_command_buffer(); + buf[0] = 80; + EXPECT_TRUE(object->process_mac_commands(buf, 0, 1, 0, mlme, params, phy) == LORAWAN_STATUS_UNSUPPORTED); +} + +TEST_F(Test_LoRaMacCommand, add_link_check_req) +{ + object->add_link_check_req(); + EXPECT_TRUE(object->get_mac_commands_buffer()[0] == 2); + EXPECT_TRUE(object->get_mac_cmd_length() == 1); + object->clear_command_buffer(); + EXPECT_TRUE(object->get_mac_cmd_length() == 0); +} + +TEST_F(Test_LoRaMacCommand, set_batterylevel_callback) +{ + object->set_batterylevel_callback(my_cb); +} + diff --git a/UNITTESTS/features/lorawan/loramaccommand/unittest.cmake b/UNITTESTS/features/lorawan/loramaccommand/unittest.cmake new file mode 100644 index 0000000000..1dc3272977 --- /dev/null +++ b/UNITTESTS/features/lorawan/loramaccommand/unittest.cmake @@ -0,0 +1,38 @@ +#[[ + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +]] + +# Unit test suite name +set(TEST_SUITE_NAME "lorawan_LoRaMacCommand") + +# Source files +set(unittest-sources + ../features/lorawan/lorastack/mac/LoRaMacCommand.cpp +) + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + target_h + ../features/lorawan/lorastack/mac +) + +# Test & stub files +set(unittest-test-sources + features/lorawan/loramaccommand/Test_LoRaMacCommand.cpp + stubs/mbed_assert_stub.c + stubs/LoRaPHY_stub.cpp +) + diff --git a/UNITTESTS/features/lorawan/loramaccrypto/Test_LoRaMacCrypto.cpp b/UNITTESTS/features/lorawan/loramaccrypto/Test_LoRaMacCrypto.cpp new file mode 100644 index 0000000000..1c00938238 --- /dev/null +++ b/UNITTESTS/features/lorawan/loramaccrypto/Test_LoRaMacCrypto.cpp @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "gtest/gtest.h" +#include "LoRaMacCrypto.h" + +#include "cipher_stub.h" +#include "cmac_stub.h" +#include "aes_stub.h" + +class Test_LoRaMacCrypto : public testing::Test { +protected: + LoRaMacCrypto *object; + + virtual void SetUp() + { + cipher_stub.info_value = NULL; + cipher_stub.int_zero_counter = 0; + cipher_stub.int_value = 0; + cmac_stub.int_zero_counter = 0; + cmac_stub.int_value = 0; + aes_stub.int_zero_counter = 0; + aes_stub.int_value = 0; + object = new LoRaMacCrypto(); + } + + virtual void TearDown() + { + delete object; + } +}; + +TEST_F(Test_LoRaMacCrypto, constructor) +{ + EXPECT_TRUE(object); + LoRaMacCrypto obj; +} + +TEST_F(Test_LoRaMacCrypto, compute_mic) +{ + EXPECT_TRUE(MBEDTLS_ERR_CIPHER_ALLOC_FAILED == object->compute_mic(NULL, 0, NULL, 0, 0, 0, 0, NULL)); + + mbedtls_cipher_info_t info; + cipher_stub.info_value = &info; + cipher_stub.int_zero_counter = 0; + cipher_stub.int_value = -1; + EXPECT_TRUE(-1 == object->compute_mic(NULL, 0, NULL, 0, 0, 0, 0, NULL)); + + cipher_stub.int_value = 0; + cmac_stub.int_zero_counter = 0; + cmac_stub.int_value = -1; + EXPECT_TRUE(-1 == object->compute_mic(NULL, 0, NULL, 0, 0, 0, 0, NULL)); + + cmac_stub.int_zero_counter = 1; + cmac_stub.int_value = -1; + EXPECT_TRUE(-1 == object->compute_mic(NULL, 0, NULL, 0, 0, 0, 0, NULL)); + + cmac_stub.int_zero_counter = 2; + cmac_stub.int_value = -1; + EXPECT_TRUE(-1 == object->compute_mic(NULL, 0, NULL, 0, 0, 0, 0, NULL)); + + cmac_stub.int_zero_counter = 3; + cmac_stub.int_value = -1; + EXPECT_TRUE(-1 == object->compute_mic(NULL, 0, NULL, 0, 0, 0, 0, NULL)); + + uint32_t mic[16]; + cmac_stub.int_zero_counter = 3; + cmac_stub.int_value = 0; + EXPECT_TRUE(0 == object->compute_mic(NULL, 0, NULL, 0, 0, 0, 0, mic)); + +} + +TEST_F(Test_LoRaMacCrypto, encrypt_payload) +{ + aes_stub.int_zero_counter = 0; + aes_stub.int_value = -1; + EXPECT_TRUE(-1 == object->encrypt_payload(NULL, 0, NULL, 0, 0, 0, 0, NULL)); + + aes_stub.int_zero_counter = 1; + aes_stub.int_value = -2; + uint8_t buf[60]; + uint8_t enc[60]; + EXPECT_TRUE(-2 == object->encrypt_payload(buf, 20, NULL, 0, 0, 0, 0, enc)); + + aes_stub.int_zero_counter = 2; + aes_stub.int_value = -3; + EXPECT_TRUE(-3 == object->encrypt_payload(buf, 20, NULL, 0, 0, 0, 0, enc)); + + aes_stub.int_value = 0; + EXPECT_TRUE(0 == object->encrypt_payload(buf, 20, NULL, 0, 0, 0, 0, enc)); + + EXPECT_TRUE(0 == object->encrypt_payload(buf, 60, NULL, 0, 0, 0, 0, enc)); + + aes_stub.int_zero_counter = 0; + EXPECT_TRUE(0 == object->encrypt_payload(NULL, 0, NULL, 0, 0, 0, 0, NULL)); +} + +TEST_F(Test_LoRaMacCrypto, decrypt_payload) +{ + EXPECT_TRUE(0 == object->decrypt_payload(NULL, 0, NULL, 0, 0, 0, 0, NULL)); +} + +TEST_F(Test_LoRaMacCrypto, compute_join_frame_mic) +{ + uint32_t mic[16]; + EXPECT_TRUE(MBEDTLS_ERR_CIPHER_ALLOC_FAILED == object->compute_join_frame_mic(NULL, 0, NULL, 0, NULL)); + mbedtls_cipher_info_t info; + cipher_stub.info_value = &info; + cipher_stub.int_zero_counter = 0; + cipher_stub.int_value = -1; + EXPECT_TRUE(-1 == object->compute_join_frame_mic(NULL, 0, NULL, 0, NULL)); + + cipher_stub.int_value = 0; + cmac_stub.int_zero_counter = 0; + cmac_stub.int_value = -1; + EXPECT_TRUE(-1 == object->compute_join_frame_mic(NULL, 0, NULL, 0, NULL)); + + cmac_stub.int_zero_counter = 1; + cmac_stub.int_value = -1; + EXPECT_TRUE(-1 == object->compute_join_frame_mic(NULL, 0, NULL, 0, NULL)); + + cmac_stub.int_zero_counter = 2; + cmac_stub.int_value = -1; + EXPECT_TRUE(-1 == object->compute_join_frame_mic(NULL, 0, NULL, 0, NULL)); + + cmac_stub.int_zero_counter = 3; + cmac_stub.int_value = 0; + EXPECT_TRUE(0 == object->compute_join_frame_mic(NULL, 0, NULL, 0, mic)); +} + +TEST_F(Test_LoRaMacCrypto, decrypt_join_frame) +{ + aes_stub.int_zero_counter = 0; + aes_stub.int_value = -1; + EXPECT_TRUE(-1 == object->decrypt_join_frame(NULL, 0, NULL, 0, NULL)); + + aes_stub.int_zero_counter = 1; + aes_stub.int_value = -1; + EXPECT_TRUE(-1 == object->decrypt_join_frame(NULL, 0, NULL, 0, NULL)); + + aes_stub.int_value = 0; + uint8_t buf[60]; + uint8_t enc[60]; + EXPECT_TRUE(0 == object->decrypt_join_frame(buf, 60, NULL, 0, enc)); +} + +TEST_F(Test_LoRaMacCrypto, compute_skeys_for_join_frame) +{ + uint8_t nwk_key[16]; + uint8_t app_key[16]; + uint8_t nonce[16]; + + aes_stub.int_zero_counter = 0; + aes_stub.int_value = -1; + EXPECT_TRUE(-1 == object->compute_skeys_for_join_frame(NULL, 0, nonce, 0, nwk_key, app_key)); + + aes_stub.int_zero_counter = 1; + aes_stub.int_value = -2; + EXPECT_TRUE(-2 == object->compute_skeys_for_join_frame(NULL, 0, nonce, 0, nwk_key, app_key)); + + aes_stub.int_zero_counter = 0; + aes_stub.int_value = 0; + EXPECT_TRUE(0 == object->compute_skeys_for_join_frame(NULL, 0, nonce, 0, nwk_key, app_key)); +} diff --git a/UNITTESTS/features/lorawan/loramaccrypto/unittest.cmake b/UNITTESTS/features/lorawan/loramaccrypto/unittest.cmake new file mode 100644 index 0000000000..e41d668906 --- /dev/null +++ b/UNITTESTS/features/lorawan/loramaccrypto/unittest.cmake @@ -0,0 +1,40 @@ +#[[ + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +]] + +# Unit test suite name +set(TEST_SUITE_NAME "lorawan_LoRaMacCrypto") + +# Source files +set(unittest-sources + ../features/lorawan/lorastack/mac/LoRaMacCrypto.cpp +) + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + target_h + ../features/lorawan/lorastack/mac +) + +# Test & stub files +set(unittest-test-sources + features/lorawan/loramaccrypto/Test_LoRaMacCrypto.cpp + stubs/cipher_stub.c + stubs/aes_stub.c + stubs/cmac_stub.c + +) + diff --git a/UNITTESTS/features/lorawan/loraphy/Test_LoRaPHY.cpp b/UNITTESTS/features/lorawan/loraphy/Test_LoRaPHY.cpp new file mode 100644 index 0000000000..6b7fabaaaf --- /dev/null +++ b/UNITTESTS/features/lorawan/loraphy/Test_LoRaPHY.cpp @@ -0,0 +1,814 @@ +/* + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "gtest/gtest.h" +#include "LoRaPHY.h" + +#include "LoRaWANTimer_stub.h" + +class my_LoRaPHY : public LoRaPHY +{ +public: + my_LoRaPHY(){phy_params.adr_ack_delay = 1;} + + virtual ~my_LoRaPHY(){} + + loraphy_params_t &get_phy_params() { + return phy_params; + } +}; + +class my_radio : public LoRaRadio +{ +public: + + virtual void init_radio(radio_events_t *events){}; + + virtual void radio_reset(){}; + + virtual void sleep(void){}; + + virtual void standby(void){}; + + virtual void set_rx_config (radio_modems_t modem, uint32_t bandwidth, + uint32_t datarate, uint8_t coderate, + uint32_t bandwidth_afc, uint16_t preamble_len, + uint16_t symb_timeout, bool fix_len, + uint8_t payload_len, + bool crc_on, bool freq_hop_on, uint8_t hop_period, + bool iq_inverted, bool rx_continuous){}; + + virtual void set_tx_config(radio_modems_t modem, int8_t power, uint32_t fdev, + uint32_t bandwidth, uint32_t datarate, + uint8_t coderate, uint16_t preamble_len, + bool fix_len, bool crc_on, bool freq_hop_on, + uint8_t hop_period, bool iq_inverted, uint32_t timeout){}; + + virtual void send(uint8_t *buffer, uint8_t size){}; + + virtual void receive(void){}; + + virtual void set_channel(uint32_t freq){}; + + virtual uint32_t random(void){}; + + virtual uint8_t get_status(void){return uint8_value;}; + + virtual void set_max_payload_length(radio_modems_t modem, uint8_t max){}; + + virtual void set_public_network(bool enable){}; + + virtual uint32_t time_on_air(radio_modems_t modem, uint8_t pkt_len){}; + + virtual bool perform_carrier_sense(radio_modems_t modem, + uint32_t freq, + int16_t rssi_threshold, + uint32_t max_carrier_sense_time){ return bool_value;}; + + virtual void start_cad(void){}; + + virtual bool check_rf_frequency(uint32_t frequency){ return bool_value; }; + + virtual void set_tx_continuous_wave(uint32_t freq, int8_t power, uint16_t time){}; + + virtual void lock(void){}; + + virtual void unlock(void){}; + + bool bool_value; + uint8_t uint8_value; +}; + +class Test_LoRaPHY : public testing::Test { +protected: + my_LoRaPHY *object; + + virtual void SetUp() + { + object = new my_LoRaPHY(); + } + + virtual void TearDown() + { + delete object; + } +}; + +TEST_F(Test_LoRaPHY, initialize) +{ + object->initialize(NULL); +} + +TEST_F(Test_LoRaPHY, set_radio_instance) +{ + my_radio radio; + object->set_radio_instance(radio); +} + +TEST_F(Test_LoRaPHY, put_radio_to_sleep) +{ + my_radio radio; + object->set_radio_instance(radio); + object->put_radio_to_sleep(); +} + +TEST_F(Test_LoRaPHY, put_radio_to_standby) +{ + my_radio radio; + object->set_radio_instance(radio); + object->put_radio_to_standby(); +} + +TEST_F(Test_LoRaPHY, handle_receive) +{ + my_radio radio; + object->set_radio_instance(radio); + object->handle_receive(); +} + +TEST_F(Test_LoRaPHY, handle_send) +{ + my_radio radio; + object->set_radio_instance(radio); + object->handle_send(NULL, 0); +} + +TEST_F(Test_LoRaPHY, setup_public_network_mode) +{ + my_radio radio; + channel_params_t p; + object->get_phy_params().channels.channel_list = &p; + object->set_radio_instance(radio); + object->setup_public_network_mode(false); +} + +TEST_F(Test_LoRaPHY, get_radio_rng) +{ + my_radio radio; + object->set_radio_instance(radio); + EXPECT_TRUE(0 != object->get_radio_rng()); +} + +TEST_F(Test_LoRaPHY, calculate_backoff) +{ + channel_params_t p[1]; + p[0].band = 0; + object->get_phy_params().channels.channel_list = p; + band_t b[1]; + object->get_phy_params().bands.table = b; + object->calculate_backoff(false, false, false, 0, 10, 12); + + object->calculate_backoff(false, true, false, 0, 3600000 + 10, 12); + + object->calculate_backoff(false, false, true, 0, 3600000 + 36000000 + 10, 12); +} + +TEST_F(Test_LoRaPHY, mask_bit_test) +{ + uint16_t buf; + EXPECT_TRUE(!object->mask_bit_test(&buf, 0)); +} + +TEST_F(Test_LoRaPHY, mask_bit_set) +{ + uint16_t buf; + object->mask_bit_set(&buf, 3); +} + +TEST_F(Test_LoRaPHY, mask_bit_clear) +{ + uint16_t buf; + object->mask_bit_clear(&buf, 0); +} + +TEST_F(Test_LoRaPHY, request_new_channel) +{ + channel_params_t p; + EXPECT_TRUE(0 == object->request_new_channel(1, &p)); + + p.frequency = 0; + object->get_phy_params().custom_channelplans_supported = true; + uint16_t list; + object->get_phy_params().channels.default_mask = &list; + channel_params_t pp; + object->get_phy_params().channels.channel_list = &pp; + EXPECT_TRUE(0 == object->request_new_channel(1, &p)); + + //Default + p.frequency = 2; + EXPECT_TRUE(0 == object->request_new_channel(1, &p)); + + //Freq & DR invalid + object->get_phy_params().max_channel_cnt = 2; + EXPECT_TRUE(0 == object->request_new_channel(1, &p)); + + //Freq invalid + pp.frequency = 0; + object->get_phy_params().default_max_datarate = 1; + object->get_phy_params().max_tx_datarate = 8; + p.dr_range.fields.max = 2; + p.dr_range.fields.min = 0; + object->get_phy_params().default_channel_cnt = 3; + EXPECT_TRUE(2 == object->request_new_channel(0, &p)); + + //DR invalid + pp.frequency = 2; + p.band = 0; + object->get_phy_params().bands.size = 1; + band_t b; + object->get_phy_params().bands.table = &b; + b.higher_band_freq = 5; + b.lower_band_freq = 1; + p.dr_range.fields.max = 12; + p.dr_range.fields.min = 1; + EXPECT_TRUE(1 == object->request_new_channel(0, &p)); + + //STATUS_OK + p.dr_range.fields.max = 2; + uint16_t list2[16]; + p.dr_range.fields.min = 0; + object->get_phy_params().channels.mask = list2; + EXPECT_TRUE(3 == object->request_new_channel(0, &p)); +} + +TEST_F(Test_LoRaPHY, set_last_tx_done) +{ + channel_params_t p[1]; + p[0].band = 0; + object->get_phy_params().channels.channel_list = p; + band_t b[1]; + object->get_phy_params().bands.table = b; + object->set_last_tx_done(0, false, 0); + + object->set_last_tx_done(0, true, 0); +} + +TEST_F(Test_LoRaPHY, restore_default_channels) +{ + channel_params_t p[1]; + p[0].band = 0; + object->get_phy_params().channels.channel_list = p; + uint16_t m, dm; + object->get_phy_params().channels.mask_size = 1; + object->get_phy_params().channels.default_mask = &dm; + object->get_phy_params().channels.mask = &m; + object->restore_default_channels(); +} + +TEST_F(Test_LoRaPHY, apply_cf_list) +{ + uint8_t list[16]; + object->apply_cf_list(list, 0); + + object->get_phy_params().cflist_supported = true; + object->apply_cf_list(list, 0); + + object->get_phy_params().default_channel_cnt = 2; + object->get_phy_params().cflist_channel_cnt = 0; + object->get_phy_params().max_channel_cnt = 3; + + uint16_t mask[8]; + channel_params_t p[8]; + object->get_phy_params().channels.default_mask = mask; + object->get_phy_params().channels.mask = mask; + object->get_phy_params().channels.channel_list = p; + object->apply_cf_list(list, 16); + + list[1] = 15; + object->get_phy_params().cflist_channel_cnt = 1; + object->apply_cf_list(list, 16); +} + +TEST_F(Test_LoRaPHY, get_next_ADR) +{ + int8_t i = 0; + int8_t j = 0; + uint32_t ctr = 0; + object->get_phy_params().min_tx_datarate = 0; + EXPECT_TRUE(!object->get_next_ADR(false, i, j, ctr)); + + i = 1; + object->get_phy_params().adr_ack_limit = 3; + EXPECT_TRUE(!object->get_next_ADR(false, i, j, ctr)); + + object->get_phy_params().adr_ack_limit = 3; + ctr = 4; + object->get_phy_params().max_tx_power = 2; + object->get_phy_params().adr_ack_delay = 1; + EXPECT_TRUE(object->get_next_ADR(true, i, j, ctr)); + + ctr = 5; + object->get_phy_params().adr_ack_delay = 2; + EXPECT_TRUE(!object->get_next_ADR(true, i, j, ctr)); +} + +TEST_F(Test_LoRaPHY, rx_config) +{ + my_radio radio; + object->set_radio_instance(radio); + uint8_t list; + object->get_phy_params().datarates.table = &list; + uint8_t list2; + object->get_phy_params().payloads_with_repeater.table = &list2; + rx_config_params_t p; + p.datarate = 0; + p.rx_slot = RX_SLOT_WIN_1; + channel_params_t pp[1]; + object->get_phy_params().channels.channel_list = pp; + pp[0].rx1_frequency = 2; + p.channel = 0; + uint8_t tab[8]; + object->get_phy_params().payloads.table = tab; + object->get_phy_params().payloads_with_repeater.table = tab; + EXPECT_TRUE(object->rx_config(&p)); + + p.datarate = DR_7; + p.is_repeater_supported = true; + object->get_phy_params().fsk_supported = true; + EXPECT_TRUE(object->rx_config(&p)); +} + +TEST_F(Test_LoRaPHY, compute_rx_win_params) +{ + uint32_t list[1]; + list[0] = 0; + object->get_phy_params().bandwidths.table = list; + uint8_t list2; + object->get_phy_params().datarates.table = &list2; + rx_config_params_t p; + object->compute_rx_win_params(0, 0, 0, &p); + + p.datarate = 0; + list[0] = 125000; + object->compute_rx_win_params(0, 0, 0, &p); + + list[0] = 250000; + object->compute_rx_win_params(0, 0, 0, &p); + + list[0] = 500000; + object->get_phy_params().fsk_supported = true; + object->get_phy_params().max_rx_datarate = 0; + object->compute_rx_win_params(0, 0, 0, &p); +} + +TEST_F(Test_LoRaPHY, tx_config) +{ + band_t b; + object->get_phy_params().bands.table = &b; + channel_params_t pp; + pp.band=0; + object->get_phy_params().channels.channel_list = &pp; + uint32_t list = 0; + object->get_phy_params().bandwidths.table = &list; + uint8_t list2; + object->get_phy_params().datarates.table = &list2; + my_radio radio; + object->set_radio_instance(radio); + tx_config_params_t p; + p.channel=0; + int8_t i; + lorawan_time_t t; + object->tx_config(&p, &i, &t); + + p.datarate = 8; + object->get_phy_params().max_tx_datarate = 8; + object->tx_config(&p, &i, &t); +} + +TEST_F(Test_LoRaPHY, link_ADR_request) +{ + adr_req_params_t p; + uint8_t b[100]; + p.payload = b; + b[0] = 0x03; + b[1] = 1; + b[2] = 0; + b[3] = 0; + b[4] = 1 << 4; + b[5] = 0x03; + b[6] = 1; + b[7] = 1; + b[8] = 1; + b[9] = 6 << 4; + b[10] = 0x03; + b[11] = 1; + b[12] = 0xff; + b[13] = 0xff; + b[14] = 0; + b[15] = 0; + p.payload_size = 16; + int8_t i, j; + uint8_t k, l; + uint8_t t[5]; + t[0] = 0; + object->get_phy_params().datarates.size = 1; + object->get_phy_params().datarates.table = t; + //Test without ADR payload does not make sense here. + + object->get_phy_params().max_channel_cnt = 2; + channel_params_t li[4]; + object->get_phy_params().channels.channel_list = li; + li[0].frequency = 0; + li[1].frequency = 5; + EXPECT_TRUE(4 == object->link_ADR_request(&p, &i, &j, &k, &l)); + + t[0] = 3; + //verify adr with p.adr_enabled = false + EXPECT_TRUE(0 == object->link_ADR_request(&p, &i, &j, &k, &l)); + + p.current_nb_rep = 0; + EXPECT_TRUE(0 == object->link_ADR_request(&p, &i, &j, &k, &l)); + + p.adr_enabled = true; + li[0].dr_range.value = 0xff; + object->get_phy_params().min_tx_datarate = DR_3; + object->get_phy_params().max_tx_datarate = DR_8; + + //verify adr with status != 0 + EXPECT_TRUE(0 == object->link_ADR_request(&p, &i, &j, &k, &l)); + + object->get_phy_params().max_tx_power = 2; + object->get_phy_params().min_tx_power = 6; + //verify adr with status != 0 + EXPECT_TRUE(4 == object->link_ADR_request(&p, &i, &j, &k, &l)); + + object->get_phy_params().min_tx_datarate = DR_0; + li[0].dr_range.value = 0xf0; + EXPECT_TRUE(6 == object->link_ADR_request(&p, &i, &j, &k, &l)); + + li[1].dr_range.fields.min = DR_0; + li[1].dr_range.fields.max = DR_13; + b[4] = 6 << 4; + p.payload_size = 5; + EXPECT_TRUE(7 == object->link_ADR_request(&p, &i, &j, &k, &l)); + + uint16_t mask[2]; + object->get_phy_params().channels.mask = mask; + object->get_phy_params().channels.mask_size = 2; + EXPECT_TRUE(7 == object->link_ADR_request(&p, &i, &j, &k, &l)); + + li[0].dr_range.value = 0xff; + object->get_phy_params().max_channel_cnt = 0; + EXPECT_TRUE(5 == object->link_ADR_request(&p, &i, &j, &k, &l)); + + b[0] = 0x03; + b[1] = 1; + b[2] = 0; + b[3] = 0; + b[4] = 0; + t[0] = 0; + object->get_phy_params().datarates.size = 1; + object->get_phy_params().datarates.table = t; + //Test without ADR payload does not make sense here. + + object->get_phy_params().max_channel_cnt = 2; + li[0].frequency = 0; + li[1].frequency = 5; + EXPECT_TRUE(4 == object->link_ADR_request(&p, &i, &j, &k, &l)); +} + +TEST_F(Test_LoRaPHY, accept_rx_param_setup_req) +{ + my_radio radio; + object->set_radio_instance(radio); + rx_param_setup_req_t req; + EXPECT_TRUE(0 == object->accept_rx_param_setup_req(&req)); +} + +TEST_F(Test_LoRaPHY, accept_tx_param_setup_req) +{ + my_radio radio; + object->set_radio_instance(radio); + object->get_phy_params().accept_tx_param_setup_req = true; + EXPECT_TRUE(object->accept_tx_param_setup_req(0, 0)); +} + +TEST_F(Test_LoRaPHY, dl_channel_request) +{ + EXPECT_TRUE(0 == object->dl_channel_request(0, 0)); + + object->get_phy_params().dl_channel_req_supported = true; + object->get_phy_params().bands.size = 1; + band_t t[1]; + object->get_phy_params().bands.table = t; + channel_params_t p[4]; + object->get_phy_params().channels.channel_list = p; + + p[0].frequency = 0; + EXPECT_TRUE(0 == object->dl_channel_request(0, 1)); + + t[0].higher_band_freq = 19; + t[0].lower_band_freq = 0; + p[0].frequency = 1; + EXPECT_TRUE(3 == object->dl_channel_request(0, 1)); +} + +TEST_F(Test_LoRaPHY, get_alternate_DR) +{ + EXPECT_TRUE(0 == object->get_alternate_DR(0)); + + object->get_phy_params().default_max_datarate = 5; + object->get_phy_params().min_tx_datarate = 4; + EXPECT_TRUE(5 == object->get_alternate_DR(1)); + + object->get_phy_params().default_max_datarate = 6; + object->get_phy_params().min_tx_datarate = 4; + EXPECT_TRUE(5 == object->get_alternate_DR(2)); +} + +TEST_F(Test_LoRaPHY, set_next_channel) +{ + channel_selection_params_t p; + uint8_t ch; + lorawan_time_t t1; + lorawan_time_t t2; + p.aggregate_timeoff = 10000; + EXPECT_TRUE(LORAWAN_STATUS_DUTYCYCLE_RESTRICTED == object->set_next_channel(&p, &ch, &t1, &t2)); + + uint16_t list[16]; + list[4] = 1; + memcpy(list, "\0", 16); + object->get_phy_params().channels.mask = list; + object->get_phy_params().channels.mask_size = 1; + p.aggregate_timeoff = 10000; + EXPECT_TRUE(LORAWAN_STATUS_DUTYCYCLE_RESTRICTED == object->set_next_channel(&p, &ch, &t1, &t2)); + + LoRaWANTimer_stub::time_value = 20000; + EXPECT_TRUE(LORAWAN_STATUS_NO_CHANNEL_FOUND == object->set_next_channel(&p, &ch, &t1, &t2)); + + p.joined = false; + p.dc_enabled = false; + band_t b[4]; + object->get_phy_params().bands.size = 2; + object->get_phy_params().bands.table = &b; + b[0].off_time = 0; + b[1].off_time = 9999999; + list[4] = 0; + object->get_phy_params().channels.mask_size = 128; + p.current_datarate = DR_1; + object->get_phy_params().max_channel_cnt = 4; + EXPECT_TRUE(LORAWAN_STATUS_NO_CHANNEL_FOUND == object->set_next_channel(&p, &ch, &t1, &t2)); + + p.dc_enabled = true; + EXPECT_TRUE(LORAWAN_STATUS_NO_CHANNEL_FOUND == object->set_next_channel(&p, &ch, &t1, &t2)); + + list[4] = 1; + p.joined = true; + p.dc_enabled = false; + channel_params_t l[4]; + l[0].dr_range.value = 0xff; + l[1].dr_range.value = 0xff; + l[2].dr_range.value = 0xf0; + l[3].dr_range.value = 0xf0; + l[2].band = 2; + l[3].band = 3; + object->get_phy_params().channels.channel_list = l; + list[0] = 0xFF; + b[2].off_time = 9999999; + b[3].off_time = 0; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_next_channel(&p, &ch, &t1, &t2)); + + b[0].off_time = 10000; + LoRaWANTimer_stub::time_value = 2000; + p.aggregate_timeoff = 1000; + p.dc_enabled = true; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_next_channel(&p, &ch, &t1, &t2)); +} + +TEST_F(Test_LoRaPHY, add_channel) +{ + uint16_t list[16]; + object->get_phy_params().channels.mask = list; + object->get_phy_params().channels.default_mask = list; + channel_params_t p; + EXPECT_TRUE(LORAWAN_STATUS_PARAMETER_INVALID == object->add_channel(&p, 0)); + + object->get_phy_params().custom_channelplans_supported = true; + object->get_phy_params().max_channel_cnt = 2; + object->get_phy_params().min_tx_datarate = 0; + object->get_phy_params().max_tx_datarate = 13; + p.dr_range.fields.min = 6; + p.dr_range.fields.max = 1; + EXPECT_TRUE(LORAWAN_STATUS_FREQ_AND_DR_INVALID == object->add_channel(&p, 0)); +} + +TEST_F(Test_LoRaPHY, remove_channel) +{ + channel_params_t pp; + pp.band=0; + object->get_phy_params().channels.channel_list = &pp; + uint16_t list[16]; + list[0] = 1; + object->get_phy_params().channels.mask = list; + object->get_phy_params().channels.default_mask = list; + EXPECT_TRUE(false == object->remove_channel(0)); + + list[0] = 0; + EXPECT_TRUE(false == object->remove_channel(0)); + + object->get_phy_params().channels.mask_size = 1; + object->get_phy_params().max_channel_cnt = 0; + EXPECT_TRUE(false == object->remove_channel(0)); + + object->get_phy_params().max_channel_cnt = 1; + EXPECT_TRUE(true == object->remove_channel(0)); +} + +TEST_F(Test_LoRaPHY, set_tx_cont_mode) +{ + channel_params_t pp; + pp.band=0; + object->get_phy_params().channels.channel_list = &pp; + band_t b; + object->get_phy_params().bands.table = &b; + my_radio radio; + object->set_radio_instance(radio); + + cw_mode_params_t p; + p.max_eirp = 0; + p.channel=0; + object->set_tx_cont_mode(&p); + + p.max_eirp = 1; + p.antenna_gain = 1; + object->set_tx_cont_mode(&p, 1); +} + +TEST_F(Test_LoRaPHY, apply_DR_offset) +{ + EXPECT_TRUE(0 == object->apply_DR_offset(0, 0)); + + object->get_phy_params().min_tx_datarate = 1; + EXPECT_TRUE(1 == object->apply_DR_offset(0, 2)); +} + +TEST_F(Test_LoRaPHY, reset_to_default_values) +{ + loramac_protocol_params p; + object->reset_to_default_values(&p); + + object->reset_to_default_values(&p, true); +} + +TEST_F(Test_LoRaPHY, get_next_lower_tx_datarate) +{ + EXPECT_TRUE(DR_0 == object->get_next_lower_tx_datarate(DR_2)); + + object->get_phy_params().ul_dwell_time_setting = 1; + object->get_phy_params().dwell_limit_datarate = DR_1; + EXPECT_TRUE(DR_1 == object->get_next_lower_tx_datarate(DR_2)); +} + +TEST_F(Test_LoRaPHY, get_minimum_rx_datarate) +{ + EXPECT_TRUE(DR_0 == object->get_minimum_rx_datarate()); + + object->get_phy_params().dl_dwell_time_setting = 1; + object->get_phy_params().dwell_limit_datarate = DR_1; + EXPECT_TRUE(DR_1 == object->get_minimum_rx_datarate()); +} + +TEST_F(Test_LoRaPHY, get_minimum_tx_datarate) +{ + EXPECT_TRUE(DR_0 == object->get_minimum_tx_datarate()); + + object->get_phy_params().ul_dwell_time_setting = 1; + object->get_phy_params().dwell_limit_datarate = DR_1; + EXPECT_TRUE(DR_1 == object->get_minimum_tx_datarate()); +} + +TEST_F(Test_LoRaPHY, get_default_tx_datarate) +{ + EXPECT_TRUE(0 == object->get_default_tx_datarate()); +} + +TEST_F(Test_LoRaPHY, get_default_max_tx_datarate) +{ + EXPECT_TRUE(DR_0 == object->get_default_max_tx_datarate()); +} + +TEST_F(Test_LoRaPHY, get_default_tx_power) +{ + EXPECT_TRUE(0 == object->get_default_tx_power()); +} + +TEST_F(Test_LoRaPHY, get_max_payload) +{ + uint8_t list=8; + object->get_phy_params().payloads.table = &list; + object->get_phy_params().payloads_with_repeater.table = &list; + EXPECT_TRUE(8 == object->get_max_payload(0)); + + EXPECT_TRUE(8 == object->get_max_payload(0, true)); +} + +TEST_F(Test_LoRaPHY, get_maximum_frame_counter_gap) +{ + EXPECT_TRUE(0 == object->get_maximum_frame_counter_gap()); +} + +TEST_F(Test_LoRaPHY, get_ack_timeout) +{ + EXPECT_TRUE(0 == object->get_ack_timeout()); +} + +TEST_F(Test_LoRaPHY, get_default_rx2_frequency) +{ + EXPECT_TRUE(0 == object->get_default_rx2_frequency()); +} + +TEST_F(Test_LoRaPHY, get_default_rx2_datarate) +{ + EXPECT_TRUE(0 == object->get_default_rx2_datarate()); +} + +TEST_F(Test_LoRaPHY, get_channel_mask) +{ + EXPECT_TRUE(0 == object->get_channel_mask()); + EXPECT_TRUE(0 == object->get_channel_mask(true)); +} + +TEST_F(Test_LoRaPHY, get_max_nb_channels) +{ + EXPECT_TRUE(0 == object->get_max_nb_channels()); +} + +TEST_F(Test_LoRaPHY, get_phy_channels) +{ + EXPECT_TRUE(0 == object->get_phy_channels()); +} + +TEST_F(Test_LoRaPHY, is_custom_channel_plan_supported) +{ + EXPECT_TRUE(false == object->is_custom_channel_plan_supported()); +} + +TEST_F(Test_LoRaPHY, verify_rx_datarate) +{ + EXPECT_TRUE(false == object->verify_rx_datarate(0)); + + object->get_phy_params().datarates.size = 1; + uint8_t t[1]; + t[0] = 2; + object->get_phy_params().datarates.table = t; + object->get_phy_params().dl_dwell_time_setting = 0; + + EXPECT_TRUE(true == object->verify_rx_datarate(0)); + + object->get_phy_params().dl_dwell_time_setting = 1; + object->get_phy_params().min_rx_datarate = 0; + + EXPECT_TRUE(true == object->verify_rx_datarate(0)); +} + +TEST_F(Test_LoRaPHY, verify_tx_datarate) +{ + EXPECT_TRUE(false == object->verify_tx_datarate(0)); + + object->get_phy_params().datarates.size = 1; + uint8_t t[1]; + t[0] = 2; + object->get_phy_params().datarates.table = t; + object->get_phy_params().ul_dwell_time_setting = 0; + EXPECT_TRUE(true == object->verify_tx_datarate(0)); + + object->get_phy_params().ul_dwell_time_setting = 1; + EXPECT_TRUE(true == object->verify_tx_datarate(0)); + + object->get_phy_params().ul_dwell_time_setting = 1; + EXPECT_TRUE(true == object->verify_tx_datarate(0, true)); +} + +TEST_F(Test_LoRaPHY, verify_tx_power) +{ + EXPECT_TRUE(true == object->verify_tx_power(0)); +} + +TEST_F(Test_LoRaPHY, verify_duty_cycle) +{ + EXPECT_TRUE(true == object->verify_duty_cycle(false)); + + EXPECT_TRUE(false == object->verify_duty_cycle(true)); +} + +TEST_F(Test_LoRaPHY, verify_nb_join_trials) +{ + EXPECT_TRUE(false == object->verify_nb_join_trials(0)); + EXPECT_TRUE(true == object->verify_nb_join_trials(100)); +} + + diff --git a/UNITTESTS/features/lorawan/loraphy/unittest.cmake b/UNITTESTS/features/lorawan/loraphy/unittest.cmake new file mode 100644 index 0000000000..c1abde4e46 --- /dev/null +++ b/UNITTESTS/features/lorawan/loraphy/unittest.cmake @@ -0,0 +1,41 @@ +#[[ + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +]] + +# Unit test suite name +set(TEST_SUITE_NAME "lorawan_LoRaPHY") + +# Source files +set(unittest-sources + ../features/lorawan/lorastack/phy/LoRaPHY.cpp +) + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + target_h + ../features/lorawan/lorastack/phy +) + +# Test & stub files +set(unittest-test-sources + features/lorawan/loraphy/Test_LoRaPHY.cpp + stubs/LoRaWANTimer_stub.cpp + stubs/mbed_assert_stub.c +) + + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DMBED_CONF_LORA_UPLINK_PREAMBLE_LENGTH=8 -DMBED_CONF_LORA_DUTY_CYCLE_ON_JOIN=true") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DMBED_CONF_LORA_UPLINK_PREAMBLE_LENGTH=8 -DMBED_CONF_LORA_DUTY_CYCLE_ON_JOIN=true") diff --git a/UNITTESTS/features/lorawan/loraphyas923/Test_LoRaPHYAS923.cpp b/UNITTESTS/features/lorawan/loraphyas923/Test_LoRaPHYAS923.cpp new file mode 100644 index 0000000000..98a361810d --- /dev/null +++ b/UNITTESTS/features/lorawan/loraphyas923/Test_LoRaPHYAS923.cpp @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "gtest/gtest.h" +#include "LoRaPHYAS923.h" + +#include "LoRaPHY_stub.h" + +class my_radio : public LoRaRadio +{ +public: + + virtual void init_radio(radio_events_t *events){}; + + virtual void radio_reset(){}; + + virtual void sleep(void){}; + + virtual void standby(void){}; + + virtual void set_rx_config (radio_modems_t modem, uint32_t bandwidth, + uint32_t datarate, uint8_t coderate, + uint32_t bandwidth_afc, uint16_t preamble_len, + uint16_t symb_timeout, bool fix_len, + uint8_t payload_len, + bool crc_on, bool freq_hop_on, uint8_t hop_period, + bool iq_inverted, bool rx_continuous){}; + + virtual void set_tx_config(radio_modems_t modem, int8_t power, uint32_t fdev, + uint32_t bandwidth, uint32_t datarate, + uint8_t coderate, uint16_t preamble_len, + bool fix_len, bool crc_on, bool freq_hop_on, + uint8_t hop_period, bool iq_inverted, uint32_t timeout){}; + + virtual void send(uint8_t *buffer, uint8_t size){}; + + virtual void receive(void){}; + + virtual void set_channel(uint32_t freq){}; + + virtual uint32_t random(void){}; + + virtual uint8_t get_status(void){return uint8_value;}; + + virtual void set_max_payload_length(radio_modems_t modem, uint8_t max){}; + + virtual void set_public_network(bool enable){}; + + virtual uint32_t time_on_air(radio_modems_t modem, uint8_t pkt_len){}; + + virtual bool perform_carrier_sense(radio_modems_t modem, + uint32_t freq, + int16_t rssi_threshold, + uint32_t max_carrier_sense_time){ return bool_value;}; + + virtual void start_cad(void){}; + + virtual bool check_rf_frequency(uint32_t frequency){ return bool_value; }; + + virtual void set_tx_continuous_wave(uint32_t freq, int8_t power, uint16_t time){}; + + virtual void lock(void){}; + + virtual void unlock(void){}; + + bool bool_value; + uint8_t uint8_value; +}; + +class Test_LoRaPHYAS923 : public testing::Test { +protected: + LoRaPHYAS923 *object; + my_radio radio; + + virtual void SetUp() + { + LoRaPHY_stub::radio = &radio; + object = new LoRaPHYAS923(); + } + + virtual void TearDown() + { + LoRaPHY_stub::radio = NULL; + delete object; + } +}; + +TEST_F(Test_LoRaPHYAS923, constructor) +{ + EXPECT_TRUE(object); +} + +TEST_F(Test_LoRaPHYAS923, get_alternate_DR) +{ + EXPECT_TRUE(2 == object->get_alternate_DR(1)); +} + +TEST_F(Test_LoRaPHYAS923, set_next_channel) +{ + channel_selection_params_t next_channel; + lorawan_time_t backoff_time = 0; + lorawan_time_t time = 0; + uint8_t ch = 1; + + next_channel.aggregate_timeoff = 0; + LoRaPHY_stub::uint8_value = 0; + EXPECT_TRUE(LORAWAN_STATUS_NO_CHANNEL_FOUND == object->set_next_channel(&next_channel, &ch, &backoff_time, &time)); + + next_channel.aggregate_timeoff = 1; + radio.bool_value = false; + EXPECT_TRUE(LORAWAN_STATUS_DUTYCYCLE_RESTRICTED == object->set_next_channel(&next_channel, &ch, &backoff_time, &time)); + + next_channel.aggregate_timeoff = 0; + LoRaPHY_stub::uint8_value = 1; + EXPECT_TRUE(LORAWAN_STATUS_NO_FREE_CHANNEL_FOUND == object->set_next_channel(&next_channel, &ch, &backoff_time, &time)); + + radio.bool_value = true; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_next_channel(&next_channel, &ch, &backoff_time, &time)); +} + +TEST_F(Test_LoRaPHYAS923, apply_DR_offset) +{ + //0, 1, 2, 3, 4, 5, -1, -2 + for (int i=0; i < 8; i++) { + uint8_t val = i>5?5:2; + EXPECT_TRUE(object->apply_DR_offset(0, i)); + } +} + diff --git a/features/cellular/UNITTESTS/at/at_cellularinformation/test_at_cellularinformation.h b/UNITTESTS/features/lorawan/loraphyas923/unittest.cmake similarity index 53% rename from features/cellular/UNITTESTS/at/at_cellularinformation/test_at_cellularinformation.h rename to UNITTESTS/features/lorawan/loraphyas923/unittest.cmake index 64fabbb4d5..b4648ab904 100644 --- a/features/cellular/UNITTESTS/at/at_cellularinformation/test_at_cellularinformation.h +++ b/UNITTESTS/features/lorawan/loraphyas923/unittest.cmake @@ -1,5 +1,5 @@ -/* - * Copyright (c) 2018, Arm Limited and affiliates. +#[[ + * Copyright (c) 2018, Arm Limited and affiliates * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,24 +13,28 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ -#ifndef TEST_AT_CELLULARINFORMATION_H -#define TEST_AT_CELLULARINFORMATION_H +]] -class Test_AT_CellularInformation { -public: - Test_AT_CellularInformation(); +# Unit test suite name +set(TEST_SUITE_NAME "lorawan_LoRaPHYAS923") - virtual ~Test_AT_CellularInformation(); +# Source files +set(unittest-sources + ../features/lorawan/lorastack/phy/LoRaPHYAS923.cpp +) - void test_AT_CellularInformation_get_manufacturer(); +# Add test specific include paths +set(unittest-includes ${unittest-includes} + target_h + ../features/lorawan/lorastack/phy +) - void test_AT_CellularInformation_get_model(); +# Test & stub files +set(unittest-test-sources + features/lorawan/loraphyas923/Test_LoRaPHYAS923.cpp + stubs/LoRaPHY_stub.cpp + stubs/LoRaWANTimer_stub.cpp + stubs/mbed_assert_stub.c - void test_AT_CellularInformation_get_revision(); - - void test_AT_CellularInformation_get_serial_number(); -}; - -#endif // TEST_AT_CELLULARINFORMATION_H +) diff --git a/UNITTESTS/features/lorawan/loraphyau915/Test_LoRaPHYAU915.cpp b/UNITTESTS/features/lorawan/loraphyau915/Test_LoRaPHYAU915.cpp new file mode 100644 index 0000000000..0cdde0f104 --- /dev/null +++ b/UNITTESTS/features/lorawan/loraphyau915/Test_LoRaPHYAU915.cpp @@ -0,0 +1,231 @@ +/* + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "gtest/gtest.h" +#include "LoRaPHYAU915.h" + +#include "LoRaPHY_stub.h" + +class my_radio : public LoRaRadio +{ +public: + + virtual void init_radio(radio_events_t *events){}; + + virtual void radio_reset(){}; + + virtual void sleep(void){}; + + virtual void standby(void){}; + + virtual void set_rx_config (radio_modems_t modem, uint32_t bandwidth, + uint32_t datarate, uint8_t coderate, + uint32_t bandwidth_afc, uint16_t preamble_len, + uint16_t symb_timeout, bool fix_len, + uint8_t payload_len, + bool crc_on, bool freq_hop_on, uint8_t hop_period, + bool iq_inverted, bool rx_continuous){}; + + virtual void set_tx_config(radio_modems_t modem, int8_t power, uint32_t fdev, + uint32_t bandwidth, uint32_t datarate, + uint8_t coderate, uint16_t preamble_len, + bool fix_len, bool crc_on, bool freq_hop_on, + uint8_t hop_period, bool iq_inverted, uint32_t timeout){}; + + virtual void send(uint8_t *buffer, uint8_t size){}; + + virtual void receive(void){}; + + virtual void set_channel(uint32_t freq){}; + + virtual uint32_t random(void){}; + + virtual uint8_t get_status(void){return uint8_value;}; + + virtual void set_max_payload_length(radio_modems_t modem, uint8_t max){}; + + virtual void set_public_network(bool enable){}; + + virtual uint32_t time_on_air(radio_modems_t modem, uint8_t pkt_len){}; + + virtual bool perform_carrier_sense(radio_modems_t modem, + uint32_t freq, + int16_t rssi_threshold, + uint32_t max_carrier_sense_time){ return bool_value;}; + + virtual void start_cad(void){}; + + virtual bool check_rf_frequency(uint32_t frequency){ return bool_value; }; + + virtual void set_tx_continuous_wave(uint32_t freq, int8_t power, uint16_t time){}; + + virtual void lock(void){}; + + virtual void unlock(void){}; + + bool bool_value; + uint8_t uint8_value; +}; + +class Test_LoRaPHYAU915 : public testing::Test { +protected: + LoRaPHYAU915 *object; + my_radio radio; + + virtual void SetUp() + { + LoRaPHY_stub::radio = &radio; + object = new LoRaPHYAU915(); + } + + virtual void TearDown() + { + LoRaPHY_stub::radio = NULL; + delete object; + } +}; + +TEST_F(Test_LoRaPHYAU915, constructor) +{ + EXPECT_TRUE(object); +} + +TEST_F(Test_LoRaPHYAU915, rx_config) +{ + rx_config_params_t p; + + radio.uint8_value = 1; + EXPECT_TRUE(!object->rx_config(&p)); + + radio.uint8_value = 0; + p.is_repeater_supported = true; + EXPECT_TRUE(object->rx_config(&p)); + + p.is_repeater_supported = false; + EXPECT_TRUE(object->rx_config(&p)); +} + +TEST_F(Test_LoRaPHYAU915, tx_config) +{ + tx_config_params_t p; + int8_t tx; + lorawan_time_t time; + p.tx_power = 9; + EXPECT_TRUE(object->tx_config(&p, &tx, &time)); +} + +TEST_F(Test_LoRaPHYAU915, link_ADR_request) +{ + adr_req_params_t params; + int8_t dr_out; + int8_t tx_power_out; + uint8_t nb_rep_out; + uint8_t nb_bytes_parsed; + + LoRaPHY_stub::uint8_value = 1; + LoRaPHY_stub::ch_mask_value = 6; + LoRaPHY_stub::adr_parse_count = 2; + EXPECT_TRUE(1 == object->link_ADR_request(¶ms, &dr_out, &tx_power_out, &nb_rep_out, &nb_bytes_parsed)); + + LoRaPHY_stub::adr_parse_count = 2; + LoRaPHY_stub::ch_mask_value = 7; + EXPECT_TRUE(1 == object->link_ADR_request(¶ms, &dr_out, &tx_power_out, &nb_rep_out, &nb_bytes_parsed)); + + LoRaPHY_stub::adr_parse_count = 2; + LoRaPHY_stub::ch_mask_value = 5; + LoRaPHY_stub::uint8_value = 6; + EXPECT_TRUE(6 == object->link_ADR_request(¶ms, &dr_out, &tx_power_out, &nb_rep_out, &nb_bytes_parsed)); + + LoRaPHY_stub::adr_parse_count = 2; + LoRaPHY_stub::ch_mask_value = 66; + LoRaPHY_stub::uint8_value = 7; + EXPECT_TRUE(7 == object->link_ADR_request(¶ms, &dr_out, &tx_power_out, &nb_rep_out, &nb_bytes_parsed)); +} + +TEST_F(Test_LoRaPHYAU915, accept_rx_param_setup_req) +{ + rx_param_setup_req_t p; + radio.bool_value = false; + EXPECT_TRUE(0 == object->accept_rx_param_setup_req(&p)); + + radio.bool_value = true; + p.frequency = 923300000 - 1; + EXPECT_TRUE(0 == object->accept_rx_param_setup_req(&p)); + + radio.bool_value = true; + p.frequency = 927500000 + 1; + p.datarate = 6; + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = true; + EXPECT_TRUE(2 == object->accept_rx_param_setup_req(&p)); + + radio.bool_value = true; + p.frequency = 923300000 + 600000; + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = true; + LoRaPHY_stub::bool_table[1] = true; + EXPECT_TRUE(7 == object->accept_rx_param_setup_req(&p)); +} + +TEST_F(Test_LoRaPHYAU915, get_alternate_DR) +{ + EXPECT_TRUE(0 == object->get_alternate_DR(0)); + + EXPECT_TRUE(6 == object->get_alternate_DR(1)); +} + +TEST_F(Test_LoRaPHYAU915, set_next_channel) +{ + channel_selection_params_t params; + uint8_t channel; + lorawan_time_t time; + lorawan_time_t timeoff; + + params.current_datarate = 6; + params.aggregate_timeoff = 0; + LoRaPHY_stub::uint8_value = 0; + EXPECT_TRUE(LORAWAN_STATUS_NO_CHANNEL_FOUND == object->set_next_channel(¶ms, &channel, &time, &timeoff)); + + radio.bool_value = false; + params.aggregate_timeoff = 1; + EXPECT_TRUE(LORAWAN_STATUS_DUTYCYCLE_RESTRICTED == object->set_next_channel(¶ms, &channel, &time, &timeoff)); + + params.aggregate_timeoff = 0; + LoRaPHY_stub::uint8_value = 1; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_next_channel(¶ms, &channel, &time, &timeoff)); +} + +TEST_F(Test_LoRaPHYAU915, apply_DR_offset) +{ +// { DR_8, DR_8, DR_8, DR_8, DR_8, DR_8 }, // DR_0 +// { DR_9, DR_8, DR_8, DR_8, DR_8, DR_8 }, // DR_1 +// { DR_10, DR_9, DR_8, DR_8, DR_8, DR_8 }, // DR_2 +// { DR_11, DR_10, DR_9, DR_8, DR_8, DR_8 }, // DR_3 +// { DR_12, DR_11, DR_10, DR_9, DR_8, DR_8 }, // DR_4 +// { DR_13, DR_12, DR_11, DR_10, DR_9, DR_8 }, // DR_5 +// { DR_13, DR_13, DR_12, DR_11, DR_10, DR_9 }, // DR_6 + + for (int i = 0; i < 7; i++) { + for (int j=0; j < 6; j++ ) { + uint8_t val = 8 + i; + val -= j; + if (val > 13) val = 13; + if (val < 8) val = 8; + EXPECT_TRUE(val == object->apply_DR_offset(i, j)); + } + } +} diff --git a/UNITTESTS/features/lorawan/loraphyau915/unittest.cmake b/UNITTESTS/features/lorawan/loraphyau915/unittest.cmake new file mode 100644 index 0000000000..abc6c4752c --- /dev/null +++ b/UNITTESTS/features/lorawan/loraphyau915/unittest.cmake @@ -0,0 +1,44 @@ +#[[ + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +]] + +# Unit test suite name +set(TEST_SUITE_NAME "lorawan_LoRaPHYAU915") + +# Source files +set(unittest-sources + ../features/lorawan/lorastack/phy/LoRaPHYAU915.cpp +) + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + target_h + ../features/lorawan/lorastack/phy +) + +# Test & stub files +set(unittest-test-sources + features/lorawan/loraphyau915/Test_LoRaPHYAU915.cpp + stubs/LoRaPHY_stub.cpp + stubs/LoRaWANTimer_stub.cpp + stubs/mbed_assert_stub.c + +) + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DMBED_CONF_LORA_FSB_MASK=\"{0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0x00FF}\"") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DMBED_CONF_LORA_FSB_MASK=\"{0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0x00FF}\"") + + diff --git a/UNITTESTS/features/lorawan/loraphycn470/Test_LoRaPHYCN470.cpp b/UNITTESTS/features/lorawan/loraphycn470/Test_LoRaPHYCN470.cpp new file mode 100644 index 0000000000..983dec935e --- /dev/null +++ b/UNITTESTS/features/lorawan/loraphycn470/Test_LoRaPHYCN470.cpp @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "gtest/gtest.h" +#include "LoRaPHYCN470.h" + +#include "LoRaPHY_stub.h" + +class my_radio : public LoRaRadio +{ +public: + + virtual void init_radio(radio_events_t *events){}; + + virtual void radio_reset(){}; + + virtual void sleep(void){}; + + virtual void standby(void){}; + + virtual void set_rx_config (radio_modems_t modem, uint32_t bandwidth, + uint32_t datarate, uint8_t coderate, + uint32_t bandwidth_afc, uint16_t preamble_len, + uint16_t symb_timeout, bool fix_len, + uint8_t payload_len, + bool crc_on, bool freq_hop_on, uint8_t hop_period, + bool iq_inverted, bool rx_continuous){}; + + virtual void set_tx_config(radio_modems_t modem, int8_t power, uint32_t fdev, + uint32_t bandwidth, uint32_t datarate, + uint8_t coderate, uint16_t preamble_len, + bool fix_len, bool crc_on, bool freq_hop_on, + uint8_t hop_period, bool iq_inverted, uint32_t timeout){}; + + virtual void send(uint8_t *buffer, uint8_t size){}; + + virtual void receive(void){}; + + virtual void set_channel(uint32_t freq){}; + + virtual uint32_t random(void){}; + + virtual uint8_t get_status(void){return uint8_value;}; + + virtual void set_max_payload_length(radio_modems_t modem, uint8_t max){}; + + virtual void set_public_network(bool enable){}; + + virtual uint32_t time_on_air(radio_modems_t modem, uint8_t pkt_len){}; + + virtual bool perform_carrier_sense(radio_modems_t modem, + uint32_t freq, + int16_t rssi_threshold, + uint32_t max_carrier_sense_time){ return bool_value;}; + + virtual void start_cad(void){}; + + virtual bool check_rf_frequency(uint32_t frequency){ return bool_value; }; + + virtual void set_tx_continuous_wave(uint32_t freq, int8_t power, uint16_t time){}; + + virtual void lock(void){}; + + virtual void unlock(void){}; + + bool bool_value; + uint8_t uint8_value; +}; + +class Test_LoRaPHYCN470 : public testing::Test { +protected: + LoRaPHYCN470 *object; + my_radio radio; + + virtual void SetUp() + { + + LoRaPHY_stub::radio = &radio; + object = new LoRaPHYCN470(); + } + + virtual void TearDown() + { + + LoRaPHY_stub::radio = NULL; + delete object; + } +}; + +TEST_F(Test_LoRaPHYCN470, constructor) +{ + EXPECT_TRUE(object); +} + +TEST_F(Test_LoRaPHYCN470, set_next_channel) +{ + channel_selection_params_t params; + uint8_t channel; + lorawan_time_t time; + lorawan_time_t timeoff; + + params.current_datarate = 4; + params.aggregate_timeoff = 0; + LoRaPHY_stub::uint8_value = 0; + EXPECT_TRUE(LORAWAN_STATUS_NO_CHANNEL_FOUND == object->set_next_channel(¶ms, &channel, &time, &timeoff)); + + radio.bool_value = false; + params.aggregate_timeoff = 1; + EXPECT_TRUE(LORAWAN_STATUS_DUTYCYCLE_RESTRICTED == object->set_next_channel(¶ms, &channel, &time, &timeoff)); + + params.aggregate_timeoff = 0; + LoRaPHY_stub::uint8_value = 1; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_next_channel(¶ms, &channel, &time, &timeoff)); +} + +TEST_F(Test_LoRaPHYCN470, rx_config) +{ + rx_config_params_t p; + + radio.uint8_value = 1; + EXPECT_TRUE(!object->rx_config(&p)); + + radio.uint8_value = 0; + p.is_repeater_supported = true; + EXPECT_TRUE(object->rx_config(&p)); + + p.is_repeater_supported = false; + EXPECT_TRUE(object->rx_config(&p)); +} + +TEST_F(Test_LoRaPHYCN470, tx_config) +{ + tx_config_params_t p; + int8_t tx; + lorawan_time_t time; + p.tx_power = 9; + EXPECT_TRUE(object->tx_config(&p, &tx, &time)); +} + +TEST_F(Test_LoRaPHYCN470, link_ADR_request) +{ + adr_req_params_t params; + int8_t dr_out; + int8_t tx_power_out; + uint8_t nb_rep_out; + uint8_t nb_bytes_parsed; + + LoRaPHY_stub::uint8_value = 1; + LoRaPHY_stub::ch_mask_value = 6; + LoRaPHY_stub::adr_parse_count = 2; + EXPECT_TRUE(1 == object->link_ADR_request(¶ms, &dr_out, &tx_power_out, &nb_rep_out, &nb_bytes_parsed)); + + LoRaPHY_stub::adr_parse_count = 2; + LoRaPHY_stub::ch_mask_value = 7; + EXPECT_TRUE(1 == object->link_ADR_request(¶ms, &dr_out, &tx_power_out, &nb_rep_out, &nb_bytes_parsed)); + + LoRaPHY_stub::adr_parse_count = 2; + LoRaPHY_stub::ch_mask_value = 5; + LoRaPHY_stub::uint8_value = 6; + EXPECT_TRUE(6 == object->link_ADR_request(¶ms, &dr_out, &tx_power_out, &nb_rep_out, &nb_bytes_parsed)); + + LoRaPHY_stub::adr_parse_count = 2; + LoRaPHY_stub::ch_mask_value = 66; + LoRaPHY_stub::uint8_value = 7; + EXPECT_TRUE(7 == object->link_ADR_request(¶ms, &dr_out, &tx_power_out, &nb_rep_out, &nb_bytes_parsed)); +} + +TEST_F(Test_LoRaPHYCN470, accept_rx_param_setup_req) +{ + rx_param_setup_req_t p; + EXPECT_TRUE(0 == object->accept_rx_param_setup_req(&p)); + + radio.bool_value = true; + p.frequency = 923300000 - 1; + EXPECT_TRUE(0 == object->accept_rx_param_setup_req(&p)); + + radio.bool_value = true; + p.frequency = 927500000 + 1; + p.datarate = 6; + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = true; + EXPECT_TRUE(2 == object->accept_rx_param_setup_req(&p)); +} + + diff --git a/UNITTESTS/features/lorawan/loraphycn470/unittest.cmake b/UNITTESTS/features/lorawan/loraphycn470/unittest.cmake new file mode 100644 index 0000000000..6c6746f189 --- /dev/null +++ b/UNITTESTS/features/lorawan/loraphycn470/unittest.cmake @@ -0,0 +1,40 @@ +#[[ + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +]] + +# Unit test suite name +set(TEST_SUITE_NAME "lorawan_LoRaPHYCN470") + +# Source files +set(unittest-sources + ../features/lorawan/lorastack/phy/LoRaPHYCN470.cpp +) + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + target_h + ../features/lorawan/lorastack/phy +) + +# Test & stub files +set(unittest-test-sources + features/lorawan/loraphycn470/Test_LoRaPHYCN470.cpp + stubs/LoRaPHY_stub.cpp + stubs/LoRaWANTimer_stub.cpp + stubs/mbed_assert_stub.c + +) + diff --git a/UNITTESTS/features/cellular/framework/common/util/test_util.h b/UNITTESTS/features/lorawan/loraphycn779/Test_LoRaPHYCN779.cpp similarity index 60% rename from UNITTESTS/features/cellular/framework/common/util/test_util.h rename to UNITTESTS/features/lorawan/loraphycn779/Test_LoRaPHYCN779.cpp index bb968ef5f4..0d729b4c87 100644 --- a/UNITTESTS/features/cellular/framework/common/util/test_util.h +++ b/UNITTESTS/features/lorawan/loraphycn779/Test_LoRaPHYCN779.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Arm Limited and affiliates. + * Copyright (c) 2018, Arm Limited and affiliates * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +14,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef TEST_UTIL_H -#define TEST_UTIL_H -class Test_util { -public: - Test_util(); +#include "gtest/gtest.h" +#include "LoRaPHYCN779.h" - virtual ~Test_util(); +class Test_LoRaPHYCN779 : public testing::Test { +protected: + LoRaPHYCN779 *object; - void test_util_uint_to_binary_string(); + virtual void SetUp() + { + object = new LoRaPHYCN779(); + } - void test_util_char_str_to_hex(); - - void test_util_convert_ipv6(); - - void test_util_prefer_ipv6(); - - void test_util_separate_ip_addresses(); + virtual void TearDown() + { + delete object; + } }; -#endif // TEST_UTIL_H +TEST_F(Test_LoRaPHYCN779, constructor) +{ + EXPECT_TRUE(object); +} + diff --git a/UNITTESTS/features/lorawan/loraphycn779/unittest.cmake b/UNITTESTS/features/lorawan/loraphycn779/unittest.cmake new file mode 100644 index 0000000000..d0ccd7fece --- /dev/null +++ b/UNITTESTS/features/lorawan/loraphycn779/unittest.cmake @@ -0,0 +1,42 @@ +#[[ + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +]] + +# Unit test suite name +set(TEST_SUITE_NAME "lorawan_LoRaPHYCN779") + +# Source files +set(unittest-sources + ../features/lorawan/lorastack/phy/LoRaPHYCN779.cpp +) + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + target_h + ../features/lorawan/lorastack/phy +) + +# Test & stub files +set(unittest-test-sources + features/lorawan/loraphycn779/Test_LoRaPHYCN779.cpp + stubs/LoRaPHY_stub.cpp + stubs/mbed_assert_stub.c + +) + + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DMBED_CONF_LORA_FSB_MASK_CHINA=\"{0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0x00FF}\"") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DMBED_CONF_LORA_FSB_MASK_CHINA=\"{0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0x00FF}\"") diff --git a/features/cellular/UNITTESTS/common/util/test_util.h b/UNITTESTS/features/lorawan/loraphyeu433/Test_LoRaPHYEU433.cpp similarity index 60% rename from features/cellular/UNITTESTS/common/util/test_util.h rename to UNITTESTS/features/lorawan/loraphyeu433/Test_LoRaPHYEU433.cpp index 7f6b28ee5f..1981943a63 100644 --- a/features/cellular/UNITTESTS/common/util/test_util.h +++ b/UNITTESTS/features/lorawan/loraphyeu433/Test_LoRaPHYEU433.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Arm Limited and affiliates. + * Copyright (c) 2018, Arm Limited and affiliates * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,25 +14,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef TEST_UTIL_H -#define TEST_UTIL_H -class Test_util { -public: - Test_util(); +#include "gtest/gtest.h" +#include "LoRaPHYEU433.h" - virtual ~Test_util(); +class Test_LoRaPHYEU433 : public testing::Test { +protected: + LoRaPHYEU433 *object; - void test_util_uint_to_binary_string(); + virtual void SetUp() + { + object = new LoRaPHYEU433(); + } - void test_util_char_str_to_hex(); - - void test_util_convert_ipv6(); - - void test_util_prefer_ipv6(); - - void test_util_separate_ip_addresses(); + virtual void TearDown() + { + delete object; + } }; -#endif // TEST_UTIL_H +TEST_F(Test_LoRaPHYEU433, constructor) +{ + EXPECT_TRUE(object); +} diff --git a/features/cellular/UNITTESTS/at/at_cellularbase/test_at_cellularbase.h b/UNITTESTS/features/lorawan/loraphyeu433/unittest.cmake similarity index 54% rename from features/cellular/UNITTESTS/at/at_cellularbase/test_at_cellularbase.h rename to UNITTESTS/features/lorawan/loraphyeu433/unittest.cmake index 57dab4ea2d..5966a3ee60 100644 --- a/features/cellular/UNITTESTS/at/at_cellularbase/test_at_cellularbase.h +++ b/UNITTESTS/features/lorawan/loraphyeu433/unittest.cmake @@ -1,5 +1,5 @@ -/* - * Copyright (c) 2018, Arm Limited and affiliates. +#[[ + * Copyright (c) 2018, Arm Limited and affiliates * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,24 +13,27 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ -#ifndef TEST_AT_CELLULARBASE_H -#define TEST_AT_CELLULARBASE_H +]] -class Test_AT_CellularBase { -public: - Test_AT_CellularBase(); +# Unit test suite name +set(TEST_SUITE_NAME "lorawan_LoRaPHYEU433") - virtual ~Test_AT_CellularBase(); +# Source files +set(unittest-sources + ../features/lorawan/lorastack/phy/LoRaPHYEU433.cpp +) - void test_AT_CellularBase_get_at_handler(); +# Add test specific include paths +set(unittest-includes ${unittest-includes} + target_h + ../features/lorawan/lorastack/phy +) - void test_AT_CellularBase_get_device_error(); +# Test & stub files +set(unittest-test-sources + features/lorawan/loraphyeu433/Test_LoRaPHYEU433.cpp + stubs/LoRaPHY_stub.cpp + stubs/mbed_assert_stub.c - void test_AT_CellularBase_set_unsupported_features(); - - void test_AT_CellularBase_is_supported(); -}; - -#endif // TEST_AT_CELLULARBASE_H +) diff --git a/UNITTESTS/features/cellular/framework/AT/AT_CellularBase/test_at_cellularbase.h b/UNITTESTS/features/lorawan/loraphyeu868/Test_LoRaPHYEU868.cpp similarity index 60% rename from UNITTESTS/features/cellular/framework/AT/AT_CellularBase/test_at_cellularbase.h rename to UNITTESTS/features/lorawan/loraphyeu868/Test_LoRaPHYEU868.cpp index 3091dadb83..f216c12016 100644 --- a/UNITTESTS/features/cellular/framework/AT/AT_CellularBase/test_at_cellularbase.h +++ b/UNITTESTS/features/lorawan/loraphyeu868/Test_LoRaPHYEU868.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Arm Limited and affiliates. + * Copyright (c) 2018, Arm Limited and affiliates * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,18 +14,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef TEST_AT_CELLULARBASE_H -#define TEST_AT_CELLULARBASE_H -class Test_AT_CellularBase { -public: - Test_AT_CellularBase(); +#include "gtest/gtest.h" +#include "LoRaPHYEU868.h" - virtual ~Test_AT_CellularBase(); +class Test_LoRaPHYEU868 : public testing::Test { +protected: + LoRaPHYEU868 *object; - void test_AT_CellularBase_get_at_handler(); + virtual void SetUp() + { + object = new LoRaPHYEU868(); + } - void test_AT_CellularBase_get_device_error(); + virtual void TearDown() + { + delete object; + } }; -#endif // TEST_AT_CELLULARBASE_H +TEST_F(Test_LoRaPHYEU868, constructor) +{ + EXPECT_TRUE(object); +} + diff --git a/UNITTESTS/features/lorawan/loraphyeu868/unittest.cmake b/UNITTESTS/features/lorawan/loraphyeu868/unittest.cmake new file mode 100644 index 0000000000..1398a52257 --- /dev/null +++ b/UNITTESTS/features/lorawan/loraphyeu868/unittest.cmake @@ -0,0 +1,39 @@ +#[[ + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +]] + +# Unit test suite name +set(TEST_SUITE_NAME "lorawan_LoRaPHYEU868") + +# Source files +set(unittest-sources + ../features/lorawan/lorastack/phy/LoRaPHYEU868.cpp +) + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + target_h + ../features/lorawan/lorastack/phy +) + +# Test & stub files +set(unittest-test-sources + features/lorawan/loraphyeu868/Test_LoRaPHYEU868.cpp + stubs/LoRaPHY_stub.cpp + stubs/mbed_assert_stub.c + +) + diff --git a/UNITTESTS/features/cellular/framework/AT/AT_CellularBase/at_cellularbasetest.cpp b/UNITTESTS/features/lorawan/loraphyin865/Test_LoRaPHYIN865.cpp similarity index 60% rename from UNITTESTS/features/cellular/framework/AT/AT_CellularBase/at_cellularbasetest.cpp rename to UNITTESTS/features/lorawan/loraphyin865/Test_LoRaPHYIN865.cpp index 08ec439c7f..ecb12115f4 100644 --- a/UNITTESTS/features/cellular/framework/AT/AT_CellularBase/at_cellularbasetest.cpp +++ b/UNITTESTS/features/lorawan/loraphyin865/Test_LoRaPHYIN865.cpp @@ -14,36 +14,34 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "gtest/gtest.h" -#include "test_at_cellularbase.h" -#include "AT_CellularBase.h" -class TestAT_CellularBase : public testing::Test { +#include "gtest/gtest.h" +#include "LoRaPHYIN865.h" + +class Test_LoRaPHYIN865 : public testing::Test { protected: - Test_AT_CellularBase *unit; + LoRaPHYIN865 *object; virtual void SetUp() { - unit = new Test_AT_CellularBase(); + object = new LoRaPHYIN865(); } virtual void TearDown() { - delete unit; + delete object; } }; -TEST_F(TestAT_CellularBase, Create) +TEST_F(Test_LoRaPHYIN865, constructor) { - EXPECT_TRUE(unit); + EXPECT_TRUE(object); } -TEST_F(TestAT_CellularBase, test_AT_CellularBase_get_at_handler) +TEST_F(Test_LoRaPHYIN865, apply_DR_offset) { - unit->test_AT_CellularBase_get_at_handler(); + EXPECT_TRUE(0 == object->apply_DR_offset(0, 0)); } -TEST_F(TestAT_CellularBase, test_AT_CellularBase_get_device_error) -{ - unit->test_AT_CellularBase_get_device_error(); -} + + diff --git a/UNITTESTS/features/lorawan/loraphyin865/unittest.cmake b/UNITTESTS/features/lorawan/loraphyin865/unittest.cmake new file mode 100644 index 0000000000..2fa34a6f73 --- /dev/null +++ b/UNITTESTS/features/lorawan/loraphyin865/unittest.cmake @@ -0,0 +1,39 @@ +#[[ + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +]] + +# Unit test suite name +set(TEST_SUITE_NAME "lorawan_LoRaPHYIN865") + +# Source files +set(unittest-sources + ../features/lorawan/lorastack/phy/LoRaPHYIN865.cpp +) + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + target_h + ../features/lorawan/lorastack/phy +) + +# Test & stub files +set(unittest-test-sources + features/lorawan/loraphyin865/Test_LoRaPHYIN865.cpp + stubs/LoRaPHY_stub.cpp + stubs/mbed_assert_stub.c + +) + diff --git a/UNITTESTS/features/lorawan/loraphykr920/Test_LoRaPHYKR920.cpp b/UNITTESTS/features/lorawan/loraphykr920/Test_LoRaPHYKR920.cpp new file mode 100644 index 0000000000..5efab34c77 --- /dev/null +++ b/UNITTESTS/features/lorawan/loraphykr920/Test_LoRaPHYKR920.cpp @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "gtest/gtest.h" +#include "LoRaPHYKR920.h" +#include "LoRaPHY_stub.h" +#include "LoRaRadio.h" + +class my_radio : public LoRaRadio +{ +public: + + virtual void init_radio(radio_events_t *events){}; + + virtual void radio_reset(){}; + + virtual void sleep(void){}; + + virtual void standby(void){}; + + virtual void set_rx_config (radio_modems_t modem, uint32_t bandwidth, + uint32_t datarate, uint8_t coderate, + uint32_t bandwidth_afc, uint16_t preamble_len, + uint16_t symb_timeout, bool fix_len, + uint8_t payload_len, + bool crc_on, bool freq_hop_on, uint8_t hop_period, + bool iq_inverted, bool rx_continuous){}; + + virtual void set_tx_config(radio_modems_t modem, int8_t power, uint32_t fdev, + uint32_t bandwidth, uint32_t datarate, + uint8_t coderate, uint16_t preamble_len, + bool fix_len, bool crc_on, bool freq_hop_on, + uint8_t hop_period, bool iq_inverted, uint32_t timeout){}; + + virtual void send(uint8_t *buffer, uint8_t size){}; + + virtual void receive(void){}; + + virtual void set_channel(uint32_t freq){}; + + virtual uint32_t random(void){}; + + virtual uint8_t get_status(void){}; + + virtual void set_max_payload_length(radio_modems_t modem, uint8_t max){}; + + virtual void set_public_network(bool enable){}; + + virtual uint32_t time_on_air(radio_modems_t modem, uint8_t pkt_len){}; + + virtual bool perform_carrier_sense(radio_modems_t modem, + uint32_t freq, + int16_t rssi_threshold, + uint32_t max_carrier_sense_time){ return bool_value;}; + + virtual void start_cad(void){}; + + virtual bool check_rf_frequency(uint32_t frequency){ return bool_value; }; + + virtual void set_tx_continuous_wave(uint32_t freq, int8_t power, uint16_t time){}; + + virtual void lock(void){}; + + virtual void unlock(void){}; + + bool bool_value; +}; + +class Test_LoRaPHYKR920 : public testing::Test { +protected: + LoRaPHYKR920 *object; + my_radio radio; + + virtual void SetUp() + { + LoRaPHY_stub::radio = &radio; + object = new LoRaPHYKR920(); + } + + virtual void TearDown() + { + LoRaPHY_stub::radio = NULL; + delete object; + } +}; + +TEST_F(Test_LoRaPHYKR920, constructor) +{ + EXPECT_TRUE(object); +} + +TEST_F(Test_LoRaPHYKR920, verify_frequency_for_band) +{ + radio.bool_value = false; + EXPECT_TRUE(false == object->verify_frequency_for_band(0, 0)); + + radio.bool_value = true; + EXPECT_TRUE(false == object->verify_frequency_for_band(0, 0)); + + EXPECT_TRUE(true == object->verify_frequency_for_band(921100000, 0)); +} + +TEST_F(Test_LoRaPHYKR920, tx_config) +{ + tx_config_params_t tx_config; + int8_t tx_power = 0; + lorawan_time_t time; + + tx_config.tx_power = 9; + EXPECT_TRUE(true == object->tx_config(&tx_config, &tx_power, &time)); +} + +TEST_F(Test_LoRaPHYKR920, set_next_channel) +{ + channel_selection_params_t next_channel; + lorawan_time_t backoff_time = 0; + lorawan_time_t time = 0; + uint8_t ch = 1; + + next_channel.aggregate_timeoff = 0; + LoRaPHY_stub::uint8_value = 0; + EXPECT_TRUE(LORAWAN_STATUS_NO_CHANNEL_FOUND == object->set_next_channel(&next_channel, &ch, &backoff_time, &time)); + + next_channel.aggregate_timeoff = 1; + radio.bool_value = false; + EXPECT_TRUE(LORAWAN_STATUS_DUTYCYCLE_RESTRICTED == object->set_next_channel(&next_channel, &ch, &backoff_time, &time)); + + next_channel.aggregate_timeoff = 0; + LoRaPHY_stub::uint8_value = 1; + EXPECT_TRUE(LORAWAN_STATUS_NO_FREE_CHANNEL_FOUND == object->set_next_channel(&next_channel, &ch, &backoff_time, &time)); + + radio.bool_value = true; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_next_channel(&next_channel, &ch, &backoff_time, &time)); +} + +TEST_F(Test_LoRaPHYKR920, set_tx_cont_mode) +{ + cw_mode_params_t params; + params.tx_power = 9; + object->set_tx_cont_mode(¶ms, 0); +} + diff --git a/UNITTESTS/features/lorawan/loraphykr920/unittest.cmake b/UNITTESTS/features/lorawan/loraphykr920/unittest.cmake new file mode 100644 index 0000000000..cc32c13f02 --- /dev/null +++ b/UNITTESTS/features/lorawan/loraphykr920/unittest.cmake @@ -0,0 +1,40 @@ +#[[ + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +]] + +# Unit test suite name +set(TEST_SUITE_NAME "lorawan_LoRaPHYKR920") + +# Source files +set(unittest-sources + ../features/lorawan/lorastack/phy/LoRaPHYKR920.cpp +) + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + target_h + ../features/lorawan/lorastack/phy +) + +# Test & stub files +set(unittest-test-sources + features/lorawan/loraphykr920/Test_LoRaPHYKR920.cpp + stubs/LoRaPHY_stub.cpp + stubs/LoRaWANTimer_stub.cpp + stubs/mbed_assert_stub.c + +) + diff --git a/UNITTESTS/features/lorawan/loraphyus915/Test_LoRaPHYUS915.cpp b/UNITTESTS/features/lorawan/loraphyus915/Test_LoRaPHYUS915.cpp new file mode 100644 index 0000000000..4bd793f703 --- /dev/null +++ b/UNITTESTS/features/lorawan/loraphyus915/Test_LoRaPHYUS915.cpp @@ -0,0 +1,235 @@ +/* + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "gtest/gtest.h" +#include "LoRaPHYUS915.h" +#include "LoRaPHY_stub.h" + +class my_radio : public LoRaRadio +{ +public: + + virtual void init_radio(radio_events_t *events){}; + + virtual void radio_reset(){}; + + virtual void sleep(void){}; + + virtual void standby(void){}; + + virtual void set_rx_config (radio_modems_t modem, uint32_t bandwidth, + uint32_t datarate, uint8_t coderate, + uint32_t bandwidth_afc, uint16_t preamble_len, + uint16_t symb_timeout, bool fix_len, + uint8_t payload_len, + bool crc_on, bool freq_hop_on, uint8_t hop_period, + bool iq_inverted, bool rx_continuous){}; + + virtual void set_tx_config(radio_modems_t modem, int8_t power, uint32_t fdev, + uint32_t bandwidth, uint32_t datarate, + uint8_t coderate, uint16_t preamble_len, + bool fix_len, bool crc_on, bool freq_hop_on, + uint8_t hop_period, bool iq_inverted, uint32_t timeout){}; + + virtual void send(uint8_t *buffer, uint8_t size){}; + + virtual void receive(void){}; + + virtual void set_channel(uint32_t freq){}; + + virtual uint32_t random(void){}; + + virtual uint8_t get_status(void){return uint8_value;}; + + virtual void set_max_payload_length(radio_modems_t modem, uint8_t max){}; + + virtual void set_public_network(bool enable){}; + + virtual uint32_t time_on_air(radio_modems_t modem, uint8_t pkt_len){}; + + virtual bool perform_carrier_sense(radio_modems_t modem, + uint32_t freq, + int16_t rssi_threshold, + uint32_t max_carrier_sense_time){ return bool_value;}; + + virtual void start_cad(void){}; + + virtual bool check_rf_frequency(uint32_t frequency){ return bool_value; }; + + virtual void set_tx_continuous_wave(uint32_t freq, int8_t power, uint16_t time){}; + + virtual void lock(void){}; + + virtual void unlock(void){}; + + bool bool_value; + uint8_t uint8_value; +}; + +class Test_LoRaPHYUS915 : public testing::Test { +protected: + LoRaPHYUS915 *object; + my_radio radio; + + virtual void SetUp() + { + LoRaPHY_stub::radio = &radio; + object = new LoRaPHYUS915(); + } + + virtual void TearDown() + { + LoRaPHY_stub::radio = NULL; + delete object; + } +}; + +TEST_F(Test_LoRaPHYUS915, constructor) +{ + EXPECT_TRUE(object); +} + +TEST_F(Test_LoRaPHYUS915, restore_default_channels) +{ + object->restore_default_channels(); +} + +TEST_F(Test_LoRaPHYUS915, rx_config) +{ + rx_config_params_t p; + + radio.uint8_value = 1; + EXPECT_TRUE(!object->rx_config(&p)); + + radio.uint8_value = 0; + p.is_repeater_supported = true; + EXPECT_TRUE(object->rx_config(&p)); + + p.is_repeater_supported = false; + EXPECT_TRUE(object->rx_config(&p)); +} + +TEST_F(Test_LoRaPHYUS915, tx_config) +{ + tx_config_params_t p; + int8_t tx; + lorawan_time_t time; + EXPECT_TRUE(object->tx_config(&p, &tx, &time)); +} + +TEST_F(Test_LoRaPHYUS915, link_ADR_request) +{ + adr_req_params_t params; + int8_t dr_out; + int8_t tx_power_out; + uint8_t nb_rep_out; + uint8_t nb_bytes_parsed; + + EXPECT_TRUE(0 == object->link_ADR_request(¶ms, &dr_out, &tx_power_out, &nb_rep_out, &nb_bytes_parsed)); + + LoRaPHY_stub::uint8_value = 1; + LoRaPHY_stub::ch_mask_value = 6; + LoRaPHY_stub::adr_parse_count = 2; + EXPECT_TRUE(1 == object->link_ADR_request(¶ms, &dr_out, &tx_power_out, &nb_rep_out, &nb_bytes_parsed)); + + LoRaPHY_stub::adr_parse_count = 2; + LoRaPHY_stub::ch_mask_value = 7; + EXPECT_TRUE(1 == object->link_ADR_request(¶ms, &dr_out, &tx_power_out, &nb_rep_out, &nb_bytes_parsed)); + + LoRaPHY_stub::adr_parse_count = 2; + LoRaPHY_stub::ch_mask_value = 5; + LoRaPHY_stub::uint8_value = 6; + EXPECT_TRUE(6 == object->link_ADR_request(¶ms, &dr_out, &tx_power_out, &nb_rep_out, &nb_bytes_parsed)); + + LoRaPHY_stub::adr_parse_count = 2; + LoRaPHY_stub::ch_mask_value = 66; + LoRaPHY_stub::uint8_value = 7; + EXPECT_TRUE(7 == object->link_ADR_request(¶ms, &dr_out, &tx_power_out, &nb_rep_out, &nb_bytes_parsed)); +} + +TEST_F(Test_LoRaPHYUS915, accept_rx_param_setup_req) +{ + rx_param_setup_req_t p; + EXPECT_TRUE(0 == object->accept_rx_param_setup_req(&p)); + + radio.bool_value = true; + p.frequency = 923300000 - 1; + EXPECT_TRUE(0 == object->accept_rx_param_setup_req(&p)); + + radio.bool_value = true; + p.frequency = 927500000 + 1; + p.datarate = 6; + LoRaPHY_stub::bool_counter = 0; + LoRaPHY_stub::bool_table[0] = true; + EXPECT_TRUE(2 == object->accept_rx_param_setup_req(&p)); +} + +TEST_F(Test_LoRaPHYUS915, get_alternate_DR) +{ + EXPECT_TRUE(0 == object->get_alternate_DR(0)); + + EXPECT_TRUE(4 == object->get_alternate_DR(1)); +} + +TEST_F(Test_LoRaPHYUS915, set_next_channel) +{ + channel_selection_params_t params; + uint8_t channel; + lorawan_time_t time; + lorawan_time_t timeoff; + + params.current_datarate = 4; + params.aggregate_timeoff = 0; + LoRaPHY_stub::uint8_value = 0; + EXPECT_TRUE(LORAWAN_STATUS_NO_CHANNEL_FOUND == object->set_next_channel(¶ms, &channel, &time, &timeoff)); + + radio.bool_value = false; + params.aggregate_timeoff = 1; + EXPECT_TRUE(LORAWAN_STATUS_DUTYCYCLE_RESTRICTED == object->set_next_channel(¶ms, &channel, &time, &timeoff)); + + params.aggregate_timeoff = 0; + LoRaPHY_stub::uint8_value = 1; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_next_channel(¶ms, &channel, &time, &timeoff)); +} + +TEST_F(Test_LoRaPHYUS915, apply_DR_offset) +{ + //10, 9, 8, 8 + //11, 10, 9, 8 + //12, 11, 10, 9 + //13, 12, 11, 10 + //13, 13, 12, 11 + + for (int i = 0; i < 5; i++) { + for (int j=0; j < 4; j++ ) { + uint8_t val = 10 + i; + val -= j; + if (val > 13) val = 13; + if (val < 8) val = 8; + EXPECT_TRUE(val == object->apply_DR_offset(i, j)); + } + } +} + +TEST_F(Test_LoRaPHYUS915, set_tx_cont_mode) +{ + cw_mode_params_t p; + object->set_tx_cont_mode(&p, 0); + + p.datarate = 4; + object->set_tx_cont_mode(&p, 0); +} diff --git a/UNITTESTS/features/lorawan/loraphyus915/unittest.cmake b/UNITTESTS/features/lorawan/loraphyus915/unittest.cmake new file mode 100644 index 0000000000..f181da5e3f --- /dev/null +++ b/UNITTESTS/features/lorawan/loraphyus915/unittest.cmake @@ -0,0 +1,42 @@ +#[[ + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +]] + +# Unit test suite name +set(TEST_SUITE_NAME "lorawan_LoRaPHYUS915") + +# Source files +set(unittest-sources + ../features/lorawan/lorastack/phy/LoRaPHYUS915.cpp +) + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + target_h + ../features/lorawan/lorastack/phy +) + +# Test & stub files +set(unittest-test-sources + features/lorawan/loraphyus915/Test_LoRaPHYUS915.cpp + stubs/LoRaPHY_stub.cpp + stubs/LoRaWANTimer_stub.cpp + stubs/mbed_assert_stub.c + +) + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DMBED_CONF_LORA_FSB_MASK=\"{0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0x00FF}\"") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DMBED_CONF_LORA_FSB_MASK=\"{0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0x00FF}\"") diff --git a/UNITTESTS/features/lorawan/lorawaninterface/Test_LoRaWANInterface.cpp b/UNITTESTS/features/lorawan/lorawaninterface/Test_LoRaWANInterface.cpp new file mode 100644 index 0000000000..d02c9d68f7 --- /dev/null +++ b/UNITTESTS/features/lorawan/lorawaninterface/Test_LoRaWANInterface.cpp @@ -0,0 +1,229 @@ +/* + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "gtest/gtest.h" +#include "LoRaWANInterface.h" + +class my_radio : public LoRaRadio +{ +public: + + virtual void init_radio(radio_events_t *events){}; + + virtual void radio_reset(){}; + + virtual void sleep(void){}; + + virtual void standby(void){}; + + virtual void set_rx_config (radio_modems_t modem, uint32_t bandwidth, + uint32_t datarate, uint8_t coderate, + uint32_t bandwidth_afc, uint16_t preamble_len, + uint16_t symb_timeout, bool fix_len, + uint8_t payload_len, + bool crc_on, bool freq_hop_on, uint8_t hop_period, + bool iq_inverted, bool rx_continuous){}; + + virtual void set_tx_config(radio_modems_t modem, int8_t power, uint32_t fdev, + uint32_t bandwidth, uint32_t datarate, + uint8_t coderate, uint16_t preamble_len, + bool fix_len, bool crc_on, bool freq_hop_on, + uint8_t hop_period, bool iq_inverted, uint32_t timeout){}; + + virtual void send(uint8_t *buffer, uint8_t size){}; + + virtual void receive(void){}; + + virtual void set_channel(uint32_t freq){}; + + virtual uint32_t random(void){}; + + virtual uint8_t get_status(void){}; + + virtual void set_max_payload_length(radio_modems_t modem, uint8_t max){}; + + virtual void set_public_network(bool enable){}; + + virtual uint32_t time_on_air(radio_modems_t modem, uint8_t pkt_len){}; + + virtual bool perform_carrier_sense(radio_modems_t modem, + uint32_t freq, + int16_t rssi_threshold, + uint32_t max_carrier_sense_time){}; + + virtual void start_cad(void){}; + + virtual bool check_rf_frequency(uint32_t frequency){}; + + virtual void set_tx_continuous_wave(uint32_t freq, int8_t power, uint16_t time){}; + + virtual void lock(void){}; + + virtual void unlock(void){}; +}; + +class my_LoRaPHY : public LoRaPHY +{ +public: + my_LoRaPHY(){}; + + virtual ~my_LoRaPHY(){}; +}; + +class Test_LoRaWANInterface : public testing::Test { +protected: + LoRaWANInterface *object; + my_radio radio; + + virtual void SetUp() + { + object = new LoRaWANInterface(radio); + } + + virtual void TearDown() + { + delete object; + } +}; + +TEST_F(Test_LoRaWANInterface, constructor) +{ + EXPECT_TRUE(object); + + my_radio radio; + my_LoRaPHY phy; + LoRaWANInterface object(radio, phy); +} + +TEST_F(Test_LoRaWANInterface, initialize) +{ + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize(NULL)); +} + +TEST_F(Test_LoRaWANInterface, connect) +{ + EXPECT_TRUE(LORAWAN_STATUS_OK == object->connect()); + + lorawan_connect_t conn; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->connect(conn)); +} + +TEST_F(Test_LoRaWANInterface, disconnect) +{ + EXPECT_TRUE(LORAWAN_STATUS_OK == object->disconnect()); +} + +TEST_F(Test_LoRaWANInterface, add_link_check_request) +{ + EXPECT_TRUE(LORAWAN_STATUS_OK == object->add_link_check_request()); +} + +TEST_F(Test_LoRaWANInterface, remove_link_check_request) +{ + object->remove_link_check_request(); +} + +TEST_F(Test_LoRaWANInterface, set_datarate) +{ + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_datarate(1)); +} + +TEST_F(Test_LoRaWANInterface, enable_adaptive_datarate) +{ + EXPECT_TRUE(LORAWAN_STATUS_OK == object->enable_adaptive_datarate()); +} + +TEST_F(Test_LoRaWANInterface, disable_adaptive_datarate) +{ + object->disable_adaptive_datarate(); +} + +TEST_F(Test_LoRaWANInterface, set_confirmed_msg_retries) +{ + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_confirmed_msg_retries(1)); +} + +TEST_F(Test_LoRaWANInterface, set_channel_plan) +{ + lorawan_channelplan_t plan; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_channel_plan(plan)); +} + +TEST_F(Test_LoRaWANInterface, get_channel_plan) +{ + lorawan_channelplan_t plan; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->get_channel_plan(plan)); +} + +TEST_F(Test_LoRaWANInterface, remove_channel_plan) +{ + EXPECT_TRUE(LORAWAN_STATUS_OK == object->remove_channel_plan()); +} + +TEST_F(Test_LoRaWANInterface, remove_channel) +{ + EXPECT_TRUE(LORAWAN_STATUS_OK == object->remove_channel(1)); +} + +TEST_F(Test_LoRaWANInterface, send) +{ + EXPECT_TRUE(0 == object->send(1, NULL, 0, 0)); +} + +TEST_F(Test_LoRaWANInterface, receive) +{ + EXPECT_TRUE(0 == object->receive(1, NULL, 0, 0)); + + uint8_t port; + int flags; + EXPECT_TRUE(0 == object->receive(NULL, 0, port, flags)); +} + +TEST_F(Test_LoRaWANInterface, add_app_callbacks) +{ + lorawan_app_callbacks_t cbs; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->add_app_callbacks(&cbs)); +} + +TEST_F(Test_LoRaWANInterface, set_device_class) +{ + object->set_device_class(CLASS_A); +} + +TEST_F(Test_LoRaWANInterface, get_tx_metadata) +{ + lorawan_tx_metadata data; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->get_tx_metadata(data)); +} + +TEST_F(Test_LoRaWANInterface, get_rx_metadata) +{ + lorawan_rx_metadata data; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->get_rx_metadata(data)); +} + +TEST_F(Test_LoRaWANInterface, get_backoff_metadata) +{ + int i; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->get_backoff_metadata(i)); +} + +TEST_F(Test_LoRaWANInterface, cancel_sending) +{ + EXPECT_TRUE(LORAWAN_STATUS_OK == object->cancel_sending()); +} + diff --git a/UNITTESTS/features/lorawan/lorawaninterface/unittest.cmake b/UNITTESTS/features/lorawan/lorawaninterface/unittest.cmake new file mode 100644 index 0000000000..9e123a1c5e --- /dev/null +++ b/UNITTESTS/features/lorawan/lorawaninterface/unittest.cmake @@ -0,0 +1,51 @@ +#[[ + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +]] + +# Unit test suite name +set(TEST_SUITE_NAME "lorawan_LoRaWANInterface") + +# Source files +set(unittest-sources + ../features/lorawan/LoRaWANInterface.cpp +) + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + target_h + ../features/lorawan +) + +# Test & stub files +set(unittest-test-sources + features/lorawan/lorawaninterface/Test_LoRaWANInterface.cpp + stubs/LoRaPHY_stub.cpp + stubs/LoRaWANStack_stub.cpp + stubs/LoRaMac_stub.cpp + stubs/mbed_assert_stub.c + stubs/LoRaMacCrypto_stub.cpp + stubs/LoRaMacChannelPlan_stub.cpp + stubs/LoRaWANTimer_stub.cpp + stubs/LoRaMacCommand_stub.cpp + stubs/LoRaPHYEU868_stub.cpp +) + +# defines +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DMBED_CONF_LORA_PHY=\"EU868\"") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DMBED_CONF_LORA_PHY=\"EU868\"") + + + diff --git a/UNITTESTS/features/lorawan/lorawanstack/Test_LoRaWANStack.cpp b/UNITTESTS/features/lorawan/lorawanstack/Test_LoRaWANStack.cpp new file mode 100644 index 0000000000..43be749beb --- /dev/null +++ b/UNITTESTS/features/lorawan/lorawanstack/Test_LoRaWANStack.cpp @@ -0,0 +1,865 @@ +/* + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "gtest/gtest.h" +#include "LoRaWANStack.h" +#include "EventQueue.h" + +#include "LoRaPHY_stub.h" +#include "LoRaMac_stub.h" +#include "equeue_stub.h" +#include "lorawan_data_structures.h" + +static uint8_t batt_level = 0; + +using namespace events; + +class my_LoRaPHY : public LoRaPHY +{ +public: + my_LoRaPHY(){}; + + virtual ~my_LoRaPHY(){}; +}; + +uint8_t my_cb() +{ + return 1; +} + +class my_radio : public LoRaRadio +{ +public: + radio_events_t *_ev; + + virtual void init_radio(radio_events_t *events){_ev = events;}; + + virtual void radio_reset(){}; + + virtual void sleep(void){}; + + virtual void standby(void){}; + + virtual void set_rx_config (radio_modems_t modem, uint32_t bandwidth, + uint32_t datarate, uint8_t coderate, + uint32_t bandwidth_afc, uint16_t preamble_len, + uint16_t symb_timeout, bool fix_len, + uint8_t payload_len, + bool crc_on, bool freq_hop_on, uint8_t hop_period, + bool iq_inverted, bool rx_continuous){}; + + virtual void set_tx_config(radio_modems_t modem, int8_t power, uint32_t fdev, + uint32_t bandwidth, uint32_t datarate, + uint8_t coderate, uint16_t preamble_len, + bool fix_len, bool crc_on, bool freq_hop_on, + uint8_t hop_period, bool iq_inverted, uint32_t timeout){}; + + virtual void send(uint8_t *buffer, uint8_t size){}; + + virtual void receive(void){}; + + virtual void set_channel(uint32_t freq){}; + + virtual uint32_t random(void){}; + + virtual uint8_t get_status(void){return uint8_value;}; + + virtual void set_max_payload_length(radio_modems_t modem, uint8_t max){}; + + virtual void set_public_network(bool enable){}; + + virtual uint32_t time_on_air(radio_modems_t modem, uint8_t pkt_len){}; + + virtual bool perform_carrier_sense(radio_modems_t modem, + uint32_t freq, + int16_t rssi_threshold, + uint32_t max_carrier_sense_time){ return bool_value;}; + + virtual void start_cad(void){}; + + virtual bool check_rf_frequency(uint32_t frequency){ return bool_value; }; + + virtual void set_tx_continuous_wave(uint32_t freq, int8_t power, uint16_t time){}; + + virtual void lock(void){}; + + virtual void unlock(void){}; + + bool bool_value; + uint8_t uint8_value; +}; + + + +class Test_LoRaWANStack : public testing::Test { +protected: + LoRaWANStack *object; + + virtual void SetUp() + { + LoRaMac_stub::status_value = LORAWAN_STATUS_OK; + object = new LoRaWANStack(); + } + + virtual void TearDown() + { + delete object; + } +}; + +TEST_F(Test_LoRaWANStack, constructor) +{ + EXPECT_TRUE(object); +} + +TEST_F(Test_LoRaWANStack, bind_phy_and_radio_driver) +{ + my_radio radio; + my_LoRaPHY phy; + object->bind_phy_and_radio_driver(radio, phy); +} + +TEST_F(Test_LoRaWANStack, initialize_mac_layer) +{ + EXPECT_TRUE(LORAWAN_STATUS_PARAMETER_INVALID == object->initialize_mac_layer(NULL)); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + //Visit callback + if (LoRaMac_stub::_scheduling_failure_handler) { + LoRaMac_stub::_scheduling_failure_handler.call(); + } +} + +void events_cb(lorawan_event_t ev) +{ + +} + +void lc_resp(uint8_t a, uint8_t b) +{ + +} + +uint8_t batt_lvl() +{ + return batt_level; +} + +TEST_F(Test_LoRaWANStack, set_lora_callbacks) +{ + lorawan_app_callbacks_t cb; + EXPECT_TRUE(LORAWAN_STATUS_NOT_INITIALIZED == object->set_lora_callbacks(&cb)); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + EXPECT_TRUE(LORAWAN_STATUS_PARAMETER_INVALID == object->set_lora_callbacks(NULL)); + + cb.events = NULL; + EXPECT_TRUE(LORAWAN_STATUS_PARAMETER_INVALID == object->set_lora_callbacks(&cb)); + + cb.events = events_cb; + cb.link_check_resp = lc_resp; + cb.battery_level = batt_lvl; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_lora_callbacks(&cb)); +} + +TEST_F(Test_LoRaWANStack, connect) +{ + EXPECT_TRUE(LORAWAN_STATUS_NOT_INITIALIZED == object->connect()); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + LoRaMac_stub::status_value = LORAWAN_STATUS_BUSY; + EXPECT_TRUE(LORAWAN_STATUS_BUSY == object->connect()); + + LoRaMac_stub::status_value = LORAWAN_STATUS_OK; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->connect()); + + //_ctrl_flags & CONN_IN_PROGRESS_FLAG + EXPECT_TRUE(LORAWAN_STATUS_BUSY == object->connect()); + + my_radio radio; + my_LoRaPHY phy; + object->bind_phy_and_radio_driver(radio, phy); + + struct equeue_event ptr; + equeue_stub.void_ptr = &ptr; + equeue_stub.call_cb_immediately = true; + loramac_mcps_confirm_t conf; + LoRaMac_stub::mcps_conf_ptr = &conf; + radio._ev->tx_done(); + + loramac_mcps_indication_t ind; + LoRaMac_stub::mcps_ind_ptr = &ind; + + loramac_mlme_confirm_t mlme; + LoRaMac_stub::mlme_conf_ptr = &mlme; + mlme.pending = true; + mlme.req_type = MLME_JOIN; + mlme.status = LORAMAC_EVENT_INFO_STATUS_OK; + LoRaMac_stub::bool_value = false; + radio._ev->rx_done(NULL, 0, 0, 0); + + //_ctrl_flags & CONNECTED_FLAG + EXPECT_TRUE(LORAWAN_STATUS_ALREADY_CONNECTED == object->connect()); + + //Visit rx_interrupt_handler's first if + radio._ev->rx_done(NULL, 65535, 0, 0); +} + +TEST_F(Test_LoRaWANStack, connect_args) +{ + lorawan_connect_t conn; + EXPECT_TRUE(LORAWAN_STATUS_NOT_INITIALIZED == object->connect(conn)); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + conn.connect_type = lorawan_connect_type_t(8); + EXPECT_TRUE(LORAWAN_STATUS_PARAMETER_INVALID == object->connect(conn)); + + LoRaMac_stub::status_value = LORAWAN_STATUS_BUSY; + conn.connect_type = LORAWAN_CONNECTION_OTAA; + EXPECT_TRUE(LORAWAN_STATUS_BUSY == object->connect(conn)); + + LoRaMac_stub::status_value = LORAWAN_STATUS_OK; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->connect(conn)); + + //_ctrl_flags & CONN_IN_PROGRESS_FLAG + EXPECT_TRUE(LORAWAN_STATUS_BUSY == object->connect(conn)); + + object->shutdown(); + conn.connect_type = LORAWAN_CONNECTION_ABP; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->connect(conn)); + + //_ctrl_flags & CONNECTED_FLAG + EXPECT_TRUE(LORAWAN_STATUS_ALREADY_CONNECTED == object->connect(conn)); +} + +TEST_F(Test_LoRaWANStack, add_channels) +{ + lorawan_channelplan_t plan; + EXPECT_TRUE(LORAWAN_STATUS_NOT_INITIALIZED == object->add_channels(plan)); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + LoRaMac_stub::status_value = LORAWAN_STATUS_OK; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->add_channels(plan)); +} + +TEST_F(Test_LoRaWANStack, remove_a_channel) +{ + EXPECT_TRUE(LORAWAN_STATUS_NOT_INITIALIZED == object->remove_a_channel(1)); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + LoRaMac_stub::status_value = LORAWAN_STATUS_OK; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->remove_a_channel(1)); +} + +TEST_F(Test_LoRaWANStack, drop_channel_list) +{ + EXPECT_TRUE(LORAWAN_STATUS_NOT_INITIALIZED == object->drop_channel_list()); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + LoRaMac_stub::status_value = LORAWAN_STATUS_OK; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->drop_channel_list()); +} + +TEST_F(Test_LoRaWANStack, get_enabled_channels) +{ + lorawan_channelplan_t plan; + EXPECT_TRUE(LORAWAN_STATUS_NOT_INITIALIZED == object->get_enabled_channels(plan)); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + LoRaMac_stub::status_value = LORAWAN_STATUS_OK; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->get_enabled_channels(plan)); +} + +TEST_F(Test_LoRaWANStack, set_confirmed_msg_retry) +{ + EXPECT_TRUE(LORAWAN_STATUS_NOT_INITIALIZED == object->set_confirmed_msg_retry(1)); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + EXPECT_TRUE(LORAWAN_STATUS_PARAMETER_INVALID == object->set_confirmed_msg_retry(255)); + + LoRaMac_stub::status_value = LORAWAN_STATUS_OK; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_confirmed_msg_retry(1)); +} + +TEST_F(Test_LoRaWANStack, set_channel_data_rate) +{ + EXPECT_TRUE(LORAWAN_STATUS_NOT_INITIALIZED == object->set_channel_data_rate(4)); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + LoRaMac_stub::status_value = LORAWAN_STATUS_OK; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_channel_data_rate(4)); +} + +TEST_F(Test_LoRaWANStack, enable_adaptive_datarate) +{ + EXPECT_TRUE(LORAWAN_STATUS_NOT_INITIALIZED == object->enable_adaptive_datarate(false)); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + LoRaMac_stub::status_value = LORAWAN_STATUS_OK; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->enable_adaptive_datarate(false)); +} + +TEST_F(Test_LoRaWANStack, handle_tx) +{ + EXPECT_TRUE(LORAWAN_STATUS_NOT_INITIALIZED == object->handle_tx(0, NULL, 0, 0, true, false)); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + LoRaMac_stub::status_value = LORAWAN_STATUS_OK; + EXPECT_TRUE(LORAWAN_STATUS_PARAMETER_INVALID == object->handle_tx(0, NULL, 0, 0, false, false)); + + lorawan_app_callbacks_t cb; + cb.events = events_cb; + cb.link_check_resp = lc_resp; + cb.battery_level = batt_lvl; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_lora_callbacks(&cb)); + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_link_check_request()); + + LoRaMac_stub::status_value = LORAWAN_STATUS_OK; + EXPECT_TRUE(LORAWAN_STATUS_NO_ACTIVE_SESSIONS == object->handle_tx(0, NULL, 0, 0, true, false)); + + lorawan_connect_t conn; + conn.connect_type = LORAWAN_CONNECTION_ABP; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->connect(conn)); + + LoRaMac_stub::bool_value = false; + EXPECT_TRUE(LORAWAN_STATUS_NO_NETWORK_JOINED == object->handle_tx(0, NULL, 0, 0, true, false)); + + LoRaMac_stub::bool_value = true; + EXPECT_TRUE(LORAWAN_STATUS_WOULD_BLOCK == object->handle_tx(0, NULL, 0, 0, true, false)); + + LoRaMac_stub::bool_false_counter = 1; + LoRaMac_stub::bool_value = true; + //set_application_port fails + EXPECT_TRUE(LORAWAN_STATUS_PORT_INVALID == object->handle_tx(0, NULL, 0, 0, true, false)); + + LoRaMac_stub::bool_false_counter = 1; + LoRaMac_stub::bool_value = true; + //Wrong flags -> LORAWAN_STATUS_PARAMETER_INVALID + EXPECT_TRUE(LORAWAN_STATUS_PARAMETER_INVALID == object->handle_tx(1, NULL, 0, 0x04, true, false)); + + LoRaMac_stub::bool_false_counter = 1; + //Actual sending + EXPECT_TRUE(LORAWAN_STATUS_OK == object->handle_tx(1, NULL, 0, 0x08, true, false)); + +} + +TEST_F(Test_LoRaWANStack, handle_rx) +{ + uint8_t port; + int flags; + EXPECT_TRUE(LORAWAN_STATUS_NOT_INITIALIZED == object->handle_rx(NULL, 0, port, flags, false)); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + LoRaMac_stub::status_value = LORAWAN_STATUS_OK; + EXPECT_TRUE(LORAWAN_STATUS_NO_ACTIVE_SESSIONS == object->handle_rx(NULL, 0, port, flags, false)); + + lorawan_connect_t conn; + conn.connect_type = LORAWAN_CONNECTION_ABP; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->connect(conn)); + EXPECT_TRUE(LORAWAN_STATUS_WOULD_BLOCK == object->handle_rx(NULL, 0, port, flags, false)); + + //Prepare ready for receive state + lorawan_app_callbacks_t cb; + cb.events = events_cb; + cb.link_check_resp = lc_resp; + cb.battery_level = batt_lvl; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_lora_callbacks(&cb)); + + my_radio radio; + my_LoRaPHY phy; + object->bind_phy_and_radio_driver(radio, phy); + + struct equeue_event ptr; + equeue_stub.void_ptr = &ptr; + equeue_stub.call_cb_immediately = true; + loramac_mcps_confirm_t conf; + LoRaMac_stub::mcps_conf_ptr = &conf; + radio._ev->tx_done(); + + loramac_mcps_indication_t ind; + LoRaMac_stub::mcps_ind_ptr = &ind; + + loramac_mlme_confirm_t mlme; + LoRaMac_stub::mlme_conf_ptr = &mlme; + mlme.pending = false; + mlme.req_type = MLME_JOIN; + mlme.status = LORAMAC_EVENT_INFO_STATUS_OK; + LoRaMac_stub::bool_value = true; + conf.req_type = MCPS_PROPRIETARY; + + ind.pending = true; + LoRaMac_stub::dev_class_value = CLASS_C; + + loramac_mlme_indication_t mlme_ind; + mlme_ind.pending = false; + LoRaMac_stub::mlme_ind_ptr = &mlme_ind; + + uint8_t ind_buf[150]; + for (int i= 0; i < 110; i++) { + ind_buf[i] = i; + } + ind.buffer = ind_buf; + ind.buffer_size = 150; + ind.type = MCPS_UNCONFIRMED; + radio._ev->rx_done(NULL, 0, 0, 0); + + //data == NULL || LENGTH == 0 (2 cases) + EXPECT_TRUE(LORAWAN_STATUS_PARAMETER_INVALID == object->handle_rx(NULL, 0, port, flags, false)); + uint8_t data[50]; + EXPECT_TRUE(LORAWAN_STATUS_PARAMETER_INVALID == object->handle_rx(data, 0, port, flags, false)); + + //validate_params returns Would block + port = 43; + EXPECT_TRUE(LORAWAN_STATUS_WOULD_BLOCK == object->handle_rx(data, 50, port, flags, true)); + + ind.type = MCPS_CONFIRMED; + radio._ev->rx_done(NULL, 0, 0, 0); + EXPECT_TRUE(LORAWAN_STATUS_WOULD_BLOCK == object->handle_rx(data, 50, port, flags, true)); + //Call again to visit send_automatic_uplink_message error case + LoRaMac_stub::bool_true_counter = 1; + ind.type = MCPS_CONFIRMED; + ind.status = LORAMAC_EVENT_INFO_STATUS_ERROR; + LoRaMac_stub::bool_value = false; + radio._ev->rx_done(NULL, 0, 0, 0); + + ind.status = LORAMAC_EVENT_INFO_STATUS_OK; + + LoRaMac_stub::bool_value = true; + //convert_to_msg_flag cases + ind.fpending_status = true; + ind.type = MCPS_PROPRIETARY; + radio._ev->rx_done(NULL, 0, 0, 0); + EXPECT_TRUE(LORAWAN_STATUS_WOULD_BLOCK == object->handle_rx(data, 50, port, flags, true)); + + ind.type = MCPS_MULTICAST; + radio._ev->rx_done(NULL, 0, 0, 0); + EXPECT_TRUE(LORAWAN_STATUS_WOULD_BLOCK == object->handle_rx(data, 50, port, flags, true)); + + ind.type = MCPS_UNCONFIRMED; + radio._ev->rx_done(NULL, 0, 0, 0); + + //read not complete + EXPECT_TRUE(50 == object->handle_rx(data, 50, port, flags, false)); + EXPECT_EQ(10, data[10]); + + EXPECT_TRUE(50 == object->handle_rx(data, 50, port, flags, false)); + EXPECT_EQ(60, data[10]); + + //read complete + EXPECT_TRUE(50 == object->handle_rx(data, 50, port, flags, false)); + EXPECT_EQ(100, data[0]); + + //read can fit the buffer + for (int i= 0; i < 110; i++) { + ind_buf[i] = i; + } + ind.buffer = ind_buf; + ind.buffer_size = 50; + ind.type = mcps_type_t(66); + radio._ev->rx_done(NULL, 0, 0, 0); + EXPECT_TRUE(50 == object->handle_rx(data, 50, port, flags, false)); + EXPECT_EQ(10, data[10]); +} + +TEST_F(Test_LoRaWANStack, set_link_check_request) +{ + EXPECT_TRUE(LORAWAN_STATUS_NOT_INITIALIZED == object->set_link_check_request()); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + LoRaMac_stub::status_value = LORAWAN_STATUS_OK; + EXPECT_TRUE(LORAWAN_STATUS_PARAMETER_INVALID == object->set_link_check_request()); + + lorawan_app_callbacks_t cb; + cb.events = events_cb; + cb.link_check_resp = lc_resp; + cb.battery_level = batt_lvl; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_lora_callbacks(&cb)); + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_link_check_request()); +} + +TEST_F(Test_LoRaWANStack, remove_link_check_request) +{ + object->remove_link_check_request(); +} + +TEST_F(Test_LoRaWANStack, shutdown) +{ + EXPECT_TRUE(LORAWAN_STATUS_NOT_INITIALIZED == object->shutdown()); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + EXPECT_TRUE(LORAWAN_STATUS_DEVICE_OFF == object->shutdown()); +} + +TEST_F(Test_LoRaWANStack, set_device_class) +{ + EXPECT_TRUE(LORAWAN_STATUS_NOT_INITIALIZED == object->set_device_class(CLASS_A)); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + LoRaMac_stub::status_value = LORAWAN_STATUS_OK; + EXPECT_TRUE(LORAWAN_STATUS_UNSUPPORTED == object->set_device_class(CLASS_B)); + + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_device_class(CLASS_A)); + + //Visit callback + if (LoRaMac_stub::_ack_expiry_handler_for_class_c) { + LoRaMac_stub::_ack_expiry_handler_for_class_c.call(); + } +} + +TEST_F(Test_LoRaWANStack, acquire_tx_metadata) +{ + lorawan_tx_metadata data; + EXPECT_TRUE(LORAWAN_STATUS_NOT_INITIALIZED == object->acquire_tx_metadata(data)); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + LoRaMac_stub::status_value = LORAWAN_STATUS_OK; + // stale = true; + EXPECT_TRUE(LORAWAN_STATUS_METADATA_NOT_AVAILABLE == object->acquire_tx_metadata(data)); + + // stale = false; + my_radio radio; + my_LoRaPHY phy; + object->bind_phy_and_radio_driver(radio, phy); + + struct equeue_event ptr; + equeue_stub.void_ptr = &ptr; + equeue_stub.call_cb_immediately = true; + loramac_mcps_confirm_t conf; + LoRaMac_stub::mcps_conf_ptr = &conf; + radio._ev->tx_done(); + + EXPECT_TRUE(LORAWAN_STATUS_OK == object->acquire_tx_metadata(data)); +} + +TEST_F(Test_LoRaWANStack, acquire_rx_metadata) +{ + lorawan_rx_metadata data; + EXPECT_TRUE(LORAWAN_STATUS_NOT_INITIALIZED == object->acquire_rx_metadata(data)); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + LoRaMac_stub::status_value = LORAWAN_STATUS_OK; + // stale = true; + EXPECT_TRUE(LORAWAN_STATUS_METADATA_NOT_AVAILABLE == object->acquire_rx_metadata(data)); + + // stale = false; + my_radio radio; + my_LoRaPHY phy; + object->bind_phy_and_radio_driver(radio, phy); + + struct equeue_event ptr; + equeue_stub.void_ptr = &ptr; + equeue_stub.call_cb_immediately = true; + loramac_mcps_confirm_t conf; + LoRaMac_stub::mcps_conf_ptr = &conf; + radio._ev->tx_done(); + + loramac_mcps_indication_t ind; + LoRaMac_stub::mcps_ind_ptr = &ind; + + loramac_mlme_confirm_t mlme; + LoRaMac_stub::mlme_conf_ptr = &mlme; + mlme.pending = true; + mlme.req_type = MLME_JOIN; + + //Visit mlme_confirm_handler here also + mlme.status = LORAMAC_EVENT_INFO_STATUS_CRYPTO_FAIL; + LoRaMac_stub::bool_value = false; + radio._ev->rx_done(NULL, 0, 0, 0); + + mlme.status = LORAMAC_EVENT_INFO_STATUS_TX_TIMEOUT; + radio._ev->rx_done(NULL, 0, 0, 0); + + mlme.status = LORAMAC_EVENT_INFO_STATUS_RX1_TIMEOUT; + LoRaMac_stub::slot_value = RX_SLOT_WIN_2; + radio._ev->rx_done(NULL, 0, 0, 0); + + lorawan_app_callbacks_t cb; + cb.events = events_cb; + cb.link_check_resp = lc_resp; + cb.battery_level = batt_lvl; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_lora_callbacks(&cb)); + mlme.req_type = MLME_LINK_CHECK; + mlme.status = LORAMAC_EVENT_INFO_STATUS_OK; + radio._ev->rx_done(NULL, 0, 0, 0); + + EXPECT_TRUE(LORAWAN_STATUS_OK == object->acquire_rx_metadata(data)); +} + +TEST_F(Test_LoRaWANStack, acquire_backoff_metadata) +{ + int b; + EXPECT_TRUE(LORAWAN_STATUS_NOT_INITIALIZED == object->acquire_backoff_metadata(b)); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + LoRaMac_stub::int_value = 2; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->acquire_backoff_metadata(b)); + + LoRaMac_stub::int_value = 0; + EXPECT_TRUE(LORAWAN_STATUS_METADATA_NOT_AVAILABLE == object->acquire_backoff_metadata(b)); +} + +TEST_F(Test_LoRaWANStack, stop_sending) +{ + EXPECT_TRUE(LORAWAN_STATUS_NOT_INITIALIZED == object->stop_sending()); + + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + LoRaMac_stub::status_value = LORAWAN_STATUS_DEVICE_OFF; + EXPECT_TRUE(LORAWAN_STATUS_BUSY == object->stop_sending()); + + LoRaMac_stub::status_value = LORAWAN_STATUS_OK; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->stop_sending()); +} + +TEST_F(Test_LoRaWANStack, lock) +{ + object->lock(); +} + +TEST_F(Test_LoRaWANStack, unlock) +{ + object->unlock(); +} + +TEST_F(Test_LoRaWANStack, interrupt_functions) +{ + lorawan_connect_t conn; + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + my_radio radio; + my_LoRaPHY phy; + object->bind_phy_and_radio_driver(radio, phy); + + struct equeue_event ptr; + equeue_stub.void_ptr = &ptr; + equeue_stub.call_cb_immediately = true; + loramac_mcps_confirm_t conf; + LoRaMac_stub::mcps_conf_ptr = &conf; + radio._ev->tx_done(); + + loramac_mcps_indication_t ind; + LoRaMac_stub::mcps_ind_ptr = &ind; + + loramac_mlme_confirm_t mlme; + LoRaMac_stub::mlme_conf_ptr = &mlme; + mlme.pending = true; + mlme.req_type = MLME_JOIN; + mlme.status = LORAMAC_EVENT_INFO_STATUS_OK; + LoRaMac_stub::bool_value = false; + radio._ev->rx_done(NULL, 0, 0, 0); + + radio._ev->rx_done(NULL, 0, 0, 0); + + radio._ev->rx_error(); + LoRaMac_stub::slot_value = RX_SLOT_WIN_2; + radio._ev->rx_error(); + + conf.req_type = MCPS_UNCONFIRMED; + LoRaMac_stub::bool_value = true; + radio._ev->rx_error(); + + conf.req_type = MCPS_CONFIRMED; + radio._ev->rx_error(); + + LoRaMac_stub::bool_value = false; + + LoRaMac_stub::slot_value = RX_SLOT_WIN_1; + radio._ev->rx_timeout(); + + radio._ev->tx_timeout(); + + object->shutdown(); + conn.connect_type = LORAWAN_CONNECTION_OTAA; + object->connect(conn); + LoRaMac_stub::status_value = LORAWAN_STATUS_OK; + object->connect(conn); + radio._ev->tx_timeout(); +} + +TEST_F(Test_LoRaWANStack, process_transmission) +{ + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + lorawan_app_callbacks_t cb; + cb.events = events_cb; + cb.link_check_resp = lc_resp; + cb.battery_level = batt_lvl; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_lora_callbacks(&cb)); + + my_radio radio; + my_LoRaPHY phy; + object->bind_phy_and_radio_driver(radio, phy); + + object->connect(); + + struct equeue_event ptr; + equeue_stub.void_ptr = &ptr; + equeue_stub.call_cb_immediately = true; + loramac_mcps_confirm_t conf; + LoRaMac_stub::mcps_conf_ptr = &conf; + radio._ev->tx_done(); + + loramac_mcps_indication_t ind; + LoRaMac_stub::mcps_ind_ptr = &ind; + + loramac_mlme_confirm_t mlme; + LoRaMac_stub::mlme_conf_ptr = &mlme; + mlme.pending = true; + mlme.req_type = MLME_JOIN; + mlme.status = LORAMAC_EVENT_INFO_STATUS_OK; + LoRaMac_stub::bool_value = false; + radio._ev->rx_done(NULL, 0, 0, 0); + + LoRaMac_stub::bool_value = true; + conf.req_type = MCPS_PROPRIETARY; + LoRaMac_stub::bool_false_counter = 1; + LoRaMac_stub::dev_class_value = CLASS_A; + object->handle_tx(1, NULL, 0, MSG_UNCONFIRMED_FLAG, true, false); + radio._ev->tx_done(); + + LoRaMac_stub::bool_false_counter = 1; + LoRaMac_stub::dev_class_value = CLASS_A; + object->handle_tx(1, NULL, 0, MSG_UNCONFIRMED_FLAG, true, false); + radio._ev->tx_done(); + + LoRaMac_stub::bool_false_counter = 1; + LoRaMac_stub::dev_class_value = CLASS_C; + object->handle_tx(1, NULL, 0, MSG_UNCONFIRMED_FLAG, true, false); + radio._ev->tx_done(); + + LoRaMac_stub::bool_false_counter = 1; + conf.req_type = MCPS_CONFIRMED; + object->handle_tx(1, NULL, 0, MSG_UNCONFIRMED_FLAG, true, false); + radio._ev->tx_done(); +} + +TEST_F(Test_LoRaWANStack, process_reception) +{ + EventQueue queue; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->initialize_mac_layer(&queue)); + + //Prepare ready for receive state + lorawan_app_callbacks_t cb; + cb.events = events_cb; + cb.link_check_resp = lc_resp; + cb.battery_level = batt_lvl; + EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_lora_callbacks(&cb)); + + my_radio radio; + my_LoRaPHY phy; + object->bind_phy_and_radio_driver(radio, phy); + + struct equeue_event ptr; + equeue_stub.void_ptr = &ptr; + equeue_stub.call_cb_immediately = true; + loramac_mcps_confirm_t conf; + LoRaMac_stub::mcps_conf_ptr = &conf; + radio._ev->tx_done(); + + loramac_mcps_indication_t ind; + LoRaMac_stub::mcps_ind_ptr = &ind; + + loramac_mlme_confirm_t mlme; + LoRaMac_stub::mlme_conf_ptr = &mlme; + mlme.pending = false; + mlme.req_type = MLME_JOIN; + mlme.status = LORAMAC_EVENT_INFO_STATUS_OK; + LoRaMac_stub::bool_value = true; + conf.req_type = MCPS_PROPRIETARY; + + ind.pending = true; + LoRaMac_stub::dev_class_value = CLASS_C; + + loramac_mlme_indication_t mlme_ind; + mlme_ind.pending = false; + LoRaMac_stub::mlme_ind_ptr = &mlme_ind; + + uint8_t ind_buf[150]; + for (int i= 0; i < 110; i++) { + ind_buf[i] = i; + } + ind.buffer = ind_buf; + ind.buffer_size = 150; + + //_loramac.get_mcps_confirmation()->req_type == MCPS_CONFIRMED + conf.req_type = MCPS_CONFIRMED; + conf.status = LORAMAC_EVENT_INFO_STATUS_TX_TIMEOUT; + radio._ev->rx_done(NULL, 0, 0, 0); + + ind.is_ack_recvd = false; + LoRaMac_stub::bool_true_counter = 1; + LoRaMac_stub::bool_value = false; + LoRaMac_stub::slot_value = RX_SLOT_WIN_2; + conf.status = LORAMAC_EVENT_INFO_STATUS_TX_DR_PAYLOAD_SIZE_ERROR; + radio._ev->rx_done(NULL, 0, 0, 0); + + conf.req_type = MCPS_UNCONFIRMED; + LoRaMac_stub::dev_class_value = CLASS_A; + LoRaMac_stub::bool_value = true; + mlme_ind.pending = true; + mlme_ind.indication_type = MLME_SCHEDULE_UPLINK; + conf.status = LORAMAC_EVENT_INFO_STATUS_ERROR; + radio._ev->rx_done(NULL, 0, 0, 0); + + ind.is_ack_recvd = true; + conf.req_type = MCPS_CONFIRMED; + conf.status = LORAMAC_EVENT_INFO_STATUS_TX_TIMEOUT; + radio._ev->rx_done(NULL, 0, 0, 0); +} + diff --git a/UNITTESTS/features/lorawan/lorawanstack/unittest.cmake b/UNITTESTS/features/lorawan/lorawanstack/unittest.cmake new file mode 100644 index 0000000000..8c97d36268 --- /dev/null +++ b/UNITTESTS/features/lorawan/lorawanstack/unittest.cmake @@ -0,0 +1,56 @@ +#[[ + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +]] + +# Unit test suite name +set(TEST_SUITE_NAME "lorawan_LoRaWANStack") + +# Source files +set(unittest-sources + ../features/lorawan/LoRaWANStack.cpp +) + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + target_h + ../features/lorawan +) + +# Test & stub files +set(unittest-test-sources + features/lorawan/lorawanstack/Test_LoRaWANStack.cpp + stubs/LoRaPHY_stub.cpp + stubs/LoRaMac_stub.cpp + stubs/mbed_assert_stub.c + stubs/LoRaMacCrypto_stub.cpp + stubs/LoRaMacChannelPlan_stub.cpp + stubs/LoRaWANTimer_stub.cpp + stubs/LoRaMacCommand_stub.cpp + stubs/EventQueue_stub.cpp + stubs/equeue_stub.c + +) + +# defines +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DMBED_CONF_LORA_OVER_THE_AIR_ACTIVATION=true -DMBED_CONF_LORA_DEVICE_EUI=\"{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}\"") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DMBED_CONF_LORA_OVER_THE_AIR_ACTIVATION=true -DMBED_CONF_LORA_DEVICE_EUI=\"{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}\"") + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DMBED_CONF_LORA_AUTOMATIC_UPLINK_MESSAGE=true") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DMBED_CONF_LORA_AUTOMATIC_UPLINK_MESSAGE=true") + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DMBED_CONF_LORA_APPLICATION_EUI=\"{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}\" -DMBED_CONF_LORA_APPLICATION_KEY=\"{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}\"") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DMBED_CONF_LORA_APPLICATION_EUI=\"{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}\" -DMBED_CONF_LORA_APPLICATION_KEY=\"{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}\"") + diff --git a/UNITTESTS/features/lorawan/lorawantimer/Test_LoRaWANTimer.cpp b/UNITTESTS/features/lorawan/lorawantimer/Test_LoRaWANTimer.cpp new file mode 100644 index 0000000000..80a98460ce --- /dev/null +++ b/UNITTESTS/features/lorawan/lorawantimer/Test_LoRaWANTimer.cpp @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "gtest/gtest.h" +#include "LoRaWANTimer.h" + +using namespace events; + +class Test_LoRaWANTimer : public testing::Test { +protected: + LoRaWANTimeHandler *object; + EventQueue *queue; + + virtual void SetUp() + { + queue = new EventQueue(3, NULL); + object = new LoRaWANTimeHandler(); + object->activate_timer_subsystem(queue); + } + + virtual void TearDown() + { + delete object; + delete queue; + } +}; + +TEST_F(Test_LoRaWANTimer, constructor) +{ + EXPECT_TRUE(object); +} + +TEST_F(Test_LoRaWANTimer, get_current_time) +{ + lorawan_time_t tt = object->get_current_time(); + EXPECT_TRUE(0 == tt); +} + +TEST_F(Test_LoRaWANTimer, get_elapsed_time) +{ + lorawan_time_t tt = object->get_elapsed_time(0); + EXPECT_TRUE(0 == tt); +} + +void my_callback() +{ +} + +TEST_F(Test_LoRaWANTimer, init) +{ + timer_event_t ev; + object->init(ev, my_callback); +} + +TEST_F(Test_LoRaWANTimer, start) +{ + timer_event_t ev; + object->start(ev, 10); +} + +TEST_F(Test_LoRaWANTimer, stop) +{ + timer_event_t ev; + ev.timer_id = 4; + object->stop(ev); + EXPECT_TRUE(ev.timer_id == 0); +} + + + diff --git a/UNITTESTS/features/lorawan/lorawantimer/unittest.cmake b/UNITTESTS/features/lorawan/lorawantimer/unittest.cmake new file mode 100644 index 0000000000..48764961fc --- /dev/null +++ b/UNITTESTS/features/lorawan/lorawantimer/unittest.cmake @@ -0,0 +1,39 @@ +#[[ + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +]] + +# Unit test suite name +set(TEST_SUITE_NAME "lorawan_LoRaWANTimer") + +# Source files +set(unittest-sources + ../features/lorawan/system/LoRaWANTimer.cpp +) + +# Add test specific include paths +set(unittest-includes ${unittest-includes} + target_h + ../features/lorawan/system +) + +# Test & stub files +set(unittest-test-sources + features/lorawan/lorawantimer/Test_LoRaWANTimer.cpp + stubs/EventQueue_stub.cpp + stubs/mbed_assert_stub.c + stubs/equeue_stub.c +) + diff --git a/UNITTESTS/features/netsocket/InternetSocket/test_InternetSocket.cpp b/UNITTESTS/features/netsocket/InternetSocket/test_InternetSocket.cpp index fae48b7ede..3b499fef42 100644 --- a/UNITTESTS/features/netsocket/InternetSocket/test_InternetSocket.cpp +++ b/UNITTESTS/features/netsocket/InternetSocket/test_InternetSocket.cpp @@ -19,17 +19,13 @@ #include "features/netsocket/InternetSocket.h" #include "NetworkStack_stub.h" +extern std::list eventFlagsStubNextRetval; + +// InternetSocket is an abstract class, so we have to test it via its child. class stubInternetSocket : public InternetSocket { protected: nsapi_error_t return_value = 0; public: - virtual void event() - { - if (_callback) { - _callback.call(); - } - } - virtual nsapi_error_t connect(const SocketAddress &address) { return return_value; @@ -60,6 +56,15 @@ public: { return return_value; } + + // Testing functions + void add_reader (void) { _readers++;} + void rem_reader (void) { _readers--;} + void add_writer (void) { _writers++;} + void rem_writer (void) { _writers--;} + void add_pending (void) { _pending++;} + void rem_pending (void) { _pending--;} + protected: virtual nsapi_protocol_t get_proto() { @@ -94,7 +99,6 @@ TEST_F(TestInternetSocket, constructor) EXPECT_TRUE(socket); } - TEST_F(TestInternetSocket, open_null_stack) { EXPECT_EQ(socket->open(NULL), NSAPI_ERROR_PARAMETER); @@ -126,34 +130,81 @@ TEST_F(TestInternetSocket, close) EXPECT_EQ(socket->close(), NSAPI_ERROR_OK); } +TEST_F(TestInternetSocket, close_no_open) +{ + stack.return_value = NSAPI_ERROR_OK; + EXPECT_EQ(socket->close(), NSAPI_ERROR_OK); +} + +TEST_F(TestInternetSocket, close_during_read) +{ + stack.return_value = NSAPI_ERROR_OK; + socket->open((NetworkStack *)&stack); + // when c++11 is available use something like the code below to test the blocking behavior + // socket->add_reader(); + // std::async(c[](){std::this_thread::sleep_for(1ms); socket->rem_reader()}); + EXPECT_EQ(socket->close(), NSAPI_ERROR_OK); +} + TEST_F(TestInternetSocket, modify_multicast_group) { SocketAddress a("127.0.0.1", 1024); stack.return_value = NSAPI_ERROR_OK; socket->open((NetworkStack *)&stack); - + // when c++11 is available use something like the code below to test the blocking behavior + // socket->add_reader(); + // std::async(c[](){std::this_thread::sleep_for(1ms); socket->rem_reader()}); EXPECT_EQ(socket->join_multicast_group(a), NSAPI_ERROR_UNSUPPORTED); EXPECT_EQ(socket->leave_multicast_group(a), NSAPI_ERROR_UNSUPPORTED); } -TEST_F(TestInternetSocket, set_blocking) +// set_blocking and set_timeout are tested within TCPSocket. + +TEST_F(TestInternetSocket, bind_no_socket) { - socket->set_blocking(false); - socket->set_blocking(true); + EXPECT_EQ(socket->bind(1), NSAPI_ERROR_NO_SOCKET); } +TEST_F(TestInternetSocket, bind) +{ + socket->open((NetworkStack *)&stack); + EXPECT_EQ(socket->bind("127.0.0.1", 80), NSAPI_ERROR_OK); +} + +TEST_F(TestInternetSocket, bind_nullstring) +{ + socket->open((NetworkStack *)&stack); + EXPECT_EQ(socket->bind(NULL, 80), NSAPI_ERROR_OK); +} + +// setsockopt and getsockopt are really just calling the underlying stack functions + TEST_F(TestInternetSocket, setsockopt_no_stack) { - socket->close(); EXPECT_EQ(socket->setsockopt(0, 0, 0, 0), NSAPI_ERROR_NO_SOCKET); } +TEST_F(TestInternetSocket, setsockopt) +{ + socket->open((NetworkStack *)&stack); + EXPECT_EQ(socket->setsockopt(0, 0, 0, 0), NSAPI_ERROR_UNSUPPORTED); +} + +TEST_F(TestInternetSocket, getsockopt_no_stack) +{ + EXPECT_EQ(socket->getsockopt(0, 0, 0, 0), NSAPI_ERROR_NO_SOCKET); +} + +TEST_F(TestInternetSocket, getsockopt) +{ + socket->open((NetworkStack *)&stack); + EXPECT_EQ(socket->getsockopt(0, 0, 0, 0), NSAPI_ERROR_UNSUPPORTED); +} + TEST_F(TestInternetSocket, sigio) { callback_is_called = false; - // I'm calling sigio() through the DEPRECATED method, just to get coverage for both. - // Not sure if this is wise at all, we should not aim for 100% - socket->attach(mbed::callback(my_callback)); - socket->event(); + socket->sigio(mbed::callback(my_callback)); + socket->close(); // Trigger event; EXPECT_EQ(callback_is_called, true); } diff --git a/UNITTESTS/features/netsocket/InternetSocket/unittest.cmake b/UNITTESTS/features/netsocket/InternetSocket/unittest.cmake index ee22788fa4..3d4297e530 100644 --- a/UNITTESTS/features/netsocket/InternetSocket/unittest.cmake +++ b/UNITTESTS/features/netsocket/InternetSocket/unittest.cmake @@ -3,9 +3,6 @@ # UNIT TESTS #################### -# Unit test suite name -set(TEST_SUITE_NAME "features-netsocket-InternetSocket") - set(unittest-sources ../features/netsocket/SocketAddress.cpp ../features/netsocket/NetworkStack.cpp @@ -15,6 +12,7 @@ set(unittest-sources ) set(unittest-test-sources + features/netsocket/InternetSocket/test_InternetSocket.cpp stubs/Mutex_stub.cpp stubs/mbed_assert_stub.c stubs/equeue_stub.c @@ -22,5 +20,6 @@ set(unittest-test-sources stubs/mbed_shared_queues_stub.cpp stubs/nsapi_dns_stub.cpp stubs/EventFlags_stub.cpp - features/netsocket/InternetSocket/test_InternetSocket.cpp + stubs/stoip4_stub.c + stubs/ip4tos_stub.c ) diff --git a/UNITTESTS/features/netsocket/NetworkInterface/test_NetworkInterface.cpp b/UNITTESTS/features/netsocket/NetworkInterface/test_NetworkInterface.cpp index 9ea4937471..15fb805e04 100644 --- a/UNITTESTS/features/netsocket/NetworkInterface/test_NetworkInterface.cpp +++ b/UNITTESTS/features/netsocket/NetworkInterface/test_NetworkInterface.cpp @@ -17,6 +17,7 @@ #include "gtest/gtest.h" #include "features/netsocket/NetworkInterface.h" +#include "NetworkStack_stub.h" class stubNetworkInterface : public NetworkInterface { virtual nsapi_error_t connect() @@ -29,8 +30,10 @@ class stubNetworkInterface : public NetworkInterface { }; virtual NetworkStack *get_stack() { - return NULL; + return &stack; }; +public: + NetworkStackstub stack; }; class TestNetworkInterface : public testing::Test { @@ -53,8 +56,79 @@ TEST_F(TestNetworkInterface, constructor) EXPECT_TRUE(iface); } +// get_default_instance is tested along with the implementations of NetworkInterface. + TEST_F(TestNetworkInterface, get_mac_address) { char *n = 0; EXPECT_EQ(iface->get_mac_address(), n); } + +TEST_F(TestNetworkInterface, get_ip_address) +{ + char *n = 0; + EXPECT_EQ(iface->get_ip_address(), n); +} + +TEST_F(TestNetworkInterface, get_netmask) +{ + char *n = 0; + EXPECT_EQ(iface->get_netmask(), n); +} + +TEST_F(TestNetworkInterface, get_gateway) +{ + char *n = 0; + EXPECT_EQ(iface->get_gateway(), n); +} + +TEST_F(TestNetworkInterface, set_network) +{ + EXPECT_EQ(iface->set_network("127.0.0.1", "255.255.0.0", "127.0.0.1"), NSAPI_ERROR_UNSUPPORTED); +} + +TEST_F(TestNetworkInterface, set_dhcp) +{ + EXPECT_EQ(iface->set_dhcp(true), NSAPI_ERROR_OK); + EXPECT_EQ(iface->set_dhcp(false), NSAPI_ERROR_UNSUPPORTED); +} + +TEST_F(TestNetworkInterface, gethostbyname) +{ + SocketAddress a; + EXPECT_EQ(iface->gethostbyname("host", &a, NSAPI_UNSPEC), NSAPI_ERROR_OK); +} + + +static bool callback_is_called; +static void my_callback(nsapi_error_t result, SocketAddress *address) +{ + (void)result; + (void)address; + callback_is_called = true; +} + +TEST_F(TestNetworkInterface, gethostbyname_async) +{ + SocketAddress a; + EXPECT_EQ(iface->gethostbyname_async("host", mbed::callback(my_callback), NSAPI_UNSPEC), NSAPI_ERROR_OK); + EXPECT_EQ(iface->gethostbyname_async_cancel(1), NSAPI_ERROR_OK); +} + +TEST_F(TestNetworkInterface, add_dns_server) +{ + SocketAddress a("127.0.0.1", 1024); + EXPECT_EQ(iface->add_dns_server(a), NSAPI_ERROR_OK); +} + +TEST_F(TestNetworkInterface, get_connection_status) +{ + EXPECT_EQ(iface->get_connection_status(), NSAPI_ERROR_UNSUPPORTED); +} + +TEST_F(TestNetworkInterface, set_blocking) +{ + EXPECT_EQ(iface->set_blocking(true), NSAPI_ERROR_UNSUPPORTED); +} + +// No way to test attach as it doesn't do or return anything. diff --git a/UNITTESTS/features/netsocket/NetworkInterface/unittest.cmake b/UNITTESTS/features/netsocket/NetworkInterface/unittest.cmake index b89cd580b0..37ea5dc0bf 100644 --- a/UNITTESTS/features/netsocket/NetworkInterface/unittest.cmake +++ b/UNITTESTS/features/netsocket/NetworkInterface/unittest.cmake @@ -3,15 +3,23 @@ # UNIT TESTS #################### -# Unit test suite name -set(TEST_SUITE_NAME "features-netsocket-NetworkInterface") - # Source files set(unittest-sources + ../features/netsocket/SocketAddress.cpp + ../features/netsocket/NetworkStack.cpp ../features/netsocket/NetworkInterface.cpp + ../features/frameworks/nanostack-libservice/source/libip4string/ip4tos.c + ../features/frameworks/nanostack-libservice/source/libip4string/stoip4.c ) # Test files set(unittest-test-sources + stubs/Mutex_stub.cpp + stubs/mbed_assert_stub.c + stubs/equeue_stub.c + stubs/EventQueue_stub.cpp + stubs/mbed_shared_queues_stub.cpp + stubs/nsapi_dns_stub.cpp + stubs/EventFlags_stub.cpp features/netsocket/NetworkInterface/test_NetworkInterface.cpp ) diff --git a/UNITTESTS/features/netsocket/NetworkStack/test_NetworkStack.cpp b/UNITTESTS/features/netsocket/NetworkStack/test_NetworkStack.cpp new file mode 100644 index 0000000000..6ae21c633c --- /dev/null +++ b/UNITTESTS/features/netsocket/NetworkStack/test_NetworkStack.cpp @@ -0,0 +1,241 @@ +/* + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "gtest/gtest.h" +#include "features/netsocket/NetworkStack.h" +#include "netsocket/nsapi_dns.h" +#include "events/EventQueue.h" +#include + +#include "equeue_stub.h" + +// Control nsapi stub return value. See stubs/nsapi_dns_stub.cpp +extern nsapi_error_t nsapi_stub_return_value; + +// For testing async calls which require callback +static bool callback_is_called; +static SocketAddress address_received; +static nsapi_error_t result_received; +static void my_callback(nsapi_error_t result, SocketAddress *address) +{ + result_received = result; + address_received = *address; + callback_is_called = true; +} + +static bool noarg_callback_is_called; +static void noarg_callback(void) +{ + noarg_callback_is_called = true; +} + +extern call_in_callback_cb_t callin_callback; + +namespace mbed { +extern events::EventQueue *mbed_shared_queue_stub; +} + +// NetworkStack is an abstract class we need to provide a child class for tests. +class NetworkStackChild : public NetworkStack { + virtual nsapi_error_t socket_open(nsapi_socket_t *handle, nsapi_protocol_t proto) + { + return NSAPI_ERROR_OK; + } + virtual nsapi_error_t socket_close(nsapi_socket_t handle) + { + return NSAPI_ERROR_OK; + } + virtual nsapi_error_t socket_bind(nsapi_socket_t handle, const SocketAddress &address) + { + return NSAPI_ERROR_OK; + } + virtual nsapi_error_t socket_listen(nsapi_socket_t handle, int backlog) + { + return NSAPI_ERROR_OK; + } + virtual nsapi_error_t socket_connect(nsapi_socket_t handle, const SocketAddress &address) + { + return NSAPI_ERROR_OK; + } + virtual nsapi_error_t socket_accept(nsapi_socket_t server, + nsapi_socket_t *handle, SocketAddress *address = 0) + { + return NSAPI_ERROR_OK; + } + virtual nsapi_size_or_error_t socket_send(nsapi_socket_t handle, + const void *data, nsapi_size_t size) + { + return NSAPI_ERROR_OK; + } + virtual nsapi_size_or_error_t socket_recv(nsapi_socket_t handle, + void *data, nsapi_size_t size) + { + return NSAPI_ERROR_OK; + } + virtual nsapi_size_or_error_t socket_sendto(nsapi_socket_t handle, const SocketAddress &address, + const void *data, nsapi_size_t size) + { + return NSAPI_ERROR_OK; + } + virtual nsapi_size_or_error_t socket_recvfrom(nsapi_socket_t handle, SocketAddress *address, + void *buffer, nsapi_size_t size) + { + return NSAPI_ERROR_OK; + } + virtual void socket_attach(nsapi_socket_t handle, void (*callback)(void *), void *data) + { + } +public: + std::string ip_address; + const char *get_ip_address() + { + return ip_address.c_str(); + + } +}; + +class TestNetworkStack : public testing::Test { +protected: + NetworkStackChild *stack; + + virtual void SetUp() + { + stack = new NetworkStackChild(); + address_received = SocketAddress(); + result_received = NSAPI_ERROR_OK; + callback_is_called = false; + noarg_callback_is_called = false; + mbed::mbed_shared_queue_stub = 0; + } + + virtual void TearDown() + { + delete stack; + if (mbed::mbed_shared_queue_stub) + { + delete mbed::mbed_shared_queue_stub; + mbed::mbed_shared_queue_stub = 0; + } + } + + void SetUpQueue() + { + mbed::mbed_shared_queue_stub = new events::EventQueue(); + } +}; + +TEST_F(TestNetworkStack, constructor) +{ + EXPECT_TRUE(stack); +} + +TEST_F(TestNetworkStack, get_ip_address_default) +{ + EXPECT_EQ(stack->NetworkStack::get_ip_address(), (char*)NULL); +} + +/* gethostbyname */ + +TEST_F(TestNetworkStack, gethostbyname) +{ + SocketAddress a; + stack->ip_address = std::string("127.0.0.1"); + EXPECT_EQ(stack->gethostbyname("host", &a, NSAPI_UNSPEC), NSAPI_ERROR_DNS_FAILURE); +} + +TEST_F(TestNetworkStack, gethostbyname_simple_address) +{ + SocketAddress a; + EXPECT_EQ(stack->gethostbyname("127.0.0.1", &a, NSAPI_UNSPEC), NSAPI_ERROR_OK); +} + +TEST_F(TestNetworkStack, gethostbyname_simple_address_right_version) +{ + SocketAddress a; + EXPECT_EQ(stack->gethostbyname("127.0.0.1", &a, NSAPI_IPv4), NSAPI_ERROR_OK); +} + +TEST_F(TestNetworkStack, gethostbyname_simple_address_wrong_version) +{ + SocketAddress a; + EXPECT_EQ(stack->gethostbyname("127.0.0.1", &a, NSAPI_IPv6), NSAPI_ERROR_DNS_FAILURE); +} + +TEST_F(TestNetworkStack, gethostbyname_empty_host) +{ + SocketAddress a; + EXPECT_EQ(stack->gethostbyname("", &a, NSAPI_UNSPEC), NSAPI_ERROR_PARAMETER); +} + +/* gethostbyname_async */ + +TEST_F(TestNetworkStack, gethostbyname_async_delay) +{ + SocketAddress a; + stack->ip_address = std::string("127.0.0.1"); + SetUpQueue(); + struct equeue_event ptr; + equeue_stub.void_ptr = &ptr; + equeue_stub.call_cb_immediately = true; + EXPECT_EQ(stack->gethostbyname_async("localhost", mbed::callback(my_callback), NSAPI_UNSPEC), NSAPI_ERROR_DNS_FAILURE); + EXPECT_EQ(callin_callback(1, mbed::callback(noarg_callback)), NSAPI_ERROR_OK); + EXPECT_TRUE(noarg_callback_is_called); + EXPECT_FALSE(callback_is_called); +} + +TEST_F(TestNetworkStack, gethostbyname_async) +{ + SocketAddress a; + stack->ip_address = std::string("127.0.0.1"); + SetUpQueue(); + struct equeue_event ptr; + equeue_stub.void_ptr = &ptr; + equeue_stub.call_cb_immediately = true; + EXPECT_EQ(stack->gethostbyname_async("localhost", mbed::callback(my_callback), NSAPI_UNSPEC), NSAPI_ERROR_DNS_FAILURE); + EXPECT_EQ(callin_callback(0, mbed::callback(noarg_callback)), NSAPI_ERROR_OK); + EXPECT_TRUE(noarg_callback_is_called); + EXPECT_FALSE(callback_is_called); +} + +TEST_F(TestNetworkStack, gethostbyname_async_eventqueue_simple_address) +{ + SocketAddress a; + stack->ip_address = std::string("127.0.0.1"); + EXPECT_EQ(stack->gethostbyname_async("127.0.0.1", mbed::callback(my_callback), NSAPI_IPv6), NSAPI_ERROR_DNS_FAILURE); + EXPECT_FALSE(callback_is_called); + EXPECT_EQ(stack->gethostbyname_async("127.0.0.1", mbed::callback(my_callback), NSAPI_IPv4), NSAPI_ERROR_OK); + EXPECT_TRUE(callback_is_called); + EXPECT_EQ(result_received, NSAPI_ERROR_OK); + EXPECT_EQ(std::string(address_received.get_ip_address()), stack->ip_address); +} + +TEST_F(TestNetworkStack, gethostbyname_async_empty_host) +{ + SocketAddress a; + EXPECT_EQ(stack->gethostbyname_async("", mbed::callback(my_callback), NSAPI_UNSPEC), NSAPI_ERROR_PARAMETER); +} + +TEST_F(TestNetworkStack, getstackopt) +{ + EXPECT_EQ(stack->getstackopt(0,0,0,0), NSAPI_ERROR_UNSUPPORTED); +} + +TEST_F(TestNetworkStack, setstackopt) +{ + EXPECT_EQ(stack->setstackopt(0,0,0,0), NSAPI_ERROR_UNSUPPORTED); +} + diff --git a/UNITTESTS/features/netsocket/NetworkStack/unittest.cmake b/UNITTESTS/features/netsocket/NetworkStack/unittest.cmake new file mode 100644 index 0000000000..f17d68852e --- /dev/null +++ b/UNITTESTS/features/netsocket/NetworkStack/unittest.cmake @@ -0,0 +1,28 @@ + +#################### +# UNIT TESTS +#################### + +# Unit test suite name +set(TEST_SUITE_NAME "features_netsocket_NetworkStack") + +# Source files +set(unittest-sources + ../features/netsocket/SocketAddress.cpp + ../features/netsocket/NetworkStack.cpp + ../features/netsocket/NetworkInterface.cpp + ../features/frameworks/nanostack-libservice/source/libip4string/ip4tos.c + ../features/frameworks/nanostack-libservice/source/libip4string/stoip4.c +) + +# Test files +set(unittest-test-sources + stubs/Mutex_stub.cpp + stubs/mbed_assert_stub.c + stubs/equeue_stub.c + stubs/EventQueue_stub.cpp + stubs/mbed_shared_queues_stub.cpp + stubs/nsapi_dns_stub.cpp + stubs/EventFlags_stub.cpp + features/netsocket/NetworkStack/test_NetworkStack.cpp +) diff --git a/UNITTESTS/features/netsocket/TCPServer/test_TCPServer.cpp b/UNITTESTS/features/netsocket/TCPServer/test_TCPServer.cpp new file mode 100644 index 0000000000..c2cf9532fb --- /dev/null +++ b/UNITTESTS/features/netsocket/TCPServer/test_TCPServer.cpp @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2018, Arm Limited and affiliates + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "gtest/gtest.h" +#include "features/netsocket/TCPSocket.h" +#include "features/netsocket/TCPServer.h" +#include "NetworkStack_stub.h" + +// Control the rtos EventFlags stub. See EventFlags_stub.cpp +extern std::list eventFlagsStubNextRetval; + +class TestTCPServer : public testing::Test { +public: + unsigned int dataSize = 10; + char dataBuf[10]; +protected: + TCPSocket *socket; + TCPServer *server; + NetworkStackstub stack; + + virtual void SetUp() + { + server = new TCPServer(); + socket = new TCPSocket(); + } + + virtual void TearDown() + { + stack.return_values.clear(); + eventFlagsStubNextRetval.clear(); + delete socket; + delete server; + } +}; + +TEST_F(TestTCPServer, constructor) +{ + EXPECT_TRUE(server); +} + +TEST_F(TestTCPServer, constructor_parameters) +{ + TCPServer serverParam = TCPServer(dynamic_cast(&stack)); + const SocketAddress a("127.0.0.1", 1024); + EXPECT_EQ(serverParam.connect(a), NSAPI_ERROR_OK); +} + +TEST_F(TestTCPServer, accept) +{ + const SocketAddress a("127.0.0.1", 1024); + EXPECT_EQ(socket->open(static_cast(&stack)), NSAPI_ERROR_OK); + EXPECT_EQ(socket->connect(a), NSAPI_ERROR_OK); + nsapi_error_t error; + EXPECT_EQ(server->open(static_cast(&stack)), NSAPI_ERROR_OK); + EXPECT_EQ(server->bind(a), NSAPI_ERROR_OK); + server->listen(1); + SocketAddress client_addr; + EXPECT_EQ(server->accept(socket, &client_addr), NSAPI_ERROR_OK); +} + +TEST_F(TestTCPServer, accept_no_socket) +{ + SocketAddress client_addr; + EXPECT_EQ(server->accept(socket, &client_addr), NSAPI_ERROR_NO_SOCKET); +} + +TEST_F(TestTCPServer, accept_error) +{ + SocketAddress client_addr; + EXPECT_EQ(server->open(static_cast(&stack)), NSAPI_ERROR_OK); + stack.return_value = NSAPI_ERROR_AUTH_FAILURE; + EXPECT_EQ(server->accept(socket, &client_addr), NSAPI_ERROR_AUTH_FAILURE); +} + +TEST_F(TestTCPServer, accept_error_would_block) +{ + SocketAddress client_addr; + EXPECT_EQ(server->open(static_cast(&stack)), NSAPI_ERROR_OK); + stack.return_value = NSAPI_ERROR_WOULD_BLOCK; + eventFlagsStubNextRetval.push_back(0); + eventFlagsStubNextRetval.push_back(osFlagsError); // Break the wait loop + + EXPECT_EQ(server->accept(socket, &client_addr), NSAPI_ERROR_WOULD_BLOCK); +} diff --git a/UNITTESTS/features/netsocket/TCPServer/unittest.cmake b/UNITTESTS/features/netsocket/TCPServer/unittest.cmake new file mode 100644 index 0000000000..d0b1e031b1 --- /dev/null +++ b/UNITTESTS/features/netsocket/TCPServer/unittest.cmake @@ -0,0 +1,28 @@ + +#################### +# UNIT TESTS +#################### + +# Unit test suite name +set(TEST_SUITE_NAME "features_netsocket_TCPServer") + +set(unittest-sources + ../features/netsocket/SocketAddress.cpp + ../features/netsocket/NetworkStack.cpp + ../features/netsocket/InternetSocket.cpp + ../features/netsocket/TCPSocket.cpp + ../features/netsocket/TCPServer.cpp + ../features/frameworks/nanostack-libservice/source/libip4string/ip4tos.c + ../features/frameworks/nanostack-libservice/source/libip4string/stoip4.c +) + +set(unittest-test-sources + stubs/Mutex_stub.cpp + stubs/mbed_assert_stub.c + stubs/equeue_stub.c + stubs/EventQueue_stub.cpp + stubs/mbed_shared_queues_stub.cpp + stubs/nsapi_dns_stub.cpp + stubs/EventFlags_stub.cpp + features/netsocket/TCPServer/test_TCPServer.cpp +) diff --git a/UNITTESTS/features/netsocket/TCPSocket/test_TCPSocket.cpp b/UNITTESTS/features/netsocket/TCPSocket/test_TCPSocket.cpp index 113baa26d8..16022ca525 100644 --- a/UNITTESTS/features/netsocket/TCPSocket/test_TCPSocket.cpp +++ b/UNITTESTS/features/netsocket/TCPSocket/test_TCPSocket.cpp @@ -17,10 +17,24 @@ #include "gtest/gtest.h" #include "features/netsocket/TCPSocket.h" +#include "NetworkStack_stub.h" + +// Control the rtos EventFlags stub. See EventFlags_stub.cpp +extern std::list eventFlagsStubNextRetval; + +// To test protected functions +class TCPSocketFriend : public TCPSocket { + friend class TestTCPSocket; + FRIEND_TEST(TestTCPSocket, get_proto); +}; class TestTCPSocket : public testing::Test { +public: + unsigned int dataSize = 10; + char dataBuf[10]; protected: TCPSocket *socket; + NetworkStackstub stack; virtual void SetUp() { @@ -29,11 +43,245 @@ protected: virtual void TearDown() { + stack.return_values.clear(); + eventFlagsStubNextRetval.clear(); delete socket; } }; +TEST_F(TestTCPSocket, get_proto) +{ + TCPSocketFriend tcpFriend; + EXPECT_EQ(tcpFriend.get_proto(), NSAPI_TCP); +} + TEST_F(TestTCPSocket, constructor) { EXPECT_TRUE(socket); } + +TEST_F(TestTCPSocket, constructor_parameters) +{ + TCPSocket socketParam = TCPSocket(dynamic_cast(&stack)); + const SocketAddress a("127.0.0.1", 1024); + EXPECT_EQ(socketParam.connect(a), NSAPI_ERROR_OK); +} + +/* connect */ + +TEST_F(TestTCPSocket, connect) +{ + socket->open((NetworkStack *)&stack); + + stack.return_value = NSAPI_ERROR_OK; + const SocketAddress a("127.0.0.1", 1024); + EXPECT_EQ(socket->connect(a), NSAPI_ERROR_OK); +} + +TEST_F(TestTCPSocket, connect_no_open) +{ + stack.return_value = NSAPI_ERROR_OK; + const SocketAddress a("127.0.0.1", 1024); + EXPECT_EQ(socket->connect(a), NSAPI_ERROR_NO_SOCKET); +} + +TEST_F(TestTCPSocket, connect_error_in_progress_no_timeout) +{ + socket->open((NetworkStack *)&stack); + stack.return_value = NSAPI_ERROR_IN_PROGRESS; + const SocketAddress a("127.0.0.1", 1024); + eventFlagsStubNextRetval.push_back(osFlagsError); // Break the wait loop + EXPECT_EQ(socket->connect(a), NSAPI_ERROR_IN_PROGRESS); +} + +TEST_F(TestTCPSocket, connect_with_timeout) +{ + socket->open((NetworkStack *)&stack); + stack.return_value = NSAPI_ERROR_IN_PROGRESS; + const SocketAddress a("127.0.0.1", 1024); + eventFlagsStubNextRetval.push_back(osFlagsError); // Break the wait loop + socket->set_blocking(true); + EXPECT_EQ(socket->connect(a), NSAPI_ERROR_IN_PROGRESS); +} + +TEST_F(TestTCPSocket, connect_error_is_connected) +{ + socket->open((NetworkStack *)&stack); + stack.return_values.push_back(NSAPI_ERROR_ALREADY); + stack.return_values.push_back(NSAPI_ERROR_IS_CONNECTED); + const SocketAddress a("127.0.0.1", 1024); + socket->set_timeout(1); + EXPECT_EQ(socket->connect(a), NSAPI_ERROR_OK); +} + +TEST_F(TestTCPSocket, connect_by_name_and_port) +{ + socket->open((NetworkStack *)&stack); + stack.return_value = NSAPI_ERROR_OK; + EXPECT_EQ(socket->connect("testhost", 80), NSAPI_ERROR_OK); +} + +TEST_F(TestTCPSocket, connect_by_name_and_port_dns_fail) +{ + socket->open((NetworkStack *)&stack); + stack.return_value = NSAPI_ERROR_DNS_FAILURE; + EXPECT_EQ(socket->connect("testhost", 80), NSAPI_ERROR_DNS_FAILURE); +} + +/* send */ + +TEST_F(TestTCPSocket, send_no_open) +{ + stack.return_value = NSAPI_ERROR_OK; + EXPECT_EQ(socket->send(dataBuf, dataSize), NSAPI_ERROR_NO_SOCKET); +} + +TEST_F(TestTCPSocket, send_in_one_chunk) +{ + socket->open((NetworkStack *)&stack); + stack.return_value = dataSize; + EXPECT_EQ(socket->send(dataBuf, dataSize), dataSize); +} + +TEST_F(TestTCPSocket, send_in_two_chunks) +{ + socket->open((NetworkStack *)&stack); + stack.return_values.push_back(4); + stack.return_values.push_back(dataSize - 4); + EXPECT_EQ(socket->send(dataBuf, dataSize), dataSize); +} + +TEST_F(TestTCPSocket, send_error_would_block) +{ + socket->open((NetworkStack *)&stack); + stack.return_value = NSAPI_ERROR_WOULD_BLOCK; + eventFlagsStubNextRetval.push_back(osFlagsError); // Break the wait loop + EXPECT_EQ(socket->send(dataBuf, dataSize), NSAPI_ERROR_WOULD_BLOCK); +} + +TEST_F(TestTCPSocket, send_error_other) +{ + socket->open((NetworkStack *)&stack); + stack.return_value = NSAPI_ERROR_NO_MEMORY; + EXPECT_EQ(socket->send(dataBuf, dataSize), NSAPI_ERROR_NO_MEMORY); +} + +TEST_F(TestTCPSocket, send_error_no_timeout) +{ + socket->open((NetworkStack *)&stack); + stack.return_value = NSAPI_ERROR_WOULD_BLOCK; + socket->set_blocking(false); + EXPECT_EQ(socket->send(dataBuf, dataSize), NSAPI_ERROR_WOULD_BLOCK); +} + +TEST_F(TestTCPSocket, send_to) +{ + socket->open((NetworkStack *)&stack); + stack.return_value = 10; + const SocketAddress a("127.0.0.1", 1024); + EXPECT_EQ(socket->sendto(a, dataBuf, dataSize), dataSize); +} + +/* recv */ + +TEST_F(TestTCPSocket, recv_no_open) +{ + stack.return_value = NSAPI_ERROR_OK; + EXPECT_EQ(socket->recv(dataBuf, dataSize), NSAPI_ERROR_NO_SOCKET); +} + +TEST_F(TestTCPSocket, recv_all_data) +{ + socket->open((NetworkStack *)&stack); + stack.return_value = dataSize; + EXPECT_EQ(socket->recv(dataBuf, dataSize), dataSize); +} + +TEST_F(TestTCPSocket, recv_less_than_expected) +{ + socket->open((NetworkStack *)&stack); + unsigned int lessThanDataSize = dataSize -1; + stack.return_values.push_back(lessThanDataSize); + EXPECT_EQ(socket->recv(dataBuf, dataSize), lessThanDataSize); +} + +TEST_F(TestTCPSocket, recv_would_block) +{ + socket->open((NetworkStack *)&stack); + stack.return_value = NSAPI_ERROR_WOULD_BLOCK; + eventFlagsStubNextRetval.push_back(0); + eventFlagsStubNextRetval.push_back(osFlagsError); // Break the wait loop + EXPECT_EQ(socket->recv(dataBuf, dataSize), NSAPI_ERROR_WOULD_BLOCK); +} + +TEST_F(TestTCPSocket, recv_from_no_socket) +{ + stack.return_value = NSAPI_ERROR_OK; + SocketAddress a("127.0.0.1", 1024); + EXPECT_EQ(socket->recvfrom(&a, dataBuf, dataSize), NSAPI_ERROR_NO_SOCKET); +} + +TEST_F(TestTCPSocket, recv_from) +{ + stack.return_value = NSAPI_ERROR_OK; + SocketAddress a("127.0.0.1", 1024); + EXPECT_EQ(socket->open((NetworkStack *)&stack), NSAPI_ERROR_OK); + EXPECT_EQ(socket->connect(a), NSAPI_ERROR_OK); + SocketAddress b; + EXPECT_EQ(socket->recvfrom(&b, dataBuf, dataSize), NSAPI_ERROR_OK); + EXPECT_EQ(a, b); +} + +TEST_F(TestTCPSocket, recv_from_null) +{ + stack.return_value = NSAPI_ERROR_OK; + SocketAddress a("127.0.0.1", 1024); + EXPECT_EQ(socket->open((NetworkStack *)&stack), NSAPI_ERROR_OK); + EXPECT_EQ(socket->connect(a), NSAPI_ERROR_OK); + EXPECT_EQ(socket->recvfrom(NULL, dataBuf, dataSize), NSAPI_ERROR_OK); +} + +/* listen */ + +TEST_F(TestTCPSocket, listen_no_open) +{ + stack.return_value = NSAPI_ERROR_OK; + EXPECT_EQ(socket->listen(1), NSAPI_ERROR_NO_SOCKET); +} + +TEST_F(TestTCPSocket, listen) +{ + stack.return_value = NSAPI_ERROR_OK; + socket->open((NetworkStack *)&stack); + EXPECT_EQ(socket->listen(1), NSAPI_ERROR_OK); +} + +/* these tests will have to be readjusted after TCPServer is deprecated. */ + +TEST_F(TestTCPSocket, accept_no_open) +{ + nsapi_error_t error; + stack.return_value = NSAPI_ERROR_OK; + EXPECT_EQ(socket->accept(&error), static_cast(NULL)); + EXPECT_EQ(error, NSAPI_ERROR_NO_SOCKET); +} + +TEST_F(TestTCPSocket, accept) +{ + nsapi_error_t error; + stack.return_value = NSAPI_ERROR_OK; + socket->open((NetworkStack *)&stack); + EXPECT_NE(socket->accept(&error), static_cast(NULL)); + EXPECT_EQ(error, NSAPI_ERROR_OK); +} + +TEST_F(TestTCPSocket, accept_would_block) +{ + nsapi_error_t error; + socket->open((NetworkStack *)&stack); + stack.return_value = NSAPI_ERROR_WOULD_BLOCK; + eventFlagsStubNextRetval.push_back(0); + eventFlagsStubNextRetval.push_back(osFlagsError); // Break the wait loop + EXPECT_EQ(socket->accept(&error), static_cast(NULL)); + EXPECT_EQ(error, NSAPI_ERROR_WOULD_BLOCK); +} diff --git a/UNITTESTS/features/netsocket/TCPSocket/unittest.cmake b/UNITTESTS/features/netsocket/TCPSocket/unittest.cmake index 437463ee31..58367cfede 100644 --- a/UNITTESTS/features/netsocket/TCPSocket/unittest.cmake +++ b/UNITTESTS/features/netsocket/TCPSocket/unittest.cmake @@ -3,11 +3,9 @@ # UNIT TESTS #################### -# Unit test suite name -set(TEST_SUITE_NAME "features-netsocket-TCPSocket") - set(unittest-sources ../features/netsocket/SocketAddress.cpp + ../features/netsocket/NetworkStack.cpp ../features/netsocket/InternetSocket.cpp ../features/netsocket/TCPSocket.cpp ../features/frameworks/nanostack-libservice/source/libip4string/ip4tos.c @@ -15,8 +13,14 @@ set(unittest-sources ) set(unittest-test-sources + features/netsocket/TCPSocket/test_TCPSocket.cpp stubs/Mutex_stub.cpp stubs/mbed_assert_stub.c + stubs/equeue_stub.c + stubs/EventQueue_stub.cpp + stubs/mbed_shared_queues_stub.cpp + stubs/nsapi_dns_stub.cpp stubs/EventFlags_stub.cpp - features/netsocket/TCPSocket/test_TCPSocket.cpp + stubs/stoip4_stub.c + stubs/ip4tos_stub.c ) diff --git a/UNITTESTS/features/netsocket/UDPSocket/test_UDPSocket.cpp b/UNITTESTS/features/netsocket/UDPSocket/test_UDPSocket.cpp index 7c590e7970..d631cc7573 100644 --- a/UNITTESTS/features/netsocket/UDPSocket/test_UDPSocket.cpp +++ b/UNITTESTS/features/netsocket/UDPSocket/test_UDPSocket.cpp @@ -26,21 +26,25 @@ * following the documentation of google test. * [*](https://github.com/google/googletest/blob/master/googletest/docs/advanced.md) */ -class stubUDPSocket : public UDPSocket { +class UDPSocketFriend : public UDPSocket { friend class TestUDPSocket; FRIEND_TEST(TestUDPSocket, get_proto); }; +// Control the rtos EventFlags stub. See EventFlags_stub.cpp +extern std::list eventFlagsStubNextRetval; + class TestUDPSocket : public testing::Test { protected: - stubUDPSocket *socket; + UDPSocket *socket; NetworkStackstub stack; + unsigned int dataSize = 10; + char dataBuf[10]; virtual void SetUp() { - socket = new stubUDPSocket; + socket = new UDPSocket; stack.return_value = NSAPI_ERROR_OK; - socket->open((NetworkStack *)&stack); } virtual void TearDown() @@ -51,31 +55,97 @@ protected: TEST_F(TestUDPSocket, get_proto) { - EXPECT_EQ(socket->get_proto(), NSAPI_UDP); + UDPSocketFriend udpFriend; + EXPECT_EQ(udpFriend.get_proto(), NSAPI_UDP); } TEST_F(TestUDPSocket, sendto_addr_port) { + // The code below causes a segfault. Should we add a check? + //EXPECT_EQ(socket->sendto("127.0.0.1", 0, 0, 0), NSAPI_ERROR_NO_SOCKET); + + const SocketAddress a("127.0.0.1", 1024); + EXPECT_EQ(socket->sendto(a, 0, 0), NSAPI_ERROR_NO_SOCKET); + + socket->open((NetworkStack *)&stack); + stack.return_value = NSAPI_ERROR_PARAMETER; EXPECT_EQ(socket->sendto("127.0.0.1", 0, 0, 0), NSAPI_ERROR_DNS_FAILURE); + stack.return_value = NSAPI_ERROR_OK; EXPECT_EQ(socket->sendto("127.0.0.1", 0, 0, 0), 0); } -TEST_F(TestUDPSocket, sendto) +TEST_F(TestUDPSocket, connect) { - SocketAddress addr("127.0.0.1", 1024); stack.return_value = NSAPI_ERROR_OK; + const nsapi_addr_t addr = {NSAPI_IPv4, {127,0,0,1} }; + const SocketAddress a(addr, 1024); + + socket->open((NetworkStack *)&stack); + EXPECT_EQ(socket->send(dataBuf, dataSize), NSAPI_ERROR_NO_ADDRESS); + + EXPECT_EQ(socket->connect(a), NSAPI_ERROR_OK); + + stack.return_value = 100; + EXPECT_EQ(socket->send(dataBuf, dataSize), 100); +} + +TEST_F(TestUDPSocket, sendto_timeout) +{ + const nsapi_addr_t saddr = {NSAPI_IPv4, {127,0,0,1} }; + const SocketAddress addr(saddr, 1024); socket->open((NetworkStack *)&stack); - stack.return_value = 100; - EXPECT_EQ(socket->sendto(addr, 0, 100), 100); - socket->set_timeout(0); stack.return_value = NSAPI_ERROR_WOULD_BLOCK; + eventFlagsStubNextRetval.push_back(0); + eventFlagsStubNextRetval.push_back(osFlagsError); // Break the wait loop EXPECT_EQ(socket->sendto(addr, 0, 100), NSAPI_ERROR_WOULD_BLOCK); - socket->set_timeout(-1); - stack.return_value = NSAPI_ERROR_NO_CONNECTION; - EXPECT_EQ(socket->sendto(addr, 0, 100), NSAPI_ERROR_NO_CONNECTION); + stack.return_value = NSAPI_ERROR_NO_MEMORY; + socket->set_timeout(1); + + EXPECT_EQ(socket->sendto(addr, 0, 100), NSAPI_ERROR_NO_MEMORY); +} + +TEST_F(TestUDPSocket, recv) +{ + EXPECT_EQ(socket->recv(&dataBuf, dataSize), NSAPI_ERROR_NO_SOCKET); + + socket->open((NetworkStack *)&stack); + + stack.return_value = 100; + EXPECT_EQ(socket->recv(&dataBuf, dataSize), 100); + + stack.return_value = NSAPI_ERROR_WOULD_BLOCK; + eventFlagsStubNextRetval.push_back(0); + eventFlagsStubNextRetval.push_back(osFlagsError); // Break the wait loop + EXPECT_EQ(socket->recv(&dataBuf, dataSize), NSAPI_ERROR_WOULD_BLOCK); +} + +TEST_F(TestUDPSocket, recv_address_filtering) +{ + socket->open((NetworkStack *)&stack); + const nsapi_addr_t addr1 = {NSAPI_IPv4, {127,0,0,1} }; + const nsapi_addr_t addr2 = {NSAPI_IPv4, {127,0,0,2} }; + SocketAddress a1(addr1, 1024); + SocketAddress a2(addr2, 1024); + + EXPECT_EQ(socket->connect(a1), NSAPI_ERROR_OK); + + stack.return_values.push_back(100); //This will not return, because wrong address is used. + stack.return_values.push_back(NSAPI_ERROR_NO_MEMORY); //Break the loop of waiting for data from a1. + EXPECT_EQ(socket->recvfrom(&a2, &dataBuf, dataSize), NSAPI_ERROR_NO_MEMORY); + + stack.return_values.push_back(100); + EXPECT_EQ(socket->recvfrom(&a1, &dataBuf, dataSize), 100); +} + +TEST_F(TestUDPSocket, unsupported_api) +{ + nsapi_error_t error; + EXPECT_EQ(socket->accept(&error), static_cast(NULL)); + EXPECT_EQ(error, NSAPI_ERROR_UNSUPPORTED); + EXPECT_EQ(socket->listen(1), NSAPI_ERROR_UNSUPPORTED); } diff --git a/UNITTESTS/features/netsocket/UDPSocket/unittest.cmake b/UNITTESTS/features/netsocket/UDPSocket/unittest.cmake index ee0f7f54b2..b57c38e6f4 100644 --- a/UNITTESTS/features/netsocket/UDPSocket/unittest.cmake +++ b/UNITTESTS/features/netsocket/UDPSocket/unittest.cmake @@ -3,9 +3,6 @@ # UNIT TESTS #################### -# Unit test suite name -set(TEST_SUITE_NAME "features-netsocket-UDPSocket") - set(unittest-sources ../features/netsocket/SocketAddress.cpp ../features/netsocket/NetworkStack.cpp @@ -16,6 +13,7 @@ set(unittest-sources ) set(unittest-test-sources + features/netsocket/UDPSocket/test_UDPSocket.cpp stubs/Mutex_stub.cpp stubs/mbed_assert_stub.c stubs/equeue_stub.c @@ -23,5 +21,6 @@ set(unittest-test-sources stubs/mbed_shared_queues_stub.cpp stubs/EventFlags_stub.cpp stubs/nsapi_dns_stub.cpp - features/netsocket/UDPSocket/test_UDPSocket.cpp + stubs/stoip4_stub.c + stubs/ip4tos_stub.c ) diff --git a/UNITTESTS/mbed_unittest.py b/UNITTESTS/mbed_unittest.py index e8e6eadad9..627c58ed0e 100755 --- a/UNITTESTS/mbed_unittest.py +++ b/UNITTESTS/mbed_unittest.py @@ -23,12 +23,14 @@ UNIT TEST BUILD & RUN from __future__ import print_function import os import logging +import re from unit_test.options import get_options_parser, \ pretty_print_test_options from unit_test.settings import DEFAULT_CMAKE_GENERATORS from unit_test.test import UnitTestTool from unit_test.new import UnitTestGeneratorTool +from unit_test.coverage import CoverageAPI def _mbed_unittest_test(options, cwd, pwd): if options is None: @@ -80,14 +82,28 @@ def _mbed_unittest_test(options, cwd, pwd): tool.build_tests() if options.run_only: + tool.run_tests(filter_regex=options.test_regex) + # If code coverage generation: if options.coverage: - # Run tests and generate reports - tool.generate_coverage_report(coverage_output_type=options.coverage, - excludes=[pwd, options.build], - build_path=options.build) - else: - tool.run_tests(filter_regex=options.test_regex) # Only run tests + cov_api = CoverageAPI( + mbed_os_root=os.path.normpath(os.path.join(pwd, "..")), + build_dir=options.build) + + # Generate reports + outputs = [options.coverage] + if options.coverage == "both": + outputs = ["html", "xml"] + + excludes = [pwd, options.build] + + if not options.include_headers: + excludes.append(re.compile(".*\\.h")) + + cov_api.generate_reports(outputs=outputs, + excludes=excludes, + filter_regex=options.test_regex, + build_path=options.build) def _mbed_unittest_new(options, pwd): if options is None: diff --git a/UNITTESTS/platform/CircularBuffer/unittest.cmake b/UNITTESTS/platform/CircularBuffer/unittest.cmake index 8beeb88efb..34187f4f95 100644 --- a/UNITTESTS/platform/CircularBuffer/unittest.cmake +++ b/UNITTESTS/platform/CircularBuffer/unittest.cmake @@ -3,9 +3,6 @@ # UNIT TESTS #################### -# Unit test suite name -set(TEST_SUITE_NAME "platform-CircularBuffer") - set(unittest-sources ) diff --git a/features/cellular/UNITTESTS/stubs/ATCmdParser.cpp b/UNITTESTS/stubs/ATCmdParser_stub.cpp similarity index 99% rename from features/cellular/UNITTESTS/stubs/ATCmdParser.cpp rename to UNITTESTS/stubs/ATCmdParser_stub.cpp index d9157ec848..233dd039dc 100644 --- a/features/cellular/UNITTESTS/stubs/ATCmdParser.cpp +++ b/UNITTESTS/stubs/ATCmdParser_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Arm Limited and affiliates. + * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/UNITTESTS/stubs/ATHandler_stub.cpp b/UNITTESTS/stubs/ATHandler_stub.cpp index cee8e30579..599d48b812 100644 --- a/UNITTESTS/stubs/ATHandler_stub.cpp +++ b/UNITTESTS/stubs/ATHandler_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Arm Limited and affiliates. + * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -31,6 +31,10 @@ const int DEFAULT_AT_TIMEOUT = 1000; // at default timeout in milliseconds nsapi_error_t ATHandler_stub::nsapi_error_value = 0; uint8_t ATHandler_stub::nsapi_error_ok_counter = 0; int ATHandler_stub::int_value = -1; +int ATHandler_stub::ref_count = 0; +int ATHandler_stub::timeout = 0; +bool ATHandler_stub::default_timeout = 0; +bool ATHandler_stub::debug_on = 0; ssize_t ATHandler_stub::ssize_value = 0; char *ATHandler_stub::read_string_value = NULL; size_t ATHandler_stub::size_value = 0; @@ -40,29 +44,47 @@ uint8_t ATHandler_stub::uint8_value = 0; FileHandle_stub *ATHandler_stub::fh_value = NULL; device_err_t ATHandler_stub::device_err_value; Callback ATHandler_stub::callback = NULL; +bool ATHandler_stub::call_immediately = false; uint8_t ATHandler_stub::resp_info_true_counter = false; +uint8_t ATHandler_stub::info_elem_true_counter = false; +int ATHandler_stub::int_valid_count_table[kRead_int_table_size]; +int ATHandler_stub::int_count = kRead_int_table_size; -ATHandler::ATHandler(FileHandle *fh, EventQueue &queue, int timeout, const char *output_delimiter, uint16_t send_delay) : _nextATHandler(0), +int ATHandler_stub::read_string_index = kRead_string_table_size; +char *ATHandler_stub::read_string_table[kRead_string_table_size]; +int ATHandler_stub::resp_stop_success_count = kResp_stop_count_default; + +ATHandler::ATHandler(FileHandle *fh, EventQueue &queue, int timeout, const char *output_delimiter, uint16_t send_delay) : + _nextATHandler(0), _fileHandle(fh), _queue(queue) { + ATHandler_stub::ref_count = 1; +} + +void ATHandler::set_debug(bool debug_on) +{ + ATHandler_stub::debug_on = debug_on; } ATHandler::~ATHandler() { + ATHandler_stub::ref_count = kATHandler_destructor_ref_ount; } void ATHandler::inc_ref_count() { + ATHandler_stub::ref_count++; } void ATHandler::dec_ref_count() { + ATHandler_stub::ref_count--; } int ATHandler::get_ref_count() { - return ATHandler_stub::int_value; + return ATHandler_stub::ref_count; } FileHandle *ATHandler::get_file_handle() @@ -77,7 +99,10 @@ void ATHandler::set_file_handle(FileHandle *fh) nsapi_error_t ATHandler::set_urc_handler(const char *urc, mbed::Callback cb) { ATHandler_stub::callback = cb; - return NSAPI_ERROR_OK; + if (ATHandler_stub::call_immediately) { + cb(); + } + return ATHandler_stub::nsapi_error_value; } void ATHandler::remove_urc_handler(const char *prefix, mbed::Callback callback) @@ -108,6 +133,8 @@ nsapi_error_t ATHandler::unlock_return_error() void ATHandler::set_at_timeout(uint32_t timeout_milliseconds, bool default_timeout) { + ATHandler_stub::timeout = timeout_milliseconds; + ATHandler_stub::default_timeout = default_timeout; } void ATHandler::restore_at_timeout() @@ -120,10 +147,12 @@ void ATHandler::process_oob() void ATHandler::clear_error() { + ATHandler_stub::nsapi_error_ok_counter++; } void ATHandler::skip_param(uint32_t count) { + } void ATHandler::skip_param(ssize_t len, uint32_t count) @@ -137,15 +166,44 @@ ssize_t ATHandler::read_bytes(uint8_t *buf, size_t len) ssize_t ATHandler::read_string(char *buf, size_t size, bool read_even_stop_tag) { - if (ATHandler_stub::read_string_value && ATHandler_stub::ssize_value >= 0) { - memcpy(buf, ATHandler_stub::read_string_value, ATHandler_stub::ssize_value); + + if (ATHandler_stub::read_string_index == kRead_string_table_size) { + if (ATHandler_stub::read_string_value && ATHandler_stub::ssize_value >= 0) { + memcpy(buf, ATHandler_stub::read_string_value, ATHandler_stub::ssize_value + 1); + } + return ATHandler_stub::ssize_value; } - return ATHandler_stub::ssize_value; + + ATHandler_stub::read_string_index--; + if (ATHandler_stub::read_string_index >= 0) { + char *tmp = ATHandler_stub::read_string_table[ATHandler_stub::read_string_index]; + ssize_t len = strlen(tmp); + memcpy(buf, tmp, len + 1); + return len; + } + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + return -1; } -int ATHandler::read_int() +int32_t ATHandler::read_int() { - return ATHandler_stub::int_value; + if (ATHandler_stub::nsapi_error_value != NSAPI_ERROR_OK) { + return -1; + } + + if (ATHandler_stub::int_count == kRead_int_table_size) { + return ATHandler_stub::int_value; + } + + //printf("ATHandler_stub::int_count: %d", ATHandler_stub::int_count); + ATHandler_stub::int_count--; + if (ATHandler_stub::int_count < kRead_int_table_size && ATHandler_stub::int_count >= 0) { + return ATHandler_stub::int_valid_count_table[ATHandler_stub::int_count]; + } + + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; + return -1; } void ATHandler::set_delimiter(char delimiter) @@ -180,6 +238,10 @@ bool ATHandler::info_resp() bool ATHandler::info_elem(char start_tag) { + if (ATHandler_stub::info_elem_true_counter) { + ATHandler_stub::info_elem_true_counter--; + return true; + } return ATHandler_stub::bool_value; } @@ -190,13 +252,18 @@ bool ATHandler::consume_to_stop_tag() void ATHandler::resp_stop() { + if (ATHandler_stub::resp_stop_success_count > 0) { + ATHandler_stub::resp_stop_success_count--; + return; + } + ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; } void ATHandler::cmd_start(const char *cmd) { } -void ATHandler::write_int(int param) +void ATHandler::write_int(int32_t param) { } @@ -223,4 +290,5 @@ device_err_t ATHandler::get_last_device_error() const void ATHandler::flush() { + } diff --git a/UNITTESTS/stubs/ATHandler_stub.h b/UNITTESTS/stubs/ATHandler_stub.h index 6ea956601a..a3b1cfb5e8 100644 --- a/UNITTESTS/stubs/ATHandler_stub.h +++ b/UNITTESTS/stubs/ATHandler_stub.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Arm Limited and affiliates. + * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,21 +23,40 @@ #include "FileHandle_stub.h" #include "Callback.h" -namespace ATHandler_stub -{ +#ifndef __AT_HANDLER_STUB_H__ +#define __AT_HANDLER_STUB_H__ +static const int kRead_string_table_size = 100; +static const int kRead_int_table_size = 100; +static const int kResp_stop_count_default = 100; +// set reference count to -909 to separate it from zero so we can test that ATHandler is really deleted. +static const int kATHandler_destructor_ref_ount = -909; + +namespace ATHandler_stub { extern nsapi_error_t nsapi_error_value; extern uint8_t nsapi_error_ok_counter; extern int int_value; +extern int ref_count; +extern int timeout; +extern bool default_timeout; +extern bool debug_on; extern ssize_t ssize_value; extern char *read_string_value; extern size_t size_value; extern size_t return_given_size; extern bool bool_value; extern uint8_t resp_info_true_counter; +extern uint8_t info_elem_true_counter; extern uint8_t uint8_value; extern mbed::FileHandle_stub *fh_value; extern mbed::device_err_t device_err_value; extern mbed::Callback callback; +extern bool call_immediately; +extern char *read_string_table[kRead_string_table_size]; +extern int read_string_index; +extern int int_valid_count_table[kRead_int_table_size]; +extern int int_count; +extern int resp_stop_success_count; +} -} // namespace ATHandler_stub +#endif diff --git a/features/cellular/UNITTESTS/stubs/AT_CellularBase_stub.cpp b/UNITTESTS/stubs/AT_CellularBase_stub.cpp similarity index 96% rename from features/cellular/UNITTESTS/stubs/AT_CellularBase_stub.cpp rename to UNITTESTS/stubs/AT_CellularBase_stub.cpp index e1f8526f5f..179c2e42e1 100644 --- a/features/cellular/UNITTESTS/stubs/AT_CellularBase_stub.cpp +++ b/UNITTESTS/stubs/AT_CellularBase_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Arm Limited and affiliates. + * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/features/cellular/UNITTESTS/stubs/AT_CellularBase_stub.h b/UNITTESTS/stubs/AT_CellularBase_stub.h similarity index 94% rename from features/cellular/UNITTESTS/stubs/AT_CellularBase_stub.h rename to UNITTESTS/stubs/AT_CellularBase_stub.h index f7d117d192..ec32d8eb28 100644 --- a/features/cellular/UNITTESTS/stubs/AT_CellularBase_stub.h +++ b/UNITTESTS/stubs/AT_CellularBase_stub.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Arm Limited and affiliates. + * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/features/cellular/UNITTESTS/stubs/AT_CellularDevice_stub.cpp b/UNITTESTS/stubs/AT_CellularDevice_stub.cpp similarity index 97% rename from features/cellular/UNITTESTS/stubs/AT_CellularDevice_stub.cpp rename to UNITTESTS/stubs/AT_CellularDevice_stub.cpp index 2010018ced..9f6749a8f8 100644 --- a/features/cellular/UNITTESTS/stubs/AT_CellularDevice_stub.cpp +++ b/UNITTESTS/stubs/AT_CellularDevice_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Arm Limited and affiliates. + * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/features/cellular/UNITTESTS/stubs/AT_CellularInformation_stub.cpp b/UNITTESTS/stubs/AT_CellularInformation_stub.cpp similarity index 96% rename from features/cellular/UNITTESTS/stubs/AT_CellularInformation_stub.cpp rename to UNITTESTS/stubs/AT_CellularInformation_stub.cpp index a41b3080d5..ae35f29bde 100644 --- a/features/cellular/UNITTESTS/stubs/AT_CellularInformation_stub.cpp +++ b/UNITTESTS/stubs/AT_CellularInformation_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Arm Limited and affiliates. + * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/features/cellular/UNITTESTS/stubs/AT_CellularMultiplexer_stub.cpp b/UNITTESTS/stubs/AT_CellularMultiplexer_stub.cpp similarity index 94% rename from features/cellular/UNITTESTS/stubs/AT_CellularMultiplexer_stub.cpp rename to UNITTESTS/stubs/AT_CellularMultiplexer_stub.cpp index c397d5fb38..21ea7e9f54 100644 --- a/features/cellular/UNITTESTS/stubs/AT_CellularMultiplexer_stub.cpp +++ b/UNITTESTS/stubs/AT_CellularMultiplexer_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Arm Limited and affiliates. + * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/features/cellular/UNITTESTS/stubs/AT_CellularNetwork_stub.cpp b/UNITTESTS/stubs/AT_CellularNetwork_stub.cpp similarity index 99% rename from features/cellular/UNITTESTS/stubs/AT_CellularNetwork_stub.cpp rename to UNITTESTS/stubs/AT_CellularNetwork_stub.cpp index c4ba878439..b28c8ebb9e 100644 --- a/features/cellular/UNITTESTS/stubs/AT_CellularNetwork_stub.cpp +++ b/UNITTESTS/stubs/AT_CellularNetwork_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Arm Limited and affiliates. + * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/features/cellular/UNITTESTS/stubs/AT_CellularPower_stub.cpp b/UNITTESTS/stubs/AT_CellularPower_stub.cpp similarity index 97% rename from features/cellular/UNITTESTS/stubs/AT_CellularPower_stub.cpp rename to UNITTESTS/stubs/AT_CellularPower_stub.cpp index 3459088ce5..56d8a4ca87 100644 --- a/features/cellular/UNITTESTS/stubs/AT_CellularPower_stub.cpp +++ b/UNITTESTS/stubs/AT_CellularPower_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Arm Limited and affiliates. + * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/features/cellular/UNITTESTS/stubs/AT_CellularSIM_stub.cpp b/UNITTESTS/stubs/AT_CellularSIM_stub.cpp similarity index 96% rename from features/cellular/UNITTESTS/stubs/AT_CellularSIM_stub.cpp rename to UNITTESTS/stubs/AT_CellularSIM_stub.cpp index fc4be35b94..afab1012bd 100644 --- a/features/cellular/UNITTESTS/stubs/AT_CellularSIM_stub.cpp +++ b/UNITTESTS/stubs/AT_CellularSIM_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Arm Limited and affiliates. + * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/features/cellular/UNITTESTS/stubs/AT_CellularSMS_stub.cpp b/UNITTESTS/stubs/AT_CellularSMS_stub.cpp similarity index 98% rename from features/cellular/UNITTESTS/stubs/AT_CellularSMS_stub.cpp rename to UNITTESTS/stubs/AT_CellularSMS_stub.cpp index 66456d7295..c43d4b2c82 100644 --- a/features/cellular/UNITTESTS/stubs/AT_CellularSMS_stub.cpp +++ b/UNITTESTS/stubs/AT_CellularSMS_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Arm Limited and affiliates. + * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/features/cellular/UNITTESTS/stubs/AT_CellularStack_stub.cpp b/UNITTESTS/stubs/AT_CellularStack_stub.cpp similarity index 97% rename from features/cellular/UNITTESTS/stubs/AT_CellularStack_stub.cpp rename to UNITTESTS/stubs/AT_CellularStack_stub.cpp index 640d8c1b68..a4dd04732c 100644 --- a/features/cellular/UNITTESTS/stubs/AT_CellularStack_stub.cpp +++ b/UNITTESTS/stubs/AT_CellularStack_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Arm Limited and affiliates. + * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/UNITTESTS/stubs/BufferedBlockDevice_stub.cpp b/UNITTESTS/stubs/BufferedBlockDevice_stub.cpp new file mode 100644 index 0000000000..ce7e2aba88 --- /dev/null +++ b/UNITTESTS/stubs/BufferedBlockDevice_stub.cpp @@ -0,0 +1,105 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "BufferedBlockDevice.h" +#include "mbed_assert.h" +#include "mbed_critical.h" +#include +#include + +static inline uint32_t align_down(bd_size_t val, bd_size_t size) +{ + return 0; +} + +BufferedBlockDevice::BufferedBlockDevice(BlockDevice *bd) +{ +} + +BufferedBlockDevice::~BufferedBlockDevice() +{ +} + +int BufferedBlockDevice::init() +{ + return 0; +} + +int BufferedBlockDevice::deinit() +{ + return 0; +} + +int BufferedBlockDevice::flush() +{ + return 0; +} + +int BufferedBlockDevice::sync() +{ + return 0; +} + +int BufferedBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int BufferedBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int BufferedBlockDevice::erase(bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int BufferedBlockDevice::trim(bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +bd_size_t BufferedBlockDevice::get_read_size() const +{ + return 1; +} + +bd_size_t BufferedBlockDevice::get_program_size() const +{ + return 1; +} + +bd_size_t BufferedBlockDevice::get_erase_size() const +{ + return 0; +} + +bd_size_t BufferedBlockDevice::get_erase_size(bd_addr_t addr) const +{ + return 0; +} + +int BufferedBlockDevice::get_erase_value() const +{ + return 0; +} + +bd_size_t BufferedBlockDevice::size() const +{ + return 0; +} diff --git a/features/cellular/UNITTESTS/stubs/CellularUtil_stub.cpp b/UNITTESTS/stubs/CellularUtil_stub.cpp similarity index 99% rename from features/cellular/UNITTESTS/stubs/CellularUtil_stub.cpp rename to UNITTESTS/stubs/CellularUtil_stub.cpp index d4bcaf4916..7de3907310 100644 --- a/features/cellular/UNITTESTS/stubs/CellularUtil_stub.cpp +++ b/UNITTESTS/stubs/CellularUtil_stub.cpp @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "CellularUtil.h" #include #include diff --git a/UNITTESTS/stubs/ChainingBlockDevice_stub.cpp b/UNITTESTS/stubs/ChainingBlockDevice_stub.cpp new file mode 100644 index 0000000000..b31de2eec2 --- /dev/null +++ b/UNITTESTS/stubs/ChainingBlockDevice_stub.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ChainingBlockDevice.h" +#include "mbed_critical.h" + + +ChainingBlockDevice::ChainingBlockDevice(BlockDevice **bds, size_t bd_count) +{ +} + +static bool is_aligned(uint64_t x, uint64_t alignment) +{ + return true; +} + +int ChainingBlockDevice::init() +{ + return 0; +} + +int ChainingBlockDevice::deinit() +{ + return 0; +} + +int ChainingBlockDevice::sync() +{ + return 0; +} + +int ChainingBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int ChainingBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int ChainingBlockDevice::erase(bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +bd_size_t ChainingBlockDevice::get_read_size() const +{ + return 0; +} + +bd_size_t ChainingBlockDevice::get_program_size() const +{ + return 0; +} + +bd_size_t ChainingBlockDevice::get_erase_size() const +{ + return 0; +} + +bd_size_t ChainingBlockDevice::get_erase_size(bd_addr_t addr) const +{ + return 0; +} + +int ChainingBlockDevice::get_erase_value() const +{ + return 0; +} + +bd_size_t ChainingBlockDevice::size() const +{ + return 0; +} diff --git a/UNITTESTS/stubs/EventFlags_stub.cpp b/UNITTESTS/stubs/EventFlags_stub.cpp index 95762b8b83..82b1f48f62 100644 --- a/UNITTESTS/stubs/EventFlags_stub.cpp +++ b/UNITTESTS/stubs/EventFlags_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Arm Limited and affiliates. + * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +15,12 @@ * limitations under the License. */ +#include #include "rtos/EventFlags.h" +#include + +/** Store the next value to be returned by Event Flags member functions */ +std::list eventFlagsStubNextRetval; rtos::EventFlags::EventFlags() {} rtos::EventFlags::~EventFlags() {} @@ -37,5 +42,11 @@ uint32_t rtos::EventFlags::wait_all(uint32_t flags, uint32_t timeout, bool clear } uint32_t rtos::EventFlags::wait_any(uint32_t flags, uint32_t timeout, bool clear) { + if (!eventFlagsStubNextRetval.empty()) + { + uint32_t ret = eventFlagsStubNextRetval.front(); + eventFlagsStubNextRetval.pop_front(); + return ret; + } return 0; } diff --git a/UNITTESTS/stubs/EventQueue_stub.cpp b/UNITTESTS/stubs/EventQueue_stub.cpp index e3436647b7..abbfc8ac21 100644 --- a/UNITTESTS/stubs/EventQueue_stub.cpp +++ b/UNITTESTS/stubs/EventQueue_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Arm Limited and affiliates. + * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -17,9 +17,13 @@ #include "EventQueue.h" #include "Callback.h" +#include "EventQueue_stub.h" using namespace mbed; +int EventQueue_stub::int_value = 0; +unsigned EventQueue_stub::unsigned_value = 0; + namespace events { EventQueue::EventQueue(unsigned event_size, unsigned char *event_pointer) @@ -40,13 +44,18 @@ void EventQueue::break_dispatch() unsigned EventQueue::tick() { - return 0; + return EventQueue_stub::unsigned_value; } void EventQueue::cancel(int id) { } +int EventQueue::time_left(int id) +{ + return EventQueue_stub::int_value; +} + void EventQueue::background(Callback update) { } diff --git a/features/cellular/UNITTESTS/stubs/mbed_assert_stub.cpp b/UNITTESTS/stubs/EventQueue_stub.h similarity index 86% rename from features/cellular/UNITTESTS/stubs/mbed_assert_stub.cpp rename to UNITTESTS/stubs/EventQueue_stub.h index 341881a7f5..4dfb6ac567 100644 --- a/features/cellular/UNITTESTS/stubs/mbed_assert_stub.cpp +++ b/UNITTESTS/stubs/EventQueue_stub.h @@ -15,10 +15,11 @@ * limitations under the License. */ -#include "mbed_assert.h" +#include -void mbed_assert_internal(const char *expr, const char *file, int line) +namespace EventQueue_stub { - +extern int int_value; +extern unsigned unsigned_value; } diff --git a/UNITTESTS/stubs/ExhaustibleBlockDevice_stub.cpp b/UNITTESTS/stubs/ExhaustibleBlockDevice_stub.cpp new file mode 100644 index 0000000000..845da43e6d --- /dev/null +++ b/UNITTESTS/stubs/ExhaustibleBlockDevice_stub.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ExhaustibleBlockDevice.h" +#include "mbed.h" +#include "mbed_critical.h" + + +ExhaustibleBlockDevice::ExhaustibleBlockDevice(BlockDevice *bd, uint32_t erase_cycles) +{ +} + +ExhaustibleBlockDevice::~ExhaustibleBlockDevice() +{ +} + +int ExhaustibleBlockDevice::init() +{ + return 0; +} + +int ExhaustibleBlockDevice::deinit() +{ + return 0; +} + +int ExhaustibleBlockDevice::sync() +{ + return 0; +} + +int ExhaustibleBlockDevice::read(void *buffer, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int ExhaustibleBlockDevice::program(const void *buffer, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int ExhaustibleBlockDevice::erase(bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +bd_size_t ExhaustibleBlockDevice::get_read_size() const +{ + return 0; +} + +bd_size_t ExhaustibleBlockDevice::get_program_size() const +{ + return 0; +} + +bd_size_t ExhaustibleBlockDevice::get_erase_size() const +{ + return 0; +} + +bd_size_t ExhaustibleBlockDevice::get_erase_size(bd_addr_t addr) const +{ + return 0; +} + +int ExhaustibleBlockDevice::get_erase_value() const +{ + return 0; +} + +bd_size_t ExhaustibleBlockDevice::size() const +{ + return 0; +} diff --git a/UNITTESTS/stubs/FileHandle_stub.h b/UNITTESTS/stubs/FileHandle_stub.h index ef68572c1e..41fb365ea6 100644 --- a/UNITTESTS/stubs/FileHandle_stub.h +++ b/UNITTESTS/stubs/FileHandle_stub.h @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef __FILE_HANDLE_STUB_H__ #define __FILE_HANDLE_STUB_H__ diff --git a/UNITTESTS/stubs/FlashSimBlockDevice_stub.cpp b/UNITTESTS/stubs/FlashSimBlockDevice_stub.cpp new file mode 100644 index 0000000000..4f0e368981 --- /dev/null +++ b/UNITTESTS/stubs/FlashSimBlockDevice_stub.cpp @@ -0,0 +1,98 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "FlashSimBlockDevice.h" +#include "mbed_assert.h" +#include "mbed_critical.h" +#include +#include +#include + +static const bd_size_t min_blank_buf_size = 32; + +static inline uint32_t align_up(bd_size_t val, bd_size_t size) +{ + return (((val - 1) / size) + 1) * size; +} + +FlashSimBlockDevice::FlashSimBlockDevice(BlockDevice *bd, uint8_t erase_value) +{ +} + +FlashSimBlockDevice::~FlashSimBlockDevice() +{ +} + +int FlashSimBlockDevice::init() +{ + return 0; +} + +int FlashSimBlockDevice::deinit() +{ + return 0; +} + +int FlashSimBlockDevice::sync() +{ + return 0; +} + +bd_size_t FlashSimBlockDevice::get_read_size() const +{ + return 0; +} + +bd_size_t FlashSimBlockDevice::get_program_size() const +{ + return 0; +} + +bd_size_t FlashSimBlockDevice::get_erase_size() const +{ + return 0; +} + +bd_size_t FlashSimBlockDevice::get_erase_size(bd_addr_t addr) const +{ + return 0; +} + +bd_size_t FlashSimBlockDevice::size() const +{ + return 0; +} + +int FlashSimBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int FlashSimBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int FlashSimBlockDevice::erase(bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int FlashSimBlockDevice::get_erase_value() const +{ + return 0; +} diff --git a/UNITTESTS/stubs/HeapBlockDevice_stub.cpp b/UNITTESTS/stubs/HeapBlockDevice_stub.cpp new file mode 100644 index 0000000000..dd39ffc28c --- /dev/null +++ b/UNITTESTS/stubs/HeapBlockDevice_stub.cpp @@ -0,0 +1,83 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "HeapBlockDevice.h" +#include "mbed_critical.h" + + +HeapBlockDevice::HeapBlockDevice(bd_size_t size, bd_size_t block) +{ +} + +HeapBlockDevice::HeapBlockDevice(bd_size_t size, bd_size_t read, bd_size_t program, bd_size_t erase) +{ +} + +HeapBlockDevice::~HeapBlockDevice() +{ +} + +int HeapBlockDevice::init() +{ + return 0; +} + +int HeapBlockDevice::deinit() +{ + return 0; +} + +bd_size_t HeapBlockDevice::get_read_size() const +{ + return 0; +} + +bd_size_t HeapBlockDevice::get_program_size() const +{ + return 0; +} + +bd_size_t HeapBlockDevice::get_erase_size() const +{ + return 0; +} + +bd_size_t HeapBlockDevice::get_erase_size(bd_addr_t addr) const +{ + return 0; +} + +bd_size_t HeapBlockDevice::size() const +{ + return 0; +} + +int HeapBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int HeapBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int HeapBlockDevice::erase(bd_addr_t addr, bd_size_t size) +{ + return 0; +} + diff --git a/features/cellular/UNITTESTS/stubs/Kernel.cpp b/UNITTESTS/stubs/Kernel_stub.cpp similarity index 99% rename from features/cellular/UNITTESTS/stubs/Kernel.cpp rename to UNITTESTS/stubs/Kernel_stub.cpp index ecfa1d80af..0050f4481a 100644 --- a/features/cellular/UNITTESTS/stubs/Kernel.cpp +++ b/UNITTESTS/stubs/Kernel_stub.cpp @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "Kernel.h" namespace rtos { diff --git a/UNITTESTS/stubs/LoRaMacChannelPlan_stub.cpp b/UNITTESTS/stubs/LoRaMacChannelPlan_stub.cpp new file mode 100644 index 0000000000..e4ebeeb849 --- /dev/null +++ b/UNITTESTS/stubs/LoRaMacChannelPlan_stub.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "LoRaMacChannelPlan.h" + +LoRaMacChannelPlan::LoRaMacChannelPlan() : _lora_phy(NULL) +{ +} + +LoRaMacChannelPlan::~LoRaMacChannelPlan() +{ +} + +void LoRaMacChannelPlan::activate_channelplan_subsystem(LoRaPHY *phy) +{ +} + +lorawan_status_t LoRaMacChannelPlan::set_plan(const lorawan_channelplan_t& plan) +{ + return LORAWAN_STATUS_OK; +} + +lorawan_status_t LoRaMacChannelPlan::get_plan(lorawan_channelplan_t& plan, + const channel_params_t* channel_list) +{ + return LORAWAN_STATUS_OK; +} + +lorawan_status_t LoRaMacChannelPlan::remove_plan() +{ + return LORAWAN_STATUS_OK; +} + +lorawan_status_t LoRaMacChannelPlan::remove_single_channel(uint8_t channel_id) +{ + return LORAWAN_STATUS_OK; +} + diff --git a/UNITTESTS/stubs/LoRaMacCommand_stub.cpp b/UNITTESTS/stubs/LoRaMacCommand_stub.cpp new file mode 100644 index 0000000000..4e67194d36 --- /dev/null +++ b/UNITTESTS/stubs/LoRaMacCommand_stub.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "LoRaMacCommand.h" +#include "LoRaMac.h" + +#include "LoRaMacCommand_stub.h" + +lorawan_status_t LoRaMacCommand_stub::status_value = LORAWAN_STATUS_OK; +bool LoRaMacCommand_stub::bool_value = false; +uint8_t LoRaMacCommand_stub::uint8_value = 0; +int32_t LoRaMacCommand_stub::int32_value = 0; + +LoRaMacCommand::LoRaMacCommand() +{ +} + +void LoRaMacCommand::clear_command_buffer() +{ +} + +uint8_t LoRaMacCommand::get_mac_cmd_length() const +{ + return LoRaMacCommand_stub::uint8_value; +} + +uint8_t *LoRaMacCommand::get_mac_commands_buffer() +{ + return &LoRaMacCommand_stub::uint8_value; +} + +void LoRaMacCommand::parse_mac_commands_to_repeat() +{ +} + + +void LoRaMacCommand::clear_repeat_buffer() +{ +} + +void LoRaMacCommand::copy_repeat_commands_to_buffer() +{ +} + +uint8_t LoRaMacCommand::get_repeat_commands_length() const +{ + return LoRaMacCommand_stub::uint8_value; +} + +void LoRaMacCommand::clear_sticky_mac_cmd() +{ +} + +bool LoRaMacCommand::has_sticky_mac_cmd() const +{ + return LoRaMacCommand_stub::bool_value; +} + +lorawan_status_t LoRaMacCommand::process_mac_commands(const uint8_t *payload, uint8_t mac_index, + uint8_t commands_size, uint8_t snr, + loramac_mlme_confirm_t& mlme_conf, + lora_mac_system_params_t &mac_sys_params, + LoRaPHY &lora_phy) +{ + return LoRaMacCommand_stub::status_value; +} + +int32_t LoRaMacCommand::cmd_buffer_remaining() const +{ + return LoRaMacCommand_stub::int32_value; +} + +void LoRaMacCommand::set_batterylevel_callback(mbed::Callback battery_level) +{ +} + +lorawan_status_t LoRaMacCommand::add_link_check_req() +{ + return LoRaMacCommand_stub::status_value; +} + +lorawan_status_t LoRaMacCommand::add_link_adr_ans(uint8_t status) +{ + return LoRaMacCommand_stub::status_value; +} + +lorawan_status_t LoRaMacCommand::add_duty_cycle_ans() +{ + return LoRaMacCommand_stub::status_value; +} + +lorawan_status_t LoRaMacCommand::add_rx_param_setup_ans(uint8_t status) +{ + return LoRaMacCommand_stub::status_value; +} + +lorawan_status_t LoRaMacCommand::add_dev_status_ans(uint8_t battery, uint8_t margin) +{ + return LoRaMacCommand_stub::status_value; +} + +lorawan_status_t LoRaMacCommand::add_new_channel_ans(uint8_t status) +{ + return LoRaMacCommand_stub::status_value; +} + +lorawan_status_t LoRaMacCommand::add_rx_timing_setup_ans() +{ + return LoRaMacCommand_stub::status_value; +} + +lorawan_status_t LoRaMacCommand::add_tx_param_setup_ans() +{ + return LoRaMacCommand_stub::status_value; +} + +lorawan_status_t LoRaMacCommand::add_dl_channel_ans(uint8_t status) +{ + return LoRaMacCommand_stub::status_value; +} diff --git a/features/cellular/UNITTESTS/stubs/FileHandle_stub.cpp b/UNITTESTS/stubs/LoRaMacCommand_stub.h similarity index 76% rename from features/cellular/UNITTESTS/stubs/FileHandle_stub.cpp rename to UNITTESTS/stubs/LoRaMacCommand_stub.h index d14d52b6fb..c7ce5f3716 100644 --- a/features/cellular/UNITTESTS/stubs/FileHandle_stub.cpp +++ b/UNITTESTS/stubs/LoRaMacCommand_stub.h @@ -15,18 +15,14 @@ * limitations under the License. */ -#include "FileHandle_stub.h" -namespace mbed { +#include +#include "lorawan_types.h" -off_t FileHandle::size() +namespace LoRaMacCommand_stub { - return 0; -} - -std::FILE *fdopen(FileHandle *fh, const char *mode) -{ - return NULL; -} - +extern lorawan_status_t status_value; +extern bool bool_value; +extern uint8_t uint8_value; +extern int32_t int32_value; } diff --git a/UNITTESTS/stubs/LoRaMacCrypto_stub.cpp b/UNITTESTS/stubs/LoRaMacCrypto_stub.cpp new file mode 100644 index 0000000000..b4b272d23c --- /dev/null +++ b/UNITTESTS/stubs/LoRaMacCrypto_stub.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "LoRaMacCrypto.h" +#include "system/lorawan_data_structures.h" + +#include "LoRaMacCrypto_stub.h" + +int LoRaMacCrypto_stub::int_table_idx_value = 0; +int LoRaMacCrypto_stub::int_table[20] = {}; + +LoRaMacCrypto::LoRaMacCrypto() +{ +} + +int LoRaMacCrypto::compute_mic(const uint8_t *, uint16_t , const uint8_t *, uint32_t, uint32_t, + uint8_t dir, uint32_t, uint32_t *) +{ + return LoRaMacCrypto_stub::int_table[LoRaMacCrypto_stub::int_table_idx_value++]; +} + +int LoRaMacCrypto::encrypt_payload(const uint8_t *, uint16_t , const uint8_t *, uint32_t, uint32_t, + uint8_t , uint32_t , uint8_t *) +{ + return LoRaMacCrypto_stub::int_table[LoRaMacCrypto_stub::int_table_idx_value++]; +} + +int LoRaMacCrypto::decrypt_payload(const uint8_t *, uint16_t , const uint8_t *, uint32_t, uint32_t, + uint8_t , uint32_t , uint8_t *) +{ + return LoRaMacCrypto_stub::int_table[LoRaMacCrypto_stub::int_table_idx_value++]; +} + +int LoRaMacCrypto::compute_join_frame_mic(const uint8_t *, uint16_t , const uint8_t *, uint32_t, uint32_t *) +{ + return LoRaMacCrypto_stub::int_table[LoRaMacCrypto_stub::int_table_idx_value++]; +} + +int LoRaMacCrypto::decrypt_join_frame(const uint8_t *in, uint16_t size, const uint8_t *, uint32_t, uint8_t *out) +{ + memcpy(out, in, size); + return LoRaMacCrypto_stub::int_table[LoRaMacCrypto_stub::int_table_idx_value++]; +} + +int LoRaMacCrypto::compute_skeys_for_join_frame(const uint8_t *, uint32_t, const uint8_t *, uint16_t , + uint8_t *, uint8_t *) +{ + return LoRaMacCrypto_stub::int_table[LoRaMacCrypto_stub::int_table_idx_value++]; +} diff --git a/features/cellular/UNITTESTS/target_h/PinNames.h b/UNITTESTS/stubs/LoRaMacCrypto_stub.h similarity index 85% rename from features/cellular/UNITTESTS/target_h/PinNames.h rename to UNITTESTS/stubs/LoRaMacCrypto_stub.h index 9f92be6f1d..4a3a568efa 100644 --- a/features/cellular/UNITTESTS/target_h/PinNames.h +++ b/UNITTESTS/stubs/LoRaMacCrypto_stub.h @@ -14,14 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef __PINNAMES_H__ -#define __PINNAMES_H__ +#include -typedef enum { - -} PinName; - -#endif - +namespace LoRaMacCrypto_stub +{ +extern int int_table_idx_value; +extern int int_table[20]; +} diff --git a/UNITTESTS/stubs/LoRaMac_stub.cpp b/UNITTESTS/stubs/LoRaMac_stub.cpp new file mode 100644 index 0000000000..b9b5139bea --- /dev/null +++ b/UNITTESTS/stubs/LoRaMac_stub.cpp @@ -0,0 +1,458 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "LoRaMac.h" +#include "LoRaMac_stub.h" + +using namespace events; +using namespace mbed; + +int LoRaMac_stub::bool_false_counter = 0; +int LoRaMac_stub::bool_true_counter = 0; +bool LoRaMac_stub::bool_value = false; +int LoRaMac_stub::int_value = 0; +rx_slot_t LoRaMac_stub::slot_value = RX_SLOT_WIN_1; +lorawan_status_t LoRaMac_stub::status_value = LORAWAN_STATUS_OK; +loramac_mcps_confirm_t *LoRaMac_stub::mcps_conf_ptr = NULL; +loramac_mcps_indication_t *LoRaMac_stub::mcps_ind_ptr = NULL; +loramac_mlme_confirm_t *LoRaMac_stub::mlme_conf_ptr = NULL; +loramac_mlme_indication_t *LoRaMac_stub::mlme_ind_ptr = NULL; +device_class_t LoRaMac_stub::dev_class_value = CLASS_A; +mbed::Callback LoRaMac_stub::_ack_expiry_handler_for_class_c = NULL; +mbed::Callback LoRaMac_stub::_scheduling_failure_handler = NULL; + + +LoRaMac::LoRaMac() + : _lora_time(), + _lora_phy(NULL), + _mac_commands(), + _channel_plan(), + _lora_crypto(), + _ev_queue(NULL), + _mcps_indication(), + _mcps_confirmation(), + _mlme_indication(), + _mlme_confirmation(), + _is_nwk_joined(false), + _continuous_rx2_window_open(false), + _device_class(CLASS_A) +{} + +LoRaMac::~LoRaMac() +{ +} + +const loramac_mcps_confirm_t *LoRaMac::get_mcps_confirmation() const +{ + return LoRaMac_stub::mcps_conf_ptr; +} + +const loramac_mcps_indication_t *LoRaMac::get_mcps_indication() const +{ + return LoRaMac_stub::mcps_ind_ptr; +} + +const loramac_mlme_confirm_t *LoRaMac::get_mlme_confirmation() const +{ + return LoRaMac_stub::mlme_conf_ptr; +} + +const loramac_mlme_indication_t *LoRaMac::get_mlme_indication() const +{ + return LoRaMac_stub::mlme_ind_ptr; +} + +void LoRaMac::post_process_mlme_request() +{ +} + +void LoRaMac::post_process_mcps_req() +{ +} + +void LoRaMac::post_process_mcps_ind() +{ +} + +void LoRaMac::post_process_mlme_ind() +{ +} + +lorawan_time_t LoRaMac::get_current_time(void) +{ +} + +rx_slot_t LoRaMac::get_current_slot(void) +{ + return LoRaMac_stub::slot_value; +} + +void LoRaMac::handle_join_accept_frame(const uint8_t *payload, uint16_t size) +{ +} + +void LoRaMac::check_frame_size(uint16_t size) +{ +} + +bool LoRaMac::message_integrity_check(const uint8_t *const payload, + const uint16_t size, + uint8_t *const ptr_pos, + uint32_t address, + uint32_t *downlink_counter, + const uint8_t *nwk_skey) +{ + if (LoRaMac_stub::bool_false_counter) { + LoRaMac_stub::bool_false_counter--; + return false; + } + if (LoRaMac_stub::bool_true_counter) { + LoRaMac_stub::bool_true_counter--; + return true; + } + + return LoRaMac_stub::bool_value; +} + +void LoRaMac::extract_data_and_mac_commands(const uint8_t *payload, + uint16_t size, + uint8_t fopts_len, + uint8_t *nwk_skey, + uint8_t *app_skey, + uint32_t address, + uint32_t downlink_counter, + int16_t rssi, + int8_t snr) +{ +} + +void LoRaMac::extract_mac_commands_only(const uint8_t *payload, + int8_t snr, + uint8_t fopts_len) +{ +} + +void LoRaMac::handle_data_frame(const uint8_t *const payload, + const uint16_t size, + uint8_t ptr_pos, + uint8_t msg_type, + int16_t rssi, + int8_t snr) +{ +} + +void LoRaMac::set_batterylevel_callback(mbed::Callback battery_level) +{ +} + +void LoRaMac::on_radio_tx_done(lorawan_time_t timestamp) +{ +} + +void LoRaMac::on_radio_rx_done(const uint8_t *const payload, uint16_t size, + int16_t rssi, int8_t snr) +{ +} + +void LoRaMac::on_radio_tx_timeout(void) +{ +} + +void LoRaMac::on_radio_rx_timeout(bool is_timeout) +{ +} + +bool LoRaMac::continue_joining_process() +{ + if (LoRaMac_stub::bool_false_counter) { + LoRaMac_stub::bool_false_counter--; + return false; + } + if (LoRaMac_stub::bool_true_counter) { + LoRaMac_stub::bool_true_counter--; + return true; + } + return LoRaMac_stub::bool_value; +} + +bool LoRaMac::continue_sending_process() +{ + if (LoRaMac_stub::bool_false_counter) { + LoRaMac_stub::bool_false_counter--; + return false; + } + if (LoRaMac_stub::bool_true_counter) { + LoRaMac_stub::bool_true_counter--; + return true; + } + return LoRaMac_stub::bool_value; +} + +lorawan_status_t LoRaMac::send_join_request() +{ + return LoRaMac_stub::status_value; +} + +lorawan_status_t LoRaMac::handle_retransmission() +{ + return LoRaMac_stub::status_value; +} + +void LoRaMac::on_backoff_timer_expiry(void) +{ +} + +void LoRaMac::open_rx1_window(void) +{ +} + +void LoRaMac::open_rx2_window() +{ +} + +void LoRaMac::on_ack_timeout_timer_event(void) +{ +} + +bool LoRaMac::validate_payload_length(uint16_t length, + int8_t datarate, + uint8_t fopts_len) +{ + if (LoRaMac_stub::bool_false_counter) { + LoRaMac_stub::bool_false_counter--; + return false; + } + if (LoRaMac_stub::bool_true_counter) { + LoRaMac_stub::bool_true_counter--; + return true; + } + return LoRaMac_stub::bool_value; +} + +void LoRaMac::set_mlme_schedule_ul_indication(void) +{ +} + +// This is not actual transmission. It just schedules a message in response +// to MCPS request +lorawan_status_t LoRaMac::send(loramac_mhdr_t *machdr, const uint8_t fport, + const void *fbuffer, uint16_t fbuffer_size) +{ + return LoRaMac_stub::status_value; +} + +int LoRaMac::get_backoff_timer_event_id(void) +{ + return LoRaMac_stub::int_value; +} + +lorawan_status_t LoRaMac::clear_tx_pipe(void) +{ + return LoRaMac_stub::status_value; +} + +lorawan_status_t LoRaMac::schedule_tx() +{ + return LoRaMac_stub::status_value; +} + +void LoRaMac::calculate_backOff(uint8_t channel) +{ +} + +void LoRaMac::reset_mac_parameters(void) +{ +} + +uint8_t LoRaMac::get_default_tx_datarate() +{ + return 0; +} + +void LoRaMac::enable_adaptive_datarate(bool adr_enabled) +{ +} + +lorawan_status_t LoRaMac::set_channel_data_rate(uint8_t data_rate) +{ + return LoRaMac_stub::status_value; +} + +bool LoRaMac::tx_ongoing() +{ + if (LoRaMac_stub::bool_false_counter) { + LoRaMac_stub::bool_false_counter--; + return false; + } + if (LoRaMac_stub::bool_true_counter) { + LoRaMac_stub::bool_true_counter--; + return true; + } + return LoRaMac_stub::bool_value; +} + +void LoRaMac::set_tx_ongoing(bool ongoing) +{ +} + +void LoRaMac::reset_ongoing_tx(bool reset_pending) +{ +} + +int16_t LoRaMac::prepare_ongoing_tx(const uint8_t port, + const uint8_t *const data, + uint16_t length, + uint8_t flags, + uint8_t num_retries) +{ + return 0; +} + +lorawan_status_t LoRaMac::send_ongoing_tx() +{ + return LoRaMac_stub::status_value; +} + +device_class_t LoRaMac::get_device_class() const +{ + return LoRaMac_stub::dev_class_value; +} + +void LoRaMac::set_device_class(const device_class_t &device_class, + mbed::Callbackack_expiry_handler) +{ + LoRaMac_stub::_ack_expiry_handler_for_class_c = ack_expiry_handler; +} + +void LoRaMac::setup_link_check_request() +{ +} + +lorawan_status_t LoRaMac::prepare_join(const lorawan_connect_t *params, bool is_otaa) +{ + return LoRaMac_stub::status_value; +} + +lorawan_status_t LoRaMac::join(bool is_otaa) +{ + return LoRaMac_stub::status_value; +} + +static void memcpy_convert_endianess(uint8_t *dst, + const uint8_t *src, + uint16_t size) +{ +} + +lorawan_status_t LoRaMac::prepare_frame(loramac_mhdr_t *machdr, + loramac_frame_ctrl_t *fctrl, + const uint8_t fport, + const void *fbuffer, + uint16_t fbuffer_size) +{ + return LoRaMac_stub::status_value; +} + +lorawan_status_t LoRaMac::send_frame_on_channel(uint8_t channel) +{ + return LoRaMac_stub::status_value; +} + +void LoRaMac::reset_mcps_confirmation() +{ +} + +void LoRaMac::reset_mlme_confirmation() +{ +} + +void LoRaMac::reset_mcps_indication() +{ +} + +void LoRaMac::set_tx_continuous_wave(uint8_t channel, int8_t datarate, int8_t tx_power, + float max_eirp, float antenna_gain, uint16_t timeout) +{ +} + +lorawan_status_t LoRaMac::initialize(EventQueue *queue, + mbed::Callbackscheduling_failure_handler) +{ + LoRaMac_stub::_scheduling_failure_handler = scheduling_failure_handler; + return LoRaMac_stub::status_value; +} + +void LoRaMac::disconnect() +{ +} + +uint8_t LoRaMac::get_max_possible_tx_size(uint8_t fopts_len) +{ + return 0; +} + +bool LoRaMac::nwk_joined() +{ + if (LoRaMac_stub::bool_false_counter) { + LoRaMac_stub::bool_false_counter--; + return false; + } + if (LoRaMac_stub::bool_true_counter) { + LoRaMac_stub::bool_true_counter--; + return true; + } + return LoRaMac_stub::bool_value; +} + +void LoRaMac::set_nwk_joined(bool joined) +{ +} + +lorawan_status_t LoRaMac::add_channel_plan(const lorawan_channelplan_t &plan) +{ + return LoRaMac_stub::status_value; +} + +lorawan_status_t LoRaMac::remove_channel_plan() +{ + return LoRaMac_stub::status_value; +} + +lorawan_status_t LoRaMac::get_channel_plan(lorawan_channelplan_t &plan) +{ + return LoRaMac_stub::status_value; +} + +lorawan_status_t LoRaMac::remove_single_channel(uint8_t id) +{ + return LoRaMac_stub::status_value; +} + +lorawan_status_t LoRaMac::multicast_channel_link(multicast_params_t *channel_param) +{ + return LoRaMac_stub::status_value; +} + +lorawan_status_t LoRaMac::multicast_channel_unlink(multicast_params_t *channel_param) +{ + return LoRaMac_stub::status_value; +} + +void LoRaMac::bind_phy(LoRaPHY &phy) +{ +} diff --git a/UNITTESTS/stubs/LoRaMac_stub.h b/UNITTESTS/stubs/LoRaMac_stub.h new file mode 100644 index 0000000000..f1bbd10517 --- /dev/null +++ b/UNITTESTS/stubs/LoRaMac_stub.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "stdint.h" +#include "stdbool.h" +#include + +#include "lorawan_types.h" +#include "lorawan_data_structures.h" + +namespace LoRaMac_stub +{ +extern bool bool_value; +extern int bool_false_counter; +extern int bool_true_counter; +extern int int_value; +extern rx_slot_t slot_value; +extern lorawan_status_t status_value; +extern loramac_mcps_confirm_t *mcps_conf_ptr; +extern loramac_mcps_indication_t *mcps_ind_ptr; +extern loramac_mlme_confirm_t *mlme_conf_ptr; +extern loramac_mlme_indication_t *mlme_ind_ptr; +extern device_class_t dev_class_value; +extern mbed::Callback _ack_expiry_handler_for_class_c; +extern mbed::Callback _scheduling_failure_handler; +} diff --git a/features/cellular/UNITTESTS/target_h/mbed_rtos1_types.h b/UNITTESTS/stubs/LoRaPHYEU868_stub.cpp similarity index 84% rename from features/cellular/UNITTESTS/target_h/mbed_rtos1_types.h rename to UNITTESTS/stubs/LoRaPHYEU868_stub.cpp index 2b9bd19f67..a425f30a12 100644 --- a/features/cellular/UNITTESTS/target_h/mbed_rtos1_types.h +++ b/UNITTESTS/stubs/LoRaPHYEU868_stub.cpp @@ -15,4 +15,14 @@ * limitations under the License. */ -#include "cmsis_os.h" +#include "LoRaPHYEU868.h" +#include "lora_phy_ds.h" + +LoRaPHYEU868::LoRaPHYEU868() +{ +} + +LoRaPHYEU868::~LoRaPHYEU868() +{ +} + diff --git a/UNITTESTS/stubs/LoRaPHY_stub.cpp b/UNITTESTS/stubs/LoRaPHY_stub.cpp new file mode 100644 index 0000000000..978cf1dd0b --- /dev/null +++ b/UNITTESTS/stubs/LoRaPHY_stub.cpp @@ -0,0 +1,413 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include + +#include "LoRaPHY.h" +#include "LoRaPHY_stub.h" + +LoRaRadio *LoRaPHY_stub::radio = NULL; +uint32_t LoRaPHY_stub::uint32_value = 0; +uint16_t LoRaPHY_stub::uint16_value = 0; +uint8_t LoRaPHY_stub::uint8_value = 0; +int8_t LoRaPHY_stub::int8_value = 0; +int LoRaPHY_stub::int_value = 0; +double LoRaPHY_stub::double_value = 0; +lorawan_status_t LoRaPHY_stub::lorawan_status_value = LORAWAN_STATUS_OK; +channel_params_t *LoRaPHY_stub::channel_params_ptr = NULL; +uint8_t LoRaPHY_stub::bool_counter = 0; +bool LoRaPHY_stub::bool_table[20] = {}; +uint8_t LoRaPHY_stub::linkAdrNbBytesParsed = 0; +uint8_t LoRaPHY_stub::ch_mask_value = 0; +uint8_t LoRaPHY_stub::adr_parse_count = 0; + +LoRaPHY::LoRaPHY() + : _radio(LoRaPHY_stub::radio) +{ +} + +LoRaPHY::~LoRaPHY() +{ +} + +void LoRaPHY::initialize(LoRaWANTimeHandler *lora_time) +{ +} + +bool LoRaPHY::mask_bit_test(const uint16_t *mask, unsigned bit) +{ + return LoRaPHY_stub::bool_table[LoRaPHY_stub::bool_counter++]; +} + +void LoRaPHY::mask_bit_set(uint16_t *mask, unsigned bit) +{ +} + +void LoRaPHY::mask_bit_clear(uint16_t *mask, unsigned bit) +{ +} + +void LoRaPHY::set_radio_instance(LoRaRadio &radio) +{ +} + +void LoRaPHY::put_radio_to_sleep() +{ +} + +void LoRaPHY::put_radio_to_standby() +{ +} + +void LoRaPHY::setup_public_network_mode(bool set) +{ +} + +void LoRaPHY::handle_receive(void) +{ +} + +uint32_t LoRaPHY::get_radio_rng() +{ + return LoRaPHY_stub::uint32_value; +} + +void LoRaPHY::handle_send(uint8_t *buf, uint8_t size) +{ +} + +uint8_t LoRaPHY::request_new_channel(int8_t channel_id, channel_params_t *new_channel) +{ + return LoRaPHY_stub::uint8_value; +} + +int32_t LoRaPHY::get_random(int32_t min, int32_t max) +{ + return LoRaPHY_stub::uint32_value; +} + +bool LoRaPHY::verify_channel_DR(uint16_t *channel_mask, int8_t dr) +{ + return LoRaPHY_stub::bool_table[LoRaPHY_stub::bool_counter++]; +} + +bool LoRaPHY::val_in_range(int8_t value, int8_t min, int8_t max) +{ + return LoRaPHY_stub::bool_table[LoRaPHY_stub::bool_counter++]; +} + +bool LoRaPHY::disable_channel(uint16_t *channel_mask, uint8_t id, + uint8_t max_channels_num) +{ + return LoRaPHY_stub::bool_table[LoRaPHY_stub::bool_counter++]; +} + +uint8_t LoRaPHY::count_bits(uint16_t mask, uint8_t nbBits) +{ + return LoRaPHY_stub::uint8_value; +} + +uint8_t LoRaPHY::num_active_channels(uint16_t *channel_mask, uint8_t start_idx, + uint8_t stop_idx) +{ + return LoRaPHY_stub::uint8_value; +} + +void LoRaPHY::copy_channel_mask(uint16_t *dest_mask, uint16_t *src_mask, uint8_t len) +{ + if ((dest_mask != NULL) && (src_mask != NULL)) { + for (uint8_t i = 0; i < len; i++) { + dest_mask[i] = src_mask[i]; + } + } +} + +void LoRaPHY::set_last_tx_done(uint8_t channel, bool joined, lorawan_time_t last_tx_done_time) +{ +} + +lorawan_time_t LoRaPHY::update_band_timeoff(bool joined, bool duty_cycle, + band_t *bands, uint8_t nb_bands) +{ + return LoRaPHY_stub::uint32_value; +} + +uint8_t LoRaPHY::parse_link_ADR_req(const uint8_t *payload, + link_adr_params_t *params) +{ + params->ch_mask_ctrl = LoRaPHY_stub::ch_mask_value; + + if (LoRaPHY_stub::adr_parse_count) { + return --LoRaPHY_stub::adr_parse_count; + } + + return LoRaPHY_stub::uint8_value; +} + +uint8_t LoRaPHY::verify_link_ADR_req(verify_adr_params_t *verify_params, + int8_t *dr, int8_t *tx_pow, uint8_t *nb_rep) +{ + return LoRaPHY_stub::uint8_value; +} + +void LoRaPHY::get_rx_window_params(double t_symb, uint8_t min_rx_symb, + uint32_t rx_error, uint32_t wakeup_time, + uint32_t *window_timeout, int32_t *window_offset) +{ +} + +int8_t LoRaPHY::compute_tx_power(int8_t tx_power_idx, float max_eirp, + float antenna_gain) +{ + return LoRaPHY_stub::int8_value; +} + + +int8_t LoRaPHY::get_next_lower_dr(int8_t dr, int8_t min_dr) +{ + return LoRaPHY_stub::int8_value; +} + +uint8_t LoRaPHY::get_bandwidth(uint8_t dr) +{ + return LoRaPHY_stub::uint8_value; +} + +uint8_t LoRaPHY::enabled_channel_count(uint8_t datarate, + const uint16_t *channel_mask, + uint8_t *channel_indices, + uint8_t *delayTx) +{ + return LoRaPHY_stub::uint8_value; +} + +bool LoRaPHY::is_datarate_supported(const int8_t datarate) const +{ + return LoRaPHY_stub::bool_table[LoRaPHY_stub::bool_counter++]; +} + +void LoRaPHY::reset_to_default_values(loramac_protocol_params *params, bool init) +{ +} + +int8_t LoRaPHY::get_next_lower_tx_datarate(int8_t datarate) +{ + return LoRaPHY_stub::int8_value; +} + +uint8_t LoRaPHY::get_minimum_rx_datarate() +{ + return LoRaPHY_stub::uint8_value; +} + +uint8_t LoRaPHY::get_minimum_tx_datarate() +{ + return LoRaPHY_stub::uint8_value; +} + +uint8_t LoRaPHY::get_default_tx_datarate() +{ + return LoRaPHY_stub::uint8_value; +} + +uint8_t LoRaPHY::get_default_max_tx_datarate() +{ + return LoRaPHY_stub::uint8_value; +} + +uint8_t LoRaPHY::get_default_tx_power() +{ + return LoRaPHY_stub::uint8_value; +} + +uint8_t LoRaPHY::get_max_payload(uint8_t datarate, bool use_repeater) +{ + return LoRaPHY_stub::uint8_value; +} + +uint16_t LoRaPHY::get_maximum_frame_counter_gap() +{ + return LoRaPHY_stub::uint16_value; +} + +uint32_t LoRaPHY::get_ack_timeout() +{ + return LoRaPHY_stub::uint32_value; +} + +uint32_t LoRaPHY::get_default_rx2_frequency() +{ + return LoRaPHY_stub::uint32_value; +} + +uint8_t LoRaPHY::get_default_rx2_datarate() +{ + return phy_params.rx_window2_datarate; +} + +uint16_t *LoRaPHY::get_channel_mask(bool get_default) +{ + return &LoRaPHY_stub::uint16_value; +} + +uint8_t LoRaPHY::get_max_nb_channels() +{ + return LoRaPHY_stub::uint8_value; +} + +channel_params_t *LoRaPHY::get_phy_channels() +{ + return LoRaPHY_stub::channel_params_ptr; +} + +bool LoRaPHY::is_custom_channel_plan_supported() +{ + return LoRaPHY_stub::bool_table[LoRaPHY_stub::bool_counter++]; +} + +void LoRaPHY::restore_default_channels() +{ +} + +bool LoRaPHY::verify_rx_datarate(uint8_t datarate) +{ + return LoRaPHY_stub::bool_table[LoRaPHY_stub::bool_counter++]; +} + +bool LoRaPHY::verify_tx_datarate(uint8_t datarate, bool use_default) +{ + return LoRaPHY_stub::bool_table[LoRaPHY_stub::bool_counter++]; +} + +bool LoRaPHY::verify_tx_power(uint8_t tx_power) +{ + return LoRaPHY_stub::bool_table[LoRaPHY_stub::bool_counter++]; +} + +bool LoRaPHY::verify_duty_cycle(bool cycle) +{ + return LoRaPHY_stub::bool_table[LoRaPHY_stub::bool_counter++]; +} + +bool LoRaPHY::verify_nb_join_trials(uint8_t nb_join_trials) +{ + return LoRaPHY_stub::bool_table[LoRaPHY_stub::bool_counter++]; +} + +void LoRaPHY::apply_cf_list(const uint8_t *payload, uint8_t size) +{ +} + + +bool LoRaPHY::get_next_ADR(bool restore_channel_mask, int8_t &dr_out, + int8_t &tx_power_out, uint32_t &adr_ack_cnt) +{ + return LoRaPHY_stub::bool_table[LoRaPHY_stub::bool_counter++]; +} + +void LoRaPHY::compute_rx_win_params(int8_t datarate, uint8_t min_rx_symbols, + uint32_t rx_error, + rx_config_params_t *rx_conf_params) +{ +} + +bool LoRaPHY::rx_config(rx_config_params_t *rx_conf) +{ + return LoRaPHY_stub::bool_table[LoRaPHY_stub::bool_counter++]; +} + +bool LoRaPHY::tx_config(tx_config_params_t *tx_conf, int8_t *tx_power, + lorawan_time_t *tx_toa) +{ + return LoRaPHY_stub::bool_table[LoRaPHY_stub::bool_counter++]; +} + +uint8_t LoRaPHY::link_ADR_request(adr_req_params_t *link_adr_req, + int8_t *dr_out, int8_t *tx_power_out, + uint8_t *nb_rep_out, uint8_t *nb_bytes_processed) +{ + *nb_bytes_processed = LoRaPHY_stub::linkAdrNbBytesParsed; + return LoRaPHY_stub::uint8_value; +} + +uint8_t LoRaPHY::accept_rx_param_setup_req(rx_param_setup_req_t *params) +{ + return LoRaPHY_stub::uint8_value; +} + +bool LoRaPHY::accept_tx_param_setup_req(uint8_t ul_dwell_time, uint8_t dl_dwell_time) +{ + return LoRaPHY_stub::bool_table[LoRaPHY_stub::bool_counter++]; +} + +int LoRaPHY::lookup_band_for_frequency(uint32_t freq) const +{ + return LoRaPHY_stub::int_value; +} + +bool LoRaPHY::verify_frequency_for_band(uint32_t freq, uint8_t band) const +{ + return LoRaPHY_stub::bool_table[LoRaPHY_stub::bool_counter++]; +} + +uint8_t LoRaPHY::dl_channel_request(uint8_t channel_id, uint32_t rx1_frequency) +{ + return LoRaPHY_stub::uint8_value; +} + +int8_t LoRaPHY::get_alternate_DR(uint8_t nb_trials) +{ + return LoRaPHY_stub::int8_value; +} + +void LoRaPHY::calculate_backoff(bool joined, bool last_tx_was_join_req, bool dc_enabled, uint8_t channel, + lorawan_time_t elapsed_time, lorawan_time_t tx_toa) +{ +} + +lorawan_status_t LoRaPHY::set_next_channel(channel_selection_params_t *params, + uint8_t *channel, lorawan_time_t *time, + lorawan_time_t *aggregate_timeoff) +{ + return LoRaPHY_stub::lorawan_status_value; +} + +lorawan_status_t LoRaPHY::add_channel(const channel_params_t *new_channel, + uint8_t id) +{ + return LoRaPHY_stub::lorawan_status_value; +} + +bool LoRaPHY::remove_channel(uint8_t channel_id) +{ + return LoRaPHY_stub::bool_table[LoRaPHY_stub::bool_counter++]; +} + +void LoRaPHY::set_tx_cont_mode(cw_mode_params_t *params, uint32_t given_frequency) +{ +} + +uint8_t LoRaPHY::apply_DR_offset(int8_t dr, int8_t dr_offset) +{ + return LoRaPHY_stub::uint8_value; +} + + diff --git a/UNITTESTS/stubs/LoRaPHY_stub.h b/UNITTESTS/stubs/LoRaPHY_stub.h new file mode 100644 index 0000000000..12a4e589bf --- /dev/null +++ b/UNITTESTS/stubs/LoRaPHY_stub.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "stdint.h" +#include "stdbool.h" +#include + +#include "lorawan_types.h" + +namespace LoRaPHY_stub +{ +extern LoRaRadio *radio; +extern uint8_t bool_counter; +extern bool bool_table[20]; +extern uint32_t uint32_value; +extern uint8_t uint8_value; +extern int8_t int8_value; +extern int int_value; +extern double double_value; +extern uint16_t uint16_value; +extern lorawan_status_t lorawan_status_value; +extern channel_params_t* channel_params_ptr; +extern uint8_t linkAdrNbBytesParsed; +extern uint8_t ch_mask_value; +extern uint8_t adr_parse_count; +} diff --git a/UNITTESTS/stubs/LoRaWANStack_stub.cpp b/UNITTESTS/stubs/LoRaWANStack_stub.cpp new file mode 100644 index 0000000000..628ea0faf6 --- /dev/null +++ b/UNITTESTS/stubs/LoRaWANStack_stub.cpp @@ -0,0 +1,298 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "LoRaWANStack.h" + +using namespace mbed; +using namespace events; + +/***************************************************************************** + * Constructor * + ****************************************************************************/ +LoRaWANStack::LoRaWANStack() + : _loramac(), + _device_current_state(DEVICE_STATE_NOT_INITIALIZED), + _lw_session(), + _tx_msg(), + _rx_msg(), + _tx_metadata(), + _rx_metadata(), + _num_retry(1), + _ctrl_flags(0), + _app_port(12), + _link_check_requested(false), + _automatic_uplink_ongoing(false), + _ready_for_rx(true), + _queue(NULL) +{ +} + +void LoRaWANStack::bind_phy_and_radio_driver(LoRaRadio &radio, LoRaPHY &phy) +{ +} + +lorawan_status_t LoRaWANStack::initialize_mac_layer(EventQueue *queue) +{ + return LORAWAN_STATUS_OK; +} + +lorawan_status_t LoRaWANStack::set_lora_callbacks(const lorawan_app_callbacks_t *callbacks) +{ + return LORAWAN_STATUS_OK; +} + +lorawan_status_t LoRaWANStack::connect() +{ + return LORAWAN_STATUS_OK; +} + +lorawan_status_t LoRaWANStack::connect(const lorawan_connect_t &connect) +{ + return LORAWAN_STATUS_OK; +} + +lorawan_status_t LoRaWANStack::add_channels(const lorawan_channelplan_t &channel_plan) +{ + return LORAWAN_STATUS_OK; +} + +lorawan_status_t LoRaWANStack::remove_a_channel(uint8_t channel_id) +{ + return LORAWAN_STATUS_OK; +} + +lorawan_status_t LoRaWANStack::drop_channel_list() +{ + return LORAWAN_STATUS_OK; +} + +lorawan_status_t LoRaWANStack::get_enabled_channels(lorawan_channelplan_t &channel_plan) +{ + return LORAWAN_STATUS_OK; +} + +lorawan_status_t LoRaWANStack::set_confirmed_msg_retry(uint8_t count) +{ + return LORAWAN_STATUS_OK; +} + +lorawan_status_t LoRaWANStack::set_channel_data_rate(uint8_t data_rate) +{ + return LORAWAN_STATUS_OK; +} + +lorawan_status_t LoRaWANStack::enable_adaptive_datarate(bool adr_enabled) +{ + return LORAWAN_STATUS_OK; +} + +lorawan_status_t LoRaWANStack::stop_sending(void) +{ + return LORAWAN_STATUS_OK; +} + +int16_t LoRaWANStack::handle_tx(const uint8_t port, const uint8_t *data, + uint16_t length, uint8_t flags, + bool null_allowed, bool allow_port_0) +{ + return 0; +} + +int16_t LoRaWANStack::handle_rx(uint8_t *data, uint16_t length, uint8_t &port, int &flags, bool validate_params) +{ + return 0; +} + +lorawan_status_t LoRaWANStack::set_link_check_request() +{ + return LORAWAN_STATUS_OK; +} + +void LoRaWANStack::remove_link_check_request() +{ +} + +lorawan_status_t LoRaWANStack::shutdown() +{ + return LORAWAN_STATUS_OK; +} + +lorawan_status_t LoRaWANStack::set_device_class(const device_class_t &device_class) +{ + return LORAWAN_STATUS_OK; +} + +lorawan_status_t LoRaWANStack::acquire_tx_metadata(lorawan_tx_metadata &tx_metadata) +{ + return LORAWAN_STATUS_OK; +} + +lorawan_status_t LoRaWANStack::acquire_rx_metadata(lorawan_rx_metadata &metadata) +{ + return LORAWAN_STATUS_OK; +} + +lorawan_status_t LoRaWANStack::acquire_backoff_metadata(int &backoff) +{ + return LORAWAN_STATUS_OK; +} + +/***************************************************************************** + * Interrupt handlers * + ****************************************************************************/ +void LoRaWANStack::tx_interrupt_handler(void) +{ +} + +void LoRaWANStack::rx_interrupt_handler(const uint8_t *payload, uint16_t size, + int16_t rssi, int8_t snr) +{ +} + +void LoRaWANStack::rx_error_interrupt_handler(void) +{ +} + +void LoRaWANStack::tx_timeout_interrupt_handler(void) +{ +} + +void LoRaWANStack::rx_timeout_interrupt_handler(void) +{ +} + +void LoRaWANStack::process_transmission_timeout() +{ +} + +void LoRaWANStack::process_transmission(void) +{ +} + +void LoRaWANStack::handle_ack_expiry_for_class_c(void) +{ +} + +void LoRaWANStack::handle_scheduling_failure(void) +{ +} + +void LoRaWANStack::process_reception(const uint8_t *const payload, uint16_t size, + int16_t rssi, int8_t snr) +{ +} + +void LoRaWANStack::process_reception_timeout(bool is_timeout) +{ +} + +void LoRaWANStack::make_tx_metadata_available(void) +{ +} + +void LoRaWANStack::make_rx_metadata_available(void) +{ +} + +bool LoRaWANStack::is_port_valid(const uint8_t port, bool allow_port_0) +{ + return true; +} + +lorawan_status_t LoRaWANStack::set_application_port(const uint8_t port, bool allow_port_0) +{ + return LORAWAN_STATUS_OK; +} + +void LoRaWANStack::state_machine_run_to_completion() +{ +} + +void LoRaWANStack::send_event_to_application(const lorawan_event_t event) const +{ +} + +void LoRaWANStack::send_automatic_uplink_message(const uint8_t port) +{ +} + +int LoRaWANStack::convert_to_msg_flag(const mcps_type_t type) +{ + return 0; +} + +lorawan_status_t LoRaWANStack::handle_connect(bool is_otaa) +{ + return LORAWAN_STATUS_OK; +} + +void LoRaWANStack::mlme_indication_handler() +{ +} + +void LoRaWANStack::mlme_confirm_handler() +{ +} + +void LoRaWANStack::mcps_confirm_handler() +{ +} + +void LoRaWANStack::mcps_indication_handler() +{ +} + +lorawan_status_t LoRaWANStack::state_controller(device_states_t new_state) +{ + return LORAWAN_STATUS_OK; +} + +void LoRaWANStack::process_shutdown_state(lorawan_status_t &op_status) +{ +} + +void LoRaWANStack::process_status_check_state() +{ +} + +void LoRaWANStack::process_scheduling_state(lorawan_status_t &op_status) +{ +} + +void LoRaWANStack::process_joining_state(lorawan_status_t &op_status) +{ +} + +void LoRaWANStack::process_connected_state() +{ +} + +void LoRaWANStack::process_connecting_state(lorawan_status_t &op_status) +{ +} + +void LoRaWANStack::process_idle_state(lorawan_status_t &op_status) +{ +} + +void LoRaWANStack::process_uninitialized_state(lorawan_status_t &op_status) +{ +} + diff --git a/UNITTESTS/stubs/LoRaWANTimer_stub.cpp b/UNITTESTS/stubs/LoRaWANTimer_stub.cpp new file mode 100644 index 0000000000..a66381c45f --- /dev/null +++ b/UNITTESTS/stubs/LoRaWANTimer_stub.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mbed_assert.h" +#include "LoRaWANTimer.h" + +#include "LoRaWANTimer_stub.h" + +lorawan_time_t LoRaWANTimer_stub::time_value = 0; +bool LoRaWANTimer_stub::call_cb_immediately = false; + +LoRaWANTimeHandler::LoRaWANTimeHandler() + : _queue(NULL) +{ +} + +LoRaWANTimeHandler::~LoRaWANTimeHandler() +{ +} + +void LoRaWANTimeHandler::activate_timer_subsystem(events::EventQueue *queue) +{ +} + +lorawan_time_t LoRaWANTimeHandler::get_current_time( void ) +{ + return LoRaWANTimer_stub::time_value; +} + +lorawan_time_t LoRaWANTimeHandler::get_elapsed_time(lorawan_time_t saved_time) +{ + return LoRaWANTimer_stub::time_value; +} + +void LoRaWANTimeHandler::init(timer_event_t &obj, mbed::Callback callback) +{ + if (callback && LoRaWANTimer_stub::call_cb_immediately) { + callback(); + } + obj.timer_id = 1; +} + +void LoRaWANTimeHandler::start(timer_event_t &obj, const uint32_t timeout) +{ +} + +void LoRaWANTimeHandler::stop(timer_event_t &obj) +{ + obj.timer_id = 0; +} diff --git a/UNITTESTS/stubs/LoRaWANTimer_stub.h b/UNITTESTS/stubs/LoRaWANTimer_stub.h new file mode 100644 index 0000000000..54a0f66633 --- /dev/null +++ b/UNITTESTS/stubs/LoRaWANTimer_stub.h @@ -0,0 +1,24 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "LoRaWANTimer.h" + +namespace LoRaWANTimer_stub +{ +extern lorawan_time_t time_value; +extern bool call_cb_immediately; +} diff --git a/UNITTESTS/stubs/MBRBlockDevice_stub.cpp b/UNITTESTS/stubs/MBRBlockDevice_stub.cpp new file mode 100644 index 0000000000..9759f749c9 --- /dev/null +++ b/UNITTESTS/stubs/MBRBlockDevice_stub.cpp @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2017, Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "MBRBlockDevice.h" +#include "mbed_critical.h" +#include + + +// On disk structures, all entries are little endian +MBED_PACKED(struct) mbr_entry { + uint8_t status; + uint8_t chs_start[3]; + uint8_t type; + uint8_t chs_stop[3]; + uint32_t lba_offset; + uint32_t lba_size; +}; + +MBED_PACKED(struct) mbr_table { + struct mbr_entry entries[4]; + uint8_t signature[2]; +}; + +// Little-endian conversion, should compile to noop +// if system is little-endian +static inline uint32_t tole32(uint32_t a) +{ + return 0; +} + +static inline uint32_t fromle32(uint32_t a) +{ + return 0; +} + +static void tochs(uint32_t lba, uint8_t chs[3]) +{ +} + + +// Partition after address are turned into absolute +// addresses, assumes bd is initialized +static int partition_absolute( + BlockDevice *bd, int part, uint8_t type, + bd_size_t offset, bd_size_t size) +{ + return 0; +} + +int MBRBlockDevice::partition(BlockDevice *bd, int part, uint8_t type, bd_addr_t start) +{ + return 0; +} + +int MBRBlockDevice::partition(BlockDevice *bd, int part, uint8_t type, + bd_addr_t start, bd_addr_t stop) +{ + return 0; +} + +MBRBlockDevice::MBRBlockDevice(BlockDevice *bd, int part) +{ +} + +int MBRBlockDevice::init() +{ + return 0; +} + +int MBRBlockDevice::deinit() +{ + return 0; +} + +int MBRBlockDevice::sync() +{ + return 0; +} + +int MBRBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int MBRBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int MBRBlockDevice::erase(bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +bd_size_t MBRBlockDevice::get_read_size() const +{ + return 0; +} + +bd_size_t MBRBlockDevice::get_program_size() const +{ + return 0; +} + +bd_size_t MBRBlockDevice::get_erase_size() const +{ + return 0; +} + +bd_size_t MBRBlockDevice::get_erase_size(bd_addr_t addr) const +{ + return 0; +} + +int MBRBlockDevice::get_erase_value() const +{ + return 0; +} + +bd_size_t MBRBlockDevice::size() const +{ + return 0; +} + +bd_size_t MBRBlockDevice::get_partition_start() const +{ + return 0; +} + +bd_size_t MBRBlockDevice::get_partition_stop() const +{ + return 0; +} + +uint8_t MBRBlockDevice::get_partition_type() const +{ + return 0; +} + +int MBRBlockDevice::get_partition_number() const +{ + return 0; +} diff --git a/UNITTESTS/stubs/Mutex_stub.cpp b/UNITTESTS/stubs/Mutex_stub.cpp index cd226064f8..153e8e5e19 100644 --- a/UNITTESTS/stubs/Mutex_stub.cpp +++ b/UNITTESTS/stubs/Mutex_stub.cpp @@ -27,11 +27,6 @@ rtos::Mutex::~Mutex() return; } -osStatus rtos::Mutex::lock(void) -{ - return osOK; -} - osStatus rtos::Mutex::lock(uint32_t millisec) { return osOK; diff --git a/features/cellular/UNITTESTS/stubs/NetworkInterface_stub.cpp b/UNITTESTS/stubs/NetworkInterface_stub.cpp similarity index 97% rename from features/cellular/UNITTESTS/stubs/NetworkInterface_stub.cpp rename to UNITTESTS/stubs/NetworkInterface_stub.cpp index 0e8eaa15a9..cfe6bdaa79 100644 --- a/features/cellular/UNITTESTS/stubs/NetworkInterface_stub.cpp +++ b/UNITTESTS/stubs/NetworkInterface_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Arm Limited and affiliates. + * Copyright (c) 2017, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/features/cellular/UNITTESTS/stubs/NetworkStack_stub.cpp b/UNITTESTS/stubs/NetworkStack_stub.cpp similarity index 97% rename from features/cellular/UNITTESTS/stubs/NetworkStack_stub.cpp rename to UNITTESTS/stubs/NetworkStack_stub.cpp index 372812effb..2d3a451a3c 100644 --- a/features/cellular/UNITTESTS/stubs/NetworkStack_stub.cpp +++ b/UNITTESTS/stubs/NetworkStack_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Arm Limited and affiliates. + * Copyright (c) 2017, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/UNITTESTS/stubs/NetworkStack_stub.h b/UNITTESTS/stubs/NetworkStack_stub.h index 2d18f94873..3a8955a6e0 100644 --- a/UNITTESTS/stubs/NetworkStack_stub.h +++ b/UNITTESTS/stubs/NetworkStack_stub.h @@ -19,10 +19,11 @@ #define NETWORKSTACKSTUB_H #include "netsocket/NetworkStack.h" - +#include class NetworkStackstub : public NetworkStack { public: + std::list return_values; nsapi_error_t return_value = 0; virtual const char *get_ip_address() { @@ -46,6 +47,11 @@ public: protected: virtual nsapi_error_t socket_open(nsapi_socket_t *handle, nsapi_protocol_t proto) { + if (return_value == NSAPI_ERROR_OK && return_values.front() == NSAPI_ERROR_OK) + { + // Make sure a non-NULL value is returned if error is not expected + *handle = reinterpret_cast(1234); + } return return_value; }; virtual nsapi_error_t socket_close(nsapi_socket_t handle) @@ -62,6 +68,12 @@ protected: }; virtual nsapi_error_t socket_connect(nsapi_socket_t handle, const SocketAddress &address) { + if (!return_values.empty()) + { + nsapi_error_t ret = return_values.front(); + return_values.pop_front(); + return ret; + } return return_value; }; virtual nsapi_error_t socket_accept(nsapi_socket_t server, @@ -72,11 +84,23 @@ protected: virtual nsapi_size_or_error_t socket_send(nsapi_socket_t handle, const void *data, nsapi_size_t size) { + if (!return_values.empty()) + { + nsapi_error_t ret = return_values.front(); + return_values.pop_front(); + return ret; + } return return_value; }; virtual nsapi_size_or_error_t socket_recv(nsapi_socket_t handle, void *data, nsapi_size_t size) { + if (!return_values.empty()) + { + nsapi_error_t ret = return_values.front(); + return_values.pop_front(); + return ret; + } return return_value; }; virtual nsapi_size_or_error_t socket_sendto(nsapi_socket_t handle, const SocketAddress &address, @@ -87,6 +111,12 @@ protected: virtual nsapi_size_or_error_t socket_recvfrom(nsapi_socket_t handle, SocketAddress *address, void *buffer, nsapi_size_t size) { + if (!return_values.empty()) + { + nsapi_error_t ret = return_values.front(); + return_values.pop_front(); + return ret; + } return return_value; }; virtual void socket_attach(nsapi_socket_t handle, void (*callback)(void *), void *data) {}; diff --git a/UNITTESTS/stubs/ObservingBlockDevice_stub.cpp b/UNITTESTS/stubs/ObservingBlockDevice_stub.cpp new file mode 100644 index 0000000000..550bf722a3 --- /dev/null +++ b/UNITTESTS/stubs/ObservingBlockDevice_stub.cpp @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2017, Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ObservingBlockDevice.h" +#include "ReadOnlyBlockDevice.h" +#include "mbed.h" + + +ObservingBlockDevice::ObservingBlockDevice(BlockDevice *bd) +{ + // Does nothing +} + +ObservingBlockDevice::~ObservingBlockDevice() +{ + // Does nothing +} + +void ObservingBlockDevice::attach(Callback cb) +{ +} + +int ObservingBlockDevice::init() +{ + return 0; +} + +int ObservingBlockDevice::deinit() +{ + return 0; +} + +int ObservingBlockDevice::sync() +{ + return 0; +} + +int ObservingBlockDevice::read(void *buffer, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int ObservingBlockDevice::program(const void *buffer, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int ObservingBlockDevice::erase(bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +bd_size_t ObservingBlockDevice::get_read_size() const +{ + return 0; +} + +bd_size_t ObservingBlockDevice::get_program_size() const +{ + return 0; +} + +bd_size_t ObservingBlockDevice::get_erase_size() const +{ + return 0; +} + +bd_size_t ObservingBlockDevice::get_erase_size(bd_addr_t addr) const +{ + return 0; +} + +int ObservingBlockDevice::get_erase_value() const +{ + return 0; +} + +bd_size_t ObservingBlockDevice::size() const +{ + return 0; +} diff --git a/UNITTESTS/stubs/ProfilingBlockDevice_stub.cpp b/UNITTESTS/stubs/ProfilingBlockDevice_stub.cpp new file mode 100644 index 0000000000..52a94fa5b1 --- /dev/null +++ b/UNITTESTS/stubs/ProfilingBlockDevice_stub.cpp @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2017, Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ProfilingBlockDevice.h" + + +ProfilingBlockDevice::ProfilingBlockDevice(BlockDevice *bd) +{ +} + +int ProfilingBlockDevice::init() +{ + return 0; +} + +int ProfilingBlockDevice::deinit() +{ + return 0; +} + +int ProfilingBlockDevice::sync() +{ + return 0; +} + +int ProfilingBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int ProfilingBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int ProfilingBlockDevice::erase(bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +bd_size_t ProfilingBlockDevice::get_read_size() const +{ + return 0; +} + +bd_size_t ProfilingBlockDevice::get_program_size() const +{ + return 0; +} + +bd_size_t ProfilingBlockDevice::get_erase_size() const +{ + return 0; +} + +bd_size_t ProfilingBlockDevice::get_erase_size(bd_addr_t addr) const +{ + return 0; +} + +int ProfilingBlockDevice::get_erase_value() const +{ + return 0; +} + +bd_size_t ProfilingBlockDevice::size() const +{ + return 0; +} + +void ProfilingBlockDevice::reset() +{ +} + +bd_size_t ProfilingBlockDevice::get_read_count() const +{ + return 0; +} + +bd_size_t ProfilingBlockDevice::get_program_count() const +{ + return 0; +} + +bd_size_t ProfilingBlockDevice::get_erase_count() const +{ + return 0; +} diff --git a/UNITTESTS/stubs/ReadOnlyBlockDevice_stub.cpp b/UNITTESTS/stubs/ReadOnlyBlockDevice_stub.cpp new file mode 100644 index 0000000000..17a42915bb --- /dev/null +++ b/UNITTESTS/stubs/ReadOnlyBlockDevice_stub.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ReadOnlyBlockDevice.h" +#include "mbed_error.h" + + +ReadOnlyBlockDevice::ReadOnlyBlockDevice(BlockDevice *bd) +{ + // Does nothing +} + +ReadOnlyBlockDevice::~ReadOnlyBlockDevice() +{ + // Does nothing +} + +int ReadOnlyBlockDevice::init() +{ + return 0; +} + +int ReadOnlyBlockDevice::deinit() +{ + return 0; +} + +int ReadOnlyBlockDevice::sync() +{ + return 0; +} + +int ReadOnlyBlockDevice::read(void *buffer, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int ReadOnlyBlockDevice::program(const void *buffer, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int ReadOnlyBlockDevice::erase(bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +bd_size_t ReadOnlyBlockDevice::get_read_size() const +{ + return 0; +} + +bd_size_t ReadOnlyBlockDevice::get_program_size() const +{ + return 0; +} + +bd_size_t ReadOnlyBlockDevice::get_erase_size() const +{ + return 0; +} + +bd_size_t ReadOnlyBlockDevice::get_erase_size(bd_addr_t addr) const +{ + return 0; +} + +int ReadOnlyBlockDevice::get_erase_value() const +{ + return 0; +} + +bd_size_t ReadOnlyBlockDevice::size() const +{ + return 0; +} diff --git a/features/cellular/UNITTESTS/stubs/Semaphore_stub.cpp b/UNITTESTS/stubs/Semaphore_stub.cpp similarity index 100% rename from features/cellular/UNITTESTS/stubs/Semaphore_stub.cpp rename to UNITTESTS/stubs/Semaphore_stub.cpp diff --git a/UNITTESTS/stubs/SlicingBlockDevice_stub.cpp b/UNITTESTS/stubs/SlicingBlockDevice_stub.cpp new file mode 100644 index 0000000000..d0b75ee194 --- /dev/null +++ b/UNITTESTS/stubs/SlicingBlockDevice_stub.cpp @@ -0,0 +1,84 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "SlicingBlockDevice.h" + + +SlicingBlockDevice::SlicingBlockDevice(BlockDevice *bd, bd_addr_t start, bd_addr_t stop) +{ + +} + +int SlicingBlockDevice::init() +{ + return 0; +} + +int SlicingBlockDevice::deinit() +{ + return 0; +} + +int SlicingBlockDevice::sync() +{ + return 0; +} + +int SlicingBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int SlicingBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +int SlicingBlockDevice::erase(bd_addr_t addr, bd_size_t size) +{ + return 0; +} + +bd_size_t SlicingBlockDevice::get_read_size() const +{ + return 0; +} + +bd_size_t SlicingBlockDevice::get_program_size() const +{ + return 0; +} + +bd_size_t SlicingBlockDevice::get_erase_size() const +{ + return 0; +} + +bd_size_t SlicingBlockDevice::get_erase_size(bd_addr_t addr) const +{ + return 0; +} + +int SlicingBlockDevice::get_erase_value() const +{ + return 0; +} + +bd_size_t SlicingBlockDevice::size() const +{ + return 0; +} diff --git a/features/cellular/UNITTESTS/stubs/SocketAddress_stub.cpp b/UNITTESTS/stubs/SocketAddress_stub.cpp similarity index 85% rename from features/cellular/UNITTESTS/stubs/SocketAddress_stub.cpp rename to UNITTESTS/stubs/SocketAddress_stub.cpp index 76e02aa12b..874e5ce667 100644 --- a/features/cellular/UNITTESTS/stubs/SocketAddress_stub.cpp +++ b/UNITTESTS/stubs/SocketAddress_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Arm Limited and affiliates. + * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -22,40 +22,16 @@ #include "mbed.h" -static bool ipv4_is_valid(const char *addr) -{ - return false; -} - static bool ipv6_is_valid(const char *addr) { return false; } -static void ipv4_from_address(uint8_t *bytes, const char *addr) -{ - -} - static int ipv6_scan_chunk(uint16_t *shorts, const char *chunk) { return 0; } -static void ipv6_from_address(uint8_t *bytes, const char *addr) -{ - -} - -static void ipv4_to_address(char *addr, const uint8_t *bytes) -{ - -} - -static void ipv6_to_address(char *addr, const uint8_t *bytes) -{ -} - SocketAddress::SocketAddress(nsapi_addr_t addr, uint16_t port) { diff --git a/features/cellular/UNITTESTS/stubs/Thread_stub.cpp b/UNITTESTS/stubs/Thread_stub.cpp similarity index 100% rename from features/cellular/UNITTESTS/stubs/Thread_stub.cpp rename to UNITTESTS/stubs/Thread_stub.cpp diff --git a/features/cellular/UNITTESTS/stubs/Timer_stub.cpp b/UNITTESTS/stubs/Timer_stub.cpp similarity index 100% rename from features/cellular/UNITTESTS/stubs/Timer_stub.cpp rename to UNITTESTS/stubs/Timer_stub.cpp diff --git a/features/cellular/UNITTESTS/stubs/Timer_stub.h b/UNITTESTS/stubs/Timer_stub.h similarity index 99% rename from features/cellular/UNITTESTS/stubs/Timer_stub.h rename to UNITTESTS/stubs/Timer_stub.h index 699fdd0c53..a97333fe63 100644 --- a/features/cellular/UNITTESTS/stubs/Timer_stub.h +++ b/UNITTESTS/stubs/Timer_stub.h @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef TIMER_STUB_H #define TIMER_STUB_H diff --git a/UNITTESTS/stubs/aes_stub.c b/UNITTESTS/stubs/aes_stub.c new file mode 100644 index 0000000000..fad4b276f1 --- /dev/null +++ b/UNITTESTS/stubs/aes_stub.c @@ -0,0 +1,232 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "mbedtls/config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include + +#include "mbedtls/aes.h" + +#include "aes_stub.h" +aes_stub_def aes_stub; + + +void mbedtls_aes_init( mbedtls_aes_context *ctx ) +{ +} + +void mbedtls_aes_free( mbedtls_aes_context *ctx ) +{ +} + +#if defined(MBEDTLS_CIPHER_MODE_XTS) +void mbedtls_aes_xts_init( mbedtls_aes_xts_context *ctx ) +{ +} + +void mbedtls_aes_xts_free( mbedtls_aes_xts_context *ctx ) +{ +} +#endif + +#if !defined(MBEDTLS_AES_SETKEY_ENC_ALT) +int mbedtls_aes_setkey_enc( mbedtls_aes_context *ctx, const unsigned char *key, + unsigned int keybits ) +{ + if (aes_stub.int_zero_counter) { + aes_stub.int_zero_counter--; + return 0; + } + return aes_stub.int_value; +} +#endif + +#if !defined(MBEDTLS_AES_SETKEY_DEC_ALT) +int mbedtls_aes_setkey_dec( mbedtls_aes_context *ctx, const unsigned char *key, + unsigned int keybits ) +{ + if (aes_stub.int_zero_counter) { + aes_stub.int_zero_counter--; + return 0; + } + return aes_stub.int_value; +} +#endif + +#if defined(MBEDTLS_CIPHER_MODE_XTS) +int mbedtls_aes_xts_setkey_enc( mbedtls_aes_xts_context *ctx, + const unsigned char *key, + unsigned int keybits) +{ + if (aes_stub.int_zero_counter) { + aes_stub.int_zero_counter--; + return 0; + } + return aes_stub.int_value; +} + +int mbedtls_aes_xts_setkey_dec( mbedtls_aes_xts_context *ctx, + const unsigned char *key, + unsigned int keybits) +{ + if (aes_stub.int_zero_counter) { + aes_stub.int_zero_counter--; + return 0; + } + return aes_stub.int_value; +} +#endif + +int mbedtls_internal_aes_encrypt( mbedtls_aes_context *ctx, + const unsigned char input[16], + unsigned char output[16] ) +{ + if (aes_stub.int_zero_counter) { + aes_stub.int_zero_counter--; + return 0; + } + return aes_stub.int_value; +} + +void mbedtls_aes_encrypt( mbedtls_aes_context *ctx, + const unsigned char input[16], + unsigned char output[16] ) +{ +} + +int mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx, + const unsigned char input[16], + unsigned char output[16] ) +{ + if (aes_stub.int_zero_counter) { + aes_stub.int_zero_counter--; + return 0; + } + return aes_stub.int_value; +} + +void mbedtls_aes_decrypt( mbedtls_aes_context *ctx, + const unsigned char input[16], + unsigned char output[16] ) +{ +} + +int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx, + int mode, + const unsigned char input[16], + unsigned char output[16] ) +{ + if (aes_stub.int_zero_counter) { + aes_stub.int_zero_counter--; + return 0; + } + return aes_stub.int_value; +} + +int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx, + int mode, + size_t length, + unsigned char iv[16], + const unsigned char *input, + unsigned char *output ) +{ + if (aes_stub.int_zero_counter) { + aes_stub.int_zero_counter--; + return 0; + } + return aes_stub.int_value; +} + + +#if defined(MBEDTLS_CIPHER_MODE_XTS) +int mbedtls_aes_crypt_xts( mbedtls_aes_xts_context *ctx, + int mode, + size_t length, + const unsigned char data_unit[16], + const unsigned char *input, + unsigned char *output ) +{ + if (aes_stub.int_zero_counter) { + aes_stub.int_zero_counter--; + return 0; + } + return aes_stub.int_value; +} +#endif + +int mbedtls_aes_crypt_cfb128( mbedtls_aes_context *ctx, + int mode, + size_t length, + size_t *iv_off, + unsigned char iv[16], + const unsigned char *input, + unsigned char *output ) +{ + if (aes_stub.int_zero_counter) { + aes_stub.int_zero_counter--; + return 0; + } + return aes_stub.int_value; +} + +int mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx, + int mode, + size_t length, + unsigned char iv[16], + const unsigned char *input, + unsigned char *output ) +{ + if (aes_stub.int_zero_counter) { + aes_stub.int_zero_counter--; + return 0; + } + return aes_stub.int_value; +} + +int mbedtls_aes_crypt_ofb( mbedtls_aes_context *ctx, + size_t length, + size_t *iv_off, + unsigned char iv[16], + const unsigned char *input, + unsigned char *output ) +{ + if (aes_stub.int_zero_counter) { + aes_stub.int_zero_counter--; + return 0; + } + return aes_stub.int_value; +} + +int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx, + size_t length, + size_t *nc_off, + unsigned char nonce_counter[16], + unsigned char stream_block[16], + const unsigned char *input, + unsigned char *output ) +{ + if (aes_stub.int_zero_counter) { + aes_stub.int_zero_counter--; + return 0; + } + return aes_stub.int_value; +} diff --git a/UNITTESTS/stubs/aes_stub.h b/UNITTESTS/stubs/aes_stub.h new file mode 100644 index 0000000000..c361b0a031 --- /dev/null +++ b/UNITTESTS/stubs/aes_stub.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include + +typedef struct { + int int_value; + uint8_t int_zero_counter; +} aes_stub_def; + +extern aes_stub_def aes_stub; diff --git a/UNITTESTS/stubs/cipher_stub.c b/UNITTESTS/stubs/cipher_stub.c new file mode 100644 index 0000000000..e55a685193 --- /dev/null +++ b/UNITTESTS/stubs/cipher_stub.c @@ -0,0 +1,213 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "mbedtls/config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "mbedtls/cipher.h" +#include "mbedtls/cipher_internal.h" +#include "mbedtls/platform_util.h" + +#include +#include + +#if defined(MBEDTLS_GCM_C) +#include "mbedtls/gcm.h" +#endif + +#if defined(MBEDTLS_CCM_C) +#include "mbedtls/ccm.h" +#endif + +#if defined(MBEDTLS_CMAC_C) +#include "mbedtls/cmac.h" +#endif + +#include "cipher_stub.h" + +cipher_stub_def cipher_stub; + +const int *mbedtls_cipher_list( void ) +{ + return cipher_stub.int_ptr; +} + +const mbedtls_cipher_info_t *mbedtls_cipher_info_from_type( const mbedtls_cipher_type_t cipher_type ) +{ + return cipher_stub.info_value; +} + +const mbedtls_cipher_info_t *mbedtls_cipher_info_from_string( const char *cipher_name ) +{ + return cipher_stub.info_value; +} + +const mbedtls_cipher_info_t *mbedtls_cipher_info_from_values( const mbedtls_cipher_id_t cipher_id, + int key_bitlen, + const mbedtls_cipher_mode_t mode ) +{ + return cipher_stub.info_value; +} + +void mbedtls_cipher_init( mbedtls_cipher_context_t *ctx ) +{ +} + +void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx ) +{ +} + +int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, const mbedtls_cipher_info_t *cipher_info ) +{ + if (cipher_stub.int_zero_counter) { + cipher_stub.int_zero_counter--; + return 0; + } + return cipher_stub.int_value; +} + +int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, const unsigned char *key, + int key_bitlen, const mbedtls_operation_t operation ) +{ + if (cipher_stub.int_zero_counter) { + cipher_stub.int_zero_counter--; + return 0; + } + return cipher_stub.int_value; +} + +int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx, + const unsigned char *iv, size_t iv_len ) +{ + if (cipher_stub.int_zero_counter) { + cipher_stub.int_zero_counter--; + return 0; + } + return cipher_stub.int_value; +} + +int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx ) +{ + if (cipher_stub.int_zero_counter) { + cipher_stub.int_zero_counter--; + return 0; + } + return cipher_stub.int_value; +} + +int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx, + const unsigned char *ad, size_t ad_len ) +{ + if (cipher_stub.int_zero_counter) { + cipher_stub.int_zero_counter--; + return 0; + } + return cipher_stub.int_value; +} + +int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *input, + size_t ilen, unsigned char *output, size_t *olen ) +{ + if (cipher_stub.int_zero_counter) { + cipher_stub.int_zero_counter--; + return 0; + } + return cipher_stub.int_value; +} + +int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx, + unsigned char *output, size_t *olen ) +{ + if (cipher_stub.int_zero_counter) { + cipher_stub.int_zero_counter--; + return 0; + } + return cipher_stub.int_value; +} + +int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, mbedtls_cipher_padding_t mode ) +{ + if (cipher_stub.int_zero_counter) { + cipher_stub.int_zero_counter--; + return 0; + } + return cipher_stub.int_value; +} + +int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx, + unsigned char *tag, size_t tag_len ) +{ + if (cipher_stub.int_zero_counter) { + cipher_stub.int_zero_counter--; + return 0; + } + return cipher_stub.int_value; +} + +int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx, + const unsigned char *tag, size_t tag_len ) +{ + if (cipher_stub.int_zero_counter) { + cipher_stub.int_zero_counter--; + return 0; + } + return cipher_stub.int_value; +} + +int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx, + const unsigned char *iv, size_t iv_len, + const unsigned char *input, size_t ilen, + unsigned char *output, size_t *olen ) +{ + if (cipher_stub.int_zero_counter) { + cipher_stub.int_zero_counter--; + return 0; + } + return cipher_stub.int_value; +} + +int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx, + const unsigned char *iv, size_t iv_len, + const unsigned char *ad, size_t ad_len, + const unsigned char *input, size_t ilen, + unsigned char *output, size_t *olen, + unsigned char *tag, size_t tag_len ) +{ + if (cipher_stub.int_zero_counter) { + cipher_stub.int_zero_counter--; + return 0; + } + return cipher_stub.int_value; +} + +int mbedtls_cipher_auth_decrypt( mbedtls_cipher_context_t *ctx, + const unsigned char *iv, size_t iv_len, + const unsigned char *ad, size_t ad_len, + const unsigned char *input, size_t ilen, + unsigned char *output, size_t *olen, + const unsigned char *tag, size_t tag_len ) +{ + if (cipher_stub.int_zero_counter) { + cipher_stub.int_zero_counter--; + return 0; + } + return cipher_stub.int_value; +} + diff --git a/UNITTESTS/stubs/cipher_stub.h b/UNITTESTS/stubs/cipher_stub.h new file mode 100644 index 0000000000..9a16f04666 --- /dev/null +++ b/UNITTESTS/stubs/cipher_stub.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "mbedtls/cipher.h" + +typedef struct { + mbedtls_cipher_info_t *info_value; + int int_value; + int *int_ptr; + uint8_t int_zero_counter; +} cipher_stub_def; + +extern cipher_stub_def cipher_stub; diff --git a/UNITTESTS/stubs/cmac_stub.c b/UNITTESTS/stubs/cmac_stub.c new file mode 100644 index 0000000000..382579fe1a --- /dev/null +++ b/UNITTESTS/stubs/cmac_stub.c @@ -0,0 +1,94 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "mbedtls/config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + + +#include "mbedtls/cmac.h" +#include "mbedtls/platform_util.h" +#include + +#include "cmac_stub.h" + +cmac_stub_def cmac_stub; + +int mbedtls_cipher_cmac_starts( mbedtls_cipher_context_t *ctx, + const unsigned char *key, size_t keybits ) +{ + if (cmac_stub.int_zero_counter) { + cmac_stub.int_zero_counter--; + return 0; + } + return cmac_stub.int_value; +} + +int mbedtls_cipher_cmac_update( mbedtls_cipher_context_t *ctx, + const unsigned char *input, size_t ilen ) +{ + if (cmac_stub.int_zero_counter) { + cmac_stub.int_zero_counter--; + return 0; + } + return cmac_stub.int_value; +} + +int mbedtls_cipher_cmac_finish( mbedtls_cipher_context_t *ctx, + unsigned char *output ) +{ + if (cmac_stub.int_zero_counter) { + cmac_stub.int_zero_counter--; + return 0; + } + return cmac_stub.int_value; +} + +int mbedtls_cipher_cmac_reset( mbedtls_cipher_context_t *ctx ) +{ + if (cmac_stub.int_zero_counter) { + cmac_stub.int_zero_counter--; + return 0; + } + return cmac_stub.int_value; +} + +int mbedtls_cipher_cmac( const mbedtls_cipher_info_t *cipher_info, + const unsigned char *key, size_t keylen, + const unsigned char *input, size_t ilen, + unsigned char *output ) +{ + if (cmac_stub.int_zero_counter) { + cmac_stub.int_zero_counter--; + return 0; + } + return cmac_stub.int_value; +} + +int mbedtls_aes_cmac_prf_128( const unsigned char *key, size_t key_length, + const unsigned char *input, size_t in_len, + unsigned char *output ) +{ + if (cmac_stub.int_zero_counter) { + cmac_stub.int_zero_counter--; + return 0; + } + return cmac_stub.int_value; +} + diff --git a/UNITTESTS/stubs/cmac_stub.h b/UNITTESTS/stubs/cmac_stub.h new file mode 100644 index 0000000000..4134f9d6cf --- /dev/null +++ b/UNITTESTS/stubs/cmac_stub.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include + +typedef struct { + int int_value; + uint8_t int_zero_counter; +} cmac_stub_def; + +extern cmac_stub_def cmac_stub; diff --git a/UNITTESTS/stubs/equeue_stub.c b/UNITTESTS/stubs/equeue_stub.c index bd9852bec2..4fea449ab1 100644 --- a/UNITTESTS/stubs/equeue_stub.c +++ b/UNITTESTS/stubs/equeue_stub.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Arm Limited and affiliates. + * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,25 +15,100 @@ * limitations under the License. */ -#include "equeue/equeue.h" +#include "equeue.h" +#include -void *equeue_alloc(equeue_t *q, size_t size) -{ -} +#include "equeue_stub.h" -int equeue_post(equeue_t *q, void (*cb)(void *), void *p) +equeue_stub_def equeue_stub; + +int equeue_create(equeue_t *queue, size_t size) { return 0; } -void equeue_event_delay(void *p, int ms) +int equeue_create_inplace(equeue_t *queue, size_t size, void *buffer) { + return 0; } -void equeue_event_period(void *p, int ms) +void equeue_destroy(equeue_t *queue) { + } -void equeue_event_dtor(void *p, void (*dtor)(void *)) +void equeue_dispatch(equeue_t *queue, int ms) { + +} + +void equeue_break(equeue_t *queue) +{ + +} + +int equeue_call(equeue_t *queue, void (*cb)(void *), void *data) +{ + return 0; +} + +int equeue_call_every(equeue_t *queue, int ms, void (*cb)(void *), void *data) +{ + return 0; +} + +void *equeue_alloc(equeue_t *queue, size_t size) +{ + return equeue_stub.void_ptr; +} + +void equeue_dealloc(equeue_t *queue, void *event) +{ + +} + +void equeue_event_delay(void *event, int ms) +{ + +} + +void equeue_event_period(void *event, int ms) +{ + +} + +void equeue_event_dtor(void *event, void (*dtor)(void *)) +{ + +} + +int equeue_post(equeue_t *queue, void (*cb)(void *), void *event) +{ + struct equeue_event *e = (struct equeue_event*)event - 1; + if (cb && equeue_stub.call_cb_immediately) { + cb(e + 1); + return 1; + } + return 0; +} + +void equeue_cancel(equeue_t *queue, int id) +{ + +} + +void equeue_background(equeue_t *queue, + void (*update)(void *timer, int ms), void *timer) +{ + +} + +void equeue_chain(equeue_t *queue, equeue_t *target) +{ + +} + +int equeue_call_in(equeue_t *q, int ms, void (*cb)(void*), void *data) { + // The stub does not implement the delay mechanism. + return equeue_post(q, cb, data); } diff --git a/UNITTESTS/stubs/equeue_stub.h b/UNITTESTS/stubs/equeue_stub.h new file mode 100644 index 0000000000..648d920058 --- /dev/null +++ b/UNITTESTS/stubs/equeue_stub.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "stdint.h" +#include "stdbool.h" + +typedef struct { + void *void_ptr; + bool call_cb_immediately; +} equeue_stub_def; + +extern equeue_stub_def equeue_stub; diff --git a/UNITTESTS/stubs/ip4tos_stub.c b/UNITTESTS/stubs/ip4tos_stub.c new file mode 100644 index 0000000000..c45c1383bb --- /dev/null +++ b/UNITTESTS/stubs/ip4tos_stub.c @@ -0,0 +1,32 @@ +/* + * Copyright (c) , Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "common_functions.h" +#include "ip4string.h" + +static void ipv4_itoa(char *string, uint8_t byte); + +uint_fast8_t ip4tos(const void *ip4addr, char *p) +{ + return 0; +} + +static void ipv4_itoa(char *string, uint8_t byte) +{ +} diff --git a/UNITTESTS/stubs/mbed_assert_stub.c b/UNITTESTS/stubs/mbed_assert_stub.c index 9029a6192d..afe6fb3ff3 100644 --- a/UNITTESTS/stubs/mbed_assert_stub.c +++ b/UNITTESTS/stubs/mbed_assert_stub.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Arm Limited and affiliates. + * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/UNITTESTS/stubs/mbed_critical_stub.c b/UNITTESTS/stubs/mbed_critical_stub.c new file mode 100644 index 0000000000..ca08e252d4 --- /dev/null +++ b/UNITTESTS/stubs/mbed_critical_stub.c @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2017, Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Declare __STDC_LIMIT_MACROS so stdint.h defines UINT32_MAX when using C++ */ +#define __STDC_LIMIT_MACROS +#include "hal/critical_section_api.h" + +#include "cmsis.h" +#include "platform/mbed_assert.h" +#include "platform/mbed_critical.h" +#include "platform/mbed_toolchain.h" + +static volatile uint32_t critical_section_reentrancy_counter = 0; + +bool core_util_are_interrupts_enabled(void) +{ + return false; +} + +bool core_util_is_isr_active(void) +{ + return false; +} + +bool core_util_in_critical_section(void) +{ + return false; +} + +void core_util_critical_section_enter(void) +{ +} + +void core_util_critical_section_exit(void) +{ +} + +bool core_util_atomic_cas_u8(volatile uint8_t *ptr, uint8_t *expectedCurrentValue, uint8_t desiredValue) +{ + return false; +} + +bool core_util_atomic_cas_u16(volatile uint16_t *ptr, uint16_t *expectedCurrentValue, uint16_t desiredValue) +{ + return false; +} + + +bool core_util_atomic_cas_u32(volatile uint32_t *ptr, uint32_t *expectedCurrentValue, uint32_t desiredValue) +{ + return false; +} + + +uint8_t core_util_atomic_incr_u8(volatile uint8_t *valuePtr, uint8_t delta) +{ + return 0; +} + +uint16_t core_util_atomic_incr_u16(volatile uint16_t *valuePtr, uint16_t delta) +{ + return 0; +} + +uint32_t core_util_atomic_incr_u32(volatile uint32_t *valuePtr, uint32_t delta) +{ + return 0; +} + + +uint8_t core_util_atomic_decr_u8(volatile uint8_t *valuePtr, uint8_t delta) +{ + return 0; +} + +uint16_t core_util_atomic_decr_u16(volatile uint16_t *valuePtr, uint16_t delta) +{ + return 0; +} + +uint32_t core_util_atomic_decr_u32(volatile uint32_t *valuePtr, uint32_t delta) +{ + return 0; +} + + +bool core_util_atomic_cas_ptr(void *volatile *ptr, void **expectedCurrentValue, void *desiredValue) +{ + return false; +} + +void *core_util_atomic_incr_ptr(void *volatile *valuePtr, ptrdiff_t delta) +{ + return NULL; +} + +void *core_util_atomic_decr_ptr(void *volatile *valuePtr, ptrdiff_t delta) +{ + return NULL; +} + diff --git a/features/cellular/UNITTESTS/stubs/mbed_poll_stub.cpp b/UNITTESTS/stubs/mbed_poll_stub.cpp similarity index 94% rename from features/cellular/UNITTESTS/stubs/mbed_poll_stub.cpp rename to UNITTESTS/stubs/mbed_poll_stub.cpp index 1914399d2a..4db534ed10 100644 --- a/features/cellular/UNITTESTS/stubs/mbed_poll_stub.cpp +++ b/UNITTESTS/stubs/mbed_poll_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) , Arm Limited and affiliates. + * Copyright (c) 2017, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/features/cellular/UNITTESTS/stubs/mbed_poll_stub.h b/UNITTESTS/stubs/mbed_poll_stub.h similarity index 93% rename from features/cellular/UNITTESTS/stubs/mbed_poll_stub.h rename to UNITTESTS/stubs/mbed_poll_stub.h index 6c0a4327a9..930766e840 100644 --- a/features/cellular/UNITTESTS/stubs/mbed_poll_stub.h +++ b/UNITTESTS/stubs/mbed_poll_stub.h @@ -1,5 +1,5 @@ /* - * Copyright (c) , Arm Limited and affiliates. + * Copyright (c) 2017, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef __MBED_POLL_STUB_H__ #define __MBED_POLL_STUB_H__ diff --git a/UNITTESTS/stubs/mbed_shared_queues_stub.cpp b/UNITTESTS/stubs/mbed_shared_queues_stub.cpp index e0c0c2ba20..7f0474badc 100644 --- a/UNITTESTS/stubs/mbed_shared_queues_stub.cpp +++ b/UNITTESTS/stubs/mbed_shared_queues_stub.cpp @@ -21,8 +21,9 @@ using namespace events; namespace mbed { +EventQueue *mbed_shared_queue_stub; EventQueue *mbed_event_queue() { - return 0; + return mbed_shared_queue_stub; } } // namespace mbed diff --git a/features/cellular/UNITTESTS/stubs/mbed_wait_api_stub.cpp b/UNITTESTS/stubs/mbed_wait_api_stub.cpp similarity index 93% rename from features/cellular/UNITTESTS/stubs/mbed_wait_api_stub.cpp rename to UNITTESTS/stubs/mbed_wait_api_stub.cpp index f8b240544d..68a265308c 100644 --- a/features/cellular/UNITTESTS/stubs/mbed_wait_api_stub.cpp +++ b/UNITTESTS/stubs/mbed_wait_api_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) , Arm Limited and affiliates. + * Copyright (c) 2017, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/UNITTESTS/stubs/nsapi_dns_stub.cpp b/UNITTESTS/stubs/nsapi_dns_stub.cpp index dcfe7ef0a3..6fd0f92de9 100644 --- a/UNITTESTS/stubs/nsapi_dns_stub.cpp +++ b/UNITTESTS/stubs/nsapi_dns_stub.cpp @@ -19,6 +19,8 @@ nsapi_error_t nsapi_stub_return_value = NSAPI_ERROR_DNS_FAILURE; +NetworkStack::hostbyname_cb_t query_callback; +call_in_callback_cb_t callin_callback; nsapi_error_t nsapi_dns_query(NetworkStack *stack, const char *host, SocketAddress *addr, nsapi_version_t version) @@ -30,6 +32,8 @@ nsapi_error_t nsapi_dns_query_async(NetworkStack *stack, const char *host, NetworkStack::hostbyname_cb_t callback, call_in_callback_cb_t call_in_cb, nsapi_version_t version) { + query_callback = callback; + callin_callback = call_in_cb; return nsapi_stub_return_value; } diff --git a/UNITTESTS/stubs/nvic_wrapper_stub.c b/UNITTESTS/stubs/nvic_wrapper_stub.c index 636f05bae5..9cd88195c0 100644 --- a/UNITTESTS/stubs/nvic_wrapper_stub.c +++ b/UNITTESTS/stubs/nvic_wrapper_stub.c @@ -1,3 +1,20 @@ +/* + * Copyright (c) 2017, Arm Limited and affiliates. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + #include "nvic_wrapper.h" void NVIC_SystemReset(void) {} diff --git a/UNITTESTS/stubs/randLIB_stub.c b/UNITTESTS/stubs/randLIB_stub.c index 97154cf2ee..e9fd486adb 100644 --- a/UNITTESTS/stubs/randLIB_stub.c +++ b/UNITTESTS/stubs/randLIB_stub.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014-2017, Arm Limited and affiliates. + * Copyright (c) 2017, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include #include #include diff --git a/features/cellular/UNITTESTS/stubs/randLIB_stub.cpp b/UNITTESTS/stubs/randLIB_stub.cpp similarity index 99% rename from features/cellular/UNITTESTS/stubs/randLIB_stub.cpp rename to UNITTESTS/stubs/randLIB_stub.cpp index 61cd893d0e..28989c444e 100644 --- a/features/cellular/UNITTESTS/stubs/randLIB_stub.cpp +++ b/UNITTESTS/stubs/randLIB_stub.cpp @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "randLIB.h" void randLIB_seed_random(void) diff --git a/features/cellular/UNITTESTS/stubs/EventQueue_stub.cpp b/UNITTESTS/stubs/stoip4_stub.c similarity index 58% rename from features/cellular/UNITTESTS/stubs/EventQueue_stub.cpp rename to UNITTESTS/stubs/stoip4_stub.c index 2df6028977..9cb8036577 100644 --- a/features/cellular/UNITTESTS/stubs/EventQueue_stub.cpp +++ b/UNITTESTS/stubs/stoip4_stub.c @@ -15,44 +15,20 @@ * limitations under the License. */ -#include "EventQueue.h" -#include "Callback.h" +#include +#include +#include +#include "common_functions.h" +#include "ip4string.h" -using namespace mbed; - -namespace events { - -EventQueue::EventQueue(unsigned event_size, unsigned char *event_pointer) +/** + * Convert numeric IPv4 address string to a binary. + * \param ip4addr IPv4 address in string format. + * \param len Length of IPv4 string, maximum of 16.. + * \param dest buffer for address. MUST be 4 bytes. + * \return boolean set to true if conversion succeded, false if it didn't + */ +bool stoip4(const char *ip4addr, size_t len, void *dest) { -} - -EventQueue::~EventQueue() -{ -} - -void EventQueue::dispatch(int ms) -{ -} - -void EventQueue::break_dispatch() -{ -} - -unsigned EventQueue::tick() -{ - return 0; -} - -void EventQueue::cancel(int id) -{ -} - -void EventQueue::background(Callback update) -{ -} - -void EventQueue::chain(EventQueue *target) -{ -} - + return true; } diff --git a/features/cellular/UNITTESTS/stubs/us_ticker_stub.cpp b/UNITTESTS/stubs/us_ticker_stub.cpp similarity index 100% rename from features/cellular/UNITTESTS/stubs/us_ticker_stub.cpp rename to UNITTESTS/stubs/us_ticker_stub.cpp diff --git a/features/cellular/UNITTESTS/target_h/ATCmdParser.h b/UNITTESTS/target_h/ATCmdParser.h similarity index 100% rename from features/cellular/UNITTESTS/target_h/ATCmdParser.h rename to UNITTESTS/target_h/ATCmdParser.h diff --git a/features/cellular/UNITTESTS/target_h/arm_math.h b/UNITTESTS/target_h/arm_math.h similarity index 100% rename from features/cellular/UNITTESTS/target_h/arm_math.h rename to UNITTESTS/target_h/arm_math.h diff --git a/features/cellular/UNITTESTS/target_h/cmsis.h b/UNITTESTS/target_h/cmsis.h similarity index 100% rename from features/cellular/UNITTESTS/target_h/cmsis.h rename to UNITTESTS/target_h/cmsis.h diff --git a/features/cellular/UNITTESTS/target_h/cmsis_compiler.h b/UNITTESTS/target_h/cmsis_compiler.h similarity index 100% rename from features/cellular/UNITTESTS/target_h/cmsis_compiler.h rename to UNITTESTS/target_h/cmsis_compiler.h diff --git a/features/cellular/UNITTESTS/target_h/cmsis_os.h b/UNITTESTS/target_h/cmsis_os.h similarity index 100% rename from features/cellular/UNITTESTS/target_h/cmsis_os.h rename to UNITTESTS/target_h/cmsis_os.h diff --git a/features/cellular/UNITTESTS/target_h/cmsis_os2.h b/UNITTESTS/target_h/cmsis_os2.h similarity index 50% rename from features/cellular/UNITTESTS/target_h/cmsis_os2.h rename to UNITTESTS/target_h/cmsis_os2.h index dcd0c20c61..c2a601fb16 100644 --- a/features/cellular/UNITTESTS/target_h/cmsis_os2.h +++ b/UNITTESTS/target_h/cmsis_os2.h @@ -18,6 +18,8 @@ #ifndef __CMSIS_OS2_H__ #define __CMSIS_OS2_H__ +#include + //If conflicts, then remove these, copied from cmsis_os.h typedef int32_t osStatus; @@ -42,11 +44,35 @@ typedef enum { typedef void *osThreadId_t; +typedef void *osEventFlagsId_t; + /// Attributes structure for thread. typedef struct { } osThreadAttr_t; -#define osWaitForever 0xFFFFFFFFU +#define osWaitForever 0xFFFFFFFFU ///< Wait forever timeout value. + +// Flags options (\ref osThreadFlagsWait and \ref osEventFlagsWait). +#define osFlagsWaitAny 0x00000000U ///< Wait for any flag (default). +#define osFlagsWaitAll 0x00000001U ///< Wait for all flags. +#define osFlagsNoClear 0x00000002U ///< Do not clear flags which have been specified to wait for. + +// Flags errors (returned by osThreadFlagsXxxx and osEventFlagsXxxx). +#define osFlagsError 0x80000000U ///< Error indicator. +#define osFlagsErrorUnknown 0xFFFFFFFFU ///< osError (-1). +#define osFlagsErrorTimeout 0xFFFFFFFEU ///< osErrorTimeout (-2). +#define osFlagsErrorResource 0xFFFFFFFDU ///< osErrorResource (-3). +#define osFlagsErrorParameter 0xFFFFFFFCU ///< osErrorParameter (-4). +#define osFlagsErrorISR 0xFFFFFFFAU ///< osErrorISR (-6). + +// Thread attributes (attr_bits in \ref osThreadAttr_t). +#define osThreadDetached 0x00000000U ///< Thread created in detached mode (default) +#define osThreadJoinable 0x00000001U ///< Thread created in joinable mode + +// Mutex attributes (attr_bits in \ref osMutexAttr_t). +#define osMutexRecursive 0x00000001U ///< Recursive mutex. +#define osMutexPrioInherit 0x00000002U ///< Priority inherit protocol. +#define osMutexRobust 0x00000008U ///< Robust mutex. #endif diff --git a/UNITTESTS/target_h/mbed.h b/UNITTESTS/target_h/mbed.h index 1f88324deb..276aebc58b 100644 --- a/UNITTESTS/target_h/mbed.h +++ b/UNITTESTS/target_h/mbed.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Arm Limited and affiliates. + * Copyright (c) 2018, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -22,6 +22,7 @@ #include #include "events/mbed_events.h" +#include "events/mbed_shared_queues.h" namespace mbed { #include "platform/Callback.h" diff --git a/UNITTESTS/target_h/mbed_rtos1_types.h b/UNITTESTS/target_h/mbed_rtos1_types.h index e200f189f2..4ff0189351 100644 --- a/UNITTESTS/target_h/mbed_rtos1_types.h +++ b/UNITTESTS/target_h/mbed_rtos1_types.h @@ -18,6 +18,7 @@ #ifndef MBED_RTOS1_TYPES_H #define MBED_RTOS1_TYPES_H +#include "cmsis_os.h" #include "mbed_rtos_storage.h" #endif // MBED_RTOS1_TYPES_H diff --git a/UNITTESTS/target_h/mbed_rtos_storage.h b/UNITTESTS/target_h/mbed_rtos_storage.h index 48923f2a23..e1b1276138 100644 --- a/UNITTESTS/target_h/mbed_rtos_storage.h +++ b/UNITTESTS/target_h/mbed_rtos_storage.h @@ -23,17 +23,13 @@ extern "C" { #endif #include "cmsis_os2.h" +#include "rtx_os.h" +#include "rtx_lib.h" +#include "mbed_rtx_conf.h" -typedef osMutexId_t mbed_rtos_storage_mutex_t; -typedef osSemaphoreId_t mbed_rtos_storage_semaphore_t; -typedef osThreadId_t mbed_rtos_storage_thread_t; -typedef osThreadId_t osThreadId; -typedef osMemoryPoolId_t mbed_rtos_storage_mem_pool_t; -typedef osMessageQueueId_t mbed_rtos_storage_msg_queue_t; -typedef osEventFlagsId_t mbed_rtos_storage_event_flags_t; -typedef void *mbed_rtos_storage_message_t; -typedef osTimerId_t mbed_rtos_storage_timer_t; -typedef osStatus_t osStatus; +typedef os_semaphore_t mbed_rtos_storage_semaphore_t; +typedef os_thread_t mbed_rtos_storage_thread_t; +typedef osRtxEventFlags_t mbed_rtos_storage_event_flags_t; #ifdef __cplusplus } diff --git a/features/cellular/UNITTESTS/target_h/mbed_rtx.h b/UNITTESTS/target_h/mbed_rtx.h similarity index 100% rename from features/cellular/UNITTESTS/target_h/mbed_rtx.h rename to UNITTESTS/target_h/mbed_rtx.h diff --git a/features/cellular/UNITTESTS/target_h/mbed_rtx_conf.h b/UNITTESTS/target_h/mbed_rtx_conf.h similarity index 95% rename from features/cellular/UNITTESTS/target_h/mbed_rtx_conf.h rename to UNITTESTS/target_h/mbed_rtx_conf.h index 18d985fa49..17620e86e8 100644 --- a/features/cellular/UNITTESTS/target_h/mbed_rtx_conf.h +++ b/UNITTESTS/target_h/mbed_rtx_conf.h @@ -15,4 +15,6 @@ * limitations under the License. */ +#ifndef OS_STACK_SIZE #define OS_STACK_SIZE 0 +#endif diff --git a/features/cellular/UNITTESTS/target_h/nsapi_ppp.h b/UNITTESTS/target_h/nsapi_ppp.h similarity index 100% rename from features/cellular/UNITTESTS/target_h/nsapi_ppp.h rename to UNITTESTS/target_h/nsapi_ppp.h diff --git a/features/cellular/UNITTESTS/target_h/platform/mbed_power_mgmt.h b/UNITTESTS/target_h/platform/mbed_power_mgmt.h similarity index 100% rename from features/cellular/UNITTESTS/target_h/platform/mbed_power_mgmt.h rename to UNITTESTS/target_h/platform/mbed_power_mgmt.h diff --git a/UNITTESTS/target_h/platform/mbed_retarget.h b/UNITTESTS/target_h/platform/mbed_retarget.h index 0c513f53e3..c4f381ff3b 100644 --- a/UNITTESTS/target_h/platform/mbed_retarget.h +++ b/UNITTESTS/target_h/platform/mbed_retarget.h @@ -18,7 +18,15 @@ #ifndef RETARGET_H #define RETARGET_H +#include #include +#include + +#include + +namespace mbed { + +#define NAME_MAX 255 #undef EPERM #define EPERM 1 /* Operation not permitted */ @@ -283,4 +291,75 @@ #undef ENOTRECOVERABLE #define ENOTRECOVERABLE 131 /* State not recoverable */ +#define _IFMT 0170000 //< type of file +#define _IFSOCK 0140000 //< socket +#define _IFLNK 0120000 //< symbolic link +#define _IFREG 0100000 //< regular +#define _IFBLK 0060000 //< block special +#define _IFDIR 0040000 //< directory +#define _IFCHR 0020000 //< character special +#define _IFIFO 0010000 //< fifo special + + +#define O_RDONLY 0 ///< Open for reading +#define O_WRONLY 1 ///< Open for writing +#define O_RDWR 2 ///< Open for reading and writing +#define O_NONBLOCK 0x0004 ///< Non-blocking mode +#define O_APPEND 0x0008 ///< Set file offset to end of file prior to each write +#define O_CREAT 0x0200 ///< Create file if it does not exist +#define O_TRUNC 0x0400 ///< Truncate file to zero length +#define O_EXCL 0x0800 ///< Fail if file exists +#define O_BINARY 0x8000 ///< Open file in binary mode + +#define O_ACCMODE (O_RDONLY|O_WRONLY|O_RDWR) + +#define NAME_MAX 255 ///< Maximum size of a name in a file path + +#define STDIN_FILENO 0 +#define STDOUT_FILENO 1 +#define STDERR_FILENO 2 + + +struct statvfs { + unsigned long f_bsize; ///< Filesystem block size + unsigned long f_frsize; ///< Fragment size (block size) + + unsigned long long f_blocks; ///< Number of blocks + unsigned long long f_bfree; ///< Number of free blocks + unsigned long long f_bavail; ///< Number of free blocks for unprivileged users + + unsigned long f_fsid; ///< Filesystem ID + + unsigned long f_namemax; ///< Maximum filename length +}; + + +struct dirent { + char d_name[NAME_MAX + 1]; ///< Name of file + uint8_t d_type; ///< Type of file +}; + +enum { + DT_UNKNOWN, ///< The file type could not be determined. + DT_FIFO, ///< This is a named pipe (FIFO). + DT_CHR, ///< This is a character device. + DT_DIR, ///< This is a directory. + DT_BLK, ///< This is a block device. + DT_REG, ///< This is a regular file. + DT_LNK, ///< This is a symbolic link. + DT_SOCK, ///< This is a UNIX domain socket. +}; + +/* fcntl.h defines */ +#define F_GETFL 3 +#define F_SETFL 4 + +struct pollfd { + int fd; + short events; + short revents; +}; + +} + #endif //RETARGET_H diff --git a/features/cellular/UNITTESTS/target_h/mbed.h b/UNITTESTS/target_h/platform/mbed_wait_api.h similarity index 70% rename from features/cellular/UNITTESTS/target_h/mbed.h rename to UNITTESTS/target_h/platform/mbed_wait_api.h index e401087fec..e6b21b44e1 100644 --- a/features/cellular/UNITTESTS/target_h/mbed.h +++ b/UNITTESTS/target_h/platform/mbed_wait_api.h @@ -1,6 +1,6 @@ -/* - * Copyright (c) 2018, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 + +/* mbed Microcontroller Library + * Copyright (c) 2018 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,11 +14,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef MBED_H -#define MBED_H +#ifndef MBED_WAIT_API_H +#define MBED_WAIT_API_H -#include -#include +#ifdef __cplusplus +extern "C" { +#endif -#endif // MBED_H +void wait_ms(int ms); + +void wait_us(int us); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/features/cellular/UNITTESTS/target_h/randLIB.h b/UNITTESTS/target_h/randLIB.h similarity index 100% rename from features/cellular/UNITTESTS/target_h/randLIB.h rename to UNITTESTS/target_h/randLIB.h diff --git a/features/cellular/UNITTESTS/target_h/mbed_rtos_storage.h b/UNITTESTS/target_h/rtos/Mutex.h similarity index 63% rename from features/cellular/UNITTESTS/target_h/mbed_rtos_storage.h rename to UNITTESTS/target_h/rtos/Mutex.h index f2282eed38..a804e17212 100644 --- a/features/cellular/UNITTESTS/target_h/mbed_rtos_storage.h +++ b/UNITTESTS/target_h/rtos/Mutex.h @@ -14,11 +14,35 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef __MUTEX_H__ +#define __MUTEX_H__ +#include #include "cmsis_os2.h" -#include "rtx_os.h" -#include "rtx_lib.h" -#include "mbed_rtx_conf.h" -typedef os_semaphore_t mbed_rtos_storage_semaphore_t; -typedef os_thread_t mbed_rtos_storage_thread_t; +namespace rtos { + +class Mutex { +public: + Mutex(); + + Mutex(const char *name); + + osStatus lock(uint32_t millisec=osWaitForever); + + bool trylock(); + + bool trylock_for(uint32_t millisec); + + bool trylock_until(uint64_t millisec); + + osStatus unlock(); + + osThreadId_t get_owner(); + + ~Mutex(); +}; + +} + +#endif diff --git a/features/cellular/UNITTESTS/target_h/rtos/Semaphore.h b/UNITTESTS/target_h/rtos/Semaphore.h similarity index 100% rename from features/cellular/UNITTESTS/target_h/rtos/Semaphore.h rename to UNITTESTS/target_h/rtos/Semaphore.h diff --git a/features/cellular/UNITTESTS/target_h/rtx_lib.h b/UNITTESTS/target_h/rtx_lib.h similarity index 100% rename from features/cellular/UNITTESTS/target_h/rtx_lib.h rename to UNITTESTS/target_h/rtx_lib.h diff --git a/features/cellular/UNITTESTS/target_h/rtx_os.h b/UNITTESTS/target_h/rtx_os.h similarity index 87% rename from features/cellular/UNITTESTS/target_h/rtx_os.h rename to UNITTESTS/target_h/rtx_os.h index bb29a2164c..dfa7082fa1 100644 --- a/features/cellular/UNITTESTS/target_h/rtx_os.h +++ b/UNITTESTS/target_h/rtx_os.h @@ -57,4 +57,14 @@ typedef struct osRtxThread_s { void *context; ///< Context for OsEventObserver objects } osRtxThread_t; +typedef struct { + uint8_t id; ///< Object Identifier + uint8_t state; ///< Object State + uint8_t flags; ///< Object Flags + uint8_t reserved; + const char *name; ///< Object Name + osRtxThread_t *thread_list; ///< Waiting Threads List + uint32_t event_flags; ///< Event Flags +} osRtxEventFlags_t; + #endif diff --git a/features/cellular/UNITTESTS/target_h/sys/syslimits.h b/UNITTESTS/target_h/sys/syslimits.h similarity index 100% rename from features/cellular/UNITTESTS/target_h/sys/syslimits.h rename to UNITTESTS/target_h/sys/syslimits.h diff --git a/UNITTESTS/template/unittest.cmake.template b/UNITTESTS/template/unittest.cmake.template index bd463665df..a5f0301525 100644 --- a/UNITTESTS/template/unittest.cmake.template +++ b/UNITTESTS/template/unittest.cmake.template @@ -3,9 +3,6 @@ # UNIT TESTS #################### -# Unit test suite name -set(TEST_SUITE_NAME "suitename") - set(unittest-includes ${unittest-includes} headerfile ) diff --git a/UNITTESTS/unit_test/coverage.py b/UNITTESTS/unit_test/coverage.py new file mode 100644 index 0000000000..add8e1d2a9 --- /dev/null +++ b/UNITTESTS/unit_test/coverage.py @@ -0,0 +1,148 @@ +""" +Copyright (c) 2018, Arm Limited +SPDX-License-Identifier: Apache-2.0 + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +GENERATE TEST CODE COVERAGE +""" + +import os +import logging +import posixpath +import re + +from .utils import execute_program +from .get_tools import get_gcov_program, \ + get_gcovr_program +from .settings import COVERAGE_OUTPUT_TYPES + + +class CoverageAPI(object): + """ + Generate code coverage reports for unit tests. + """ + + def __init__(self, mbed_os_root=None, build_dir=None): + self.root = mbed_os_root + + if not self.root: + self.root = os.path.normpath(os.path.join( + os.path.dirname(os.path.realpath(__file__)), + "../..")) + + self.build_dir = build_dir + + if not self.build_dir: + logging.error("No build directory given for CoverageAPI.") + + def _gen_cmd(self, coverage_type, excludes, filter_regex): + # Generate coverage generation command: + args = [get_gcovr_program(), + "--gcov-executable", + get_gcov_program(), + "-r", + os.path.relpath(self.root, self.build_dir), + "."] + + if coverage_type == "html": + args.extend(["--html", + "--html-detail", + "-o", + "./coverage/index.html"]) + elif coverage_type == "xml": + args.extend(["-x", + "-o", + "./coverage.xml"]) + else: + logging.error("Invalid coverage output type: %s" % coverage_type) + + # Add exclude filters: + for path in excludes: + # Use posix separators if path is string + if isinstance(path, ("".__class__, u"".__class__)): + path = path.replace("\\", "/") + args.extend(["-e", path]) + # Use regular expressions as is + elif isinstance(path, type(re.compile(""))): + args.extend(["-e", path.pattern]) + + # Add include filters: + if filter_regex: + filters = filter_regex.split(",") + + for filt in filters: + regex = "(.+/)?%s" % filt.replace("-", "/") + args.extend(["-f", regex]) + + if logging.getLogger().getEffectiveLevel() == logging.DEBUG: + args.append("-v") + + return args + + def generate_reports(self, + outputs, + excludes=None, + filter_regex=None, + build_path=None): + """ + Run tests to generate coverage data, and generate coverage reports. + + Positional arguments: + outputs - list of types to generate + + Keyword arguments: + excludes - list of paths to exclude from the report + filter_regex - comma-separated string to use for test filtering + build_path - build path + """ + + # Check for the tool + if get_gcovr_program() is None: + logging.error( + "No gcovr tool found in path. " + + "Cannot generate coverage reports.") + return + + if build_path is None: + build_path = os.getcwd() + + if outputs is None: + outputs = [] + + if excludes is None: + excludes = [] + + for output in outputs: + # Skip if invalid/unsupported output type + if output not in COVERAGE_OUTPUT_TYPES: + logging.warning( + "Invalid output type. " + + "Skip coverage report for type: %s." % output.upper()) + continue + + if output == "html": + # Create a build directory if not exist + coverage_path = os.path.join(build_path, "coverage") + if not os.path.exists(coverage_path): + os.mkdir(coverage_path) + + # Generate the command + args = self._gen_cmd(output, excludes, filter_regex) + + # Run the coverage tool + execute_program( + args, + "%s code coverage report generation failed." % output.upper(), + "%s code coverage report created." % output.upper()) diff --git a/UNITTESTS/unit_test/new.py b/UNITTESTS/unit_test/new.py index f9fb748d85..772e310696 100644 --- a/UNITTESTS/unit_test/new.py +++ b/UNITTESTS/unit_test/new.py @@ -28,7 +28,7 @@ class UnitTestGeneratorTool(object): Generator tool to create new unit tests from template """ - def _replace_content(self, template_content, dirname, classname, suite_name, extension): + def _replace_content(self, template_content, dirname, classname, extension): if extension == "h": content = re.sub(r"cppfile", "", @@ -41,7 +41,6 @@ class UnitTestGeneratorTool(object): content = re.sub(r"headerfile", "../dirname/template.h", content) content = re.sub(r"dirname", dirname, content) content = re.sub(r"template", classname, content) - content = re.sub(r"suitename", suite_name, content) return content @@ -111,7 +110,6 @@ class UnitTestGeneratorTool(object): content = self._replace_content(template_content, dir_name, class_name, - suite_name, file_extension) output_file.writelines(content) @@ -130,7 +128,6 @@ class UnitTestGeneratorTool(object): content = self._replace_content(template_content, dir_name, class_name, - suite_name, file_extension) output_file.writelines(content) diff --git a/UNITTESTS/unit_test/options.py b/UNITTESTS/unit_test/options.py index f192006cdf..211c5d10b9 100644 --- a/UNITTESTS/unit_test/options.py +++ b/UNITTESTS/unit_test/options.py @@ -21,7 +21,7 @@ UNIT TEST OPTIONS import argparse import logging -from .settings import CMAKE_GENERATORS, MAKE_PROGRAMS, COVERAGE_TYPES +from .settings import CMAKE_GENERATORS, MAKE_PROGRAMS, COVERAGE_ARGS from .get_tools import get_make_tool def get_options_parser(): @@ -71,10 +71,15 @@ def get_options_parser(): dest="debug_build") parser.add_argument("--coverage", - choices=COVERAGE_TYPES, + choices=COVERAGE_ARGS, help="Generate code coverage report", dest="coverage") + parser.add_argument("--include-headers", + action="store_true", + help="Include headers to coverage reports, defaults to false.", + dest="include_headers") + parser.add_argument("-m", "--make-program", default=get_make_tool(), @@ -140,3 +145,4 @@ Mbed OS unit testing: if options.coverage: logging.info(" [%s] \tGenerate coverage reports", "SET") logging.info(" \t\t - Output: %s", options.coverage) + logging.info(" \t\t - Include headers: %s", options.include_headers) diff --git a/UNITTESTS/unit_test/settings.py b/UNITTESTS/unit_test/settings.py index 717cab8523..883b4a82f4 100644 --- a/UNITTESTS/unit_test/settings.py +++ b/UNITTESTS/unit_test/settings.py @@ -29,10 +29,12 @@ DEFAULT_CMAKE_GENERATORS = { "ninja": "Ninja" } -COVERAGE_TYPES = ["html", +COVERAGE_ARGS = ["html", "xml", "both"] +COVERAGE_OUTPUT_TYPES = ["html", "xml"] + CXX_COMPILERS = ["g++-6", "g++-8", "g++-7", "g++-5", "g++-4.9", "g++"] C_COMPILERS = ["gcc-6", "gcc-8", "gcc-7", "gcc-5", "gcc-4.9", "gcc"] diff --git a/UNITTESTS/unit_test/test.py b/UNITTESTS/unit_test/test.py index 889b0a35b3..dbf515e4e0 100644 --- a/UNITTESTS/unit_test/test.py +++ b/UNITTESTS/unit_test/test.py @@ -27,9 +27,7 @@ from .utils import execute_program from .get_tools import get_make_tool, \ get_cmake_tool, \ get_cxx_tool, \ - get_c_tool, \ - get_gcov_program, \ - get_gcovr_program + get_c_tool from .settings import DEFAULT_CMAKE_GENERATORS class UnitTestTool(object): @@ -115,77 +113,6 @@ class UnitTestTool(object): "Building unit tests failed.", "Unit tests built successfully.") - def _get_coverage_script(self, coverage_type, excludes): - args = [get_gcovr_program(), - "--gcov-executable", - get_gcov_program(), - "-r", - "../..", - "."] - - if coverage_type == "html": - args.extend(["--html", - "--html-detail", - "-o", - "./coverage/index.html"]) - elif coverage_type == "xml": - args.extend(["-x", - "-o", - "./coverage.xml"]) - - for path in excludes: - args.extend(["-e", path.replace("\\", "/")]) - - if logging.getLogger().getEffectiveLevel() == logging.DEBUG: - args.append("-v") - - return args - - def generate_coverage_report(self, - coverage_output_type=None, - excludes=None, - build_path=None): - """ - Run tests to generate coverage data, and generate coverage reports. - """ - - self.run_tests() - - if get_gcovr_program() is None: - logging.error("No gcovr tool found in path. \ - Cannot generate coverage report.") - return - - if build_path is None: - build_path = os.getcwd() - - if coverage_output_type is None: - logging.warning("No coverage output type give. \ - Cannot generate coverage reports.") - return - - if excludes is None: - excludes = [] - - if coverage_output_type == "html" or coverage_output_type == "both": - # Create build directory if not exist. - coverage_path = os.path.join(build_path, "coverage") - if not os.path.exists(coverage_path): - os.mkdir(coverage_path) - - args = self._get_coverage_script("html", excludes) - - execute_program(args, - "HTML code coverage report generation failed.", - "HTML code coverage report created.") - - if coverage_output_type == "xml" or coverage_output_type == "both": - args = self._get_coverage_script("xml", excludes) - - execute_program(args, - "XML code coverage report generation failed.", - "XML code coverage report created.") - def run_tests(self, filter_regex=None): """ Run unit tests. diff --git a/doxygen_options.json b/doxygen_options.json index 073b66e8f9..1362e6b4c3 100644 --- a/doxygen_options.json +++ b/doxygen_options.json @@ -10,5 +10,5 @@ "EXPAND_AS_DEFINED": "", "SKIP_FUNCTION_MACROS": "NO", "STRIP_CODE_COMMENTS": "NO", - "EXCLUDE_PATTERNS": "*/tools/* */targets/* */features/mbedtls/* */features/storage/cfstore/* */features/storage/FEATURE_STORAGE/* */features/unsupported/* */BUILD/* */rtos/TARGET_CORTEX/rtx*/* */cmsis/* */features/lwipstack/* */nanostack/sal-stack-nanostack/* */nanostack/coap-service/* */ble/generic/* */ble/pal/* */mbed-trace/* */mbed-coap/* */nanostack-libservice/* */mbed-client-randlib/* */nanostack/sal-stack-nanostack-eventloop/* */components/802.15.4_RF/* */components/wifi/* */features/nfc/stack/*" + "EXCLUDE_PATTERNS": "*/tools/* */targets/* */features/mbedtls/* */features/storage/cfstore/* */features/storage/FEATURE_STORAGE/* */features/unsupported/* */BUILD/* */rtos/TARGET_CORTEX/rtx*/* */cmsis/* */features/lwipstack/* */nanostack/sal-stack-nanostack/* */nanostack/coap-service/* */ble/generic/* */ble/pal/* */mbed-trace/* */mbed-coap/* */nanostack-libservice/* */mbed-client-randlib/* */nanostack/sal-stack-nanostack-eventloop/* */components/802.15.4_RF/* */components/wifi/* */features/nfc/stack/* */UNITTESTS/*" } diff --git a/drivers/FlashIAP.cpp b/drivers/FlashIAP.cpp index 8f71061472..879a74f3c8 100644 --- a/drivers/FlashIAP.cpp +++ b/drivers/FlashIAP.cpp @@ -24,7 +24,7 @@ #include #include #include "FlashIAP.h" -#include "mbed_assert.h" +#include "platform/mbed_assert.h" #ifdef DEVICE_FLASH diff --git a/drivers/SPI.cpp b/drivers/SPI.cpp index fc52be754d..d679a9c0a8 100644 --- a/drivers/SPI.cpp +++ b/drivers/SPI.cpp @@ -41,9 +41,14 @@ SPI::SPI(PinName mosi, PinName miso, PinName sclk, PinName ssel) : _write_fill(SPI_FILL_CHAR) { // No lock needed in the constructor - spi_init(&_spi, mosi, miso, sclk, ssel); - _acquire(); +} + +SPI::~SPI() +{ + if (_owner == this) { + _owner = NULL; + } } void SPI::format(int bits, int mode) diff --git a/drivers/SPI.h b/drivers/SPI.h index 8d24dcc966..7c8e7d6103 100644 --- a/drivers/SPI.h +++ b/drivers/SPI.h @@ -87,6 +87,7 @@ public: * @param ssel SPI chip select pin */ SPI(PinName mosi, PinName miso, PinName sclk, PinName ssel = NC); + virtual ~SPI(); /** Configure the data transmission format * @@ -272,11 +273,6 @@ private: #endif -public: - virtual ~SPI() - { - } - protected: spi_t _spi; diff --git a/drivers/Serial.h b/drivers/Serial.h index 11e237bffa..7c5e536acb 100644 --- a/drivers/Serial.h +++ b/drivers/Serial.h @@ -20,10 +20,10 @@ #if defined (DEVICE_SERIAL) || defined(DOXYGEN_ONLY) -#include "Stream.h" +#include "platform/Stream.h" #include "SerialBase.h" -#include "PlatformMutex.h" -#include "serial_api.h" +#include "platform/PlatformMutex.h" +#include "hal/serial_api.h" #include "platform/NonCopyable.h" namespace mbed { diff --git a/drivers/SerialBase.h b/drivers/SerialBase.h index 9fe5ddef25..5d7989ecb5 100644 --- a/drivers/SerialBase.h +++ b/drivers/SerialBase.h @@ -20,14 +20,14 @@ #if defined (DEVICE_SERIAL) || defined(DOXYGEN_ONLY) -#include "Callback.h" -#include "serial_api.h" -#include "mbed_toolchain.h" +#include "platform/Callback.h" +#include "hal/serial_api.h" +#include "platform/mbed_toolchain.h" #include "platform/NonCopyable.h" #if DEVICE_SERIAL_ASYNCH -#include "CThunk.h" -#include "dma_api.h" +#include "platform/CThunk.h" +#include "hal/dma_api.h" #endif namespace mbed { diff --git a/drivers/UARTSerial.h b/drivers/UARTSerial.h index c3a110fd65..667591bf82 100644 --- a/drivers/UARTSerial.h +++ b/drivers/UARTSerial.h @@ -21,12 +21,12 @@ #if (DEVICE_SERIAL && DEVICE_INTERRUPTIN) || defined(DOXYGEN_ONLY) -#include "FileHandle.h" +#include "platform/FileHandle.h" #include "SerialBase.h" #include "InterruptIn.h" -#include "PlatformMutex.h" -#include "serial_api.h" -#include "CircularBuffer.h" +#include "platform/PlatformMutex.h" +#include "hal/serial_api.h" +#include "platform/CircularBuffer.h" #include "platform/NonCopyable.h" #ifndef MBED_CONF_DRIVERS_UART_SERIAL_RXBUF_SIZE diff --git a/features/FEATURE_BLE/ble/generic/SecurityDb.h b/features/FEATURE_BLE/ble/generic/SecurityDb.h index 8fa9e96d18..a5577f1929 100644 --- a/features/FEATURE_BLE/ble/generic/SecurityDb.h +++ b/features/FEATURE_BLE/ble/generic/SecurityDb.h @@ -603,7 +603,7 @@ public: sizeof(BLEProtocol::AddressBytes_t) ); - if (flags->peer_address_is_public) { + if (identity->identity_address_is_public) { whitelist->addresses[whitelist->size].type = BLEProtocol::AddressType::PUBLIC; } else { whitelist->addresses[whitelist->size].type = BLEProtocol::AddressType::RANDOM_STATIC; diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioBLE.h b/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioBLE.h index e4eeafba1d..fe3cc0e348 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioBLE.h +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioBLE.h @@ -30,7 +30,7 @@ #include "CordioPalGenericAccessService.h" #include "ble/generic/GenericGap.h" #include "ble/generic/GenericSecurityManager.h" -#include "ble/pal/SimpleEventQueue.h" +#include "SimpleEventQueue.h" namespace ble { namespace vendor { @@ -152,7 +152,7 @@ private: } initialization_status; ::BLE::InstanceID_t instanceID; - mutable pal::SimpleEventQueue _event_queue; + mutable SimpleEventQueue _event_queue; class SigningEventMonitorProxy : public pal::SigningEventMonitor { public: diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioGattServer.h b/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioGattServer.h index f882fa98ce..6f102d05d9 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioGattServer.h +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioGattServer.h @@ -222,8 +222,8 @@ private: void add_generic_attribute_service(); void* alloc_block(size_t block_size); GattCharacteristic* get_auth_char(uint16_t value_handle); - bool get_cccd_id(GattAttribute::Handle_t cccd_handle, uint8_t& idx) const; - bool has_cccd(GattAttribute::Handle_t char_handle) const; + bool get_cccd_index_by_cccd_handle(GattAttribute::Handle_t cccd_handle, uint8_t& idx) const; + bool get_cccd_index_by_value_handle(GattAttribute::Handle_t char_handle, uint8_t& idx) const; bool is_update_authorized(Gap::Handle_t connection, GattAttribute::Handle_t value_handle); struct alloc_block_t { diff --git a/features/FEATURE_BLE/ble/pal/SimpleEventQueue.h b/features/FEATURE_BLE/targets/TARGET_CORDIO/SimpleEventQueue.h similarity index 83% rename from features/FEATURE_BLE/ble/pal/SimpleEventQueue.h rename to features/FEATURE_BLE/targets/TARGET_CORDIO/SimpleEventQueue.h index 84ccacfd48..c84063205e 100644 --- a/features/FEATURE_BLE/ble/pal/SimpleEventQueue.h +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/SimpleEventQueue.h @@ -23,12 +23,13 @@ #include "ble/BLE.h" namespace ble { -namespace pal { +namespace vendor { +namespace cordio { /** * Simple implementation of the pal::EventQueue. */ -struct SimpleEventQueue : EventQueue { +struct SimpleEventQueue : pal::EventQueue { typedef mbed::Callback event_t; @@ -51,7 +52,7 @@ struct SimpleEventQueue : EventQueue { * * @param ble_id Id of the BLE instance using that event queue. */ - void initialize(BLEInstanceBase* ble_base, BLE::InstanceID_t ble_id) + void initialize(BLEInstanceBase* ble_base, ::BLE::InstanceID_t ble_id) { _ble_base = ble_base; _ble_instance_id = ble_id; @@ -73,8 +74,12 @@ struct SimpleEventQueue : EventQueue { if (_ble_base == NULL) { return false; } - - EventNode* next = new (std::nothrow) EventNode(event); + void* event_buf = WsfBufAlloc(sizeof(EventNode)); + MBED_ASSERT(event_buf != NULL); + if (event_buf == NULL) { + return false; + } + EventNode* next = new(event_buf) EventNode(event); if (next == NULL) { return false; } @@ -102,7 +107,8 @@ struct SimpleEventQueue : EventQueue { { while (_events) { EventNode* next = _events->next; - delete _events; + _events->~EventNode(); + WsfBufFree(_events); _events = next; } } @@ -115,7 +121,8 @@ struct SimpleEventQueue : EventQueue { while (_events) { EventNode* next = _events->next; _events->event(); - delete _events; + _events->~EventNode(); + WsfBufFree(_events); _events = next; } } @@ -133,11 +140,12 @@ private: } BLEInstanceBase* _ble_base; - BLE::InstanceID_t _ble_instance_id; + ::BLE::InstanceID_t _ble_instance_id; EventNode* _events; }; -} // namespace pal +} // namespace cordio +} // namespace vendor } // namespace ble #endif /* BLE_PAL_SIMPLE_EVENT_QUEUE_H_ */ diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioGattServer.cpp b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioGattServer.cpp index 41568ab5f3..4e1b5bad68 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioGattServer.cpp +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioGattServer.cpp @@ -560,7 +560,7 @@ ble_error_t GattServer::read( ) { // Check to see if this is a CCCD uint8_t cccd_index; - if (get_cccd_id(att_handle, cccd_index)) { + if (get_cccd_index_by_cccd_handle(att_handle, cccd_index)) { if (connection == DM_CONN_ID_NONE) { return BLE_ERROR_PARAM_OUT_OF_RANGE; } @@ -588,7 +588,7 @@ ble_error_t GattServer::write( // Check to see if this is a CCCD, if it is the case update the value for all // connections uint8_t cccd_index; - if (get_cccd_id(att_handle, cccd_index)) { + if (get_cccd_index_by_cccd_handle(att_handle, cccd_index)) { if (len != sizeof(uint16_t)) { return BLE_ERROR_INVALID_PARAM; } @@ -615,7 +615,7 @@ ble_error_t GattServer::write( } // return if the update does not have to be propagated to peers - if (local_only || !has_cccd(att_handle)) { + if (local_only || !get_cccd_index_by_value_handle(att_handle, cccd_index)) { return BLE_ERROR_NONE; } @@ -624,6 +624,8 @@ ble_error_t GattServer::write( // successful uint16_t conn_id = 0; uint16_t conn_found = 0; + size_t updates_sent = 0; + while((conn_found < DM_CONN_MAX) && (conn_id < CONNECTION_ID_LIMIT)) { if (DmConnInUse(conn_id) == true) { ++conn_found; @@ -631,15 +633,21 @@ ble_error_t GattServer::write( uint16_t cccd_config = AttsCccEnabled(conn_id, cccd_index); if (cccd_config & ATT_CLIENT_CFG_NOTIFY) { AttsHandleValueNtf(conn_id, att_handle, len, (uint8_t*)buffer); + updates_sent++; } if (cccd_config & ATT_CLIENT_CFG_INDICATE) { AttsHandleValueInd(conn_id, att_handle, len, (uint8_t*)buffer); + updates_sent++; } } } ++conn_id; } + if (updates_sent) { + handleDataSentEvent(updates_sent); + } + return BLE_ERROR_NONE; } @@ -652,7 +660,7 @@ ble_error_t GattServer::write( ) { // Check to see if this is a CCCD uint8_t cccd_index; - if (get_cccd_id(att_handle, cccd_index)) { + if (get_cccd_index_by_cccd_handle(att_handle, cccd_index)) { if ((connection == DM_CONN_ID_NONE) || (len != 2)) { // CCCDs are always 16 bits return BLE_ERROR_PARAM_OUT_OF_RANGE; } @@ -669,21 +677,29 @@ ble_error_t GattServer::write( } // return if the update does not have to be propagated to peers - if (local_only || !has_cccd(att_handle)) { + if (local_only || !get_cccd_index_by_value_handle(att_handle, cccd_index)) { return BLE_ERROR_NONE; } // This characteristic has a CCCD attribute. Handle notifications and indications. + size_t updates_sent = 0; + if (is_update_authorized(connection, att_handle)) { uint16_t cccEnabled = AttsCccEnabled(connection, cccd_index); if (cccEnabled & ATT_CLIENT_CFG_NOTIFY) { AttsHandleValueNtf(connection, att_handle, len, (uint8_t*)buffer); + updates_sent++; } if (cccEnabled & ATT_CLIENT_CFG_INDICATE) { AttsHandleValueInd(connection, att_handle, len, (uint8_t*)buffer); + updates_sent++; } } + if (updates_sent) { + handleDataSentEvent(updates_sent); + } + return BLE_ERROR_NONE; } @@ -1195,7 +1211,7 @@ GattCharacteristic* GattServer::get_auth_char(uint16_t value_handle) return NULL; } -bool GattServer::get_cccd_id(GattAttribute::Handle_t cccd_handle, uint8_t& idx) const +bool GattServer::get_cccd_index_by_cccd_handle(GattAttribute::Handle_t cccd_handle, uint8_t& idx) const { for (idx = 0; idx < cccd_cnt; idx++) { if (cccd_handle == cccds[idx].handle) { @@ -1205,10 +1221,10 @@ bool GattServer::get_cccd_id(GattAttribute::Handle_t cccd_handle, uint8_t& idx) return false; } -bool GattServer::has_cccd(GattAttribute::Handle_t char_handle) const +bool GattServer::get_cccd_index_by_value_handle(GattAttribute::Handle_t char_handle, uint8_t& idx) const { - for (uint8_t cccd_index = 0; cccd_index < cccd_cnt; ++cccd_index) { - if (char_handle == cccd_handles[cccd_index]) { + for (idx = 0; idx < cccd_cnt; ++idx) { + if (char_handle == cccd_handles[idx]) { return true; } } diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF51/source/nRF5xn.h b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF51/source/nRF5xn.h index 25d6c21656..74836bb255 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF51/source/nRF5xn.h +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF51/source/nRF5xn.h @@ -22,10 +22,8 @@ #include "ble/BLEInstanceBase.h" #include "ble/generic/GenericGattClient.h" #include "ble/generic/GenericSecurityManager.h" -#include "ble/pal/SimpleEventQueue.h" #include "nRF5xPalSecurityManager.h" - #include "nRF5xGap.h" #include "nRF5xGattServer.h" diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xCrypto.cpp b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xCrypto.cpp index 8b8c57474e..32419875a2 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xCrypto.cpp +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xCrypto.cpp @@ -47,7 +47,7 @@ namespace vendor { namespace nordic { CryptoToolbox::CryptoToolbox() : _initialized(false) { - mbedtls_platform_setup(&_platform_context); + mbedtls_platform_setup(NULL); mbedtls_entropy_init(&_entropy_context); mbedtls_ecp_group_init(&_group); int err = mbedtls_ecp_group_load( @@ -60,7 +60,7 @@ CryptoToolbox::CryptoToolbox() : _initialized(false) { CryptoToolbox::~CryptoToolbox() { mbedtls_ecp_group_free(&_group); mbedtls_entropy_free(&_entropy_context); - mbedtls_platform_teardown(&_platform_context); + mbedtls_platform_teardown(NULL); } bool CryptoToolbox::generate_keys( diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xCrypto.h b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xCrypto.h index 7a522e2222..35c56a875e 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xCrypto.h +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xCrypto.h @@ -132,7 +132,6 @@ private: void swap_endian(uint8_t* buf, size_t len); bool _initialized; - mbedtls_platform_context _platform_context; mbedtls_entropy_context _entropy_context; mbedtls_ecp_group _group; }; diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xn.h b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xn.h index 6efd3ec37a..088944faa6 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xn.h +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xn.h @@ -22,7 +22,6 @@ #include "ble/BLEInstanceBase.h" #include "ble/generic/GenericGattClient.h" #include "ble/generic/GenericSecurityManager.h" -#include "ble/pal/SimpleEventQueue.h" #include "nRF5xPalSecurityManager.h" #include "nRF5xGap.h" diff --git a/features/FEATURE_BOOTLOADER/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/LICENCE b/features/FEATURE_BOOTLOADER/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/LICENCE new file mode 100644 index 0000000000..591ac29615 --- /dev/null +++ b/features/FEATURE_BOOTLOADER/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/LICENCE @@ -0,0 +1,49 @@ +Permissive Binary License + +Version 1.0, September 2015 + +Redistribution. Redistribution and use in binary form, without +modification, are permitted provided that the following conditions are +met: + +1) Redistributions must reproduce the above copyright notice and the + following disclaimer in the documentation and/or other materials + provided with the distribution. + +2) Unless to the extent explicitly permitted by law, no reverse + engineering, decompilation, or disassembly of this software is + permitted. + +3) Redistribution as part of a software development kit must include the + accompanying file named "DEPENDENCIES" and any dependencies listed in + that file. + +4) Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +Limited patent license. The copyright holders (and contributors) grant a +worldwide, non-exclusive, no-charge, royalty-free patent license to +make, have made, use, offer to sell, sell, import, and otherwise +transfer this software, where such license applies only to those patent +claims licensable by the copyright holders (and contributors) that are +necessarily infringed by this software. This patent license shall not +apply to any combinations that include this software. No hardware is +licensed hereunder. + +If you institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the software +itself infringes your patent(s), then your rights granted under this +license shall terminate as of the date such litigation is filed. + +DISCLAIMER. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND +CONTRIBUTORS "AS IS." ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT +NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/features/FEATURE_BOOTLOADER/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/mbed-bootloader-nucleo_f207zg-block_device-sotp-v3.4.0-3-gdbbb.bin b/features/FEATURE_BOOTLOADER/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/mbed-bootloader-nucleo_f207zg-block_device-sotp-v3.4.0-3-gdbbb.bin new file mode 100755 index 0000000000..f24ada043b Binary files /dev/null and b/features/FEATURE_BOOTLOADER/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/mbed-bootloader-nucleo_f207zg-block_device-sotp-v3.4.0-3-gdbbb.bin differ diff --git a/features/FEATURE_BOOTLOADER/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/mbed_lib.json b/features/FEATURE_BOOTLOADER/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/mbed_lib.json new file mode 100644 index 0000000000..d7ef4d0513 --- /dev/null +++ b/features/FEATURE_BOOTLOADER/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/mbed_lib.json @@ -0,0 +1,10 @@ +{ + "name": "bootloader_NUCLEO_F207ZG", + "target_overrides": { + "*": { + "target.app_offset": "0x10400", + "target.header_offset": "0x10000", + "target.bootloader_img": "mbed-bootloader-nucleo_f207zg-block_device-sotp-v3.4.0-3-gdbbb.bin" + } + } +} diff --git a/features/cellular/TESTS/socket/udp/main.cpp b/features/cellular/TESTS/socket/udp/main.cpp index d8013ab846..00efa7083c 100644 --- a/features/cellular/TESTS/socket/udp/main.cpp +++ b/features/cellular/TESTS/socket/udp/main.cpp @@ -162,7 +162,7 @@ static void udp_network_stack() cellular.set_sim_pin(MBED_CONF_APP_CELLULAR_SIM_PIN); #ifdef MBED_CONF_APP_APN CellularNetwork *network = cellular.get_network(); - TEST_ASSERT(network->set_credentials(MBED_CONF_APP_APN) == NSAPI_ERROR_OK); + TEST_ASSERT(network->set_credentials(MBED_CONF_APP_APN, MBED_CONF_APP_USERNAME, MBED_CONF_APP_PASSWORD) == NSAPI_ERROR_OK); #endif cellular_target_state = CellularConnectionFSM::STATE_CONNECTED; TEST_ASSERT(cellular.continue_to_state(cellular_target_state) == NSAPI_ERROR_OK); diff --git a/features/cellular/UNITTESTS/Makefile b/features/cellular/UNITTESTS/Makefile deleted file mode 100755 index 1327cf4601..0000000000 --- a/features/cellular/UNITTESTS/Makefile +++ /dev/null @@ -1,19 +0,0 @@ -#scan for folders having "Makefile" in them and remove 'this' to prevent loop -DIRS := $(filter-out ./, $(sort $(dir $(shell find . -name 'Makefile')))) - -all: - for dir in $(DIRS); do \ - cd $$dir; make gcov; cd ..; cd ..;\ - done - -clean: - for dir in $(DIRS); do \ - cd $$dir; make clean; cd ..; cd ..;\ - done - rm -rf ../source/*gcov ../source/*gcda ../source/*o - rm -rf stubs/*gcov stubs/*gcda stubs/*o - rm -rf results/* - rm -rf coverages/* - rm -rf results - rm -rf coverages - diff --git a/features/cellular/UNITTESTS/MakefileWorker.mk b/features/cellular/UNITTESTS/MakefileWorker.mk deleted file mode 100755 index 2096ced036..0000000000 --- a/features/cellular/UNITTESTS/MakefileWorker.mk +++ /dev/null @@ -1,562 +0,0 @@ -#--------- -# -# MakefileWorker.mk -# -# Include this helper file in your makefile -# It makes -# A static library -# A test executable -# -# See this example for parameter settings -# examples/Makefile -# -#---------- -# Inputs - these variables describe what to build -# -# INCLUDE_DIRS - Directories used to search for include files. -# This generates a -I for each directory -# SRC_DIRS - Directories containing source file to built into the library -# SRC_FILES - Specific source files to build into library. Helpful when not all code -# in a directory can be built for test (hopefully a temporary situation) -# TEST_SRC_DIRS - Directories containing unit test code build into the unit test runner -# These do not go in a library. They are explicitly included in the test runner -# TEST_SRC_FILES - Specific source files to build into the unit test runner -# These do not go in a library. They are explicitly included in the test runner -# MOCKS_SRC_DIRS - Directories containing mock source files to build into the test runner -# These do not go in a library. They are explicitly included in the test runner -#---------- -# You can adjust these variables to influence how to build the test target -# and where to put and name outputs -# See below to determine defaults -# COMPONENT_NAME - the name of the thing being built -# TEST_TARGET - name the test executable. By default it is -# $(COMPONENT_NAME)_tests -# Helpful if you want 1 > make files in the same directory with different -# executables as output. -# CPPUTEST_HOME - where CppUTest home dir found -# TARGET_PLATFORM - Influences how the outputs are generated by modifying the -# CPPUTEST_OBJS_DIR and CPPUTEST_LIB_DIR to use a sub-directory under the -# normal objs and lib directories. Also modifies where to search for the -# CPPUTEST_LIB to link against. -# CPPUTEST_OBJS_DIR - a directory where o and d files go -# CPPUTEST_LIB_DIR - a directory where libs go -# CPPUTEST_ENABLE_DEBUG - build for debug -# CPPUTEST_USE_MEM_LEAK_DETECTION - Links with overridden new and delete -# CPPUTEST_USE_STD_CPP_LIB - Set to N to keep the standard C++ library out -# of the test harness -# CPPUTEST_USE_GCOV - Turn on coverage analysis -# Clean then build with this flag set to Y, then 'make gcov' -# CPPUTEST_MAPFILE - generate a map file -# CPPUTEST_WARNINGFLAGS - overly picky by default -# OTHER_MAKEFILE_TO_INCLUDE - a hook to use this makefile to make -# other targets. Like CSlim, which is part of fitnesse -# CPPUTEST_USE_VPATH - Use Make's VPATH functionality to support user -# specification of source files and directories that aren't below -# the user's Makefile in the directory tree, like: -# SRC_DIRS += ../../lib/foo -# It defaults to N, and shouldn't be necessary except in the above case. -#---------- -# -# Other flags users can initialize to sneak in their settings -# CPPUTEST_CXXFLAGS - flags for the C++ compiler -# CPPUTEST_CPPFLAGS - flags for the C++ AND C preprocessor -# CPPUTEST_CFLAGS - flags for the C complier -# CPPUTEST_LDFLAGS - Linker flags -#---------- - -# Some behavior is weird on some platforms. Need to discover the platform. - -# Platforms -UNAME_OUTPUT = "$(shell uname -a)" -MACOSX_STR = Darwin -MINGW_STR = MINGW -CYGWIN_STR = CYGWIN -LINUX_STR = Linux -SUNOS_STR = SunOS -UNKNWOWN_OS_STR = Unknown - -# Compilers -CC_VERSION_OUTPUT ="$(shell $(CXX) -v 2>&1)" -CLANG_STR = clang -SUNSTUDIO_CXX_STR = SunStudio - -UNAME_OS = $(UNKNWOWN_OS_STR) - -ifeq ($(findstring $(MINGW_STR),$(UNAME_OUTPUT)),$(MINGW_STR)) - UNAME_OS = $(MINGW_STR) -endif - -ifeq ($(findstring $(CYGWIN_STR),$(UNAME_OUTPUT)),$(CYGWIN_STR)) - UNAME_OS = $(CYGWIN_STR) -endif - -ifeq ($(findstring $(LINUX_STR),$(UNAME_OUTPUT)),$(LINUX_STR)) - UNAME_OS = $(LINUX_STR) -endif - -ifeq ($(findstring $(MACOSX_STR),$(UNAME_OUTPUT)),$(MACOSX_STR)) - UNAME_OS = $(MACOSX_STR) -#lion has a problem with the 'v' part of -a - UNAME_OUTPUT = "$(shell uname -pmnrs)" -endif - -ifeq ($(findstring $(SUNOS_STR),$(UNAME_OUTPUT)),$(SUNOS_STR)) - UNAME_OS = $(SUNOS_STR) - - SUNSTUDIO_CXX_ERR_STR = CC -flags -ifeq ($(findstring $(SUNSTUDIO_CXX_ERR_STR),$(CC_VERSION_OUTPUT)),$(SUNSTUDIO_CXX_ERR_STR)) - CC_VERSION_OUTPUT ="$(shell $(CXX) -V 2>&1)" - COMPILER_NAME = $(SUNSTUDIO_CXX_STR) -endif -endif - -ifeq ($(findstring $(CLANG_STR),$(CC_VERSION_OUTPUT)),$(CLANG_STR)) - COMPILER_NAME = $(CLANG_STR) -endif - -#Kludge for mingw, it does not have cc.exe, but gcc.exe will do -ifeq ($(UNAME_OS),$(MINGW_STR)) - CC := gcc -endif - -#And another kludge. Exception handling in gcc 4.6.2 is broken when linking the -# Standard C++ library as a shared library. Unbelievable. -ifeq ($(UNAME_OS),$(MINGW_STR)) - CPPUTEST_LDFLAGS += -static -endif -ifeq ($(UNAME_OS),$(CYGWIN_STR)) - CPPUTEST_LDFLAGS += -static -endif - - -#Kludge for MacOsX gcc compiler on Darwin9 who can't handle pendantic -ifeq ($(UNAME_OS),$(MACOSX_STR)) -ifeq ($(findstring Version 9,$(UNAME_OUTPUT)),Version 9) - CPPUTEST_PEDANTIC_ERRORS = N -endif -endif - -ifndef COMPONENT_NAME - COMPONENT_NAME = name_this_in_the_makefile -endif - -# Debug on by default -ifndef CPPUTEST_ENABLE_DEBUG - CPPUTEST_ENABLE_DEBUG = Y -endif - -# new and delete for memory leak detection on by default -ifndef CPPUTEST_USE_MEM_LEAK_DETECTION - CPPUTEST_USE_MEM_LEAK_DETECTION = Y -endif - -# Use the standard C library -ifndef CPPUTEST_USE_STD_C_LIB - CPPUTEST_USE_STD_C_LIB = Y -endif - -# Use the standard C++ library -ifndef CPPUTEST_USE_STD_CPP_LIB - CPPUTEST_USE_STD_CPP_LIB = Y -endif - -# Use gcov, off by default -ifndef CPPUTEST_USE_GCOV - CPPUTEST_USE_GCOV = N -endif - -ifndef CPPUTEST_PEDANTIC_ERRORS - CPPUTEST_PEDANTIC_ERRORS = Y -endif - -# Default warnings -ifndef CPPUTEST_WARNINGFLAGS - CPPUTEST_WARNINGFLAGS = -Wall -Wextra -Wshadow -Wswitch-default -Wswitch-enum -Wconversion -ifeq ($(CPPUTEST_PEDANTIC_ERRORS), Y) -# CPPUTEST_WARNINGFLAGS += -pedantic-errors - CPPUTEST_WARNINGFLAGS += -pedantic -endif -ifeq ($(UNAME_OS),$(LINUX_STR)) - CPPUTEST_WARNINGFLAGS += -Wsign-conversion -endif - CPPUTEST_CXX_WARNINGFLAGS = -Woverloaded-virtual - CPPUTEST_C_WARNINGFLAGS = -Wstrict-prototypes -endif - -#Wonderful extra compiler warnings with clang -ifeq ($(COMPILER_NAME),$(CLANG_STR)) -# -Wno-disabled-macro-expansion -> Have to disable the macro expansion warning as the operator new overload warns on that. -# -Wno-padded -> I sort-of like this warning but if there is a bool at the end of the class, it seems impossible to remove it! (except by making padding explicit) -# -Wno-global-constructors Wno-exit-time-destructors -> Great warnings, but in CppUTest it is impossible to avoid as the automatic test registration depends on the global ctor and dtor -# -Wno-weak-vtables -> The TEST_GROUP macro declares a class and will automatically inline its methods. Thats ok as they are only in one translation unit. Unfortunately, the warning can't detect that, so it must be disabled. - CPPUTEST_CXX_WARNINGFLAGS += -Weverything -Wno-disabled-macro-expansion -Wno-padded -Wno-global-constructors -Wno-exit-time-destructors -Wno-weak-vtables - CPPUTEST_C_WARNINGFLAGS += -Weverything -Wno-padded -endif - -# Uhm. Maybe put some warning flags for SunStudio here? -ifeq ($(COMPILER_NAME),$(SUNSTUDIO_CXX_STR)) - CPPUTEST_CXX_WARNINGFLAGS = - CPPUTEST_C_WARNINGFLAGS = -endif - -# Default dir for temporary files (d, o) -ifndef CPPUTEST_OBJS_DIR -ifndef TARGET_PLATFORM - CPPUTEST_OBJS_DIR = objs -else - CPPUTEST_OBJS_DIR = objs/$(TARGET_PLATFORM) -endif -endif - -# Default dir for the outout library -ifndef CPPUTEST_LIB_DIR -ifndef TARGET_PLATFORM - CPPUTEST_LIB_DIR = lib -else - CPPUTEST_LIB_DIR = lib/$(TARGET_PLATFORM) -endif -endif - -# No map by default -ifndef CPPUTEST_MAP_FILE - CPPUTEST_MAP_FILE = N -endif - -# No extentions is default -ifndef CPPUTEST_USE_EXTENSIONS - CPPUTEST_USE_EXTENSIONS = N -endif - -# No VPATH is default -ifndef CPPUTEST_USE_VPATH - CPPUTEST_USE_VPATH := N -endif -# Make empty, instead of 'N', for usage in $(if ) conditionals -ifneq ($(CPPUTEST_USE_VPATH), Y) - CPPUTEST_USE_VPATH := -endif - -ifndef TARGET_PLATFORM -#CPPUTEST_LIB_LINK_DIR = $(CPPUTEST_HOME)/lib -CPPUTEST_LIB_LINK_DIR = /usr/lib/x86_64-linux-gnu -else -CPPUTEST_LIB_LINK_DIR = $(CPPUTEST_HOME)/lib/$(TARGET_PLATFORM) -endif - -# -------------------------------------- -# derived flags in the following area -# -------------------------------------- - -# Without the C library, we'll need to disable the C++ library and ... -ifeq ($(CPPUTEST_USE_STD_C_LIB), N) - CPPUTEST_USE_STD_CPP_LIB = N - CPPUTEST_USE_MEM_LEAK_DETECTION = N - CPPUTEST_CPPFLAGS += -DCPPUTEST_STD_C_LIB_DISABLED - CPPUTEST_CPPFLAGS += -nostdinc -endif - -CPPUTEST_CPPFLAGS += -DCPPUTEST_COMPILATION - -ifeq ($(CPPUTEST_USE_MEM_LEAK_DETECTION), N) - CPPUTEST_CPPFLAGS += -DCPPUTEST_MEM_LEAK_DETECTION_DISABLED -else - ifndef CPPUTEST_MEMLEAK_DETECTOR_NEW_MACRO_FILE - CPPUTEST_MEMLEAK_DETECTOR_NEW_MACRO_FILE = -include $(CPPUTEST_HOME)/include/CppUTest/MemoryLeakDetectorNewMacros.h - endif - ifndef CPPUTEST_MEMLEAK_DETECTOR_MALLOC_MACRO_FILE - CPPUTEST_MEMLEAK_DETECTOR_MALLOC_MACRO_FILE = -include $(CPPUTEST_HOME)/include/CppUTest/MemoryLeakDetectorMallocMacros.h - endif -endif - -ifeq ($(CPPUTEST_ENABLE_DEBUG), Y) - CPPUTEST_CXXFLAGS += -g - CPPUTEST_CFLAGS += -g - CPPUTEST_LDFLAGS += -g -endif - -ifeq ($(CPPUTEST_USE_STD_CPP_LIB), N) - CPPUTEST_CPPFLAGS += -DCPPUTEST_STD_CPP_LIB_DISABLED -ifeq ($(CPPUTEST_USE_STD_C_LIB), Y) - CPPUTEST_CXXFLAGS += -nostdinc++ -endif -endif - -ifdef $(GMOCK_HOME) - GTEST_HOME = $(GMOCK_HOME)/gtest - CPPUTEST_CPPFLAGS += -I$(GMOCK_HOME)/include - GMOCK_LIBRARY = $(GMOCK_HOME)/lib/.libs/libgmock.a - LD_LIBRARIES += $(GMOCK_LIBRARY) - CPPUTEST_CPPFLAGS += -DINCLUDE_GTEST_TESTS - CPPUTEST_WARNINGFLAGS = - CPPUTEST_CPPFLAGS += -I$(GTEST_HOME)/include -I$(GTEST_HOME) - GTEST_LIBRARY = $(GTEST_HOME)/lib/.libs/libgtest.a - LD_LIBRARIES += $(GTEST_LIBRARY) -endif - - -ifeq ($(CPPUTEST_USE_GCOV), Y) - CPPUTEST_CXXFLAGS += -fprofile-arcs -ftest-coverage - CPPUTEST_CFLAGS += -fprofile-arcs -ftest-coverage -endif - -CPPUTEST_CXXFLAGS += $(CPPUTEST_WARNINGFLAGS) $(CPPUTEST_CXX_WARNINGFLAGS) -CPPUTEST_CPPFLAGS += $(CPPUTEST_WARNINGFLAGS) -CPPUTEST_CXXFLAGS += $(CPPUTEST_MEMLEAK_DETECTOR_NEW_MACRO_FILE) -CPPUTEST_CPPFLAGS += $(CPPUTEST_MEMLEAK_DETECTOR_MALLOC_MACRO_FILE) -CPPUTEST_CFLAGS += $(CPPUTEST_C_WARNINGFLAGS) - -TARGET_MAP = $(COMPONENT_NAME).map.txt -ifeq ($(CPPUTEST_MAP_FILE), Y) - CPPUTEST_LDFLAGS += -Wl,-map,$(TARGET_MAP) -endif - -# Link with CppUTest lib -CPPUTEST_LIB = $(CPPUTEST_LIB_LINK_DIR)/libCppUTest.a - -ifeq ($(CPPUTEST_USE_EXTENSIONS), Y) -CPPUTEST_LIB += $(CPPUTEST_LIB_LINK_DIR)/libCppUTestExt.a -endif - -ifdef CPPUTEST_STATIC_REALTIME - LD_LIBRARIES += -lrt -endif - -TARGET_LIB = \ - $(CPPUTEST_LIB_DIR)/lib$(COMPONENT_NAME).a - -ifndef TEST_TARGET - ifndef TARGET_PLATFORM - TEST_TARGET = $(COMPONENT_NAME)_tests - else - TEST_TARGET = $(COMPONENT_NAME)_$(TARGET_PLATFORM)_tests - endif -endif - -#Helper Functions -get_src_from_dir = $(wildcard $1/*.cpp) $(wildcard $1/*.cc) $(wildcard $1/*.c) -get_dirs_from_dirspec = $(wildcard $1) -get_src_from_dir_list = $(foreach dir, $1, $(call get_src_from_dir,$(dir))) -__src_to = $(subst .c,$1, $(subst .cc,$1, $(subst .cpp,$1,$(if $(CPPUTEST_USE_VPATH),$(notdir $2),$2)))) -src_to = $(addprefix $(CPPUTEST_OBJS_DIR)/,$(call __src_to,$1,$2)) -src_to_o = $(call src_to,.o,$1) -src_to_d = $(call src_to,.d,$1) -src_to_gcda = $(call src_to,.gcda,$1) -src_to_gcno = $(call src_to,.gcno,$1) -time = $(shell date +%s) -delta_t = $(eval minus, $1, $2) -debug_print_list = $(foreach word,$1,echo " $(word)";) echo; - -#Derived -STUFF_TO_CLEAN += $(TEST_TARGET) $(TEST_TARGET).exe $(TARGET_LIB) $(TARGET_MAP) - -SRC += $(call get_src_from_dir_list, $(SRC_DIRS)) $(SRC_FILES) -OBJ = $(call src_to_o,$(SRC)) - -STUFF_TO_CLEAN += $(OBJ) - -TEST_SRC += $(call get_src_from_dir_list, $(TEST_SRC_DIRS)) $(TEST_SRC_FILES) -TEST_OBJS = $(call src_to_o,$(TEST_SRC)) -STUFF_TO_CLEAN += $(TEST_OBJS) - - -MOCKS_SRC += $(call get_src_from_dir_list, $(MOCKS_SRC_DIRS)) -MOCKS_OBJS = $(call src_to_o,$(MOCKS_SRC)) -STUFF_TO_CLEAN += $(MOCKS_OBJS) - -ALL_SRC = $(SRC) $(TEST_SRC) $(MOCKS_SRC) - -# If we're using VPATH -ifeq ($(CPPUTEST_USE_VPATH), Y) -# gather all the source directories and add them - VPATH += $(sort $(dir $(ALL_SRC))) -# Add the component name to the objs dir path, to differentiate between same-name objects - CPPUTEST_OBJS_DIR := $(addsuffix /$(COMPONENT_NAME),$(CPPUTEST_OBJS_DIR)) -endif - -#Test coverage with gcov -GCOV_OUTPUT = gcov_output.txt -GCOV_REPORT = gcov_report.txt -GCOV_ERROR = gcov_error.txt -GCOV_GCDA_FILES = $(call src_to_gcda, $(ALL_SRC)) -GCOV_GCNO_FILES = $(call src_to_gcno, $(ALL_SRC)) -TEST_OUTPUT = $(TEST_TARGET).txt -STUFF_TO_CLEAN += \ - $(GCOV_OUTPUT)\ - $(GCOV_REPORT)\ - $(GCOV_REPORT).html\ - $(GCOV_ERROR)\ - $(GCOV_GCDA_FILES)\ - $(GCOV_GCNO_FILES)\ - $(TEST_OUTPUT) - -#The gcda files for gcov need to be deleted before each run -#To avoid annoying messages. -GCOV_CLEAN = $(SILENCE)rm -f $(GCOV_GCDA_FILES) $(GCOV_OUTPUT) $(GCOV_REPORT) $(GCOV_ERROR) -RUN_TEST_TARGET = $(SILENCE) $(GCOV_CLEAN) ; echo "Running $(TEST_TARGET)"; ./$(TEST_TARGET) $(CPPUTEST_EXE_FLAGS) -ojunit - -ifeq ($(CPPUTEST_USE_GCOV), Y) - - ifeq ($(COMPILER_NAME),$(CLANG_STR)) - LD_LIBRARIES += --coverage - else - LD_LIBRARIES += -lgcov - endif -endif - - -INCLUDES_DIRS_EXPANDED = $(call get_dirs_from_dirspec, $(INCLUDE_DIRS)) -INCLUDES += $(foreach dir, $(INCLUDES_DIRS_EXPANDED), -I$(dir)) -MOCK_DIRS_EXPANDED = $(call get_dirs_from_dirspec, $(MOCKS_SRC_DIRS)) -INCLUDES += $(foreach dir, $(MOCK_DIRS_EXPANDED), -I$(dir)) - -CPPUTEST_CPPFLAGS += $(INCLUDES) $(CPPUTESTFLAGS) - -DEP_FILES = $(call src_to_d, $(ALL_SRC)) -STUFF_TO_CLEAN += $(DEP_FILES) $(PRODUCTION_CODE_START) $(PRODUCTION_CODE_END) -STUFF_TO_CLEAN += $(STDLIB_CODE_START) $(MAP_FILE) cpputest_*.xml junit_run_output - -# We'll use the CPPUTEST_CFLAGS etc so that you can override AND add to the CppUTest flags -CFLAGS = $(CPPUTEST_CFLAGS) $(CPPUTEST_ADDITIONAL_CFLAGS) -CPPFLAGS = $(CPPUTEST_CPPFLAGS) $(CPPUTEST_ADDITIONAL_CPPFLAGS) -CXXFLAGS = $(CPPUTEST_CXXFLAGS) $(CPPUTEST_ADDITIONAL_CXXFLAGS) -LDFLAGS = $(CPPUTEST_LDFLAGS) $(CPPUTEST_ADDITIONAL_LDFLAGS) - -# Don't consider creating the archive a warning condition that does STDERR output -ARFLAGS := $(ARFLAGS)c - -DEP_FLAGS=-MMD -MP - -# Some macros for programs to be overridden. For some reason, these are not in Make defaults -RANLIB = ranlib - -# Targets - -.PHONY: all -all: start $(TEST_TARGET) - $(RUN_TEST_TARGET) - -.PHONY: start -start: $(TEST_TARGET) - $(SILENCE)START_TIME=$(call time) - -.PHONY: all_no_tests -all_no_tests: $(TEST_TARGET) - -.PHONY: flags -flags: - @echo - @echo "OS ${UNAME_OS}" - @echo "Compile C and C++ source with CPPFLAGS:" - @$(call debug_print_list,$(CPPFLAGS)) - @echo "Compile C++ source with CXXFLAGS:" - @$(call debug_print_list,$(CXXFLAGS)) - @echo "Compile C source with CFLAGS:" - @$(call debug_print_list,$(CFLAGS)) - @echo "Link with LDFLAGS:" - @$(call debug_print_list,$(LDFLAGS)) - @echo "Link with LD_LIBRARIES:" - @$(call debug_print_list,$(LD_LIBRARIES)) - @echo "Create libraries with ARFLAGS:" - @$(call debug_print_list,$(ARFLAGS)) - -TEST_DEPS = $(TEST_OBJS) $(MOCKS_OBJS) $(PRODUCTION_CODE_START) $(TARGET_LIB) $(USER_LIBS) $(PRODUCTION_CODE_END) $(CPPUTEST_LIB) $(STDLIB_CODE_START) -test-deps: $(TEST_DEPS) - -$(TEST_TARGET): $(TEST_DEPS) - @echo Linking $@ - $(SILENCE)$(CXX) -o $@ $^ $(LD_LIBRARIES) $(LDFLAGS) - -$(TARGET_LIB): $(OBJ) - @echo Building archive $@ - $(SILENCE)mkdir -p $(dir $@) - $(SILENCE)$(AR) $(ARFLAGS) $@ $^ - $(SILENCE)$(RANLIB) $@ - -test: $(TEST_TARGET) - $(RUN_TEST_TARGET) | tee $(TEST_OUTPUT) - -vtest: $(TEST_TARGET) - $(RUN_TEST_TARGET) -v | tee $(TEST_OUTPUT) - -$(CPPUTEST_OBJS_DIR)/%.o: %.cc - @echo compiling $(notdir $<) - $(SILENCE)mkdir -p $(dir $@) - $(SILENCE)$(COMPILE.cpp) $(DEP_FLAGS) $(OUTPUT_OPTION) $< - -$(CPPUTEST_OBJS_DIR)/%.o: %.cpp - @echo compiling $(notdir $<) - $(SILENCE)mkdir -p $(dir $@) - $(SILENCE)$(COMPILE.cpp) $(DEP_FLAGS) $(OUTPUT_OPTION) $< - -$(CPPUTEST_OBJS_DIR)/%.o: %.c - @echo compiling $(notdir $<) - $(SILENCE)mkdir -p $(dir $@) - $(SILENCE)$(COMPILE.c) $(DEP_FLAGS) $(OUTPUT_OPTION) $< - -ifneq "$(MAKECMDGOALS)" "clean" --include $(DEP_FILES) -endif - -.PHONY: clean -clean: - @echo Making clean - $(SILENCE)$(RM) $(STUFF_TO_CLEAN) - $(SILENCE)rm -rf gcov objs #$(CPPUTEST_OBJS_DIR) - $(SILENCE)rm -rf $(CPPUTEST_LIB_DIR) - $(SILENCE)find . -name "*.gcno" | xargs rm -f - $(SILENCE)find . -name "*.gcda" | xargs rm -f - -#realclean gets rid of all gcov, o and d files in the directory tree -#not just the ones made by this makefile -.PHONY: realclean -realclean: clean - $(SILENCE)rm -rf gcov - $(SILENCE)find . -name "*.gdcno" | xargs rm -f - $(SILENCE)find . -name "*.[do]" | xargs rm -f - -gcov: test -ifeq ($(CPPUTEST_USE_VPATH), Y) - $(SILENCE)gcov --object-directory $(CPPUTEST_OBJS_DIR) $(SRC) >> $(GCOV_OUTPUT) 2>> $(GCOV_ERROR) -else - $(SILENCE)for d in $(SRC_DIRS) ; do \ - gcov --object-directory $(CPPUTEST_OBJS_DIR)/$$d $$d/*.c $$d/*.cpp >> $(GCOV_OUTPUT) 2>>$(GCOV_ERROR) ; \ - done - $(SILENCE)for f in $(SRC_FILES) ; do \ - gcov --object-directory $(CPPUTEST_OBJS_DIR)/$$f $$f >> $(GCOV_OUTPUT) 2>>$(GCOV_ERROR) ; \ - done -endif -# $(CPPUTEST_HOME)/scripts/filterGcov.sh $(GCOV_OUTPUT) $(GCOV_ERROR) $(GCOV_REPORT) $(TEST_OUTPUT) - /usr/share/cpputest/scripts/filterGcov.sh $(GCOV_OUTPUT) $(GCOV_ERROR) $(GCOV_REPORT) $(TEST_OUTPUT) - $(SILENCE)cat $(GCOV_REPORT) - $(SILENCE)mkdir -p gcov - $(SILENCE)mv *.gcov gcov - $(SILENCE)mv gcov_* gcov - @echo "See gcov directory for details" - -.PHONEY: format -format: - $(CPPUTEST_HOME)/scripts/reformat.sh $(PROJECT_HOME_DIR) - -.PHONEY: debug -debug: - @echo - @echo "Target Source files:" - @$(call debug_print_list,$(SRC)) - @echo "Target Object files:" - @$(call debug_print_list,$(OBJ)) - @echo "Test Source files:" - @$(call debug_print_list,$(TEST_SRC)) - @echo "Test Object files:" - @$(call debug_print_list,$(TEST_OBJS)) - @echo "Mock Source files:" - @$(call debug_print_list,$(MOCKS_SRC)) - @echo "Mock Object files:" - @$(call debug_print_list,$(MOCKS_OBJS)) - @echo "All Input Dependency files:" - @$(call debug_print_list,$(DEP_FILES)) - @echo Stuff to clean: - @$(call debug_print_list,$(STUFF_TO_CLEAN)) - @echo Includes: - @$(call debug_print_list,$(INCLUDES)) - --include $(OTHER_MAKEFILE_TO_INCLUDE) diff --git a/features/cellular/UNITTESTS/at/at_cellularbase/Makefile b/features/cellular/UNITTESTS/at/at_cellularbase/Makefile deleted file mode 100644 index 119b84aae9..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularbase/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -include ../../makefile_defines.txt - -COMPONENT_NAME = AT_CellularBase_unit - -#This must be changed manually -SRC_FILES = \ - ../../../framework/AT/AT_CellularBase.cpp - -TEST_SRC_FILES = \ - main.cpp \ - at_cellularbasetest.cpp \ - test_at_cellularbase.cpp \ - ../../stubs/ATHandler_stub.cpp \ - ../../stubs/EventQueue_stub.cpp \ - ../../stubs/FileHandle_stub.cpp \ - ../../stubs/mbed_assert_stub.cpp \ - -include ../../MakefileWorker.mk - -CPPUTESTFLAGS += -DFEA_TRACE_SUPPORT - diff --git a/features/cellular/UNITTESTS/at/at_cellularbase/at_cellularbasetest.cpp b/features/cellular/UNITTESTS/at/at_cellularbase/at_cellularbasetest.cpp deleted file mode 100644 index 0c7ff37f60..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularbase/at_cellularbasetest.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2015, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "CppUTest/TestHarness.h" -#include "test_at_cellularbase.h" -#include "AT_CellularBase.h" - -// AStyle ignored as the definition is not clear due to preprocessor usage -// *INDENT-OFF* -TEST_GROUP(AT_CellularBase) -{ - Test_AT_CellularBase *unit; - - void setup() - { - unit = new Test_AT_CellularBase(); - } - - void teardown() - { - delete unit; - } -}; -// *INDENT-ON* - -TEST(AT_CellularBase, Create) -{ - CHECK(unit != NULL); -} - -TEST(AT_CellularBase, test_AT_CellularBase_get_at_handler) -{ - unit->test_AT_CellularBase_get_at_handler(); -} - -TEST(AT_CellularBase, test_AT_CellularBase_get_device_error) -{ - unit->test_AT_CellularBase_get_device_error(); -} - -TEST(AT_CellularBase, test_AT_CellularBase_set_unsupported_features) -{ - unit->test_AT_CellularBase_set_unsupported_features(); -} - -TEST(AT_CellularBase, test_AT_CellularBase_is_supported) -{ - unit->test_AT_CellularBase_is_supported(); -} diff --git a/features/cellular/UNITTESTS/at/at_cellularbase/main.cpp b/features/cellular/UNITTESTS/at/at_cellularbase/main.cpp deleted file mode 100644 index 2c5e6a6356..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularbase/main.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2015, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "CppUTest/CommandLineTestRunner.h" -#include "CppUTest/TestPlugin.h" -#include "CppUTest/TestRegistry.h" -#include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char **av) -{ - return CommandLineTestRunner::RunAllTests(ac, av); -} - -IMPORT_TEST_GROUP(AT_CellularBase); - diff --git a/features/cellular/UNITTESTS/at/at_cellulardevice/Makefile b/features/cellular/UNITTESTS/at/at_cellulardevice/Makefile deleted file mode 100644 index cdc3e27799..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellulardevice/Makefile +++ /dev/null @@ -1,29 +0,0 @@ -include ../../makefile_defines.txt - -COMPONENT_NAME = AT_CellularDevice_unit - -#This must be changed manually -SRC_FILES = \ - ../../../framework/AT/AT_CellularDevice.cpp - -TEST_SRC_FILES = \ - main.cpp \ - at_cellulardevicetest.cpp \ - test_at_cellulardevice.cpp \ - ../../stubs/AT_CellularNetwork_stub.cpp \ - ../../stubs/ATHandler_stub.cpp \ - ../../stubs/AT_CellularSMS_stub.cpp \ - ../../stubs/AT_CellularSIM_stub.cpp \ - ../../stubs/AT_CellularPower_stub.cpp \ - ../../stubs/AT_CellularInformation_stub.cpp \ - ../../stubs/CellularUtil_stub.cpp \ - ../../stubs/AT_CellularBase_stub.cpp \ - ../../stubs/NetworkInterface_stub.cpp \ - ../../stubs/EventQueue_stub.cpp \ - ../../stubs/FileHandle_stub.cpp \ - ../../stubs/mbed_assert_stub.cpp \ - -include ../../MakefileWorker.mk - -CPPUTESTFLAGS += -DFEA_TRACE_SUPPORT - diff --git a/features/cellular/UNITTESTS/at/at_cellulardevice/at_cellulardevicetest.cpp b/features/cellular/UNITTESTS/at/at_cellulardevice/at_cellulardevicetest.cpp deleted file mode 100644 index 8dae6677a0..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellulardevice/at_cellulardevicetest.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2018, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "CppUTest/TestHarness.h" -#include "test_at_cellulardevice.h" - -TEST_GROUP(AT_CellularDevice) -{ - Test_AT_CellularDevice *unit; - - void setup() { - unit = new Test_AT_CellularDevice(); - } - - void teardown() { - delete unit; - } -}; - -TEST(AT_CellularDevice, Create) -{ - CHECK(unit != NULL); -} - -TEST(AT_CellularDevice, test_AT_CellularDevice_constructor) -{ - unit->test_AT_CellularDevice_constructor(); -} - -TEST(AT_CellularDevice, test_AT_CellularDevice_get_at_handler) -{ - unit->test_AT_CellularDevice_get_at_handler(); -} - -TEST(AT_CellularDevice, test_AT_CellularDevice_open_network) -{ - unit->test_AT_CellularDevice_open_network(); -} - -TEST(AT_CellularDevice, test_AT_CellularDevice_open_sms) -{ - unit->test_AT_CellularDevice_open_sms(); -} - -TEST(AT_CellularDevice, test_AT_CellularDevice_open_power) -{ - unit->test_AT_CellularDevice_open_power(); -} - -TEST(AT_CellularDevice, test_AT_CellularDevice_open_sim) -{ - unit->test_AT_CellularDevice_open_sim(); -} - -TEST(AT_CellularDevice, test_AT_CellularDevice_open_information) -{ - unit->test_AT_CellularDevice_open_information(); -} - -TEST(AT_CellularDevice, test_AT_CellularDevice_close_network) -{ - unit->test_AT_CellularDevice_close_network(); -} - -TEST(AT_CellularDevice, test_AT_CellularDevice_close_sms) -{ - unit->test_AT_CellularDevice_close_sms(); -} - -TEST(AT_CellularDevice, test_AT_CellularDevice_close_power) -{ - unit->test_AT_CellularDevice_close_power(); -} - -TEST(AT_CellularDevice, test_AT_CellularDevice_close_sim) -{ - unit->test_AT_CellularDevice_close_sim(); -} - -TEST(AT_CellularDevice, test_AT_CellularDevice_close_information) -{ - unit->test_AT_CellularDevice_close_information(); -} - -TEST(AT_CellularDevice, test_AT_CellularDevice_set_timeout) -{ - unit->test_AT_CellularDevice_set_timeout(); -} - -TEST(AT_CellularDevice, test_AT_CellularDevice_modem_debug_on) -{ - unit->test_AT_CellularDevice_modem_debug_on(); -} - -TEST(AT_CellularDevice, test_AT_CellularDevice_get_stack) -{ - unit->test_AT_CellularDevice_get_stack(); -} - -TEST(AT_CellularDevice, test_AT_CellularDevice_get_send_delay) -{ - unit->test_AT_CellularDevice_get_send_delay(); -} diff --git a/features/cellular/UNITTESTS/at/at_cellulardevice/main.cpp b/features/cellular/UNITTESTS/at/at_cellulardevice/main.cpp deleted file mode 100644 index 827f00e9d4..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellulardevice/main.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2015, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "CppUTest/CommandLineTestRunner.h" -#include "CppUTest/TestPlugin.h" -#include "CppUTest/TestRegistry.h" -#include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char **av) -{ - return CommandLineTestRunner::RunAllTests(ac, av); -} - -IMPORT_TEST_GROUP(AT_CellularDevice); - diff --git a/features/cellular/UNITTESTS/at/at_cellulardevice/test_at_cellulardevice.h b/features/cellular/UNITTESTS/at/at_cellulardevice/test_at_cellulardevice.h deleted file mode 100644 index 6bc72d20ad..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellulardevice/test_at_cellulardevice.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2018, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef TEST_AT_CELLULARDEVICE_H -#define TEST_AT_CELLULARDEVICE_H - -class Test_AT_CellularDevice { -public: - Test_AT_CellularDevice(); - - virtual ~Test_AT_CellularDevice(); - - void test_AT_CellularDevice_constructor(); - - void test_AT_CellularDevice_get_at_handler(); //tests also releasing of those - - void test_AT_CellularDevice_open_network(); - - void test_AT_CellularDevice_open_sms(); - - void test_AT_CellularDevice_open_power(); - - void test_AT_CellularDevice_open_sim(); - - void test_AT_CellularDevice_open_information(); - - void test_AT_CellularDevice_close_network(); - - void test_AT_CellularDevice_close_sms(); - - void test_AT_CellularDevice_close_power(); - - void test_AT_CellularDevice_close_sim(); - - void test_AT_CellularDevice_close_information(); - - void test_AT_CellularDevice_set_timeout(); - - void test_AT_CellularDevice_modem_debug_on(); - - void test_AT_CellularDevice_get_stack(); - - void test_AT_CellularDevice_get_send_delay(); -}; - -#endif // TEST_AT_CELLULARDEVICE_H - diff --git a/features/cellular/UNITTESTS/at/at_cellularinformation/Makefile b/features/cellular/UNITTESTS/at/at_cellularinformation/Makefile deleted file mode 100644 index cd74bc1b01..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularinformation/Makefile +++ /dev/null @@ -1,22 +0,0 @@ -include ../../makefile_defines.txt - -COMPONENT_NAME = AT_CellularInformation_unit - -#This must be changed manually -SRC_FILES = \ - ../../../framework/AT/AT_CellularInformation.cpp - -TEST_SRC_FILES = \ - main.cpp \ - at_cellularinformationtest.cpp \ - test_at_cellularinformation.cpp \ - ../../stubs/ATHandler_stub.cpp \ - ../../stubs/AT_CellularBase_stub.cpp \ - ../../stubs/EventQueue_stub.cpp \ - ../../stubs/FileHandle_stub.cpp \ - ../../stubs/mbed_assert_stub.cpp \ - -include ../../MakefileWorker.mk - -CPPUTESTFLAGS += -DFEA_TRACE_SUPPORT - diff --git a/features/cellular/UNITTESTS/at/at_cellularinformation/at_cellularinformationtest.cpp b/features/cellular/UNITTESTS/at/at_cellularinformation/at_cellularinformationtest.cpp deleted file mode 100644 index 25581e69b1..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularinformation/at_cellularinformationtest.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2015, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "CppUTest/TestHarness.h" -#include "test_at_cellularinformation.h" - -// AStyle ignored as the definition is not clear due to preprocessor usage -// *INDENT-OFF* -TEST_GROUP(AT_CellularInformation) -{ - Test_AT_CellularInformation *unit; - - void setup() - { - unit = new Test_AT_CellularInformation(); - } - - void teardown() - { - delete unit; - } -}; -// *INDENT-ON* - -TEST(AT_CellularInformation, Create) -{ - CHECK(unit != NULL); -} - -TEST(AT_CellularInformation, test_AT_CellularInformation_get_manufacturer) -{ - unit->test_AT_CellularInformation_get_manufacturer(); -} - -TEST(AT_CellularInformation, test_AT_CellularInformation_get_model) -{ - unit->test_AT_CellularInformation_get_model(); -} - -TEST(AT_CellularInformation, test_AT_CellularInformation_get_revision) -{ - unit->test_AT_CellularInformation_get_revision(); -} - -TEST(AT_CellularInformation, test_AT_CellularInformation_get_serial_number) -{ - unit->test_AT_CellularInformation_get_serial_number(); -} diff --git a/features/cellular/UNITTESTS/at/at_cellularnetwork/Makefile b/features/cellular/UNITTESTS/at/at_cellularnetwork/Makefile deleted file mode 100644 index f834d5787f..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularnetwork/Makefile +++ /dev/null @@ -1,29 +0,0 @@ -include ../../makefile_defines.txt - -COMPONENT_NAME = AT_CellularNetwork_unit - -#This must be changed manually -SRC_FILES = \ - ../../../framework/AT/AT_CellularNetwork.cpp \ - ../../../framework/AT/AT_CellularStack.cpp \ - ../../../framework/common/CellularUtil.cpp \ - -TEST_SRC_FILES = \ - main.cpp \ - at_cellularnetworktest.cpp \ - test_at_cellularnetwork.cpp \ - ../../stubs/ATHandler_stub.cpp \ - ../../stubs/AT_CellularBase_stub.cpp \ - ../../stubs/EventQueue_stub.cpp \ - ../../stubs/FileHandle_stub.cpp \ - ../../stubs/NetworkInterface_stub.cpp \ - ../../stubs/NetworkStack_stub.cpp \ - ../../stubs/us_ticker_stub.cpp \ - ../../stubs/mbed_assert_stub.cpp \ - ../../stubs/SocketAddress_stub.cpp \ - ../../stubs/randLIB_stub.cpp \ - -include ../../MakefileWorker.mk - -CPPUTESTFLAGS += -DFEA_TRACE_SUPPORT - diff --git a/features/cellular/UNITTESTS/at/at_cellularnetwork/at_cellularnetworktest.cpp b/features/cellular/UNITTESTS/at/at_cellularnetwork/at_cellularnetworktest.cpp deleted file mode 100644 index 538c527544..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularnetwork/at_cellularnetworktest.cpp +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Copyright (c) 2015, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "CppUTest/TestHarness.h" -#include "test_at_cellularnetwork.h" -#include "ATHandler_stub.h" - -// AStyle ignored as the definition is not clear due to preprocessor usage -// *INDENT-OFF* -TEST_GROUP(AT_CellularNetwork) -{ - Test_AT_CellularNetwork *unit; - - void setup() - { - unit = new Test_AT_CellularNetwork(); - ATHandler_stub::int_count = kRead_int_table_size; - ATHandler_stub::read_string_index = kRead_string_table_size; - ATHandler_stub::resp_stop_success_count = kResp_stop_count_default; - } - - void teardown() - { - delete unit; - } -}; -// *INDENT-ON* - -TEST(AT_CellularNetwork, Create) -{ - CHECK(unit != NULL); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_constructor) -{ - unit->test_AT_CellularNetwork_constructor(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_init) -{ - unit->test_AT_CellularNetwork_init(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_set_credentials) -{ - unit->test_AT_CellularNetwork_set_credentials(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_activate_context) -{ - unit->test_AT_CellularNetwork_activate_context(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_connect) -{ - unit->test_AT_CellularNetwork_connect(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_disconnect) -{ - unit->test_AT_CellularNetwork_disconnect(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_get_stack) -{ - unit->test_AT_CellularNetwork_get_stack(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_set_registration) -{ - unit->test_AT_CellularNetwork_set_registration(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_get_registration_status) -{ - unit->test_AT_CellularNetwork_get_registration_status(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_get_network_registering_mode) -{ - unit->test_AT_CellularNetwork_get_network_registering_mode(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_set_registration_urc) -{ - unit->test_AT_CellularNetwork_set_registration_urc(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_set_attach) -{ - unit->test_AT_CellularNetwork_set_attach(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_get_attach) -{ - unit->test_AT_CellularNetwork_get_attach(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_detach) -{ - unit->test_AT_CellularNetwork_detach(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_get_rate_control) -{ - unit->test_AT_CellularNetwork_get_rate_control(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_get_apn_backoff_timer) -{ - unit->test_AT_CellularNetwork_get_apn_backoff_timer(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_get_ip_address) -{ - unit->test_AT_CellularNetwork_get_ip_address(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_set_access_technology) -{ - unit->test_AT_CellularNetwork_set_access_technology(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_get_access_technology) -{ - unit->test_AT_CellularNetwork_get_access_technology(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_scan_plmn) -{ - unit->test_AT_CellularNetwork_scan_plmn(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_set_ciot_optimization_config) -{ - unit->test_AT_CellularNetwork_set_ciot_optimization_config(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_get_ciot_optimization_config) -{ - unit->test_AT_CellularNetwork_get_ciot_optimization_config(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_set_stack_type) -{ - unit->test_AT_CellularNetwork_set_stack_type(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_get_stack_type) -{ - unit->test_AT_CellularNetwork_get_stack_type(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_get_pdpcontext_params) -{ - unit->test_AT_CellularNetwork_get_pdpcontext_params(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_get_extended_signal_quality) -{ - unit->test_AT_CellularNetwork_get_extended_signal_quality(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_get_signal_quality) -{ - unit->test_AT_CellularNetwork_get_signal_quality(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_get_cell_id) -{ - unit->test_AT_CellularNetwork_get_cell_id(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_get_3gpp_error) -{ - unit->test_AT_CellularNetwork_get_3gpp_error(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_get_operator_params) -{ - unit->test_AT_CellularNetwork_get_operator_params(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_get_operator_names) -{ - unit->test_AT_CellularNetwork_get_operator_names(); -} - -TEST(AT_CellularNetwork, test_AT_CellularNetwork_attach) -{ - unit->test_AT_CellularNetwork_attach(); -} - -TEST(AT_CellularNetwork, test_get_connection_status) -{ - unit->test_get_connection_status(); -} - -TEST(AT_CellularNetwork, test_set_blocking) -{ - unit->test_set_blocking(); -} - diff --git a/features/cellular/UNITTESTS/at/at_cellularnetwork/main.cpp b/features/cellular/UNITTESTS/at/at_cellularnetwork/main.cpp deleted file mode 100644 index aec2c257bd..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularnetwork/main.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2015, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "CppUTest/CommandLineTestRunner.h" -#include "CppUTest/TestPlugin.h" -#include "CppUTest/TestRegistry.h" -#include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char **av) -{ - return CommandLineTestRunner::RunAllTests(ac, av); -} - -IMPORT_TEST_GROUP(AT_CellularNetwork); - diff --git a/features/cellular/UNITTESTS/at/at_cellularnetwork/test_at_cellularnetwork.cpp b/features/cellular/UNITTESTS/at/at_cellularnetwork/test_at_cellularnetwork.cpp deleted file mode 100644 index 4dd3bbd2af..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularnetwork/test_at_cellularnetwork.cpp +++ /dev/null @@ -1,1160 +0,0 @@ -/* - * Copyright (c) 2018, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "CppUTest/TestHarness.h" -#include "test_at_cellularnetwork.h" -#include -#include "AT_CellularNetwork.h" -#include "EventQueue.h" -#include "ATHandler.h" -#include "AT_CellularDevice.h" -#include "FileHandle_stub.h" -#include "CellularLog.h" -#include "ATHandler_stub.h" -#include "AT_CellularStack.h" - -using namespace mbed; -using namespace events; - -class my_stack : public AT_CellularStack { -public: - my_stack(ATHandler &atHandler) : AT_CellularStack(atHandler, 1, IPV4_STACK) {} - virtual int get_max_socket_count() - { - return 1; - } - virtual int get_max_packet_size() - { - return 200; - } - virtual bool is_protocol_supported(nsapi_protocol_t protocol) - { - return true; - } - virtual nsapi_error_t socket_close_impl(int sock_id) - { - return NSAPI_ERROR_OK; - } - virtual nsapi_error_t create_socket_impl(CellularSocket *socket) - { - return NSAPI_ERROR_OK; - } - virtual nsapi_size_or_error_t socket_sendto_impl(CellularSocket *socket, const SocketAddress &address, - const void *data, nsapi_size_t size) - { - return 100; - } - virtual nsapi_size_or_error_t socket_recvfrom_impl(CellularSocket *socket, SocketAddress *address, - void *buffer, nsapi_size_t size) - { - return 100; - } -}; - -class my_AT_CN : public AT_CellularNetwork { -public: - my_AT_CN(ATHandler &atHandler) : AT_CellularNetwork(atHandler) {} - virtual ~my_AT_CN() {} - NetworkStack *get_stack() - { - if (!_stack) { - return new my_stack(get_at_handler()); - } else { - return _stack; - } - } - virtual AT_CellularNetwork::RegistrationMode has_registration(RegistrationType reg_type) - { - if (reg_type == C_GREG) { - return RegistrationModeDisable; - } - return RegistrationModeLAC; - } - virtual nsapi_error_t set_access_technology_impl(RadioAccessTechnology op_rat) - { - return NSAPI_ERROR_OK; - } - virtual bool get_modem_stack_type(nsapi_ip_stack_t requested_stack) - { - if (requested_stack == IPV4_STACK || requested_stack == DEFAULT_STACK) { - return true; - } - return false; - } -}; - -class my_AT_CNipv6 : public AT_CellularNetwork { -public: - my_AT_CNipv6(ATHandler &atHandler) : AT_CellularNetwork(atHandler) {} - virtual ~my_AT_CNipv6() {} - NetworkStack *get_stack() - { - if (!_stack) { - return new my_stack(get_at_handler()); - } else { - return _stack; - } - } - virtual AT_CellularNetwork::RegistrationMode has_registration(RegistrationType reg_type) - { - if (reg_type == C_GREG) { - return RegistrationModeDisable; - } - return RegistrationModeLAC; - } - virtual nsapi_error_t set_access_technology_impl(RadioAccessTechnology op_rat) - { - return NSAPI_ERROR_OK; - } - virtual bool get_modem_stack_type(nsapi_ip_stack_t requested_stack) - { - if (requested_stack == IPV6_STACK || requested_stack == DEFAULT_STACK) { - return true; - } - return false; - } -}; - -static int network_cb_count; -static void network_cb(nsapi_event_t ev, intptr_t intptr) -{ - network_cb_count++; -} - -Test_AT_CellularNetwork::Test_AT_CellularNetwork() -{ - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::int_value = -1; -} - -Test_AT_CellularNetwork::~Test_AT_CellularNetwork() -{ -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_constructor() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork *cn = new AT_CellularNetwork(at); - - delete cn; -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_init() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - AT_CellularNetwork cn(at); - - CHECK(NSAPI_ERROR_OK == cn.init()); - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_NO_MEMORY; - CHECK(NSAPI_ERROR_NO_MEMORY == cn.init()); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_set_credentials() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - CHECK(NSAPI_ERROR_OK == cn.set_credentials("apn")); - CHECK(NSAPI_ERROR_OK == cn.set_credentials("apn", CellularNetwork::CHAP)); - CHECK(NSAPI_ERROR_OK == cn.set_credentials("apn", CellularNetwork::CHAP, NULL)); - CHECK(NSAPI_ERROR_OK == cn.set_credentials("apn", CellularNetwork::CHAP, NULL, NULL)); - CHECK(NSAPI_ERROR_OK == cn.set_credentials("apn", CellularNetwork::CHAP, NULL, "passwd")); - CHECK(NSAPI_ERROR_OK == cn.set_credentials("apn", CellularNetwork::CHAP, "user", NULL)); - CHECK(NSAPI_ERROR_OK == cn.set_credentials("apn", CellularNetwork::CHAP, "user")); - CHECK(NSAPI_ERROR_OK == cn.set_credentials("apn", CellularNetwork::CHAP, "user", "passwd")); - CHECK(NSAPI_ERROR_OK == cn.set_credentials("apn", NULL)); - CHECK(NSAPI_ERROR_OK == cn.set_credentials("apn", NULL, NULL)); - CHECK(NSAPI_ERROR_OK == cn.set_credentials("apn", NULL, "passwd")); - CHECK(NSAPI_ERROR_OK == cn.set_credentials("apn", "user", NULL)); - CHECK(NSAPI_ERROR_OK == cn.set_credentials("apn", "user")); - CHECK(NSAPI_ERROR_OK == cn.set_credentials("apn", "user", "passwd")); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_activate_context() -{ - - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - my_AT_CN my_cn(at); - my_AT_CNipv6 my_cnipv6(at); - - // get_context return true and new context created. But now stack and so error. - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - CHECK(NSAPI_ERROR_UNSUPPORTED == cn.activate_context()); - - // get_context return true and new context created, also do_user_authentication called with success. - // But now stack and so error. - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - CHECK(NSAPI_ERROR_OK == cn.set_credentials("apn", CellularNetwork::CHAP, "user", "passwd")); - CHECK(NSAPI_ERROR_UNSUPPORTED == cn.activate_context()); - - // get_context return true and new context created, also do_user_authentication called with failure. - ATHandler_stub::resp_stop_success_count = 2; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - CHECK(NSAPI_ERROR_OK == cn.set_credentials("apn", CellularNetwork::CHAP, "user", "passwd")); - CHECK(NSAPI_ERROR_AUTH_FAILURE == cn.activate_context()); - - - // get_context return true and new context created, also do_user_authentication called with success. - // Now there is stack. - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - ATHandler_stub::resp_stop_success_count = kResp_stop_count_default; - CHECK(NSAPI_ERROR_OK == my_cn.set_credentials("apn", CellularNetwork::CHAP, "user", "passwd")); - CHECK(NSAPI_ERROR_OK == my_cn.activate_context()); - - // get_context return true and new context created, test delete context - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - ATHandler_stub::resp_stop_success_count = kResp_stop_count_default; - CHECK(NSAPI_ERROR_OK == my_cn.set_credentials("apn", CellularNetwork::CHAP, "user", "passwd")); - CHECK(NSAPI_ERROR_OK == my_cn.activate_context()); - - - - // get_context pdp type gives zero len, fails with no stack - ATHandler_stub::resp_info_true_counter = 1; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - ATHandler_stub::read_string_index = 1; - ATHandler_stub::read_string_table[0] = ""; - ATHandler_stub::int_value = 1; - CHECK(NSAPI_ERROR_UNSUPPORTED == cn.activate_context()); - - // get_context pdp type gives proper type, apn reading fails - ATHandler_stub::resp_info_true_counter = 1; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - ATHandler_stub::read_string_index = 1; - ATHandler_stub::read_string_table[0] = "IPV6"; - ATHandler_stub::int_value = 1; - CHECK(NSAPI_ERROR_NO_CONNECTION == cn.activate_context()); - - // get_context pdp type gives proper type, apn does not match, now other contexts so new one created - ATHandler_stub::resp_info_true_counter = 1; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - ATHandler_stub::read_string_index = 2; - ATHandler_stub::read_string_table[0] = "internet"; - ATHandler_stub::read_string_table[1] = "IP"; - ATHandler_stub::int_value = 1; - CHECK(NSAPI_ERROR_OK == my_cn.set_credentials("apn", CellularNetwork::CHAP, "user", "passwd")); - CHECK(NSAPI_ERROR_OK == my_cn.activate_context()); - - // get_context pdp type gives proper type, apn match - ATHandler_stub::resp_info_true_counter = 2; // set to 2 so cgact will give that this context is active - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - ATHandler_stub::read_string_index = 2; - ATHandler_stub::read_string_table[0] = "internet"; - ATHandler_stub::read_string_table[1] = "IPV4V6"; - ATHandler_stub::int_value = 1; - CHECK(NSAPI_ERROR_OK == my_cn.set_stack_type(IPV4_STACK)); - CHECK(NSAPI_ERROR_OK == my_cn.set_credentials("internet")); - CHECK(NSAPI_ERROR_OK == my_cn.activate_context()); - - // get_context pdp type gives proper type, apn match - ATHandler_stub::resp_info_true_counter = 1; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - ATHandler_stub::read_string_index = 2; - ATHandler_stub::read_string_table[0] = "internet"; - ATHandler_stub::read_string_table[1] = "IPV6"; - ATHandler_stub::int_value = 1; - CHECK(NSAPI_ERROR_OK == my_cnipv6.set_stack_type(IPV6_STACK)); - CHECK(NSAPI_ERROR_OK == my_cnipv6.set_credentials("internet")); - CHECK(NSAPI_ERROR_OK == my_cnipv6.activate_context()); - - // get_context pdp type gives proper type, apn match - ATHandler_stub::resp_info_true_counter = 1; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - ATHandler_stub::read_string_index = 2; - ATHandler_stub::read_string_table[0] = "internet"; - ATHandler_stub::read_string_table[1] = "IPV4V6"; - ATHandler_stub::int_value = 1; - CHECK(NSAPI_ERROR_OK == my_cn.set_stack_type(DEFAULT_STACK)); - CHECK(NSAPI_ERROR_OK == my_cn.set_credentials("internet")); - CHECK(NSAPI_ERROR_OK == my_cn.activate_context()); - - // get_context pdp type gives proper type, apn match - ATHandler_stub::resp_info_true_counter = 1; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - ATHandler_stub::read_string_index = 2; - ATHandler_stub::read_string_table[0] = "internet"; - ATHandler_stub::read_string_table[1] = "IPV4V6"; - ATHandler_stub::int_value = 1; - CHECK(NSAPI_ERROR_OK == my_cnipv6.set_stack_type(DEFAULT_STACK)); - CHECK(NSAPI_ERROR_OK == my_cnipv6.set_credentials("internet")); - CHECK(NSAPI_ERROR_OK == my_cnipv6.activate_context()); - - // get_context pdp type gives proper type, apn match - ATHandler_stub::resp_info_true_counter = 1; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - ATHandler_stub::read_string_index = 2; - ATHandler_stub::read_string_table[0] = "internet"; - ATHandler_stub::read_string_table[1] = "IPV6"; - ATHandler_stub::int_value = 1; - CHECK(NSAPI_ERROR_OK == my_cnipv6.set_stack_type(DEFAULT_STACK)); - CHECK(NSAPI_ERROR_OK == my_cnipv6.set_credentials("internet")); - CHECK(NSAPI_ERROR_OK == my_cnipv6.activate_context()); - - // get_context pdp type gives proper type, apn match - ATHandler_stub::resp_info_true_counter = 1; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - ATHandler_stub::read_string_index = 2; - ATHandler_stub::read_string_table[0] = "internet"; - ATHandler_stub::read_string_table[1] = "IP"; - ATHandler_stub::int_value = 1; - CHECK(NSAPI_ERROR_OK == my_cn.set_stack_type(DEFAULT_STACK)); - CHECK(NSAPI_ERROR_OK == my_cn.set_credentials("internet")); - CHECK(NSAPI_ERROR_OK == my_cn.activate_context()); - - // get_context pdp type gives proper type, apn match. Test Delete the created context. - ATHandler_stub::resp_info_true_counter = 0; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - ATHandler_stub::int_value = 1; - //ATHandler_stub::nsapi_error_ok_counter = 2; - ATHandler_stub::resp_stop_success_count = 2; - CHECK(NSAPI_ERROR_OK == my_cn.set_credentials(NULL, NULL, NULL)); - CHECK(NSAPI_ERROR_NO_CONNECTION == my_cn.activate_context()); - -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_connect() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - // no stack so will fail - cn.attach(&network_cb); - network_cb_count = 0; - - CHECK(NSAPI_ERROR_UNSUPPORTED == cn.connect("APN", "a", "b")); - CHECK(NSAPI_STATUS_DISCONNECTED == cn.get_connection_status()); - CHECK(network_cb_count == 2); - - network_cb_count = 0; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_NO_CONNECTION == cn.connect("APN")); - CHECK(network_cb_count == 2); - CHECK(NSAPI_STATUS_DISCONNECTED == cn.get_connection_status()); - - my_AT_CN my_cn(at); - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - cn.set_stack_type(IPV4_STACK); - CHECK(NSAPI_ERROR_OK == my_cn.connect()); - CHECK(network_cb_count == 2); - CHECK(NSAPI_STATUS_GLOBAL_UP == my_cn.get_connection_status()); - -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_disconnect() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - CHECK(NSAPI_ERROR_OK == cn.disconnect()); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_stack() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - my_AT_CN my_cn(at); - my_stack *mystack = (my_stack *)my_cn.get_stack(); - CHECK(mystack); - delete mystack; -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_set_registration() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.set_registration()); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == cn.set_registration()); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.set_registration("12345")); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == cn.set_registration("12345")); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_registration_status() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::int_value = 3; - CellularNetwork::RegistrationStatus stat = CellularNetwork::NotRegistered; - CHECK(NSAPI_ERROR_OK == cn.get_registration_status(CellularNetwork::C_EREG, stat)); - CHECK(stat == CellularNetwork::RegistrationDenied); - stat = CellularNetwork::NotRegistered; - CHECK(NSAPI_ERROR_OK == cn.get_registration_status(CellularNetwork::C_GREG, stat)); - CHECK(stat == CellularNetwork::RegistrationDenied); - - my_AT_CN nw(at); - stat = CellularNetwork::NotRegistered; - CHECK(NSAPI_ERROR_UNSUPPORTED == nw.get_registration_status(CellularNetwork::C_GREG, stat)); - CHECK(stat == CellularNetwork::NotRegistered); - CHECK(NSAPI_ERROR_OK == nw.get_registration_status(CellularNetwork::C_EREG, stat)); - CHECK(stat == CellularNetwork::RegistrationDenied); - - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - stat = CellularNetwork::NotRegistered; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.get_registration_status(CellularNetwork::C_EREG, stat)); - CHECK(stat == -1); - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.get_registration_status(CellularNetwork::C_GREG, stat)); - CHECK(stat == -1); - - stat = CellularNetwork::NotRegistered; - CHECK(NSAPI_ERROR_UNSUPPORTED == nw.get_registration_status(CellularNetwork::C_GREG, stat)); - CHECK(stat == CellularNetwork::NotRegistered); - CHECK(NSAPI_ERROR_DEVICE_ERROR == nw.get_registration_status(CellularNetwork::C_EREG, stat)); - CHECK(stat == -1); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_network_registering_mode() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - - ATHandler_stub::int_value = 0; - CellularNetwork::NWRegisteringMode mode = CellularNetwork::NWModeManual; - CHECK(NSAPI_ERROR_OK == cn.get_network_registering_mode(mode)); - CHECK(mode == CellularNetwork::NWModeAutomatic); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - mode = CellularNetwork::NWModeManual; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.get_network_registering_mode(mode)); - CHECK(mode == -1); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_set_registration_urc() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - - CellularNetwork::RegistrationType type = CellularNetwork::C_EREG; - CHECK(NSAPI_ERROR_OK == cn.set_registration_urc(type, true)); - type = CellularNetwork::C_GREG; - CHECK(NSAPI_ERROR_OK == cn.set_registration_urc(type, true)); - type = CellularNetwork::C_REG; - CHECK(NSAPI_ERROR_OK == cn.set_registration_urc(type, true)); - - my_AT_CN nw(at); - type = CellularNetwork::C_EREG; - CHECK(NSAPI_ERROR_OK == nw.set_registration_urc(type, true)); - type = CellularNetwork::C_GREG; - CHECK(NSAPI_ERROR_UNSUPPORTED == nw.set_registration_urc(type, true)); - type = CellularNetwork::C_REG; - CHECK(NSAPI_ERROR_OK == nw.set_registration_urc(type, true)); - - type = CellularNetwork::C_EREG; - CHECK(NSAPI_ERROR_OK == cn.set_registration_urc(type, false)); - type = CellularNetwork::C_GREG; - CHECK(NSAPI_ERROR_OK == cn.set_registration_urc(type, false)); - type = CellularNetwork::C_REG; - CHECK(NSAPI_ERROR_OK == cn.set_registration_urc(type, false)); - - type = CellularNetwork::C_EREG; - CHECK(NSAPI_ERROR_OK == nw.set_registration_urc(type, false)); - type = CellularNetwork::C_GREG; - CHECK(NSAPI_ERROR_UNSUPPORTED == nw.set_registration_urc(type, false)); - type = CellularNetwork::C_REG; - CHECK(NSAPI_ERROR_OK == nw.set_registration_urc(type, false)); - - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - type = CellularNetwork::C_EREG; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.set_registration_urc(type, true)); - type = CellularNetwork::C_GREG; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.set_registration_urc(type, true)); - type = CellularNetwork::C_REG; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.set_registration_urc(type, true)); - - type = CellularNetwork::C_EREG; - CHECK(NSAPI_ERROR_DEVICE_ERROR == nw.set_registration_urc(type, true)); - type = CellularNetwork::C_GREG; - CHECK(NSAPI_ERROR_UNSUPPORTED == nw.set_registration_urc(type, true)); - type = CellularNetwork::C_REG; - CHECK(NSAPI_ERROR_DEVICE_ERROR == nw.set_registration_urc(type, true)); - - type = CellularNetwork::C_EREG; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.set_registration_urc(type, false)); - type = CellularNetwork::C_GREG; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.set_registration_urc(type, false)); - type = CellularNetwork::C_REG; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.set_registration_urc(type, false)); - - type = CellularNetwork::C_EREG; - CHECK(NSAPI_ERROR_DEVICE_ERROR == nw.set_registration_urc(type, false)); - type = CellularNetwork::C_GREG; - CHECK(NSAPI_ERROR_UNSUPPORTED == nw.set_registration_urc(type, false)); - type = CellularNetwork::C_REG; - CHECK(NSAPI_ERROR_DEVICE_ERROR == nw.set_registration_urc(type, false)); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_set_attach() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - ATHandler_stub::int_value = 0; - CHECK(NSAPI_ERROR_OK == cn.set_attach()); - ATHandler_stub::int_value = 1; - CHECK(NSAPI_ERROR_OK == cn.set_attach()); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.set_attach()); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_attach() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - CellularNetwork::AttachStatus stat = CellularNetwork::Detached; - ATHandler_stub::int_value = 1; - ATHandler_stub::bool_value = true; - CHECK(NSAPI_ERROR_OK == cn.get_attach(stat)); - CHECK(stat == CellularNetwork::Attached); - - ATHandler_stub::int_value = 0; - CHECK(NSAPI_ERROR_OK == cn.get_attach(stat)); - CHECK(stat == CellularNetwork::Detached); - - stat = CellularNetwork::Attached; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.get_attach(stat)); - CHECK(stat == CellularNetwork::Detached); - - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - CHECK(NSAPI_ERROR_OK == cn.get_attach(stat)); - CHECK(stat == CellularNetwork::Detached); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - ATHandler_stub::bool_value = false; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.get_attach(stat)); - CHECK(stat == CellularNetwork::Detached); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_detach() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - my_AT_CN cn(at); - - CHECK(NSAPI_ERROR_OK == cn.detach()); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.detach()); - - // connect so we can test callback in detach - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - cn.set_stack_type(IPV4_STACK); - CHECK(NSAPI_ERROR_OK == cn.connect()); - CHECK(NSAPI_STATUS_GLOBAL_UP == cn.get_connection_status()); - // attach callback - cn.attach(&network_cb); - network_cb_count = 0; - CHECK(NSAPI_ERROR_OK == cn.detach()); - CHECK(network_cb_count == 1); - CHECK(NSAPI_STATUS_DISCONNECTED == cn.get_connection_status()); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_rate_control() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - int ur = -1; - CellularNetwork::RateControlExceptionReports reports = CellularNetwork::NotAllowedToBeSent; - CellularNetwork::RateControlUplinkTimeUnit timeUnit = CellularNetwork::Unrestricted; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.get_rate_control(reports, timeUnit, ur)); - CHECK(reports == CellularNetwork::NotAllowedToBeSent); - CHECK(timeUnit == CellularNetwork::Unrestricted); - CHECK(ur == -1); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::int_value = 1; - CHECK(NSAPI_ERROR_OK == cn.get_rate_control(reports, timeUnit, ur)); - CHECK(reports == CellularNetwork::AllowedToBeSent); - CHECK(timeUnit == CellularNetwork::Minute); - CHECK(ur == 1); - - // test second if in get_rate_control - reports = CellularNetwork::NotAllowedToBeSent; - timeUnit = CellularNetwork::Unrestricted; - ur = -1; - - ATHandler_stub::int_count = 1; - ATHandler_stub::int_valid_count_table[0] = 1; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.get_rate_control(reports, timeUnit, ur)); - CHECK(reports == CellularNetwork::NotAllowedToBeSent); - CHECK(timeUnit == CellularNetwork::Unrestricted); - CHECK(ur == -1); - - // test second if in get_rate_control - ATHandler_stub::int_count = 2; - ATHandler_stub::int_valid_count_table[0] = 1; - ATHandler_stub::int_valid_count_table[1] = 1; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.get_rate_control(reports, timeUnit, ur)); - CHECK(reports == CellularNetwork::AllowedToBeSent); - CHECK(timeUnit == CellularNetwork::Unrestricted); - CHECK(ur == -1); - - // test third if in get_rate_control - ATHandler_stub::int_count = 3; - ATHandler_stub::int_valid_count_table[0] = 3; - ATHandler_stub::int_valid_count_table[1] = 1; - ATHandler_stub::int_valid_count_table[2] = 1; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.get_rate_control(reports, timeUnit, ur)); - CHECK(reports == CellularNetwork::AllowedToBeSent); - CHECK(timeUnit == CellularNetwork::Day); - CHECK(ur == -1); - - ATHandler_stub::int_count = 4; - ATHandler_stub::int_valid_count_table[0] = 5; - ATHandler_stub::int_valid_count_table[1] = 3; - ATHandler_stub::int_valid_count_table[2] = 1; - ATHandler_stub::int_valid_count_table[3] = 1; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == cn.get_rate_control(reports, timeUnit, ur)); - CHECK(reports == CellularNetwork::AllowedToBeSent); - CHECK(timeUnit == CellularNetwork::Day); - CHECK(ur == 5); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_apn_backoff_timer() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - int time = -1; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_PARAMETER == cn.get_apn_backoff_timer(time)); - CHECK(time == -1); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_PARAMETER == cn.get_apn_backoff_timer(time)); - CHECK(time == -1); - - ATHandler_stub::resp_info_true_counter = 0; - ATHandler_stub::bool_value = false; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - cn.set_credentials("internet", NULL, NULL); - CHECK(NSAPI_ERROR_OK == cn.get_apn_backoff_timer(time)); - CHECK(time == -1); - - ATHandler_stub::resp_info_true_counter = 0; - ATHandler_stub::bool_value = true; - ATHandler_stub::int_value = 55; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - cn.set_credentials("internet", NULL, NULL); - CHECK(NSAPI_ERROR_OK == cn.get_apn_backoff_timer(time)); - CHECK(time == 55); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_ip_address() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - CHECK(!cn.get_ip_address()); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_set_access_technology() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_UNSUPPORTED == cn.set_access_technology(CellularNetwork::RAT_UNKNOWN)); - CHECK(NSAPI_ERROR_UNSUPPORTED == cn.set_access_technology(CellularNetwork::RAT_GSM_COMPACT)); - - my_AT_CN my_cn(at); - CHECK(NSAPI_ERROR_OK == my_cn.set_access_technology(CellularNetwork::RAT_GSM_COMPACT)); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_access_technology() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - CellularNetwork::RadioAccessTechnology rat; - - CHECK(NSAPI_ERROR_OK == cn.get_access_technology(rat)); - CHECK(CellularNetwork::RAT_UNKNOWN == rat); -} - - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_scan_plmn() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - int c = -1; - CellularNetwork::operList_t ops; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.scan_plmn(ops, c)); - CHECK(c == 0); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == cn.scan_plmn(ops, c)); - CHECK(c == 0); - - - ATHandler_stub::read_string_index = 3; - ATHandler_stub::read_string_table[0] = "44444"; - ATHandler_stub::read_string_table[1] = "33333"; - ATHandler_stub::read_string_table[2] = "12345"; - ATHandler_stub::int_value = 1; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::info_elem_true_counter = 1; - ATHandler_stub::bool_value = false; - CHECK(NSAPI_ERROR_OK == cn.scan_plmn(ops, c)); - CHECK(c == 1); - CHECK(ops.get_head() != NULL); - CellularNetwork::operator_t *op = ops.get_head(); - CHECK(op->op_status == CellularNetwork::operator_t::Available); - CHECK(strcmp(op->op_long, "12345") == 0); - CHECK(strcmp(op->op_short, "33333") == 0); - CHECK(strcmp(op->op_num, "44444") == 0); - ops.delete_all(); - - ATHandler_stub::read_string_index = 3; - ATHandler_stub::int_value = 6; // RAT_HSDPA_HSUPA - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::info_elem_true_counter = 1; - ATHandler_stub::bool_value = false; - CHECK(NSAPI_ERROR_UNSUPPORTED == cn.set_access_technology(CellularNetwork::RAT_UTRAN)); - CHECK(NSAPI_ERROR_OK == cn.scan_plmn(ops, c)); - CHECK(c == 0); - CHECK(ops.get_head() == NULL); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_set_ciot_optimization_config() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == cn.set_ciot_optimization_config(CellularNetwork::SUPPORTED_UE_OPT_NO_SUPPORT, CellularNetwork::PREFERRED_UE_OPT_NO_PREFERENCE)); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.set_ciot_optimization_config(CellularNetwork::SUPPORTED_UE_OPT_NO_SUPPORT, CellularNetwork::PREFERRED_UE_OPT_NO_PREFERENCE)); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_ciot_optimization_config() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - CellularNetwork::Supported_UE_Opt sup = CellularNetwork::SUPPORTED_UE_OPT_NO_SUPPORT; - CellularNetwork::Preferred_UE_Opt pref = CellularNetwork::PREFERRED_UE_OPT_NO_PREFERENCE; - ATHandler_stub::int_value = 1; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == cn.get_ciot_optimization_config(sup, pref)); - CHECK(sup == CellularNetwork::SUPPORTED_UE_OPT_CONTROL_PLANE); - CHECK(pref == CellularNetwork::PREFERRED_UE_OPT_CONTROL_PLANE); - - sup = CellularNetwork::SUPPORTED_UE_OPT_NO_SUPPORT; - pref = CellularNetwork::PREFERRED_UE_OPT_NO_PREFERENCE; - ATHandler_stub::int_value = 1; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.get_ciot_optimization_config(sup, pref)); - CHECK(sup == CellularNetwork::SUPPORTED_UE_OPT_NO_SUPPORT); - CHECK(pref == CellularNetwork::PREFERRED_UE_OPT_NO_PREFERENCE); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_set_stack_type() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - CHECK(NSAPI_ERROR_PARAMETER == cn.set_stack_type(IPV4_STACK)); - - CHECK(NSAPI_ERROR_OK == cn.set_stack_type(DEFAULT_STACK)); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_stack_type() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - CHECK(DEFAULT_STACK == cn.get_stack_type()); - - my_AT_CN my_cn(at); - CHECK(DEFAULT_STACK == my_cn.get_stack_type()); - CHECK(NSAPI_ERROR_OK == my_cn.set_stack_type(IPV4_STACK)); - CHECK(DEFAULT_STACK == my_cn.get_stack_type()); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_pdpcontext_params() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - CellularNetwork::pdpContextList_t list; - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.get_pdpcontext_params(list)); - - // don't got to while loop - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - ATHandler_stub::resp_info_true_counter = 0; - CHECK(NSAPI_ERROR_OK == cn.get_pdpcontext_params(list)); - CHECK(NULL == list.get_head()); - - // go to while loop and check values - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::resp_info_true_counter = 1; - ATHandler_stub::int_count = 9; - ATHandler_stub::int_valid_count_table[8] = 1; - ATHandler_stub::int_valid_count_table[7] = 2; - ATHandler_stub::int_valid_count_table[6] = 3; - ATHandler_stub::int_valid_count_table[5] = 4; - ATHandler_stub::int_valid_count_table[4] = 5; - ATHandler_stub::int_valid_count_table[3] = 6; - ATHandler_stub::int_valid_count_table[2] = 7; - ATHandler_stub::int_valid_count_table[1] = 8; - ATHandler_stub::int_valid_count_table[0] = 9; - - ATHandler_stub::read_string_index = 7; - ATHandler_stub::read_string_table[6] = "internet"; - ATHandler_stub::read_string_table[5] = "1.2.3.4.5.6.7.8.9.10.11.112.13.14.15.16.1.2.3.44.55.6.7.8.9.10.11.12.13.14.15.16"; - ATHandler_stub::read_string_table[4] = "23.33.44.1.2.3.55.123.225.34.11.1.0.0.123.234"; - ATHandler_stub::read_string_table[3] = "1.2.3.4"; - ATHandler_stub::read_string_table[2] = "0.255.0.255"; - ATHandler_stub::read_string_table[1] = "25.66.77.88"; - ATHandler_stub::read_string_table[0] = "004.003.002.001"; - - CHECK(NSAPI_ERROR_OK == cn.get_pdpcontext_params(list)); - CellularNetwork::pdpcontext_params_t *params = list.get_head(); - CHECK(params != NULL); - CHECK(params->next == NULL); - CHECK(params->cid == 1); - CHECK(params->bearer_id == 2); - CHECK(params->im_signalling_flag == 3); - CHECK(params->lipa_indication == 4); - CHECK(params->ipv4_mtu == 5); - CHECK(params->wlan_offload == 6); - CHECK(params->local_addr_ind == 7); - CHECK(params->non_ip_mtu == 8); - CHECK(params->serving_plmn_rate_control_value == 9); - CHECK(strcmp(params->apn, "internet") == 0); - CHECK(strcmp(params->local_addr, "102:304:506:708:90A:B70:D0E:F10") == 0); - CHECK(strcmp(params->local_subnet_mask, "102:32C:3706:708:90A:B0C:D0E:F10") == 0); - CHECK(strcmp(params->gateway_addr, "1721:2C01:203:377B:E122:B01:000:7BEA") == 0); - CHECK(strcmp(params->dns_primary_addr, "1.2.3.4") == 0); - CHECK(strcmp(params->dns_secondary_addr, "0.255.0.255") == 0); - CHECK(strcmp(params->p_cscf_prim_addr, "25.66.77.88") == 0); - CHECK(strcmp(params->p_cscf_sec_addr, "004.003.002.001") == 0); - -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_extended_signal_quality() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - int rx = -1, be = -1, rs = -1, ec = -1, rsrq = -1, rsrp = -1; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.get_extended_signal_quality(rx, be, rs, ec, rsrq, rsrp)); - CHECK(rx == -1 && be == -1 && rs == -1 && ec == -1 && rsrq == -1 && rsrp == -1); - - ATHandler_stub::int_value = 5; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == cn.get_extended_signal_quality(rx, be, rs, ec, rsrq, rsrp)); - CHECK(rx == 5 && be == 5 && rs == 5 && ec == 5 && rsrq == 5 && rsrp == 5); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_signal_quality() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - int rs = -1, ber = -1; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.get_signal_quality(rs, ber)); - CHECK(rs == -1 && ber == -1); - - ATHandler_stub::int_value = 1; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == cn.get_signal_quality(rs, ber)); - CHECK(rs == 1 && ber == 1); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_cell_id() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - int id = 0; - CHECK(NSAPI_ERROR_OK == cn.get_cell_id(id)); - CHECK(id == -1); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_OK == cn.get_cell_id(id)); - CHECK(id == -1); - - ATHandler_stub::read_string_index = 2; - ATHandler_stub::read_string_table[1] = "00C3"; - ATHandler_stub::read_string_table[0] = "1234FFC1"; //== cellid and in dec: 305463233 - ATHandler_stub::int_value = 1; - // Get registration status to modify cell_id - CellularNetwork::RegistrationType type; - CellularNetwork::RegistrationStatus status; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == cn.get_registration_status(CellularNetwork::C_EREG, status)); - CHECK(NSAPI_ERROR_OK == cn.get_cell_id(id)); - CHECK(id == 305463233); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_3gpp_error() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - ATHandler_stub::int_value = 8; - CHECK(8 == cn.get_3gpp_error()); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_operator_params() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - int format; - CellularNetwork::operator_t ops; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.get_operator_params(format, ops)); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::int_value = 0; - ATHandler_stub::read_string_index = 1; - ATHandler_stub::read_string_table[0] = "12345"; - CHECK(NSAPI_ERROR_OK == cn.get_operator_params(format, ops)); - CHECK(format == 0); - CHECK(strcmp(ops.op_long, "12345") == 0); - CHECK(strlen(ops.op_short) == 0); - CHECK(strlen(ops.op_num) == 0); - CHECK(ops.op_rat == CellularNetwork::RAT_GSM); - - ops.op_long[0] = 0; - ATHandler_stub::int_value = 1; - ATHandler_stub::read_string_index = 1; - ATHandler_stub::read_string_table[0] = "12345"; - CHECK(NSAPI_ERROR_OK == cn.get_operator_params(format, ops)); - CHECK(format == 1); - CHECK(strlen(ops.op_long) == 0); - CHECK(strcmp(ops.op_short, "12345") == 0); - CHECK(strlen(ops.op_num) == 0); - CHECK(ops.op_rat == CellularNetwork::RAT_GSM_COMPACT); - - ops.op_short[0] = 0; - ATHandler_stub::int_value = 2; - ATHandler_stub::read_string_index = 1; - ATHandler_stub::read_string_table[0] = "12345"; - CHECK(NSAPI_ERROR_OK == cn.get_operator_params(format, ops)); - CHECK(format == 2); - CHECK(strlen(ops.op_long) == 0); - CHECK(strlen(ops.op_short) == 0); - CHECK(strcmp(ops.op_num, "12345") == 0); - CHECK(ops.op_rat == CellularNetwork::RAT_UTRAN); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_operator_names() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - CellularNetwork::operator_names_list name_list; - - ATHandler_stub::resp_info_true_counter = 0; - ATHandler_stub::bool_value = false; - CHECK(NSAPI_ERROR_OK == cn.get_operator_names(name_list)); - CHECK(name_list.get_head() == NULL); - - ATHandler_stub::resp_info_true_counter = 1; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.get_operator_names(name_list)); - CHECK(name_list.get_head() != NULL); - CHECK(name_list.get_head()->next == NULL); - - ATHandler_stub::resp_info_true_counter = 1; - ATHandler_stub::bool_value = false; - ATHandler_stub::read_string_index = 2; - ATHandler_stub::read_string_table[1] = "12345"; - ATHandler_stub::read_string_table[0] = "56789"; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - name_list.delete_all(); - CHECK(NSAPI_ERROR_OK == cn.get_operator_names(name_list)); - CellularNetwork::operator_names_t *op_names = name_list.get_head(); - CHECK(op_names != NULL); - CHECK(op_names->next == NULL); - CHECK(strcmp(op_names->numeric, "12345") == 0); - CHECK(strcmp(op_names->alpha, "56789") == 0); -} - -void Test_AT_CellularNetwork::test_AT_CellularNetwork_attach() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - network_cb_count = 0; - cn.attach(&network_cb); - CHECK(NSAPI_ERROR_UNSUPPORTED == cn.connect()); - CHECK(network_cb_count == 2); // check that attached callback was called twice -} - -void Test_AT_CellularNetwork::test_get_connection_status() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - network_cb_count = 0; - cn.attach(&network_cb); - CHECK(NSAPI_ERROR_UNSUPPORTED == cn.connect()); - CHECK(network_cb_count == 2); // check that attached callback was called twice - CHECK(NSAPI_STATUS_DISCONNECTED == cn.get_connection_status()); - - my_AT_CN my_cn(at); - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::bool_value = false; - cn.set_stack_type(IPV4_STACK); - CHECK(NSAPI_ERROR_OK == my_cn.connect()); - CHECK(network_cb_count == 2); - CHECK(NSAPI_STATUS_GLOBAL_UP == my_cn.get_connection_status()); -} - -void Test_AT_CellularNetwork::test_set_blocking() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularNetwork cn(at); - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == cn.set_blocking(false)); - CHECK(NSAPI_ERROR_OK == cn.set_blocking(true)); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_OK == cn.set_blocking(false)); - CHECK(NSAPI_ERROR_OK == cn.set_blocking(true)); -} - diff --git a/features/cellular/UNITTESTS/at/at_cellularnetwork/test_at_cellularnetwork.h b/features/cellular/UNITTESTS/at/at_cellularnetwork/test_at_cellularnetwork.h deleted file mode 100644 index 2327a30979..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularnetwork/test_at_cellularnetwork.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2018, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef TEST_AT_CELLULARNETWORK_H -#define TEST_AT_CELLULARNETWORK_H - -class Test_AT_CellularNetwork { -public: - Test_AT_CellularNetwork(); - - virtual ~Test_AT_CellularNetwork(); - - void test_AT_CellularNetwork_constructor(); - - void test_AT_CellularNetwork_init(); - - void test_AT_CellularNetwork_set_credentials(); - - void test_AT_CellularNetwork_activate_context(); - - void test_AT_CellularNetwork_connect(); - - void test_AT_CellularNetwork_disconnect(); - - void test_AT_CellularNetwork_get_stack(); - - void test_AT_CellularNetwork_set_registration(); - - void test_AT_CellularNetwork_get_registration_status(); - - void test_AT_CellularNetwork_get_network_registering_mode(); - - void test_AT_CellularNetwork_set_registration_urc(); - - void test_AT_CellularNetwork_set_attach(); - - void test_AT_CellularNetwork_get_attach(); - - void test_AT_CellularNetwork_detach(); - - void test_AT_CellularNetwork_get_rate_control(); - - void test_AT_CellularNetwork_get_apn_backoff_timer(); - - void test_AT_CellularNetwork_get_ip_address(); - - void test_AT_CellularNetwork_set_access_technology(); - - void test_AT_CellularNetwork_get_access_technology(); - - void test_AT_CellularNetwork_scan_plmn(); - - void test_AT_CellularNetwork_set_ciot_optimization_config(); - - void test_AT_CellularNetwork_get_ciot_optimization_config(); - - void test_AT_CellularNetwork_set_stack_type(); - - void test_AT_CellularNetwork_get_stack_type(); - - void test_AT_CellularNetwork_get_pdpcontext_params(); - - void test_AT_CellularNetwork_get_extended_signal_quality(); - - void test_AT_CellularNetwork_get_signal_quality(); - - void test_AT_CellularNetwork_get_cell_id(); - - void test_AT_CellularNetwork_get_3gpp_error(); - - void test_AT_CellularNetwork_get_operator_params(); - - void test_AT_CellularNetwork_get_operator_names(); - - void test_AT_CellularNetwork_attach(); - - void test_get_connection_status(); - - void test_set_blocking(); -}; - -#endif // TEST_AT_CELLULARNETWORK_H - diff --git a/features/cellular/UNITTESTS/at/at_cellularpower/Makefile b/features/cellular/UNITTESTS/at/at_cellularpower/Makefile deleted file mode 100644 index 6ebcef37e4..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularpower/Makefile +++ /dev/null @@ -1,23 +0,0 @@ -include ../../makefile_defines.txt - -COMPONENT_NAME = AT_CellularPower_unit - -#This must be changed manually -SRC_FILES = \ - ../../../framework/AT/AT_CellularPower.cpp - -TEST_SRC_FILES = \ - main.cpp \ - at_cellularpowertest.cpp \ - test_at_cellularpower.cpp \ - ../../stubs/ATHandler_stub.cpp \ - ../../stubs/AT_CellularBase_stub.cpp \ - ../../stubs/EventQueue_stub.cpp \ - ../../stubs/FileHandle_stub.cpp \ - ../../stubs/CellularUtil_stub.cpp \ - ../../stubs/mbed_assert_stub.cpp \ - -include ../../MakefileWorker.mk - -CPPUTESTFLAGS += -DFEA_TRACE_SUPPORT - diff --git a/features/cellular/UNITTESTS/at/at_cellularpower/at_cellularpowertest.cpp b/features/cellular/UNITTESTS/at/at_cellularpower/at_cellularpowertest.cpp deleted file mode 100644 index 2ce7b6dd02..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularpower/at_cellularpowertest.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2015, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "CppUTest/TestHarness.h" -#include "test_at_cellularpower.h" - -// AStyle ignored as the definition is not clear due to preprocessor usage -// *INDENT-OFF* -TEST_GROUP(AT_CellularPower) -{ - Test_AT_CellularPower *unit; - - void setup() { - unit = new Test_AT_CellularPower(); - } - - void teardown() { - delete unit; - } -}; -// *INDENT-ON* - -TEST(AT_CellularPower, Create) -{ - CHECK(unit != NULL); -} - -TEST(AT_CellularPower, test_AT_CellularPower_constructor) -{ - unit->test_AT_CellularPower_constructor(); -} - -TEST(AT_CellularPower, test_AT_CellularPower_on) -{ - unit->test_AT_CellularPower_on(); -} - -TEST(AT_CellularPower, test_AT_CellularPower_off) -{ - unit->test_AT_CellularPower_off(); -} - -TEST(AT_CellularPower, test_AT_CellularPower_set_at_mode) -{ - unit->test_AT_CellularPower_set_at_mode(); -} - -TEST(AT_CellularPower, test_AT_CellularPower_set_power_level) -{ - unit->test_AT_CellularPower_set_power_level(); -} - -TEST(AT_CellularPower, test_AT_CellularPower_reset) -{ - unit->test_AT_CellularPower_reset(); -} - -TEST(AT_CellularPower, test_AT_CellularPower_opt_power_save_mode) -{ - unit->test_AT_CellularPower_opt_power_save_mode(); -} - -TEST(AT_CellularPower, test_AT_CellularPower_opt_receive_period) -{ - unit->test_AT_CellularPower_opt_receive_period(); -} - -TEST(AT_CellularPower, test_AT_CellularPower_is_device_ready) -{ - unit->test_AT_CellularPower_is_device_ready(); -} - -TEST(AT_CellularPower, test_AT_CellularPower_set_device_ready_urc_cb) -{ - unit->test_AT_CellularPower_set_device_ready_urc_cb(); -} - -TEST(AT_CellularPower, test_AT_CellularPower_remove_device_ready_urc_cb) -{ - unit->test_AT_CellularPower_remove_device_ready_urc_cb(); -} diff --git a/features/cellular/UNITTESTS/at/at_cellularpower/main.cpp b/features/cellular/UNITTESTS/at/at_cellularpower/main.cpp deleted file mode 100644 index 5580d26166..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularpower/main.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2015, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "CppUTest/CommandLineTestRunner.h" -#include "CppUTest/TestPlugin.h" -#include "CppUTest/TestRegistry.h" -#include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char **av) -{ - return CommandLineTestRunner::RunAllTests(ac, av); -} - -IMPORT_TEST_GROUP(AT_CellularPower); - diff --git a/features/cellular/UNITTESTS/at/at_cellularpower/test_at_cellularpower.h b/features/cellular/UNITTESTS/at/at_cellularpower/test_at_cellularpower.h deleted file mode 100644 index c24f7809e6..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularpower/test_at_cellularpower.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2018, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef TEST_AT_CELLULARPOWER_H -#define TEST_AT_CELLULARPOWER_H - -class Test_AT_CellularPower { -public: - Test_AT_CellularPower(); - - virtual ~Test_AT_CellularPower(); - - void test_AT_CellularPower_constructor(); - - void test_AT_CellularPower_on(); - - void test_AT_CellularPower_off(); - - void test_AT_CellularPower_set_at_mode(); - - void test_AT_CellularPower_set_power_level(); - - void test_AT_CellularPower_reset(); - - void test_AT_CellularPower_opt_power_save_mode(); - - void test_AT_CellularPower_opt_receive_period(); - - void test_AT_CellularPower_is_device_ready(); - - void test_AT_CellularPower_set_device_ready_urc_cb(); - - void test_AT_CellularPower_remove_device_ready_urc_cb(); -}; - -#endif // TEST_AT_CELLULARPOWER_H - diff --git a/features/cellular/UNITTESTS/at/at_cellularsim/Makefile b/features/cellular/UNITTESTS/at/at_cellularsim/Makefile deleted file mode 100644 index 8c50af13cc..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularsim/Makefile +++ /dev/null @@ -1,24 +0,0 @@ -include ../../makefile_defines.txt - -COMPONENT_NAME = AT_CellularSIM_unit - -#This must be changed manually -SRC_FILES = \ - ../../../framework/AT/AT_CellularSIM.cpp - -TEST_SRC_FILES = \ - main.cpp \ - at_cellularsimtest.cpp \ - test_at_cellularsim.cpp \ - ../../stubs/ATHandler_stub.cpp \ - ../../stubs/AT_CellularBase_stub.cpp \ - ../../stubs/EventQueue_stub.cpp \ - ../../stubs/FileHandle_stub.cpp \ - ../../stubs/CellularUtil_stub.cpp \ - ../../stubs/us_ticker_stub.cpp \ - ../../stubs/mbed_assert_stub.cpp \ - -include ../../MakefileWorker.mk - -CPPUTESTFLAGS += -DFEA_TRACE_SUPPORT - diff --git a/features/cellular/UNITTESTS/at/at_cellularsim/at_cellularsimtest.cpp b/features/cellular/UNITTESTS/at/at_cellularsim/at_cellularsimtest.cpp deleted file mode 100644 index 2d4c2c70ec..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularsim/at_cellularsimtest.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2015, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "CppUTest/TestHarness.h" -#include "test_at_cellularsim.h" -#include "ATHandler_stub.h" - -// AStyle ignored as the definition is not clear due to preprocessor usage -// *INDENT-OFF* -TEST_GROUP(AT_CellularSIM) -{ - Test_AT_CellularSIM *unit; - - void setup() - { - unit = new Test_AT_CellularSIM(); - ATHandler_stub::read_string_index = kRead_string_table_size; - } - - void teardown() - { - delete unit; - } -}; -// *INDENT-ON* - -TEST(AT_CellularSIM, Create) -{ - CHECK(unit != NULL); -} - -TEST(AT_CellularSIM, test_AT_CellularSIM_constructor) -{ - unit->test_AT_CellularSIM_constructor(); -} - -TEST(AT_CellularSIM, test_AT_CellularSIM_set_pin) -{ - unit->test_AT_CellularSIM_set_pin(); -} - -TEST(AT_CellularSIM, test_AT_CellularSIM_change_pin) -{ - unit->test_AT_CellularSIM_change_pin(); -} - -TEST(AT_CellularSIM, test_AT_CellularSIM_set_pin_query) -{ - unit->test_AT_CellularSIM_set_pin_query(); -} - -TEST(AT_CellularSIM, test_AT_CellularSIM_get_sim_state) -{ - unit->test_AT_CellularSIM_get_sim_state(); -} - -TEST(AT_CellularSIM, test_AT_CellularSIM_get_imsi) -{ - unit->test_AT_CellularSIM_get_imsi(); -} - -TEST(AT_CellularSIM, test_AT_CellularSIM_get_iccid) -{ - unit->test_AT_CellularSIM_get_iccid(); -} diff --git a/features/cellular/UNITTESTS/at/at_cellularsim/main.cpp b/features/cellular/UNITTESTS/at/at_cellularsim/main.cpp deleted file mode 100644 index 394a1f7d6d..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularsim/main.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2015, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "CppUTest/CommandLineTestRunner.h" -#include "CppUTest/TestPlugin.h" -#include "CppUTest/TestRegistry.h" -#include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char **av) -{ - return CommandLineTestRunner::RunAllTests(ac, av); -} - -IMPORT_TEST_GROUP(AT_CellularSIM); - diff --git a/features/cellular/UNITTESTS/at/at_cellularsim/test_at_cellularsim.cpp b/features/cellular/UNITTESTS/at/at_cellularsim/test_at_cellularsim.cpp deleted file mode 100644 index 3ba07f791e..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularsim/test_at_cellularsim.cpp +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) 2018, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "CppUTest/TestHarness.h" -#include "test_at_cellularsim.h" -#include -#include "AT_CellularNetwork.h" -#include "EventQueue.h" -#include "ATHandler.h" -#include "AT_CellularSIM.h" -#include "FileHandle_stub.h" -#include "CellularLog.h" -#include "ATHandler_stub.h" - -using namespace mbed; -using namespace events; - -Test_AT_CellularSIM::Test_AT_CellularSIM() -{ - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::read_string_value = NULL; - ATHandler_stub::ssize_value = 0; -} - -Test_AT_CellularSIM::~Test_AT_CellularSIM() -{ -} - -void Test_AT_CellularSIM::test_AT_CellularSIM_constructor() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularSIM *sim = new AT_CellularSIM(at); - - delete sim; -} - -void Test_AT_CellularSIM::test_AT_CellularSIM_set_pin() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularSIM sim(at); - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == sim.set_pin("12")); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == sim.set_pin("12")); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::read_string_value = "READY"; - ATHandler_stub::ssize_value = 5; - CHECK(NSAPI_ERROR_OK == sim.set_pin("12")); - - CHECK(NSAPI_ERROR_OK == sim.set_pin(NULL)); -} - -void Test_AT_CellularSIM::test_AT_CellularSIM_change_pin() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularSIM sim(at); - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == sim.change_pin("12", "34")); - CHECK(NSAPI_ERROR_OK == sim.change_pin(NULL, "34")); - CHECK(NSAPI_ERROR_OK == sim.change_pin("12", NULL)); - CHECK(NSAPI_ERROR_OK == sim.change_pin(NULL, NULL)); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == sim.change_pin("12", "34")); -} - -void Test_AT_CellularSIM::test_AT_CellularSIM_set_pin_query() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularSIM sim(at); - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == sim.set_pin_query("12", true)); - CHECK(NSAPI_ERROR_OK == sim.set_pin_query(NULL, true)); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == sim.set_pin_query("12", false)); - CHECK(NSAPI_ERROR_OK == sim.set_pin_query(NULL, false)); - - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - CHECK(NSAPI_ERROR_DEVICE_ERROR == sim.set_pin_query("12", false)); - CHECK(NSAPI_ERROR_DEVICE_ERROR == sim.set_pin_query("12", true)); -} - -void Test_AT_CellularSIM::test_AT_CellularSIM_get_sim_state() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - AT_CellularSIM sim(at); - CellularSIM::SimState state; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::ssize_value = -1; - ATHandler_stub::read_string_value = NULL; - CHECK(NSAPI_ERROR_OK == sim.get_sim_state(state)); - CHECK(CellularSIM::SimStateUnknown == state); - - ATHandler_stub::read_string_value = "READY"; - ATHandler_stub::ssize_value = 5; - CHECK(NSAPI_ERROR_OK == sim.get_sim_state(state)); - CHECK(CellularSIM::SimStateReady == state); - - ATHandler_stub::read_string_value = "SIM PIN"; - ATHandler_stub::ssize_value = 7; - CHECK(NSAPI_ERROR_OK == sim.get_sim_state(state)); - CHECK(CellularSIM::SimStatePinNeeded == state); - - ATHandler_stub::read_string_value = "SIM PUK"; - ATHandler_stub::ssize_value = 7; - CHECK(NSAPI_ERROR_OK == sim.get_sim_state(state)); - CHECK(CellularSIM::SimStatePukNeeded == state); - - ATHandler_stub::read_string_value = "SOME CRAP"; - ATHandler_stub::ssize_value = 9; - CHECK(NSAPI_ERROR_OK == sim.get_sim_state(state)); - CHECK(CellularSIM::SimStateUnknown == state); -} - -void Test_AT_CellularSIM::test_AT_CellularSIM_get_imsi() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - char imsi[16]; - AT_CellularSIM sim(at); - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::read_string_value = "123456789012345"; - ATHandler_stub::ssize_value = 15; - CHECK(NSAPI_ERROR_OK == sim.get_imsi(imsi)); - CHECK(strcmp(ATHandler_stub::read_string_value, imsi) == 0); - - ATHandler_stub::read_string_value = NULL; - ATHandler_stub::ssize_value = -1; - ATHandler_stub::read_string_index = -1; - imsi[0] = 0; - CHECK(NSAPI_ERROR_DEVICE_ERROR == sim.get_imsi(imsi)); - CHECK(strlen(imsi) == 0); - - CHECK(NSAPI_ERROR_PARAMETER == sim.get_imsi(NULL)); - - // this would fail as get_imsi should take another param which is the size of the buffer which we could use for validation. - // Now we have improved documentation that that the given imsi buffer size must be over 15. - //char imsi2[5]; - //CHECK(NSAPI_ERROR_PARAMETER == sim.get_imsi(imsi2)); -} - -void Test_AT_CellularSIM::test_AT_CellularSIM_get_iccid() -{ - EventQueue que; - FileHandle_stub fh1; - ATHandler at(&fh1, que, 0, ","); - - char buf[16]; - AT_CellularSIM sim(at); - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - ATHandler_stub::read_string_value = "123456789012345"; - ATHandler_stub::ssize_value = 15; - CHECK(NSAPI_ERROR_OK == sim.get_iccid(buf, 16)); - CHECK(strcmp(ATHandler_stub::read_string_value, buf) == 0); - - buf[0] = 0; - ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR; - ATHandler_stub::read_string_value = NULL; - ATHandler_stub::ssize_value = -1; - CHECK(NSAPI_ERROR_DEVICE_ERROR == sim.get_iccid(buf, 16)); - CHECK(strlen(buf) == 0); -} diff --git a/features/cellular/UNITTESTS/at/at_cellularsim/test_at_cellularsim.h b/features/cellular/UNITTESTS/at/at_cellularsim/test_at_cellularsim.h deleted file mode 100644 index 5c78cdbd40..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularsim/test_at_cellularsim.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2018, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef TEST_AT_CELLULARSIM_H -#define TEST_AT_CELLULARSIM_H - -class Test_AT_CellularSIM { -public: - Test_AT_CellularSIM(); - - virtual ~Test_AT_CellularSIM(); - - void test_AT_CellularSIM_constructor(); - - void test_AT_CellularSIM_set_pin(); - - void test_AT_CellularSIM_change_pin(); - - void test_AT_CellularSIM_set_pin_query(); - - void test_AT_CellularSIM_get_sim_state(); - - void test_AT_CellularSIM_get_imsi(); - - void test_AT_CellularSIM_get_iccid(); -}; - -#endif // TEST_AT_CELLULARSIM_H - diff --git a/features/cellular/UNITTESTS/at/at_cellularsms/Makefile b/features/cellular/UNITTESTS/at/at_cellularsms/Makefile deleted file mode 100644 index dd7a07ce1b..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularsms/Makefile +++ /dev/null @@ -1,25 +0,0 @@ -include ../../makefile_defines.txt - -COMPONENT_NAME = AT_CellularSMS_unit - -#This must be changed manually -SRC_FILES = \ - ../../../framework/AT/AT_CellularSMS.cpp - -TEST_SRC_FILES = \ - main.cpp \ - at_cellularsmstest.cpp \ - test_at_cellularsms.cpp \ - ../../stubs/ATHandler_stub.cpp \ - ../../stubs/AT_CellularBase_stub.cpp \ - ../../stubs/EventQueue_stub.cpp \ - ../../stubs/FileHandle_stub.cpp \ - ../../stubs/CellularUtil_stub.cpp \ - ../../stubs/us_ticker_stub.cpp \ - ../../stubs/mbed_assert_stub.cpp \ - ../../stubs/mbed_wait_api_stub.cpp \ - -include ../../MakefileWorker.mk - -CPPUTESTFLAGS += -DFEA_TRACE_SUPPORT - diff --git a/features/cellular/UNITTESTS/at/at_cellularsms/at_cellularsmstest.cpp b/features/cellular/UNITTESTS/at/at_cellularsms/at_cellularsmstest.cpp deleted file mode 100644 index d207cc8291..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularsms/at_cellularsmstest.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2015, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "CppUTest/TestHarness.h" -#include "test_at_cellularsms.h" - -// AStyle ignored as the definition is not clear due to preprocessor usage -// *INDENT-OFF* -TEST_GROUP(AT_CellularSMS) -{ - Test_AT_CellularSMS *unit; - - void setup() - { - unit = new Test_AT_CellularSMS(); - } - - void teardown() - { - delete unit; - } -}; -// *INDENT-ON* - -TEST(AT_CellularSMS, Create) -{ - CHECK(unit != NULL); -} - -TEST(AT_CellularSMS, test_AT_CellularSMS_constructor) -{ - unit->test_AT_CellularSMS_constructor(); -} - -TEST(AT_CellularSMS, test_AT_CellularSMS_initialize) -{ - unit->test_AT_CellularSMS_initialize(); -} - -TEST(AT_CellularSMS, test_AT_CellularSMS_send_sms) -{ - unit->test_AT_CellularSMS_send_sms(); -} - -TEST(AT_CellularSMS, test_AT_CellularSMS_get_sms) -{ - unit->test_AT_CellularSMS_get_sms(); -} - -TEST(AT_CellularSMS, test_AT_CellularSMS_set_sms_callback) -{ - unit->test_AT_CellularSMS_set_sms_callback(); -} - -TEST(AT_CellularSMS, test_AT_CellularSMS_set_cpms) -{ - unit->test_AT_CellularSMS_set_cpms(); -} - -TEST(AT_CellularSMS, test_AT_CellularSMS_set_csca) -{ - unit->test_AT_CellularSMS_set_csca(); -} - -TEST(AT_CellularSMS, test_AT_CellularSMS_set_cscs) -{ - unit->test_AT_CellularSMS_set_cscs(); -} - -TEST(AT_CellularSMS, test_AT_CellularSMS_delete_all_messages) -{ - unit->test_AT_CellularSMS_delete_all_messages(); -} - -TEST(AT_CellularSMS, test_AT_CellularSMS_set_extra_sim_wait_time) -{ - unit->test_AT_CellularSMS_set_extra_sim_wait_time(); -} diff --git a/features/cellular/UNITTESTS/at/at_cellularsms/main.cpp b/features/cellular/UNITTESTS/at/at_cellularsms/main.cpp deleted file mode 100644 index 04d6d690b0..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularsms/main.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2015, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "CppUTest/CommandLineTestRunner.h" -#include "CppUTest/TestPlugin.h" -#include "CppUTest/TestRegistry.h" -#include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char **av) -{ - return CommandLineTestRunner::RunAllTests(ac, av); -} - -IMPORT_TEST_GROUP(AT_CellularSMS); - diff --git a/features/cellular/UNITTESTS/at/at_cellularsms/test_at_cellularsms.h b/features/cellular/UNITTESTS/at/at_cellularsms/test_at_cellularsms.h deleted file mode 100644 index c83d312fa1..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularsms/test_at_cellularsms.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2018, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef TEST_AT_CELLULARSMS_H -#define TEST_AT_CELLULARSMS_H - -class Test_AT_CellularSMS { -public: - Test_AT_CellularSMS(); - - virtual ~Test_AT_CellularSMS(); - - void test_AT_CellularSMS_constructor(); - - void test_AT_CellularSMS_initialize(); - - void test_AT_CellularSMS_send_sms(); - - void test_AT_CellularSMS_get_sms(); - - void test_AT_CellularSMS_set_sms_callback(); - - void test_AT_CellularSMS_set_cpms(); - - void test_AT_CellularSMS_set_csca(); - - void test_AT_CellularSMS_set_cscs(); - - void test_AT_CellularSMS_delete_all_messages(); - - void test_AT_CellularSMS_set_extra_sim_wait_time(); -}; - -#endif // TEST_AT_CELLULARSMS_H - diff --git a/features/cellular/UNITTESTS/at/at_cellularstack/Makefile b/features/cellular/UNITTESTS/at/at_cellularstack/Makefile deleted file mode 100644 index 5371687a3e..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularstack/Makefile +++ /dev/null @@ -1,26 +0,0 @@ -include ../../makefile_defines.txt - -COMPONENT_NAME = AT_CellularStack_unit - -#This must be changed manually -SRC_FILES = \ - ../../../framework/AT/AT_CellularStack.cpp - -TEST_SRC_FILES = \ - main.cpp \ - at_cellularstacktest.cpp \ - test_at_cellularstack.cpp \ - ../../stubs/ATHandler_stub.cpp \ - ../../stubs/AT_CellularBase_stub.cpp \ - ../../stubs/EventQueue_stub.cpp \ - ../../stubs/FileHandle_stub.cpp \ - ../../stubs/CellularUtil_stub.cpp \ - ../../stubs/us_ticker_stub.cpp \ - ../../stubs/NetworkStack_stub.cpp \ - ../../stubs/SocketAddress_stub.cpp \ - ../../stubs/mbed_assert_stub.cpp \ - -include ../../MakefileWorker.mk - -CPPUTESTFLAGS += -DFEA_TRACE_SUPPORT - diff --git a/features/cellular/UNITTESTS/at/at_cellularstack/at_cellularstacktest.cpp b/features/cellular/UNITTESTS/at/at_cellularstack/at_cellularstacktest.cpp deleted file mode 100644 index 60a5ab6664..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularstack/at_cellularstacktest.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2015, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "CppUTest/TestHarness.h" -#include "test_at_cellularstack.h" - -// AStyle ignored as the definition is not clear due to preprocessor usage -// *INDENT-OFF* -TEST_GROUP(AT_CellularStack) -{ - Test_AT_CellularStack *unit; - - void setup() - { - unit = new Test_AT_CellularStack(); - } - - void teardown() - { - delete unit; - } -}; -// *INDENT-ON* - -TEST(AT_CellularStack, Create) -{ - CHECK(unit != NULL); -} - -TEST(AT_CellularStack, test_AT_CellularStack_constructor) -{ - unit->test_AT_CellularStack_constructor(); -} - -TEST(AT_CellularStack, test_AT_CellularStack_get_ip_address) -{ - unit->test_AT_CellularStack_get_ip_address(); -} - -TEST(AT_CellularStack, test_AT_CellularStack_socket_open) -{ - unit->test_AT_CellularStack_socket_open(); -} - -TEST(AT_CellularStack, test_AT_CellularStack_socket_close) -{ - unit->test_AT_CellularStack_socket_close(); -} - -TEST(AT_CellularStack, test_AT_CellularStack_socket_bind) -{ - unit->test_AT_CellularStack_socket_bind(); -} - -TEST(AT_CellularStack, test_AT_CellularStack_socket_listen) -{ - unit->test_AT_CellularStack_socket_listen(); -} - -TEST(AT_CellularStack, test_AT_CellularStack_socket_connect) -{ - unit->test_AT_CellularStack_socket_connect(); -} - -TEST(AT_CellularStack, test_AT_CellularStack_socket_accept) -{ - unit->test_AT_CellularStack_socket_accept(); -} - -TEST(AT_CellularStack, test_AT_CellularStack_socket_send) -{ - unit->test_AT_CellularStack_socket_send(); -} - -TEST(AT_CellularStack, test_AT_CellularStack_socket_recv) -{ - unit->test_AT_CellularStack_socket_recv(); -} - -TEST(AT_CellularStack, test_AT_CellularStack_socket_sendto) -{ - unit->test_AT_CellularStack_socket_sendto(); -} - -TEST(AT_CellularStack, test_AT_CellularStack_socket_recvfrom) -{ - unit->test_AT_CellularStack_socket_recvfrom(); -} - -TEST(AT_CellularStack, test_AT_CellularStack_socket_attach) -{ - unit->test_AT_CellularStack_socket_attach(); -} - diff --git a/features/cellular/UNITTESTS/at/at_cellularstack/main.cpp b/features/cellular/UNITTESTS/at/at_cellularstack/main.cpp deleted file mode 100644 index ee45007dde..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularstack/main.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2015, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "CppUTest/CommandLineTestRunner.h" -#include "CppUTest/TestPlugin.h" -#include "CppUTest/TestRegistry.h" -#include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char **av) -{ - return CommandLineTestRunner::RunAllTests(ac, av); -} - -IMPORT_TEST_GROUP(AT_CellularStack); - diff --git a/features/cellular/UNITTESTS/at/at_cellularstack/test_at_cellularstack.h b/features/cellular/UNITTESTS/at/at_cellularstack/test_at_cellularstack.h deleted file mode 100644 index b86a6d761c..0000000000 --- a/features/cellular/UNITTESTS/at/at_cellularstack/test_at_cellularstack.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2018, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef TEST_AT_CELLULARSTACK_H -#define TEST_AT_CELLULARSTACK_H - -class Test_AT_CellularStack { -public: - Test_AT_CellularStack(); - - virtual ~Test_AT_CellularStack(); - - void test_AT_CellularStack_constructor(); - - void test_AT_CellularStack_get_ip_address(); - - void test_AT_CellularStack_socket_open(); - - void test_AT_CellularStack_socket_close(); - - void test_AT_CellularStack_socket_bind(); - - void test_AT_CellularStack_socket_listen(); - - void test_AT_CellularStack_socket_connect(); - - void test_AT_CellularStack_socket_accept(); - - void test_AT_CellularStack_socket_send(); - - void test_AT_CellularStack_socket_recv(); - - void test_AT_CellularStack_socket_sendto(); - - void test_AT_CellularStack_socket_recvfrom(); - - void test_AT_CellularStack_socket_attach(); -}; - -#endif // TEST_AT_CELLULARSTACK_H - diff --git a/features/cellular/UNITTESTS/at/athandler/Makefile b/features/cellular/UNITTESTS/at/athandler/Makefile deleted file mode 100644 index 6e2b33c35c..0000000000 --- a/features/cellular/UNITTESTS/at/athandler/Makefile +++ /dev/null @@ -1,30 +0,0 @@ -include ../../makefile_defines.txt - -COMPONENT_NAME = ATHandler_unit - -#This must be changed manually -SRC_FILES = \ - ../../../framework/AT/ATHandler.cpp \ - ../../../framework/common/CellularUtil.cpp - -TEST_SRC_FILES = \ - main.cpp \ - athandlertest.cpp \ - test_athandler.cpp \ - ../../stubs/AT_CellularBase_stub.cpp \ - ../../stubs/EventQueue_stub.cpp \ - ../../stubs/FileHandle_stub.cpp \ - ../../stubs/us_ticker_stub.cpp \ - ../../stubs/mbed_wait_api_stub.cpp \ - ../../stubs/mbed_assert_stub.cpp \ - ../../stubs/mbed_poll_stub.cpp \ - ../../stubs/Timer_stub.cpp \ - ../../stubs/equeue_stub.cpp \ - ../../stubs/Kernel.cpp \ - ../../stubs/Thread_stub.cpp \ - ../../stubs/randLIB_stub.cpp - -include ../../MakefileWorker.mk - -CPPUTESTFLAGS += -DFEA_TRACE_SUPPORT -DMBED_CONF_CELLULAR_DEBUG_AT=1 - diff --git a/features/cellular/UNITTESTS/at/athandler/athandlertest.cpp b/features/cellular/UNITTESTS/at/athandler/athandlertest.cpp deleted file mode 100644 index b8b46b2ca8..0000000000 --- a/features/cellular/UNITTESTS/at/athandler/athandlertest.cpp +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Copyright (c) 2015, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "CppUTest/TestHarness.h" -#include "test_athandler.h" - -// AStyle ignored as the definition is not clear due to preprocessor usage -// *INDENT-OFF* -TEST_GROUP(ATHandler) -{ - Test_ATHandler *unit; - - void setup() - { - unit = new Test_ATHandler(); - } - - void teardown() - { - delete unit; - } -}; -// *INDENT-ON* - -TEST(ATHandler, Create) -{ - CHECK(unit != NULL); -} - -TEST(ATHandler, test_ATHandler_constructor) -{ - unit->test_ATHandler_constructor(); -} - -TEST(ATHandler, test_ATHandler_get_file_handle) -{ - unit->test_ATHandler_get_file_handle(); -} - -TEST(ATHandler, test_ATHandler_set_file_handle) -{ - unit->test_ATHandler_set_file_handle(); -} - -TEST(ATHandler, test_ATHandler_lock) -{ - unit->test_ATHandler_lock(); -} - -TEST(ATHandler, test_ATHandler_unlock) -{ - unit->test_ATHandler_unlock(); -} - -TEST(ATHandler, test_ATHandler_unlock_return_error) -{ - unit->test_ATHandler_unlock_return_error(); -} - -TEST(ATHandler, test_ATHandler_set_urc_handler) -{ - unit->test_ATHandler_set_urc_handler(); -} - -TEST(ATHandler, test_ATHandler_get_last_error) -{ - unit->test_ATHandler_get_last_error(); -} - -TEST(ATHandler, test_ATHandler_get_last_device_error) -{ - unit->test_ATHandler_get_last_device_error(); -} - -TEST(ATHandler, test_ATHandler_inc_ref_count) -{ - unit->test_ATHandler_inc_ref_count(); -} - -TEST(ATHandler, test_ATHandler_dec_ref_count) -{ - unit->test_ATHandler_dec_ref_count(); -} - -TEST(ATHandler, test_ATHandler_get_ref_count) -{ - unit->test_ATHandler_get_ref_count(); -} - -TEST(ATHandler, test_ATHandler_set_at_timeout) -{ - unit->test_ATHandler_set_at_timeout(); -} - -TEST(ATHandler, test_ATHandler_restore_at_timeout) -{ - unit->test_ATHandler_restore_at_timeout(); -} - -TEST(ATHandler, test_ATHandler_clear_error) -{ - unit->test_ATHandler_clear_error(); -} - -TEST(ATHandler, test_ATHandler_process_oob) -{ - unit->test_ATHandler_process_oob(); -} - -TEST(ATHandler, test_ATHandler_set_filehandle_sigio) -{ - unit->test_ATHandler_set_filehandle_sigio(); -} - -TEST(ATHandler, test_ATHandler_flush) -{ - unit->test_ATHandler_flush(); -} - -TEST(ATHandler, test_ATHandler_cmd_start) -{ - unit->test_ATHandler_cmd_start(); -} - -TEST(ATHandler, test_ATHandler_write_int) -{ - unit->test_ATHandler_write_int(); -} - -TEST(ATHandler, test_ATHandler_write_string) -{ - unit->test_ATHandler_write_string(); -} - -TEST(ATHandler, test_ATHandler_cmd_stop) -{ - unit->test_ATHandler_cmd_stop(); -} - -TEST(ATHandler, test_ATHandler_write_bytes) -{ - unit->test_ATHandler_write_bytes(); -} - -TEST(ATHandler, test_ATHandler_set_stop_tag) -{ - unit->test_ATHandler_set_stop_tag(); -} - -TEST(ATHandler, test_ATHandler_set_delimiter) -{ - unit->test_ATHandler_set_delimiter(); -} - -TEST(ATHandler, test_ATHandler_skip_param) -{ - unit->test_ATHandler_skip_param(); -} - -TEST(ATHandler, test_ATHandler_read_bytes) -{ - unit->test_ATHandler_read_bytes(); -} - -TEST(ATHandler, test_ATHandler_read_string) -{ - unit->test_ATHandler_read_string(); -} - -TEST(ATHandler, test_ATHandler_read_hex_string) -{ - unit->test_ATHandler_read_hex_string(); -} - -TEST(ATHandler, test_ATHandler_read_int) -{ - unit->test_ATHandler_read_int(); -} - -TEST(ATHandler, test_ATHandler_resp_start) -{ - unit->test_ATHandler_resp_start(); -} - -TEST(ATHandler, test_ATHandler_resp_stop) -{ - unit->test_ATHandler_resp_stop(); -} - -TEST(ATHandler, test_ATHandler_info_resp) -{ - unit->test_ATHandler_info_resp(); -} - -TEST(ATHandler, test_ATHandler_info_elem) -{ - unit->test_ATHandler_info_elem(); -} - -TEST(ATHandler, test_ATHandler_consume_to_stop_tag) -{ - unit->test_ATHandler_consume_to_stop_tag(); -} - -TEST(ATHandler, test_ATHandler_set_debug) -{ - unit->test_ATHandler_set_debug(); -} - -TEST(ATHandler, test_ATHandler_get_3gpp_error) -{ - unit->test_ATHandler_get_3gpp_error(); -} diff --git a/features/cellular/UNITTESTS/at/athandler/main.cpp b/features/cellular/UNITTESTS/at/athandler/main.cpp deleted file mode 100644 index 3f7505ccbb..0000000000 --- a/features/cellular/UNITTESTS/at/athandler/main.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2015, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "CppUTest/CommandLineTestRunner.h" -#include "CppUTest/TestPlugin.h" -#include "CppUTest/TestRegistry.h" -#include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char **av) -{ - return CommandLineTestRunner::RunAllTests(ac, av); -} - -IMPORT_TEST_GROUP(ATHandler); - diff --git a/features/cellular/UNITTESTS/at/athandler/test_athandler.h b/features/cellular/UNITTESTS/at/athandler/test_athandler.h deleted file mode 100644 index 3d74fb0afd..0000000000 --- a/features/cellular/UNITTESTS/at/athandler/test_athandler.h +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2018, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef TEST_ATHANDLER_H -#define TEST_ATHANDLER_H - -class Test_ATHandler { -public: - Test_ATHandler(); - - virtual ~Test_ATHandler(); - - void test_ATHandler_constructor(); - - void test_ATHandler_get_file_handle(); - - void test_ATHandler_set_file_handle(); - - void test_ATHandler_lock(); - - void test_ATHandler_unlock(); - - void test_ATHandler_unlock_return_error(); - - void test_ATHandler_set_urc_handler(); - - void test_ATHandler_get_last_error(); - - void test_ATHandler_get_last_device_error(); - - void test_ATHandler_inc_ref_count(); - - void test_ATHandler_dec_ref_count(); - - void test_ATHandler_get_ref_count(); - - void test_ATHandler_set_at_timeout(); - - void test_ATHandler_restore_at_timeout(); - - void test_ATHandler_clear_error(); - - void test_ATHandler_process_oob(); - - void test_ATHandler_set_filehandle_sigio(); - - void test_ATHandler_flush(); - - void test_ATHandler_cmd_start(); - - void test_ATHandler_write_int(); - - void test_ATHandler_write_string(); - - void test_ATHandler_cmd_stop(); - - void test_ATHandler_write_bytes(); - - void test_ATHandler_set_stop_tag(); - - void test_ATHandler_set_delimiter(); - - void test_ATHandler_skip_param(); - - void test_ATHandler_read_bytes(); - - void test_ATHandler_read_string(); - - void test_ATHandler_read_hex_string(); - - void test_ATHandler_read_int(); - - void test_ATHandler_resp_start(); - - void test_ATHandler_resp_stop(); - - void test_ATHandler_info_resp(); - - void test_ATHandler_info_elem(); - - void test_ATHandler_consume_to_stop_tag(); - - void test_ATHandler_set_debug(); - - void test_ATHandler_get_3gpp_error(); -}; - -#endif // TEST_ATHANDLER_H - diff --git a/features/cellular/UNITTESTS/common/util/Makefile b/features/cellular/UNITTESTS/common/util/Makefile deleted file mode 100644 index bcfa9092b2..0000000000 --- a/features/cellular/UNITTESTS/common/util/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -include ../../makefile_defines.txt - -COMPONENT_NAME = util_unit - -#This must be changed manually -SRC_FILES = \ - ../../../framework/common/CellularUtil.cpp - -TEST_SRC_FILES = \ - main.cpp \ - utiltest.cpp \ - test_util.cpp \ - ../../stubs/randLIB_stub.cpp \ - -include ../../MakefileWorker.mk - -CPPUTESTFLAGS += -DFEA_TRACE_SUPPORT - diff --git a/features/cellular/UNITTESTS/common/util/main.cpp b/features/cellular/UNITTESTS/common/util/main.cpp deleted file mode 100644 index 6ebe329133..0000000000 --- a/features/cellular/UNITTESTS/common/util/main.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2018, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "CppUTest/CommandLineTestRunner.h" -#include "CppUTest/TestPlugin.h" -#include "CppUTest/TestRegistry.h" -#include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char **av) -{ - return CommandLineTestRunner::RunAllTests(ac, av); -} - -IMPORT_TEST_GROUP(util); - diff --git a/features/cellular/UNITTESTS/common/util/test_util.cpp b/features/cellular/UNITTESTS/common/util/test_util.cpp deleted file mode 100644 index a8078dcf5b..0000000000 --- a/features/cellular/UNITTESTS/common/util/test_util.cpp +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright (c) 2018, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "CppUTest/TestHarness.h" -#include "test_util.h" -#include -#include "CellularUtil.h" - -using namespace mbed_cellular_util; - -Test_util::Test_util() -{ - -} - -Test_util::~Test_util() -{ -} - -void Test_util::test_util_uint_to_binary_string() -{ - char str[33]; - uint_to_binary_str(15, str, 33, 32); - str[32] = '\0'; - // 15 is "1111" in binary but we ask all 32 bits so it should return "00000000000000000000000000001111" - STRCMP_EQUAL("00000000000000000000000000001111", str); - - // test NULL pointer - uint_to_binary_str(15, NULL, 0, 32); - - // test give too small buffer - char too_small[5]; - uint_to_binary_str(15, too_small, 5, 6); -} - -void Test_util::test_util_char_str_to_hex() -{ - // basic conversion test, happy days - char hex_buf[50]; - uint16_t number_of_hex_chars = char_str_to_hex_str("1234", 4, hex_buf); - hex_buf[number_of_hex_chars] = '\0'; - STRCMP_EQUAL("31323334", hex_buf); - LONGS_EQUAL(8, number_of_hex_chars); - - number_of_hex_chars = char_str_to_hex_str("wuhuu", 5, hex_buf); - hex_buf[number_of_hex_chars] = '\0'; - STRCMP_EQUAL("7775687575", hex_buf); - LONGS_EQUAL(10, number_of_hex_chars); - - // First don't omit the leading zero and then omit and check that leading zero is missing - number_of_hex_chars = char_str_to_hex_str("\nwuhuu", 6, hex_buf); - hex_buf[number_of_hex_chars] = '\0'; - STRCMP_EQUAL("0A7775687575", hex_buf); - LONGS_EQUAL(12, number_of_hex_chars); - - number_of_hex_chars = char_str_to_hex_str("\nwuhuu", 6, hex_buf, true); - hex_buf[number_of_hex_chars] = '\0'; - STRCMP_EQUAL("A7775687575", hex_buf); - LONGS_EQUAL(11, number_of_hex_chars); - - // test giving a null pointer - number_of_hex_chars = char_str_to_hex_str(NULL, 4, hex_buf); - LONGS_EQUAL(0, number_of_hex_chars); - number_of_hex_chars = char_str_to_hex_str("1234", 4, NULL); - LONGS_EQUAL(0, number_of_hex_chars); -} - -void Test_util::test_util_convert_ipv6() -{ - // leading zeros omitted - char ipv6[64]; - strncpy(ipv6, "1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1", 64); - convert_ipv6(ipv6); - STRCMP_EQUAL("101:101:101:101:101:101:101:101", ipv6); - LONGS_EQUAL(31, strlen(ipv6)); - - // some omitted and some not so much - strncpy(ipv6, "255.1.120.2.244.12.55.45.201.110.11.2.233.154.85.96", 64); - convert_ipv6(ipv6); - STRCMP_EQUAL("FF01:7802:F40C:372D:C96E:B02:E99A:5560", ipv6); - LONGS_EQUAL(38, strlen(ipv6)); - - // test giving a null pointer - convert_ipv6(NULL); -} - -void Test_util::test_util_prefer_ipv6() -{ - char tt[20] = "62.241.198.246"; - char temp[64] = "2001:14B8:1000:000:000:000:000:002"; - - // not enough space to swap, arrays should stay the same - prefer_ipv6(tt, sizeof(tt), temp, sizeof(temp)); - STRCMP_EQUAL("62.241.198.246", tt); - STRCMP_EQUAL("2001:14B8:1000:000:000:000:000:002", temp); - - // should swap as first one was ip4 and later was ipv6 and enough space - char tt2[64] = "62.241.198.246"; - prefer_ipv6(tt2, sizeof(tt2), temp, sizeof(temp)); - STRCMP_EQUAL("62.241.198.246", temp); - STRCMP_EQUAL("2001:14B8:1000:000:000:000:000:002", tt2); -} - -void Test_util::test_util_separate_ip_addresses() -{ - char *s = (char *)malloc(128); - - char ip[64] = {0}; - char subnet[64] = {0}; - - strncpy(s, "32.1.20.187.1.112.139.245.251.136.232.110.123.51.230.138.0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15", 94); - separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); - STRCMP_EQUAL("2001:14BB:170:8BF5:FB88:E86E:7B33:E68A", ip); - STRCMP_EQUAL("001:203:405:607:809:A0B:C0D:E0F", subnet); - - strncpy(s, "32:1:20:187:1:112:139:245:251:136:232:110:123:51:230:138 0:1:2:3:4:5:6:7:8:9:10:11:12:13:14:15", 94); - separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); - STRCMP_EQUAL("32:1:20:187:1:112:139:245:251:136:232:110:123:51:230:138", ip); - STRCMP_EQUAL("0:1:2:3:4:5:6:7:8:9:10:11:12:13:14:15", subnet); - - ip[0] = '\0'; - subnet[0] = '\0'; - strncpy(s, "1.2.3.4\0", 8); - separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); - STRCMP_EQUAL("1.2.3.4", ip); - STRCMP_EQUAL("", subnet); - - ip[0] = '\0'; - subnet[0] = '\0'; - strncpy(s, "1.2.3.4.5.6.7.8\0", 16); - separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); - STRCMP_EQUAL("1.2.3.4", ip); - STRCMP_EQUAL("5.6.7.8", subnet); - - ip[0] = '\0'; - subnet[0] = '\0'; - strncpy(s, "1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16\0", 39); - separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); - STRCMP_EQUAL("102:304:506:708:90A:B0C:D0E:F10", ip); - STRCMP_EQUAL("", subnet); - - ip[0] = '\0'; - subnet[0] = '\0'; - strncpy(s, "32:1:20:187:1:112:139:245:251:136:232:110:123:51:230:138\0", 57); - separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); - STRCMP_EQUAL("32:1:20:187:1:112:139:245:251:136:232:110:123:51:230:138", ip); - STRCMP_EQUAL("", subnet); - - ip[0] = '\0'; - subnet[0] = '\0'; - strncpy(s, "1.2.3.4 32:1:20:187:1:112:139:245:251:136:232:110:123:51:230:138\0", 65); - separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); - STRCMP_EQUAL("1.2.3.4", ip); - STRCMP_EQUAL("32:1:20:187:1:112:139:245:251:136:232:110:123:51:230:138", subnet); - - ip[0] = '\0'; - subnet[0] = '\0'; - strncpy(s, "1.2.3.4 5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20\0", 51); - separate_ip_addresses(s, ip, sizeof(ip), subnet, sizeof(subnet)); - STRCMP_EQUAL("1.2.3.4", ip); - STRCMP_EQUAL("506:708:90A:B0C:D0E:F10:1112:1314", subnet); - STRCMP_EQUAL("1.2.3.4 5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20", s); - -} diff --git a/features/cellular/UNITTESTS/common/util/utiltest.cpp b/features/cellular/UNITTESTS/common/util/utiltest.cpp deleted file mode 100644 index 52a6db6c07..0000000000 --- a/features/cellular/UNITTESTS/common/util/utiltest.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2015, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "CppUTest/TestHarness.h" -#include "test_util.h" - -// AStyle ignored as the definition is not clear due to preprocessor usage -// *INDENT-OFF* -TEST_GROUP(util) -{ - Test_util *unit; - - void setup() - { - unit = new Test_util(); - } - - void teardown() - { - delete unit; - } -}; -// *INDENT-ON* - -TEST(util, Create) -{ - CHECK(unit != NULL); -} - -TEST(util, test_util_uint_to_binary_string) -{ - unit->test_util_uint_to_binary_string(); -} - -TEST(util, char_str_to_hex) -{ - unit->test_util_char_str_to_hex(); -} - -TEST(util, convert_ipv6) -{ - unit->test_util_convert_ipv6(); -} - -TEST(util, prefer_ipv6) -{ - unit->test_util_prefer_ipv6(); -} - -TEST(util, separate_ip_addresses) -{ - unit->test_util_separate_ip_addresses(); -} diff --git a/features/cellular/UNITTESTS/makefile_defines.txt b/features/cellular/UNITTESTS/makefile_defines.txt deleted file mode 100755 index d11de61cfd..0000000000 --- a/features/cellular/UNITTESTS/makefile_defines.txt +++ /dev/null @@ -1,32 +0,0 @@ -#--- Inputs ----# -CPPUTEST_HOME = /usr -CPPUTEST_USE_EXTENSIONS = Y -CPPUTEST_USE_VPATH = Y -CPPUTEST_USE_GCOV = Y -CPPUTEST_USE_MEM_LEAK_DETECTION = N -CPP_PLATFORM = gcc -INCLUDE_DIRS =\ - .\ - ../../stubs\ - ../../target_h\ - ../../..\ - ../../../../../features \ - ../../../../../features/netsocket \ - ../../../../.. \ - ../../../../../rtos \ - ../../../../../rtos/TARGET_CORTEX \ - ../../../../../platform \ - ../../../../../hal \ - ../../../../../events \ - ../../../../../events/equeue \ - ../../../../../drivers \ - ../../../framework\ - ../../../framework/common\ - ../../../framework/AT\ - ../../../framework/API\ - /usr/include\ - $(CPPUTEST_HOME)/include\ - -CPPUTESTFLAGS = -D__thumb2__ -w -D__INLINE=__inline -CPPUTEST_CFLAGS += -std=gnu99 - diff --git a/features/cellular/UNITTESTS/run_tests b/features/cellular/UNITTESTS/run_tests deleted file mode 100755 index f4f7a48298..0000000000 --- a/features/cellular/UNITTESTS/run_tests +++ /dev/null @@ -1,48 +0,0 @@ -#!/bin/bash -echo -echo Build Cellular unit tests -echo - -#replace by empty string if no branch coverage is needed -#branch_cov="--rc lcov_branch_coverage=1" -branch_cov="" -#branch_data="--rc branch-coverage=1" -branch_data="--no-branch-coverage" - -# Remember to add new test folder to Makefile -make clean >/dev/null 2>&1 -make all - -echo -echo Create results -echo -mkdir results - -find ./ -name '*.xml' | xargs cp -t ./results/ - -echo -echo Create coverage document -echo -mkdir coverages -cd coverages - -lcov -q -d ../. -c -o app.info $branch_cov -lcov -q -r app.info "/test*" -o app.info $branch_cov -lcov -q -r app.info "/usr*" -o app.info $branch_cov -lcov -q -r app.info "/UNITTESTS/common*" -o app.info $branch_cov -lcov -q -r app.info "/UNITTESTS/*" -o app.info $branch_cov -lcov -q -r app.info "/UNITTESTS/stubs*" -o app.info $branch_cov -lcov -q -r app.info "/UNITTESTS/target_h*" -o app.info $branch_cov -lcov -q -r app.info "/mbed-client*" -o app.info $branch_cov -lcov -q -r app.info "/events*" -o app.info $branch_cov -lcov -q -r app.info "/features/netsocket*" -o app.info $branch_cov -lcov -q -r app.info "/platform*" -o app.info $branch_cov -genhtml $branch_data app.info -cd .. -echo -echo -echo -echo Have a nice bug hunt! -echo -echo -echo diff --git a/features/cellular/UNITTESTS/stubs/FileHandle_stub.h b/features/cellular/UNITTESTS/stubs/FileHandle_stub.h deleted file mode 100644 index e1548f2322..0000000000 --- a/features/cellular/UNITTESTS/stubs/FileHandle_stub.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) , Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef __FILE_HANDLE_STUB_H__ -#define __FILE_HANDLE_STUB_H__ - -#include "FileHandle.h" - - -namespace mbed { - -static uint8_t filehandle_stub_short_value_counter = 0; -static char *filehandle_stub_table = NULL; -static uint8_t filehandle_stub_table_pos = 0; - -class FileHandle_stub : public FileHandle { -public: - ssize_t size_value; - - FileHandle_stub() - { - size_value = 0; - } - - virtual ssize_t read(void *buffer, size_t size) - { - if (filehandle_stub_table) { - ssize_t ret = strlen(filehandle_stub_table) - filehandle_stub_table_pos; - if (ret >= 0 && size < ret) { - ret = size; - } - if (ret >= 0) { - memcpy(buffer, filehandle_stub_table, ret); - } - - filehandle_stub_table_pos += ret; - return ret; - } - return 0; - } - - virtual ssize_t write(const void *buffer, size_t size) - { - if (size_value > 0) { - size_value--; - return size; - } else if (size_value < 0) { - return -1; - } - return 0; - } - - virtual off_t seek(off_t offset, int whence = SEEK_SET) - { - return 0; - } - - virtual int close() {} - - virtual short poll(short events) const - { - if (filehandle_stub_short_value_counter) { - filehandle_stub_short_value_counter--; - return short_value; - } - return 0; - } - - virtual void sigio(Callback func) - { - func(); - } - - short short_value; -}; - -} - -#endif - - diff --git a/features/cellular/UNITTESTS/stubs/equeue_stub.c b/features/cellular/UNITTESTS/stubs/equeue_stub.c deleted file mode 100644 index 55a52174e7..0000000000 --- a/features/cellular/UNITTESTS/stubs/equeue_stub.c +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) , Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "equeue.h" - -int equeue_create(equeue_t *queue, size_t size) -{ - return 0; -} - -int equeue_create_inplace(equeue_t *queue, size_t size, void *buffer) -{ - return 0; -} - -void equeue_destroy(equeue_t *queue) -{ - -} - -void equeue_dispatch(equeue_t *queue, int ms) -{ - -} - -void equeue_break(equeue_t *queue) -{ - -} - -int equeue_call(equeue_t *queue, void (*cb)(void *), void *data) -{ - return 0; -} - -int equeue_call_in(equeue_t *queue, int ms, void (*cb)(void *), void *data) -{ - return 0; -} - -int equeue_call_every(equeue_t *queue, int ms, void (*cb)(void *), void *data) -{ - return 0; -} - -void *equeue_alloc(equeue_t *queue, size_t size) -{ - return NULL; -} - -void equeue_dealloc(equeue_t *queue, void *event) -{ - -} - -void equeue_event_delay(void *event, int ms) -{ - -} - -void equeue_event_period(void *event, int ms) -{ - -} - -void equeue_event_dtor(void *event, void (*dtor)(void *)) -{ - -} - -int equeue_post(equeue_t *queue, void (*cb)(void *), void *event) -{ - return 0; -} - -void equeue_cancel(equeue_t *queue, int id) -{ - -} - -void equeue_background(equeue_t *queue, - void (*update)(void *timer, int ms), void *timer) -{ - -} - -void equeue_chain(equeue_t *queue, equeue_t *target) -{ - -} diff --git a/features/cellular/UNITTESTS/target_h/PeripheralNames.h b/features/cellular/UNITTESTS/target_h/PeripheralNames.h deleted file mode 100644 index a431b392e7..0000000000 --- a/features/cellular/UNITTESTS/target_h/PeripheralNames.h +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) , Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ diff --git a/features/cellular/UNITTESTS/target_h/device.h b/features/cellular/UNITTESTS/target_h/device.h deleted file mode 100644 index a431b392e7..0000000000 --- a/features/cellular/UNITTESTS/target_h/device.h +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) , Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ diff --git a/features/cellular/UNITTESTS/target_h/mbed-trace/mbed_trace.h b/features/cellular/UNITTESTS/target_h/mbed-trace/mbed_trace.h deleted file mode 100644 index 7d6e56bdd9..0000000000 --- a/features/cellular/UNITTESTS/target_h/mbed-trace/mbed_trace.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2018, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CELLULAR_UNITTESTS_MBED_TRACE_H_ -#define CELLULAR_UNITTESTS_MBED_TRACE_H_ - -#define tr_debug(...) -#define tr_info(...) -#define tr_warning(...) -#define tr_warn(...) -#define tr_error(...) -#define tr_err(...) - -#endif /* CELLULAR_UNITTESTS_MBED_TRACE_H_ */ diff --git a/features/cellular/UNITTESTS/target_h/rtos/Mutex.h b/features/cellular/UNITTESTS/target_h/rtos/Mutex.h deleted file mode 100644 index 68d797d3eb..0000000000 --- a/features/cellular/UNITTESTS/target_h/rtos/Mutex.h +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) , Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -typedef void *Mutex; diff --git a/features/cellular/easy_cellular/CellularConnectionFSM.cpp b/features/cellular/easy_cellular/CellularConnectionFSM.cpp index 657b734ae3..9f41625569 100644 --- a/features/cellular/easy_cellular/CellularConnectionFSM.cpp +++ b/features/cellular/easy_cellular/CellularConnectionFSM.cpp @@ -161,9 +161,17 @@ bool CellularConnectionFSM::open_sim() // here you could add wait(secs) if you know start delay of your SIM if (_sim->get_sim_state(state) != NSAPI_ERROR_OK) { tr_info("Waiting for SIM (err while reading)..."); + if (_event_status_cb) { + _event_status_cb((nsapi_event_t)CellularSIMStatusChanged, state); + } return false; } + // report current state so callback can set sim pin if needed + if (_event_status_cb) { + _event_status_cb((nsapi_event_t)CellularSIMStatusChanged, state); + } + if (state == CellularSIM::SimStatePinNeeded) { if (strlen(_sim_pin)) { tr_info("SIM pin required, entering pin: %s", _sim_pin); @@ -172,14 +180,13 @@ bool CellularConnectionFSM::open_sim() tr_error("SIM pin set failed with: %d, bailing out...", err); } } else { - tr_warn("PIN required but No SIM pin provided."); + // No sim pin provided even it's needed, stop state machine + tr_error("PIN required but No SIM pin provided."); + _retry_count = MAX_RETRY_ARRAY_SIZE; + return false; } } - if (_event_status_cb) { - _event_status_cb((nsapi_event_t)CellularSIMStatusChanged, state); - } - return state == CellularSIM::SimStateReady; } diff --git a/features/cellular/easy_cellular/EasyCellularConnection.cpp b/features/cellular/easy_cellular/EasyCellularConnection.cpp index 204e4b7bff..f4e73e5b5b 100644 --- a/features/cellular/easy_cellular/EasyCellularConnection.cpp +++ b/features/cellular/easy_cellular/EasyCellularConnection.cpp @@ -45,6 +45,16 @@ bool EasyCellularConnection::cellular_status(int state, int next_state) (void)_cellularSemaphore.release(); return false; // return false -> state machine is halted } + + // only in case of an error or when connected is reached state and next_state can be the same. + // Release semaphore to return application instead of waiting for semaphore to complete. + if (state == next_state) { + tr_error("cellular_status: state and next_state are same, release semaphore as this is an error in state machine"); + _stm_error = true; + (void)_cellularSemaphore.release(); + return false; // return false -> state machine is halted + } + return true; } @@ -63,9 +73,10 @@ void EasyCellularConnection::network_callback(nsapi_event_t ev, intptr_t ptr) } EasyCellularConnection::EasyCellularConnection(bool debug) : - _is_connected(false), _is_initialized(false), _target_state(CellularConnectionFSM::STATE_POWER_ON), _cellularSerial( - MDMTXD, MDMRXD, MBED_CONF_PLATFORM_DEFAULT_SERIAL_BAUD_RATE), _cellularSemaphore(0), _cellularConnectionFSM(0), _credentials_err( - NSAPI_ERROR_OK), _status_cb(0) + _is_connected(false), _is_initialized(false), _stm_error(false), + _target_state(CellularConnectionFSM::STATE_POWER_ON), + _cellularSerial(MDMTXD, MDMRXD, MBED_CONF_PLATFORM_DEFAULT_SERIAL_BAUD_RATE), _cellularSemaphore(0), + _cellularConnectionFSM(0), _credentials_err(NSAPI_ERROR_OK), _status_cb(0) { tr_info("EasyCellularConnection()"); #if USE_APN_LOOKUP @@ -86,6 +97,7 @@ EasyCellularConnection::~EasyCellularConnection() nsapi_error_t EasyCellularConnection::init() { nsapi_error_t err = NSAPI_ERROR_OK; + _stm_error = false; if (!_is_initialized) { #if defined (MDMRTS) && defined (MDMCTS) _cellularSerial.set_flow_control(SerialBase::RTSCTS, MDMRTS, MDMCTS); @@ -156,7 +168,7 @@ nsapi_error_t EasyCellularConnection::connect(const char *sim_pin, const char *a } if (sim_pin) { - this->set_sim_pin(sim_pin); + set_sim_pin(sim_pin); } return connect(); @@ -193,7 +205,7 @@ nsapi_error_t EasyCellularConnection::connect() err = _cellularConnectionFSM->continue_to_state(_target_state); if (err == NSAPI_ERROR_OK) { int sim_wait = _cellularSemaphore.wait(60 * 1000); // reserve 60 seconds to access to SIM - if (sim_wait != 1) { + if (sim_wait != 1 || _stm_error) { tr_error("NO SIM ACCESS"); err = NSAPI_ERROR_NO_CONNECTION; } else { @@ -223,7 +235,7 @@ nsapi_error_t EasyCellularConnection::connect() err = _cellularConnectionFSM->continue_to_state(_target_state); if (err == NSAPI_ERROR_OK) { int ret_wait = _cellularSemaphore.wait(10 * 60 * 1000); // cellular network searching may take several minutes - if (ret_wait != 1) { + if (ret_wait != 1 || _stm_error) { tr_info("No cellular connection"); err = NSAPI_ERROR_NO_CONNECTION; } @@ -237,6 +249,7 @@ nsapi_error_t EasyCellularConnection::disconnect() _credentials_err = NSAPI_ERROR_OK; _is_connected = false; _is_initialized = false; + _stm_error = false; #if USE_APN_LOOKUP _credentials_set = false; #endif // #if USE_APN_LOOKUP diff --git a/features/cellular/easy_cellular/EasyCellularConnection.h b/features/cellular/easy_cellular/EasyCellularConnection.h index 036fa04a78..fd8d8f07e4 100644 --- a/features/cellular/easy_cellular/EasyCellularConnection.h +++ b/features/cellular/easy_cellular/EasyCellularConnection.h @@ -168,6 +168,7 @@ private: bool _is_connected; bool _is_initialized; + bool _stm_error; #if USE_APN_LOOKUP bool _credentials_set; #endif // #if USE_APN_LOOKUP diff --git a/features/cellular/framework/API/CellularNetwork.h b/features/cellular/framework/API/CellularNetwork.h index fed04d257e..609ccd844a 100644 --- a/features/cellular/framework/API/CellularNetwork.h +++ b/features/cellular/framework/API/CellularNetwork.h @@ -150,6 +150,9 @@ public: op_status = Unknown; op_rat = RAT_UNKNOWN; next = NULL; + op_long[0] = NULL; + op_short[0] = NULL; + op_num[0] = NULL; } }; @@ -390,7 +393,7 @@ public: * * @return NSAPI_ERROR_OK on success * NSAPI_ERROR_NO_CONNECTION if fails to find suitable context to activate or activation failed (if not already activated) - * NSAPI_ERROR_UNSUPPORTED if NetworkStack was not found + * NSAPI_ERROR_UNSUPPORTED if NetworkStack was not found or cellular device does not support authentication * NSAPI_ERROR_AUTH_FAILURE if password and username were provided and authentication to network failed * Also if PPP mode * NSAPI_ERROR_DEVICE_ERROR on failure and check more error from nsapi_ppp_connect(...) diff --git a/features/cellular/framework/AT/ATHandler.cpp b/features/cellular/framework/AT/ATHandler.cpp index b52cece0bb..e3c6cdd39d 100644 --- a/features/cellular/framework/AT/ATHandler.cpp +++ b/features/cellular/framework/AT/ATHandler.cpp @@ -159,7 +159,7 @@ void ATHandler::set_is_filehandle_usable(bool usable) nsapi_error_t ATHandler::set_urc_handler(const char *prefix, mbed::Callback callback) { - if (find_urc_handler(prefix, callback)) { + if (find_urc_handler(prefix, &callback)) { tr_warn("URC already added with prefix: %s", prefix); return NSAPI_ERROR_OK; } @@ -205,11 +205,11 @@ void ATHandler::remove_urc_handler(const char *prefix, mbed::Callback ca } } -bool ATHandler::find_urc_handler(const char *prefix, mbed::Callback callback) +bool ATHandler::find_urc_handler(const char *prefix, mbed::Callback *callback) { struct oob_t *oob = _oobs; while (oob) { - if (strcmp(prefix, oob->prefix) == 0 && oob->cb == callback) { + if (strcmp(prefix, oob->prefix) == 0 && oob->cb == *callback) { return true; } oob = oob->next; diff --git a/features/cellular/framework/AT/ATHandler.h b/features/cellular/framework/AT/ATHandler.h index 17bb4d33a6..4962c14223 100644 --- a/features/cellular/framework/AT/ATHandler.h +++ b/features/cellular/framework/AT/ATHandler.h @@ -510,7 +510,7 @@ private: const char *mem_str(const char *dest, size_t dest_len, const char *src, size_t src_len); // check is urc is already added - bool find_urc_handler(const char *prefix, mbed::Callback callback); + bool find_urc_handler(const char *prefix, mbed::Callback *callback); // print contents of a buffer to trace log void debug_print(char *p, int len); diff --git a/features/cellular/framework/AT/AT_CellularBase.h b/features/cellular/framework/AT/AT_CellularBase.h index e5098e1f28..d4ef52d272 100644 --- a/features/cellular/framework/AT/AT_CellularBase.h +++ b/features/cellular/framework/AT/AT_CellularBase.h @@ -51,6 +51,7 @@ public: enum SupportedFeature { AT_CGSN_WITH_TYPE, // AT+CGSN without type is likely always supported similar to AT+GSN AT_CGDATA, // alternative is to support only ATD*99***# + AT_CGAUTH, // APN authentication AT commands supported SUPPORTED_FEATURE_END_MARK // must be last element in the array of features }; static void set_unsupported_features(const SupportedFeature *unsupported_features); diff --git a/features/cellular/framework/AT/AT_CellularNetwork.cpp b/features/cellular/framework/AT/AT_CellularNetwork.cpp index 6168eb5df6..4c6a960c56 100644 --- a/features/cellular/framework/AT/AT_CellularNetwork.cpp +++ b/features/cellular/framework/AT/AT_CellularNetwork.cpp @@ -210,6 +210,9 @@ nsapi_error_t AT_CellularNetwork::set_credentials(const char *apn, } if (username && (len = strlen(username)) > 0) { + if (!is_supported(AT_CGAUTH)) { // APN authentication is needed with username/password + return NSAPI_ERROR_UNSUPPORTED; + } _uname = (char *)malloc(len * sizeof(char) + 1); if (_uname) { memcpy(_uname, username, len + 1); @@ -279,10 +282,7 @@ nsapi_error_t AT_CellularNetwork::activate_context() nsapi_error_t err = NSAPI_ERROR_OK; // try to find or create context with suitable stack - if (get_context()) { - // try to authenticate user before activating or modifying context - err = do_user_authentication(); - } else { + if (!get_context()) { err = NSAPI_ERROR_NO_CONNECTION; } @@ -315,6 +315,13 @@ nsapi_error_t AT_CellularNetwork::activate_context() _at.resp_stop(); if (!_is_context_active) { + // authenticate before activating or modifying context + nsapi_error_t err = do_user_authentication(); + if (err != NSAPI_ERROR_OK) { + tr_error("Cellular authentication failed!"); + return err; + } + tr_info("Activate PDP context %d", _cid); _at.cmd_start("AT+CGACT=1,"); _at.write_int(_cid); @@ -509,6 +516,9 @@ nsapi_error_t AT_CellularNetwork::do_user_authentication() { // if user has defined user name and password we need to call CGAUTH before activating or modifying context if (_pwd && _uname) { + if (!is_supported(AT_CGAUTH)) { + return NSAPI_ERROR_UNSUPPORTED; + } _at.cmd_start("AT+CGAUTH="); _at.write_int(_cid); _at.write_int(_authentication_type); diff --git a/features/cellular/framework/AT/AT_CellularNetwork.h b/features/cellular/framework/AT/AT_CellularNetwork.h index 3e01f4db46..80b5665b83 100644 --- a/features/cellular/framework/AT/AT_CellularNetwork.h +++ b/features/cellular/framework/AT/AT_CellularNetwork.h @@ -146,6 +146,12 @@ protected: */ virtual nsapi_error_t set_access_technology_impl(RadioAccessTechnology op_rat); + /** APN user authentication + * + * @return NSAPI_ERROR_OK on success + * NSAPI_ERROR_UNSUPPORTED on authentication not supported by cellular device + * NSAPI_ERROR_AUTH_FAILURE on authentication to network failed + */ virtual nsapi_error_t do_user_authentication(); private: // "NO CARRIER" urc diff --git a/features/cellular/framework/AT/AT_CellularSMS.cpp b/features/cellular/framework/AT/AT_CellularSMS.cpp index 7605566cbb..3dab1509f9 100644 --- a/features/cellular/framework/AT/AT_CellularSMS.cpp +++ b/features/cellular/framework/AT/AT_CellularSMS.cpp @@ -256,8 +256,8 @@ nsapi_error_t AT_CellularSMS::set_csdh(int show_header) nsapi_error_t AT_CellularSMS::initialize(CellularSMSMmode mode) { - if (_at.set_urc_handler("+CMTI:", callback(this, &AT_CellularSMS::cmti_urc)) || - _at.set_urc_handler("+CMT:", callback(this, &AT_CellularSMS::cmt_urc))) { + if (NSAPI_ERROR_OK != _at.set_urc_handler("+CMTI:", callback(this, &AT_CellularSMS::cmti_urc)) || + NSAPI_ERROR_OK != _at.set_urc_handler("+CMT:", callback(this, &AT_CellularSMS::cmt_urc))) { return NSAPI_ERROR_NO_MEMORY; } diff --git a/features/cellular/framework/common/CellularUtil.cpp b/features/cellular/framework/common/CellularUtil.cpp index b6262996d7..c68dec2925 100644 --- a/features/cellular/framework/common/CellularUtil.cpp +++ b/features/cellular/framework/common/CellularUtil.cpp @@ -330,9 +330,7 @@ uint16_t get_dynamic_ip_port() } port_counter += randLIB_get_random_in_range(1, RANDOM_PORT_NUMBER_MAX_STEP); - if (port_counter >= RANDOM_PORT_NUMBER_COUNT) { - port_counter -= RANDOM_PORT_NUMBER_COUNT; - } + port_counter %= RANDOM_PORT_NUMBER_COUNT; return (RANDOM_PORT_NUMBER_START + port_counter); } diff --git a/features/cellular/framework/targets/QUECTEL/BC95/QUECTEL_BC95.cpp b/features/cellular/framework/targets/QUECTEL/BC95/QUECTEL_BC95.cpp index 84f446542f..c71197f380 100644 --- a/features/cellular/framework/targets/QUECTEL/BC95/QUECTEL_BC95.cpp +++ b/features/cellular/framework/targets/QUECTEL/BC95/QUECTEL_BC95.cpp @@ -31,8 +31,14 @@ using namespace events; using namespace mbed; +static const AT_CellularBase::SupportedFeature unsupported_features[] = { + AT_CellularBase::AT_CGAUTH, // BC95_AT_Commands_Manual_V1.9 + AT_CellularBase::SUPPORTED_FEATURE_END_MARK +}; + QUECTEL_BC95::QUECTEL_BC95(EventQueue &queue) : AT_CellularDevice(queue) { + AT_CellularBase::set_unsupported_features(unsupported_features); } QUECTEL_BC95::~QUECTEL_BC95() diff --git a/features/cellular/framework/targets/QUECTEL/BG96/QUECTEL_BG96_CellularNetwork.cpp b/features/cellular/framework/targets/QUECTEL/BG96/QUECTEL_BG96_CellularNetwork.cpp index 5a5140725b..6ed0bbd9e8 100644 --- a/features/cellular/framework/targets/QUECTEL/BG96/QUECTEL_BG96_CellularNetwork.cpp +++ b/features/cellular/framework/targets/QUECTEL/BG96/QUECTEL_BG96_CellularNetwork.cpp @@ -111,3 +111,24 @@ nsapi_error_t QUECTEL_BG96_CellularNetwork::set_access_technology_impl(RadioAcce return _at.unlock_return_error(); } + +nsapi_error_t QUECTEL_BG96_CellularNetwork::do_user_authentication() +{ + if (_pwd && _uname) { + _at.cmd_start("AT+QICSGP="); + _at.write_int(_cid); + _at.write_int(1); // IPv4 + _at.write_string(_apn); + _at.write_string(_uname); + _at.write_string(_pwd); + _at.write_int(_authentication_type); + _at.cmd_stop(); + _at.resp_start(); + _at.resp_stop(); + if (_at.get_last_error() != NSAPI_ERROR_OK) { + return NSAPI_ERROR_AUTH_FAILURE; + } + } + + return NSAPI_ERROR_OK; +} diff --git a/features/cellular/framework/targets/QUECTEL/BG96/QUECTEL_BG96_CellularNetwork.h b/features/cellular/framework/targets/QUECTEL/BG96/QUECTEL_BG96_CellularNetwork.h index 1504b9d1c5..292bcaf193 100644 --- a/features/cellular/framework/targets/QUECTEL/BG96/QUECTEL_BG96_CellularNetwork.h +++ b/features/cellular/framework/targets/QUECTEL/BG96/QUECTEL_BG96_CellularNetwork.h @@ -33,6 +33,8 @@ protected: virtual nsapi_error_t set_access_technology_impl(RadioAccessTechnology opRat); virtual bool get_modem_stack_type(nsapi_ip_stack_t requested_stack); + + virtual nsapi_error_t do_user_authentication(); }; } // namespace mbed diff --git a/features/cellular/framework/targets/TELIT/HE910/TELIT_HE910.cpp b/features/cellular/framework/targets/TELIT/HE910/TELIT_HE910.cpp index 308a9f9422..555513e392 100644 --- a/features/cellular/framework/targets/TELIT/HE910/TELIT_HE910.cpp +++ b/features/cellular/framework/targets/TELIT/HE910/TELIT_HE910.cpp @@ -24,6 +24,7 @@ using namespace events; static const AT_CellularBase::SupportedFeature unsupported_features[] = { AT_CellularBase::AT_CGSN_WITH_TYPE, // HE910/UE910/UL865/UE866 AT Commands Reference Guide Rev. 11-2006-10-14 + AT_CellularBase::AT_CGAUTH, // HE910/UE910/UL865/UE866 AT Commands Reference Guide Rev. 11-2006-10-14 AT_CellularBase::SUPPORTED_FEATURE_END_MARK }; diff --git a/features/lorawan/LoRaWANStack.cpp b/features/lorawan/LoRaWANStack.cpp index 42f2ba25e0..1b28e7c9d7 100644 --- a/features/lorawan/LoRaWANStack.cpp +++ b/features/lorawan/LoRaWANStack.cpp @@ -35,6 +35,7 @@ SPDX-License-Identifier: BSD-3-Clause #define INVALID_PORT 0xFF #define MAX_CONFIRMED_MSG_RETRIES 255 +#define COMPLIANCE_TESTING_PORT 224 /** * Control flags for transient states */ @@ -49,16 +50,6 @@ SPDX-License-Identifier: BSD-3-Clause using namespace mbed; using namespace events; -#if defined(LORAWAN_COMPLIANCE_TEST) -#if (MBED_CONF_LORA_PHY == 0 || MBED_CONF_LORA_PHY == 4 || MBED_CONF_LORA_PHY == 6 || MBED_CONF_LORA_PHY == 7) -#define LORAWAN_COMPLIANCE_TEST_DATA_SIZE 16 -#elif (MBED_CONF_LORA_PHY == 1 || MBED_CONF_LORA_PHY == 2 || MBED_CONF_LORA_PHY == 8 || MBED_CONF_LORA_PHY == 9) -#define LORAWAN_COMPLIANCE_TEST_DATA_SIZE 11 -#else -#error "Must set LoRa PHY layer parameters." -#endif -#endif //defined(LORAWAN_COMPLIANCE_TEST) - /** * Bit mask for message flags */ @@ -317,12 +308,6 @@ int16_t LoRaWANStack::handle_tx(const uint8_t port, const uint8_t *data, return LORAWAN_STATUS_WOULD_BLOCK; } -#if defined(LORAWAN_COMPLIANCE_TEST) - if (_compliance_test.running) { - return LORAWAN_STATUS_COMPLIANCE_TEST_ON; - } -#endif - lorawan_status_t status; if (_loramac.nwk_joined() == false) { @@ -373,12 +358,6 @@ int16_t LoRaWANStack::handle_rx(uint8_t *data, uint16_t length, uint8_t &port, i return LORAWAN_STATUS_WOULD_BLOCK; } -#if defined(LORAWAN_COMPLIANCE_TEST) - if (_compliance_test.running) { - return LORAWAN_STATUS_COMPLIANCE_TEST_ON; - } -#endif - if (data == NULL || length == 0) { return LORAWAN_STATUS_PARAMETER_INVALID; } @@ -401,35 +380,31 @@ int16_t LoRaWANStack::handle_rx(uint8_t *data, uint16_t length, uint8_t &port, i uint16_t base_size = _rx_msg.msg.mcps_indication.buffer_size; bool read_complete = false; + if (_rx_msg.pending_size == 0) { + _rx_msg.pending_size = _rx_msg.msg.mcps_indication.buffer_size; + _rx_msg.prev_read_size = 0; + } + // check the length of received message whether we can fit into user // buffer completely or not - if (_rx_msg.msg.mcps_indication.buffer_size > length - && _rx_msg.prev_read_size == 0) { - // we can't fit into user buffer. Invoke counter measures - _rx_msg.pending_size = _rx_msg.msg.mcps_indication.buffer_size - length; + if (_rx_msg.prev_read_size == 0 && _rx_msg.msg.mcps_indication.buffer_size <= length) { + memcpy(data, base_ptr, base_size); + read_complete = true; + } else if (_rx_msg.pending_size > length) { + _rx_msg.pending_size = _rx_msg.pending_size - length; base_size = length; - _rx_msg.prev_read_size = base_size; - memcpy(data, base_ptr, base_size); - } else if (_rx_msg.prev_read_size == 0) { - _rx_msg.pending_size = 0; - _rx_msg.prev_read_size = 0; - memcpy(data, base_ptr, base_size); + memcpy(data, base_ptr + _rx_msg.prev_read_size, base_size); + _rx_msg.prev_read_size += base_size; + } else { + base_size = _rx_msg.pending_size; + memcpy(data, base_ptr + _rx_msg.prev_read_size, base_size); read_complete = true; } - // If its the pending read then we should copy only the remaining part of - // the buffer. Due to checks above, in case of a pending read, this block - // will be the only one to get invoked - if (_rx_msg.pending_size > 0 && _rx_msg.prev_read_size > 0) { - memcpy(data, base_ptr + _rx_msg.prev_read_size, base_size); - } - - // we are done handing over received buffer to user. check if there is - // anything pending. If not, memset the buffer to zero and indicate - // that no read is in progress if (read_complete) { _rx_msg.msg.mcps_indication.buffer = NULL; _rx_msg.msg.mcps_indication.buffer_size = 0; + _rx_msg.pending_size = 0; _rx_msg.receive_ready = false; } @@ -655,6 +630,11 @@ void LoRaWANStack::process_reception(const uint8_t *const payload, uint16_t size if (_loramac.get_mlme_confirmation()->pending) { _loramac.post_process_mlme_request(); mlme_confirm_handler(); + + if (_loramac.get_mlme_confirmation()->req_type == MLME_JOIN) { + _ready_for_rx = true; + return; + } } if (!_loramac.nwk_joined()) { @@ -785,9 +765,17 @@ bool LoRaWANStack::is_port_valid(const uint8_t port, bool allow_port_0) //Application should not use reserved and illegal port numbers. if (port == 0) { return allow_port_0; + } else if (port == COMPLIANCE_TESTING_PORT){ +#if !defined(LORAWAN_COMPLIANCE_TEST) + return false; +#endif } else { return true; } + + // fallback for compliance testing port if LORAWAN_COMPLIANCE_TEST + // was defined + return true; } lorawan_status_t LoRaWANStack::set_application_port(const uint8_t port, bool allow_port_0) @@ -915,22 +903,16 @@ void LoRaWANStack::mlme_indication_handler() void LoRaWANStack::mlme_confirm_handler() { if (_loramac.get_mlme_confirmation()->req_type == MLME_LINK_CHECK) { - if (_loramac.get_mlme_confirmation()->status == LORAMAC_EVENT_INFO_STATUS_OK) { -#if defined(LORAWAN_COMPLIANCE_TEST) - if (_compliance_test.running == true) { - _compliance_test.link_check = true; - _compliance_test.demod_margin = _loramac.get_mlme_confirmation()->demod_margin; - _compliance_test.nb_gateways = _loramac.get_mlme_confirmation()->nb_gateways; - } else -#endif - { - if (_callbacks.link_check_resp) { - const int ret = _queue->call(_callbacks.link_check_resp, - _loramac.get_mlme_confirmation()->demod_margin, - _loramac.get_mlme_confirmation()->nb_gateways); - MBED_ASSERT(ret != 0); - (void)ret; - } + if (_loramac.get_mlme_confirmation()->status + == LORAMAC_EVENT_INFO_STATUS_OK) { + + if (_callbacks.link_check_resp) { + const int ret = _queue->call( + _callbacks.link_check_resp, + _loramac.get_mlme_confirmation()->demod_margin, + _loramac.get_mlme_confirmation()->nb_gateways); + MBED_ASSERT(ret != 0); + (void) ret; } } } @@ -999,64 +981,61 @@ void LoRaWANStack::mcps_indication_handler() _lw_session.downlink_counter = mcps_indication->dl_frame_counter; -#if defined(LORAWAN_COMPLIANCE_TEST) - if (_compliance_test.running == true) { - _compliance_test.downlink_counter++; + /** + * Check port, if it's compliance testing port and the compliance testing is + * not enabled, give up silently + */ + if (mcps_indication->port == COMPLIANCE_TESTING_PORT) { +#if !defined(LORAWAN_COMPLIANCE_TEST) + return; +#endif } -#endif - if (mcps_indication->port == 224) { -#if defined(LORAWAN_COMPLIANCE_TEST) - tr_debug("Compliance test command received."); - compliance_test_handler(mcps_indication); -#else - tr_info("Compliance test disabled."); -#endif - } else { - if (mcps_indication->is_data_recvd) { - // Valid message arrived. - _rx_msg.type = LORAMAC_RX_MCPS_INDICATION; - _rx_msg.msg.mcps_indication.buffer_size = mcps_indication->buffer_size; - _rx_msg.msg.mcps_indication.port = mcps_indication->port; - _rx_msg.msg.mcps_indication.buffer = mcps_indication->buffer; - _rx_msg.msg.mcps_indication.type = mcps_indication->type; + if (mcps_indication->is_data_recvd) { + // Valid message arrived. + _rx_msg.type = LORAMAC_RX_MCPS_INDICATION; + _rx_msg.msg.mcps_indication.buffer_size = mcps_indication->buffer_size; + _rx_msg.msg.mcps_indication.port = mcps_indication->port; + _rx_msg.msg.mcps_indication.buffer = mcps_indication->buffer; + _rx_msg.msg.mcps_indication.type = mcps_indication->type; - // Notify application about received frame.. - tr_debug("Packet Received %d bytes, Port=%d", - _rx_msg.msg.mcps_indication.buffer_size, - mcps_indication->port); - _rx_msg.receive_ready = true; - send_event_to_application(RX_DONE); - } + // Notify application about received frame.. + tr_debug("Packet Received %d bytes, Port=%d", + _rx_msg.msg.mcps_indication.buffer_size, + mcps_indication->port); + _rx_msg.receive_ready = true; + send_event_to_application(RX_DONE); + } - /* - * If fPending bit is set we try to generate an empty packet - * with CONFIRMED flag set. We always set a CONFIRMED flag so - * that we could retry a certain number of times if the uplink - * failed for some reason - * or - * Class C and node received a confirmed message so we need to - * send an empty packet to acknowledge the message. - * This scenario is unspecified by LoRaWAN 1.0.2 specification, - * but version 1.1.0 says that network SHALL not send any new - * confirmed messages until ack has been sent - */ - if ((_loramac.get_device_class() != CLASS_C && mcps_indication->fpending_status) - || - (_loramac.get_device_class() == CLASS_C && mcps_indication->type == MCPS_CONFIRMED)) { + /* + * If fPending bit is set we try to generate an empty packet + * with CONFIRMED flag set. We always set a CONFIRMED flag so + * that we could retry a certain number of times if the uplink + * failed for some reason + * or + * Class C and node received a confirmed message so we need to + * send an empty packet to acknowledge the message. + * This scenario is unspecified by LoRaWAN 1.0.2 specification, + * but version 1.1.0 says that network SHALL not send any new + * confirmed messages until ack has been sent + */ + if ((_loramac.get_device_class() != CLASS_C + && mcps_indication->fpending_status) + || (_loramac.get_device_class() == CLASS_C + && mcps_indication->type == MCPS_CONFIRMED)) { #if (MBED_CONF_LORA_AUTOMATIC_UPLINK_MESSAGE) - tr_debug("Sending empty uplink message..."); - _automatic_uplink_ongoing = true; - const int ret = _queue->call(this, &LoRaWANStack::send_automatic_uplink_message, mcps_indication->port); - MBED_ASSERT(ret != 0); - (void)ret; + tr_debug("Sending empty uplink message..."); + _automatic_uplink_ongoing = true; + const int ret = _queue->call(this, &LoRaWANStack::send_automatic_uplink_message, mcps_indication->port); + MBED_ASSERT(ret != 0); + (void)ret; #else - send_event_to_application(UPLINK_REQUIRED); + send_event_to_application(UPLINK_REQUIRED); #endif - } } } + lorawan_status_t LoRaWANStack::state_controller(device_states_t new_state) { lorawan_status_t status = LORAWAN_STATUS_OK; @@ -1084,9 +1063,9 @@ lorawan_status_t LoRaWANStack::state_controller(device_states_t new_state) process_shutdown_state(status); break; default: - tr_debug("state_controller: Unknown state!"); - status = LORAWAN_STATUS_SERVICE_UNKNOWN; - break; + //Because this is internal function only coding error causes this + tr_error("Unknown state: %d:", new_state); + MBED_ASSERT(false); } return status; @@ -1249,190 +1228,3 @@ void LoRaWANStack::process_uninitialized_state(lorawan_status_t &op_status) _device_current_state = DEVICE_STATE_IDLE; } } - -#if defined(LORAWAN_COMPLIANCE_TEST) - -lorawan_status_t LoRaWANStack::send_compliance_test_frame_to_mac() -{ - loramac_compliance_test_req_t test_req; - - //TODO: What if the port is not 224 ??? - if (_compliance_test.app_port == 224) { - // Clear any normal message stuff before compliance test. - memset(&test_req, 0, sizeof(test_req)); - - if (_compliance_test.link_check == true) { - _compliance_test.link_check = false; - _compliance_test.state = 1; - test_req.f_buffer_size = 3; - test_req.f_buffer[0] = 5; - test_req.f_buffer[1] = _compliance_test.demod_margin; - test_req.f_buffer[2] = _compliance_test.nb_gateways; - } else { - switch (_compliance_test.state) { - case 4: - _compliance_test.state = 1; - test_req.f_buffer_size = _compliance_test.app_data_size; - test_req.f_buffer[0] = _compliance_test.app_data_buffer[0]; - for (uint8_t i = 1; i < MIN(_compliance_test.app_data_size, MBED_CONF_LORA_TX_MAX_SIZE); ++i) { - test_req.f_buffer[i] = _compliance_test.app_data_buffer[i]; - } - break; - case 1: - test_req.f_buffer_size = 2; - test_req.f_buffer[0] = _compliance_test.downlink_counter >> 8; - test_req.f_buffer[1] = _compliance_test.downlink_counter; - break; - } - } - } - - //TODO: If port is not 224, this might not work! - //Is there a test case where same _tx_msg's buffer would be used, when port is not 224??? - if (!_compliance_test.is_tx_confirmed) { - test_req.type = MCPS_UNCONFIRMED; - test_req.fport = _compliance_test.app_port; - test_req.nb_trials = 1; - test_req.data_rate = _loramac.get_default_tx_datarate(); - - tr_info("Transmit unconfirmed compliance test frame %d bytes.", test_req.f_buffer_size); - - for (uint8_t i = 0; i < test_req.f_buffer_size; ++i) { - tr_info("Byte %d, data is 0x%x", i + 1, ((uint8_t *)test_req.f_buffer)[i]); - } - } else if (_compliance_test.is_tx_confirmed) { - test_req.type = MCPS_CONFIRMED; - test_req.fport = _compliance_test.app_port; - test_req.nb_trials = _num_retry; - test_req.data_rate = _loramac.get_default_tx_datarate(); - - tr_info("Transmit confirmed compliance test frame %d bytes.", test_req.f_buffer_size); - - for (uint8_t i = 0; i < test_req.f_buffer_size; ++i) { - tr_info("Byte %d, data is 0x%x", i + 1, ((uint8_t *)test_req.f_buffer)[i]); - } - } else { - return LORAWAN_STATUS_SERVICE_UNKNOWN; - } - - return _loramac.test_request(&test_req); -} - -void LoRaWANStack::compliance_test_handler(loramac_mcps_indication_t *mcps_indication) -{ - if (_compliance_test.running == false) { - // Check compliance test enable command (i) - if ((mcps_indication->buffer_size == 4) && - (mcps_indication->buffer[0] == 0x01) && - (mcps_indication->buffer[1] == 0x01) && - (mcps_indication->buffer[2] == 0x01) && - (mcps_indication->buffer[3] == 0x01)) { - _compliance_test.is_tx_confirmed = false; - _compliance_test.app_port = 224; - _compliance_test.app_data_size = 2; - _compliance_test.downlink_counter = 0; - _compliance_test.link_check = false; - _compliance_test.demod_margin = 0; - _compliance_test.nb_gateways = 0; - _compliance_test.running = true; - _compliance_test.state = 1; - - _loramac.enable_adaptive_datarate(true); - -#if MBED_CONF_LORA_PHY == 0 - _loramac.LoRaMacTestSetDutyCycleOn(false); -#endif - //5000ms - _loramac.LoRaMacSetTxTimer(5000); - - //TODO: Should we call lora_state_machine here instead of just setting the state? - _device_current_state = DEVICE_STATE_COMPLIANCE_TEST; -// lora_state_machine(DEVICE_STATE_COMPLIANCE_TEST); - tr_debug("Compliance test activated."); - } - } else { - _compliance_test.state = mcps_indication->buffer[0]; - switch (_compliance_test.state) { - case 0: // Check compliance test disable command (ii) - _compliance_test.is_tx_confirmed = true; - _compliance_test.app_port = MBED_CONF_LORA_APP_PORT; - _compliance_test.app_data_size = LORAWAN_COMPLIANCE_TEST_DATA_SIZE; - _compliance_test.downlink_counter = 0; - _compliance_test.running = false; - - _loramac.enable_adaptive_datarate(MBED_CONF_LORA_ADR_ON); - -#if MBED_CONF_LORA_PHY == 0 - _loramac.LoRaMacTestSetDutyCycleOn(MBED_CONF_LORA_DUTY_CYCLE_ON); -#endif - // Go to idle state after compliance test mode. - tr_debug("Compliance test disabled."); - _loramac.LoRaMacStopTxTimer(); - - // Clear any compliance test message stuff before going back to normal operation. - _loramac.reset_ongoing_tx(); - lora_state_machine(DEVICE_STATE_IDLE); - break; - case 1: // (iii, iv) - _compliance_test.app_data_size = 2; - break; - case 2: // Enable confirmed messages (v) - _compliance_test.is_tx_confirmed = true; - _compliance_test.state = 1; - break; - case 3: // Disable confirmed messages (vi) - _compliance_test.is_tx_confirmed = false; - _compliance_test.state = 1; - break; - case 4: // (vii) - _compliance_test.app_data_size = mcps_indication->buffer_size; - - _compliance_test.app_data_buffer[0] = 4; - for (uint8_t i = 1; i < MIN(_compliance_test.app_data_size, LORAMAC_PHY_MAXPAYLOAD); ++i) { - _compliance_test.app_data_buffer[i] = mcps_indication->buffer[i] + 1; - } - - send_compliance_test_frame_to_mac(); - break; - case 5: // (viii) - _loramac.setup_link_check_request(); - break; - case 6: // (ix) - // Disable TestMode and revert back to normal operation - _compliance_test.is_tx_confirmed = true; - _compliance_test.app_port = MBED_CONF_LORA_APP_PORT; - _compliance_test.app_data_size = LORAWAN_COMPLIANCE_TEST_DATA_SIZE; - _compliance_test.downlink_counter = 0; - _compliance_test.running = false; - - _loramac.enable_adaptive_datarate(MBED_CONF_LORA_ADR_ON); - -#if MBED_CONF_LORA_PHY == 0 - _loramac.LoRaMacTestSetDutyCycleOn(MBED_CONF_LORA_DUTY_CYCLE_ON); -#endif - _loramac.join(true); - break; - case 7: // (x) - if (mcps_indication->buffer_size == 3) { - loramac_mlme_req_t mlme_req; - mlme_req.type = MLME_TXCW; - mlme_req.cw_tx_mode.timeout = (uint16_t)((mcps_indication->buffer[1] << 8) | mcps_indication->buffer[2]); - _loramac.mlme_request(&mlme_req); - } else if (mcps_indication->buffer_size == 7) { - loramac_mlme_req_t mlme_req; - mlme_req.type = MLME_TXCW_1; - mlme_req.cw_tx_mode.timeout = (uint16_t)((mcps_indication->buffer[1] << 8) - | mcps_indication->buffer[2]); - mlme_req.cw_tx_mode.frequency = (uint32_t)((mcps_indication->buffer[3] << 16) - | (mcps_indication->buffer[4] << 8) - | mcps_indication->buffer[5]) * 100; - mlme_req.cw_tx_mode.power = mcps_indication->buffer[6]; - _loramac.mlme_request(&mlme_req); - } - _compliance_test.state = 1; - break; - } - } -} -#endif - diff --git a/features/lorawan/LoRaWANStack.h b/features/lorawan/LoRaWANStack.h index 4f052d9d1c..d417108b88 100644 --- a/features/lorawan/LoRaWANStack.h +++ b/features/lorawan/LoRaWANStack.h @@ -505,21 +505,6 @@ private: uint8_t _rx_payload[LORAMAC_PHY_MAXPAYLOAD]; events::EventQueue *_queue; lorawan_time_t _tx_timestamp; - -#if defined(LORAWAN_COMPLIANCE_TEST) - - /** - * Used only for compliance testing - */ - void compliance_test_handler(loramac_mcps_indication_t *mcps_indication); - - /** - * Used only for compliance testing - */ - lorawan_status_t send_compliance_test_frame_to_mac(); - - compliance_test_t _compliance_test; -#endif }; #endif /* LORAWANSTACK_H_ */ diff --git a/features/lorawan/lorastack/mac/LoRaMac.cpp b/features/lorawan/lorastack/mac/LoRaMac.cpp index 9aceccd529..43dbec93e8 100644 --- a/features/lorawan/lorastack/mac/LoRaMac.cpp +++ b/features/lorawan/lorastack/mac/LoRaMac.cpp @@ -163,6 +163,7 @@ void LoRaMac::post_process_mcps_req() _mcps_indication.is_ack_recvd = false; if (_params.is_ul_frame_counter_fixed == false) { _params.ul_frame_counter++; + _params.adr_ack_counter++; } } else { _mcps_confirmation.status = LORAMAC_EVENT_INFO_STATUS_ERROR; @@ -171,6 +172,7 @@ void LoRaMac::post_process_mcps_req() //UNCONFIRMED or PROPRIETARY if (_params.is_ul_frame_counter_fixed == false) { _params.ul_frame_counter++; + _params.adr_ack_counter++; } } } @@ -269,6 +271,7 @@ void LoRaMac::handle_join_accept_frame(const uint8_t *payload, uint16_t size) // Node joined successfully _params.ul_frame_counter = 0; _params.ul_nb_rep_counter = 0; + _params.adr_ack_counter = 0; } else { _mlme_confirmation.status = LORAMAC_EVENT_INFO_STATUS_JOIN_FAIL; @@ -532,6 +535,7 @@ void LoRaMac::handle_data_frame(const uint8_t *const payload, _params.adr_ack_counter = 0; _mac_commands.clear_repeat_buffer(); + _mac_commands.clear_command_buffer(); if (is_multicast) { _mcps_indication.type = MCPS_MULTICAST; @@ -580,18 +584,9 @@ void LoRaMac::handle_data_frame(const uint8_t *const payload, _params.dl_frame_counter = downlink_counter; } - // This must be done before parsing the payload and the MAC commands. - // We need to reset the MacCommandsBufferIndex here, since we need - // to take retransmissions and repetitions into account. Error cases - // will be handled in function OnMacStateCheckTimerEvent. - if (_params.is_node_ack_requested) { - if (fctrl.bits.ack) { - _mac_commands.clear_command_buffer(); - _mcps_confirmation.ack_received = fctrl.bits.ack; - _mcps_indication.is_ack_recvd = fctrl.bits.ack; - } - } else { - _mac_commands.clear_command_buffer(); + if (_params.is_node_ack_requested && fctrl.bits.ack) { + _mcps_confirmation.ack_received = fctrl.bits.ack; + _mcps_indication.is_ack_recvd = fctrl.bits.ack; } uint8_t frame_len = (size - 4) - app_payload_start_index; @@ -660,6 +655,8 @@ void LoRaMac::on_radio_tx_done(lorawan_time_t timestamp) _lora_phy->set_last_tx_done(_params.channel, _is_nwk_joined, timestamp); _params.timers.aggregated_last_tx_time = timestamp; + + _mac_commands.clear_command_buffer(); } void LoRaMac::on_radio_rx_done(const uint8_t *const payload, uint16_t size, @@ -778,8 +775,6 @@ bool LoRaMac::continue_joining_process() bool LoRaMac::continue_sending_process() { if (_params.ack_timeout_retry_counter > _params.max_ack_timeout_retries) { - _mac_commands.clear_command_buffer(); - _params.adr_ack_counter++; _lora_time.stop(_params.timers.ack_timeout_timer); return false; } @@ -1104,12 +1099,14 @@ lorawan_status_t LoRaMac::schedule_tx() break; } - tr_debug("TX: Channel=%d, DR=%d", _params.channel, next_channel.current_datarate); - - uint8_t dr_offset = _lora_phy->apply_DR_offset(_params.sys_params.channel_data_rate, + uint8_t rx1_dr = _lora_phy->apply_DR_offset(_params.sys_params.channel_data_rate, _params.sys_params.rx1_dr_offset); - _lora_phy->compute_rx_win_params(dr_offset, MBED_CONF_LORA_DOWNLINK_PREAMBLE_LENGTH, + tr_debug("TX: Channel=%d, TX DR=%d, RX1 DR=%d", + _params.channel, _params.sys_params.channel_data_rate, rx1_dr); + + + _lora_phy->compute_rx_win_params(rx1_dr, MBED_CONF_LORA_DOWNLINK_PREAMBLE_LENGTH, MBED_CONF_LORA_MAX_SYS_RX_ERROR, &_params.rx_window1_config); @@ -1191,7 +1188,6 @@ void LoRaMac::reset_mac_parameters(void) _mac_commands.clear_command_buffer(); _mac_commands.clear_repeat_buffer(); - _mac_commands.clear_mac_commands_in_next_tx(); _params.is_rx_window_enabled = true; @@ -1596,26 +1592,23 @@ lorawan_status_t LoRaMac::prepare_frame(loramac_mhdr_t *machdr, const uint8_t mac_commands_len = _mac_commands.get_mac_cmd_length(); if ((payload != NULL) && (_params.tx_buffer_len > 0)) { - if (_mac_commands.is_mac_command_in_next_tx() == true) { - if (mac_commands_len <= LORA_MAC_COMMAND_MAX_FOPTS_LENGTH) { - fctrl->bits.fopts_len += mac_commands_len; + if (mac_commands_len <= LORA_MAC_COMMAND_MAX_FOPTS_LENGTH) { + fctrl->bits.fopts_len += mac_commands_len; - // Update FCtrl field with new value of OptionsLength - _params.tx_buffer[0x05] = fctrl->value; + // Update FCtrl field with new value of OptionsLength + _params.tx_buffer[0x05] = fctrl->value; - const uint8_t *buffer = _mac_commands.get_mac_commands_buffer(); - for (i = 0; i < mac_commands_len; i++) { - _params.tx_buffer[pkt_header_len++] = buffer[i]; - } - } else { - _params.tx_buffer_len = mac_commands_len; - payload = _mac_commands.get_mac_commands_buffer(); - frame_port = 0; + const uint8_t *buffer = _mac_commands.get_mac_commands_buffer(); + for (i = 0; i < mac_commands_len; i++) { + _params.tx_buffer[pkt_header_len++] = buffer[i]; } + } else { + _params.tx_buffer_len = mac_commands_len; + payload = _mac_commands.get_mac_commands_buffer(); + frame_port = 0; } } else { - if ((mac_commands_len > 0) - && (_mac_commands.is_mac_command_in_next_tx() == true)) { + if (mac_commands_len > 0) { _params.tx_buffer_len = mac_commands_len; payload = _mac_commands.get_mac_commands_buffer(); frame_port = 0; @@ -1632,7 +1625,6 @@ lorawan_status_t LoRaMac::prepare_frame(loramac_mhdr_t *machdr, uint8_t *key = _params.keys.app_skey; uint32_t key_length = sizeof(_params.keys.app_skey) * 8; if (frame_port == 0) { - _mac_commands.clear_command_buffer(); key = _params.keys.nwk_skey; key_length = sizeof(_params.keys.nwk_skey) * 8; } @@ -1729,21 +1721,6 @@ void LoRaMac::reset_mcps_indication() _mcps_indication.status = LORAMAC_EVENT_INFO_STATUS_ERROR; } -void LoRaMac::set_tx_continuous_wave(uint8_t channel, int8_t datarate, int8_t tx_power, - float max_eirp, float antenna_gain, uint16_t timeout) -{ - cw_mode_params_t continuous_wave; - - continuous_wave.channel = channel; - continuous_wave.datarate = datarate; - continuous_wave.tx_power = tx_power; - continuous_wave.max_eirp = max_eirp; - continuous_wave.antenna_gain = antenna_gain; - continuous_wave.timeout = timeout; - - _lora_phy->set_tx_cont_mode(&continuous_wave); -} - lorawan_status_t LoRaMac::initialize(EventQueue *queue, mbed::Callbackscheduling_failure_handler) { @@ -1809,7 +1786,6 @@ void LoRaMac::disconnect() _mac_commands.clear_command_buffer(); _mac_commands.clear_repeat_buffer(); - _mac_commands.clear_mac_commands_in_next_tx(); reset_mcps_confirmation(); reset_mlme_confirmation(); @@ -1821,13 +1797,17 @@ uint8_t LoRaMac::get_max_possible_tx_size(uint8_t fopts_len) uint8_t max_possible_payload_size = 0; uint8_t allowed_frm_payload_size = 0; + int8_t datarate = _params.sys_params.channel_data_rate; + int8_t tx_power = _params.sys_params.channel_tx_power; + uint32_t adr_ack_counter = _params.adr_ack_counter; + if (_params.sys_params.adr_on) { - _lora_phy->get_next_ADR(false, _params.sys_params.channel_data_rate, - _params.sys_params.channel_tx_power, - _params.adr_ack_counter); + // Just query the information. We do not want to apply them into use + // at this point. + _lora_phy->get_next_ADR(false, datarate, tx_power, adr_ack_counter); } - allowed_frm_payload_size = _lora_phy->get_max_payload(_params.sys_params.channel_data_rate, + allowed_frm_payload_size = _lora_phy->get_max_payload(datarate, _params.is_repeater_supported); if (allowed_frm_payload_size >= fopts_len) { @@ -1942,147 +1922,3 @@ void LoRaMac::bind_phy(LoRaPHY &phy) { _lora_phy = &phy; } - -#if defined(LORAWAN_COMPLIANCE_TEST) -/*************************************************************************** - * Compliance testing * - **************************************************************************/ - - -lorawan_status_t LoRaMac::mlme_request(loramac_mlme_req_t *mlmeRequest) -{ - if (LORAMAC_IDLE != _params.mac_state) { - return LORAWAN_STATUS_BUSY; - } - - reset_mlme_confirmation(); - - _mlme_confirmation.req_type = mlmeRequest->type; - _params.flags.bits.mlme_req = 1; - - lorawan_status_t status = LORAWAN_STATUS_SERVICE_UNKNOWN; - - if (MLME_TXCW == mlmeRequest->type) { - set_tx_continuous_wave(_params.channel, _params.sys_params.channel_data_rate, _params.sys_params.channel_tx_power, - _params.sys_params.max_eirp, _params.sys_params.antenna_gain, mlmeRequest->cw_tx_mode.timeout); - _lora_time.start(_params.timers.mac_state_check_timer, - MAC_STATE_CHECK_TIMEOUT); - - _params.mac_state |= LORAMAC_TX_RUNNING; - status = LORAWAN_STATUS_OK; - } else if (MLME_TXCW_1 == mlmeRequest->type) { - set_tx_continuous_wave(0, 0, mlmeRequest->cw_tx_mode.power, 0, 0, mlmeRequest->cw_tx_mode.timeout); - _lora_time.start(_params.timers.mac_state_check_timer, - MAC_STATE_CHECK_TIMEOUT); - - _params.mac_state |= LORAMAC_TX_RUNNING; - status = LORAWAN_STATUS_OK; - } - - if (status != LORAWAN_STATUS_OK) { - _params.is_node_ack_requested = false; - _params.flags.bits.mlme_req = 0; - } - - return status; -} - -lorawan_status_t LoRaMac::test_request(loramac_compliance_test_req_t *mcpsRequest) -{ - if (_params.mac_state != LORAMAC_IDLE) { - return LORAWAN_STATUS_BUSY; - } - - loramac_mhdr_t machdr; - int8_t datarate = mcpsRequest->data_rate; - // TODO: The comment is different than the code??? - // Apply the minimum possible datarate. - // Some regions have limitations for the minimum datarate. - datarate = MAX(datarate, (int8_t)_lora_phy->get_minimum_tx_datarate()); - - machdr.value = 0; - - reset_mcps_confirmation(); - - _params.ack_timeout_retry_counter = 1; - _params.max_ack_timeout_retries = 1; - - switch (mcpsRequest->type) { - case MCPS_UNCONFIRMED: { - machdr.bits.mtype = FRAME_TYPE_DATA_UNCONFIRMED_UP; - break; - } - case MCPS_CONFIRMED: { - machdr.bits.mtype = FRAME_TYPE_DATA_CONFIRMED_UP; - _params.max_ack_timeout_retries = mcpsRequest->nb_trials; - break; - } - case MCPS_PROPRIETARY: { - machdr.bits.mtype = FRAME_TYPE_PROPRIETARY; - break; - } - default: - return LORAWAN_STATUS_PARAMETER_INVALID; - } - -// Filter fPorts -// TODO: Does not work with PROPRIETARY messages -// if( IsFPortAllowed( mcpsRequest->fport ) == false ) { -// return LORAWAN_STATUS_PARAMETER_INVALID; -// } - - if (_params.sys_params.adr_on == false) { - if (_lora_phy->verify_tx_datarate(datarate, false) == true) { - _params.sys_params.channel_data_rate = datarate; - } else { - return LORAWAN_STATUS_PARAMETER_INVALID; - } - } - - lorawan_status_t status = send(&machdr, mcpsRequest->fport, mcpsRequest->f_buffer, - mcpsRequest->f_buffer_size); - if (status == LORAWAN_STATUS_OK) { - _mcps_confirmation.req_type = mcpsRequest->type; - _params.flags.bits.mcps_req = 1; - } else { - _params.is_node_ack_requested = false; - } - - return status; -} - -lorawan_status_t LoRaMac::LoRaMacSetTxTimer(uint32_t TxDutyCycleTime) -{ - _lora_time.start(tx_next_packet_timer, TxDutyCycleTime); - return LORAWAN_STATUS_OK; -} - -lorawan_status_t LoRaMac::LoRaMacStopTxTimer() -{ - _lora_time.stop(tx_next_packet_timer); - return LORAWAN_STATUS_OK; -} - -void LoRaMac::LoRaMacTestRxWindowsOn(bool enable) -{ - _params.is_rx_window_enabled = enable; -} - -void LoRaMac::LoRaMacTestSetMic(uint16_t txPacketCounter) -{ - _params.ul_frame_counter = txPacketCounter; - _params.is_ul_frame_counter_fixed = true; -} - -void LoRaMac::LoRaMacTestSetDutyCycleOn(bool enable) -{ - if (_lora_phy->verify_duty_cycle(enable) == true) { - _params.is_dutycycle_on = enable; - } -} - -void LoRaMac::LoRaMacTestSetChannel(uint8_t channel) -{ - _params.channel = channel; -} -#endif diff --git a/features/lorawan/lorastack/mac/LoRaMac.h b/features/lorawan/lorastack/mac/LoRaMac.h index f81e7a7a0a..8ec5a8793f 100644 --- a/features/lorawan/lorastack/mac/LoRaMac.h +++ b/features/lorawan/lorastack/mac/LoRaMac.h @@ -672,136 +672,6 @@ private: bool _continuous_rx2_window_open; device_class_t _device_class; - -#if defined(LORAWAN_COMPLIANCE_TEST) -public: // Test interface - - /** - * @brief Set forth an MLME request. - * - * @details The MAC layer management entity handles the management services. - * - * @param [in] request The MLME request to perform. - * Refer to \ref loramac_mlme_req_t. - * - * @return `lorawan_status_t` The status of the operation. The possible values are: - * \ref LORAWAN_STATUS_OK - * \ref LORAWAN_STATUS_BUSY - * \ref LORAWAN_STATUS_SERVICE_UNKNOWN - * \ref LORAWAN_STATUS_PARAMETER_INVALID - * \ref LORAWAN_STATUS_NO_NETWORK_JOINED - * \ref LORAWAN_STATUS_LENGTH_ERROR - * \ref LORAWAN_STATUS_DEVICE_OFF - */ - lorawan_status_t mlme_request(loramac_mlme_req_t *request); - - /** - * @brief Set forth an MCPS request. - * - * @details The MAC Common Part Sublayer handles the data services. The following - * code-snippet shows how to use the API to send an unconfirmed - * LoRaMAC frame. - * - * @code - * - * uint8_t buffer[] = {1, 2, 3}; - * - * loramac_compliance_test_req_t request; - * request.type = MCPS_UNCONFIRMED; - * request.fport = 1; - * request.f_buffer = buffer; - * request.f_buffer_size = sizeof(buffer); - * - * if (test_request(&request) == LORAWAN_STATUS_OK) { - * // Service started successfully. Waiting for the MCPS-Confirm event - * } - * - * @endcode - * - * @param [in] request The test request to perform. - * Refer to \ref loramac_compliance_test_req_t. - * - * @return `lorawan_status_t` The status of the operation. The possible values are: - * \ref LORAWAN_STATUS_OK - * \ref LORAWAN_STATUS_BUSY - * \ref LORAWAN_STATUS_SERVICE_UNKNOWN - * \ref LORAWAN_STATUS_PARAMETER_INVALID - * \ref LORAWAN_STATUS_NO_NETWORK_JOINED - * \ref LORAWAN_STATUS_LENGTH_ERROR - * \ref LORAWAN_STATUS_DEVICE_OFF - */ - lorawan_status_t test_request(loramac_compliance_test_req_t *request); - - /** - * \brief LoRaMAC set tx timer. - * - * \details Sets up a timer for next transmission (application specific timers). - * - * \param [in] NextTxTime - Periodic time for next uplink. - - * \retval `lorawan_status_t` The status of the operation. The possible values are: - * \ref LORAWAN_STATUS_OK - * \ref LORAWAN_STATUS_PARAMETER_INVALID - */ - lorawan_status_t LoRaMacSetTxTimer(uint32_t NextTxTime); - - /** - * \brief LoRaMAC stop tx timer. - * - * \details Stops the next tx timer. - * - * \retval `lorawan_status_t` The status of the operation. The possible values are: - * \ref LORAWAN_STATUS_OK - * \ref LORAWAN_STATUS_PARAMETER_INVALID - */ - lorawan_status_t LoRaMacStopTxTimer(); - - /** - * \brief Enabled or disables the reception windows - * - * \details This is a test function. It shall be used for testing purposes only. - * Changing this attribute may lead to a non-conformance LoRaMac operation. - * - * \param [in] enable - Enabled or disables the reception windows - */ - void LoRaMacTestRxWindowsOn(bool enable); - - /** - * \brief Enables the MIC field test - * - * \details This is a test function. It shall be used for testing purposes only. - * Changing this attribute may lead to a non-conformance LoRaMac operation. - * - * \param [in] txPacketCounter - Fixed Tx packet counter value - */ - void LoRaMacTestSetMic(uint16_t txPacketCounter); - - /** - * \brief Enabled or disables the duty cycle - * - * \details This is a test function. It shall be used for testing purposes only. - * Changing this attribute may lead to a non-conformance LoRaMac operation. - * - * \param [in] enable - Enabled or disables the duty cycle - */ - void LoRaMacTestSetDutyCycleOn(bool enable); - - /** - * \brief Sets the channel index - * - * \details This is a test function. It shall be used for testing purposes only. - * Changing this attribute may lead to a non-conformance LoRaMac operation. - * - * \param [in] channel - Channel index - */ - void LoRaMacTestSetChannel(uint8_t channel); - -private: - /** - * Timer to handle the application data transmission duty cycle - */ - timer_event_t tx_next_packet_timer; -#endif }; #endif // MBED_LORAWAN_MAC_H__ diff --git a/features/lorawan/lorastack/mac/LoRaMacCommand.cpp b/features/lorawan/lorastack/mac/LoRaMacCommand.cpp index cde62355b3..87afc3409f 100644 --- a/features/lorawan/lorastack/mac/LoRaMacCommand.cpp +++ b/features/lorawan/lorastack/mac/LoRaMacCommand.cpp @@ -33,10 +33,8 @@ SPDX-License-Identifier: BSD-3-Clause */ static const uint8_t max_eirp_table[] = { 8, 10, 12, 13, 14, 16, 18, 20, 21, 24, 26, 27, 29, 30, 33, 36 }; - LoRaMacCommand::LoRaMacCommand() { - mac_cmd_in_next_tx = false; sticky_mac_cmd = false; mac_cmd_buf_idx = 0; mac_cmd_buf_idx_to_repeat = 0; @@ -94,20 +92,15 @@ void LoRaMacCommand::parse_mac_commands_to_repeat() case MOTE_MAC_LINK_CHECK_REQ: { // 0 byte payload break; } - default: - break; + default: { + MBED_ASSERT(false); + } } } - if (cmd_cnt > 0) { - mac_cmd_in_next_tx = true; - } else { - mac_cmd_in_next_tx = false; - } mac_cmd_buf_idx_to_repeat = cmd_cnt; } - void LoRaMacCommand::clear_repeat_buffer() { mac_cmd_buf_idx_to_repeat = 0; @@ -124,16 +117,6 @@ uint8_t LoRaMacCommand::get_repeat_commands_length() const return mac_cmd_buf_idx_to_repeat; } -void LoRaMacCommand::clear_mac_commands_in_next_tx() -{ - mac_cmd_in_next_tx = false; -} - -bool LoRaMacCommand::is_mac_command_in_next_tx() const -{ - return mac_cmd_in_next_tx; -} - void LoRaMacCommand::clear_sticky_mac_cmd() { sticky_mac_cmd = false; @@ -207,8 +190,7 @@ lorawan_status_t LoRaMacCommand::process_mac_commands(const uint8_t *payload, ui rx_param_setup_req_t rxParamSetupReq; rxParamSetupReq.dr_offset = (payload[mac_index] >> 4) & 0x07; - rxParamSetupReq.datarate = payload[mac_index] & 0x0F; - mac_index++; + rxParamSetupReq.datarate = payload[mac_index++] & 0x0F; rxParamSetupReq.frequency = (uint32_t) payload[mac_index++]; rxParamSetupReq.frequency |= (uint32_t) payload[mac_index++] << 8; @@ -304,20 +286,13 @@ lorawan_status_t LoRaMacCommand::process_mac_commands(const uint8_t *payload, ui break; default: // Unknown command. ABORT MAC commands processing - ret_value = LORAWAN_STATUS_UNSUPPORTED; + tr_error("Invalid MAC command (0x%X)!", payload[mac_index]); + return LORAWAN_STATUS_UNSUPPORTED; } } return ret_value; } -bool LoRaMacCommand::is_sticky_mac_command_pending() -{ - if (mac_cmd_buf_idx_to_repeat > 0) { - return true; - } - return false; -} - int32_t LoRaMacCommand::cmd_buffer_remaining() const { // The maximum buffer length must take MAC commands to re-send into account. @@ -336,7 +311,6 @@ lorawan_status_t LoRaMacCommand::add_link_check_req() mac_cmd_buffer[mac_cmd_buf_idx++] = MOTE_MAC_LINK_CHECK_REQ; // No payload for this command ret = LORAWAN_STATUS_OK; - mac_cmd_in_next_tx = true; } return ret; } @@ -348,7 +322,6 @@ lorawan_status_t LoRaMacCommand::add_link_adr_ans(uint8_t status) mac_cmd_buffer[mac_cmd_buf_idx++] = MOTE_MAC_LINK_ADR_ANS; mac_cmd_buffer[mac_cmd_buf_idx++] = status; ret = LORAWAN_STATUS_OK; - mac_cmd_in_next_tx = true; } return ret; } @@ -360,7 +333,6 @@ lorawan_status_t LoRaMacCommand::add_duty_cycle_ans() mac_cmd_buffer[mac_cmd_buf_idx++] = MOTE_MAC_DUTY_CYCLE_ANS; // No payload for this answer ret = LORAWAN_STATUS_OK; - mac_cmd_in_next_tx = true; } return ret; } @@ -375,7 +347,6 @@ lorawan_status_t LoRaMacCommand::add_rx_param_setup_ans(uint8_t status) // This is a sticky MAC command answer. Setup indication sticky_mac_cmd = true; ret = LORAWAN_STATUS_OK; - mac_cmd_in_next_tx = true; } return ret; } @@ -390,7 +361,6 @@ lorawan_status_t LoRaMacCommand::add_dev_status_ans(uint8_t battery, uint8_t mar mac_cmd_buffer[mac_cmd_buf_idx++] = battery; mac_cmd_buffer[mac_cmd_buf_idx++] = margin; ret = LORAWAN_STATUS_OK; - mac_cmd_in_next_tx = true; } return ret; } @@ -403,7 +373,6 @@ lorawan_status_t LoRaMacCommand::add_new_channel_ans(uint8_t status) // Status: Datarate range OK, Channel frequency OK mac_cmd_buffer[mac_cmd_buf_idx++] = status; ret = LORAWAN_STATUS_OK; - mac_cmd_in_next_tx = true; } return ret; } @@ -417,7 +386,6 @@ lorawan_status_t LoRaMacCommand::add_rx_timing_setup_ans() // This is a sticky MAC command answer. Setup indication sticky_mac_cmd = true; ret = LORAWAN_STATUS_OK; - mac_cmd_in_next_tx = true; } return ret; } @@ -429,7 +397,6 @@ lorawan_status_t LoRaMacCommand::add_tx_param_setup_ans() mac_cmd_buffer[mac_cmd_buf_idx++] = MOTE_MAC_TX_PARAM_SETUP_ANS; // No payload for this answer ret = LORAWAN_STATUS_OK; - mac_cmd_in_next_tx = true; } return ret; } @@ -437,14 +404,13 @@ lorawan_status_t LoRaMacCommand::add_tx_param_setup_ans() lorawan_status_t LoRaMacCommand::add_dl_channel_ans(uint8_t status) { lorawan_status_t ret = LORAWAN_STATUS_LENGTH_ERROR; - if (cmd_buffer_remaining() > 0) { + if (cmd_buffer_remaining() > 1) { mac_cmd_buffer[mac_cmd_buf_idx++] = MOTE_MAC_DL_CHANNEL_ANS; // Status: Uplink frequency exists, Channel frequency OK mac_cmd_buffer[mac_cmd_buf_idx++] = status; // This is a sticky MAC command answer. Setup indication sticky_mac_cmd = true; ret = LORAWAN_STATUS_OK; - mac_cmd_in_next_tx = true; } return ret; } diff --git a/features/lorawan/lorastack/mac/LoRaMacCommand.h b/features/lorawan/lorastack/mac/LoRaMacCommand.h index dfbcd29608..7b7d730950 100644 --- a/features/lorawan/lorastack/mac/LoRaMacCommand.h +++ b/features/lorawan/lorastack/mac/LoRaMacCommand.h @@ -76,7 +76,7 @@ public: uint8_t *get_mac_commands_buffer(); /** - * @brief Parses the MAC commands which must be resent. + * @brief Parses the MAC commands which must be re-sent. */ void parse_mac_commands_to_repeat(); @@ -97,18 +97,6 @@ public: */ uint8_t get_repeat_commands_length() const; - /** - * @brief Clear MAC commands in next TX. - */ - void clear_mac_commands_in_next_tx(); - - /** - * @brief Check if MAC command buffer has commands to be sent in next TX - * - * @return status True: buffer has MAC commands to be sent, false: no commands in buffer - */ - bool is_mac_command_in_next_tx() const; - /** * @brief Clear sticky MAC commands. */ @@ -132,13 +120,6 @@ public: lora_mac_system_params_t& mac_params, LoRaPHY& lora_phy); - /** - * @brief Verifies if sticky MAC commands are pending. - * - * @return [true: sticky MAC commands pending, false: No MAC commands pending] - */ - bool is_sticky_mac_command_pending(); - /** * @brief Adds a new LinkCheckReq MAC command to be sent. * @@ -237,11 +218,6 @@ private: lorawan_status_t add_dl_channel_ans(uint8_t status); private: - /** - * Indicates if the MAC layer wants to send MAC commands - */ - bool mac_cmd_in_next_tx; - /** * Indicates if there are any pending sticky MAC commands */ diff --git a/features/lorawan/lorastack/mac/LoRaMacCrypto.cpp b/features/lorawan/lorastack/mac/LoRaMacCrypto.cpp index f2afc8dcf5..10099fcae3 100644 --- a/features/lorawan/lorastack/mac/LoRaMacCrypto.cpp +++ b/features/lorawan/lorastack/mac/LoRaMacCrypto.cpp @@ -33,13 +33,7 @@ #if defined(MBEDTLS_CMAC_C) && defined(MBEDTLS_AES_C) && defined(MBEDTLS_CIPHER_C) LoRaMacCrypto::LoRaMacCrypto() - : mic_block_b0(), - computed_mic(), - a_block(), - s_block() { - mic_block_b0[0] = 0x49; - a_block[0] = 0x01; } int LoRaMacCrypto::compute_mic(const uint8_t *buffer, uint16_t size, @@ -47,8 +41,12 @@ int LoRaMacCrypto::compute_mic(const uint8_t *buffer, uint16_t size, uint32_t address, uint8_t dir, uint32_t seq_counter, uint32_t *mic) { + uint8_t computed_mic[16] = {}; + uint8_t mic_block_b0[16] = {}; int ret = 0; + mic_block_b0[0] = 0x49; + mic_block_b0[5] = dir; mic_block_b0[6] = (address) & 0xFF; @@ -95,7 +93,8 @@ int LoRaMacCrypto::compute_mic(const uint8_t *buffer, uint16_t size, ret = MBEDTLS_ERR_CIPHER_ALLOC_FAILED; } -exit: mbedtls_cipher_free(aes_cmac_ctx); +exit: + mbedtls_cipher_free(aes_cmac_ctx); return ret; } @@ -108,12 +107,15 @@ int LoRaMacCrypto::encrypt_payload(const uint8_t *buffer, uint16_t size, uint8_t bufferIndex = 0; uint16_t ctr = 1; int ret = 0; + uint8_t a_block[16] = {}; + uint8_t s_block[16] = {}; mbedtls_aes_init(&aes_ctx); ret = mbedtls_aes_setkey_enc(&aes_ctx, key, key_length); if (0 != ret) goto exit; + a_block[0] = 0x01; a_block[5] = dir; a_block[6] = (address) & 0xFF; @@ -153,7 +155,8 @@ int LoRaMacCrypto::encrypt_payload(const uint8_t *buffer, uint16_t size, } } -exit: mbedtls_aes_free(&aes_ctx); +exit: + mbedtls_aes_free(&aes_ctx); return ret; } @@ -170,6 +173,7 @@ int LoRaMacCrypto::compute_join_frame_mic(const uint8_t *buffer, uint16_t size, const uint8_t *key, uint32_t key_length, uint32_t *mic) { + uint8_t computed_mic[16] = {}; int ret = 0; mbedtls_cipher_init(aes_cmac_ctx); @@ -199,7 +203,8 @@ int LoRaMacCrypto::compute_join_frame_mic(const uint8_t *buffer, uint16_t size, ret = MBEDTLS_ERR_CIPHER_ALLOC_FAILED; } -exit: mbedtls_cipher_free(aes_cmac_ctx); +exit: + mbedtls_cipher_free(aes_cmac_ctx); return ret; } @@ -226,7 +231,8 @@ int LoRaMacCrypto::decrypt_join_frame(const uint8_t *buffer, uint16_t size, dec_buffer + 16); } -exit: mbedtls_aes_free(&aes_ctx); +exit: + mbedtls_aes_free(&aes_ctx); return ret; } @@ -258,7 +264,8 @@ int LoRaMacCrypto::compute_skeys_for_join_frame(const uint8_t *key, uint32_t key memcpy(nonce + 7, p_dev_nonce, 2); ret = mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, nonce, app_skey); - exit: mbedtls_aes_free(&aes_ctx); +exit: + mbedtls_aes_free(&aes_ctx); return ret; } #else diff --git a/features/lorawan/lorastack/mac/LoRaMacCrypto.h b/features/lorawan/lorastack/mac/LoRaMacCrypto.h index b74729280e..09fa1c19f0 100644 --- a/features/lorawan/lorastack/mac/LoRaMacCrypto.h +++ b/features/lorawan/lorastack/mac/LoRaMacCrypto.h @@ -147,24 +147,6 @@ public: uint8_t *nwk_skey, uint8_t *app_skey); private: - /** - * MIC field computation initial data - */ - uint8_t mic_block_b0[16]; - - /** - * Contains the computed MIC field. - * - * \remark Only the 4 first bytes are used - */ - uint8_t computed_mic[16]; - - /** - * Encryption aBlock and sBlock - */ - uint8_t a_block[16]; - uint8_t s_block[16]; - /** * AES computation context variable */ diff --git a/features/lorawan/lorastack/phy/LoRaPHY.cpp b/features/lorawan/lorastack/phy/LoRaPHY.cpp index 7a8462fa8e..6a6b5869b1 100644 --- a/features/lorawan/lorastack/phy/LoRaPHY.cpp +++ b/features/lorawan/lorastack/phy/LoRaPHY.cpp @@ -164,19 +164,18 @@ int32_t LoRaPHY::get_random(int32_t min, int32_t max) return (int32_t) rand() % (max - min + 1) + min; } -bool LoRaPHY::verify_channel_DR(uint8_t nb_channels, uint16_t *channel_mask, - int8_t dr, int8_t min_dr, int8_t max_dr, - channel_params_t *channels) +bool LoRaPHY::verify_channel_DR(uint16_t *channel_mask, int8_t dr) { - if (val_in_range(dr, min_dr, max_dr) == 0) { + if (val_in_range(dr, phy_params.min_tx_datarate, + phy_params.max_tx_datarate) == 0) { return false; } for (uint8_t i = 0; i < phy_params.max_channel_cnt; i++) { if (mask_bit_test(channel_mask, i)) { // Check datarate validity for enabled channels - if (val_in_range(dr, (channels[i].dr_range.fields.min & 0x0F), - (channels[i].dr_range.fields.max & 0x0F))) { + if (val_in_range(dr, (phy_params.channels.channel_list[i].dr_range.fields.min & 0x0F), + (phy_params.channels.channel_list[i].dr_range.fields.max & 0x0F))) { // At least 1 channel has been found we can return OK. return true; } @@ -248,45 +247,6 @@ void LoRaPHY::copy_channel_mask(uint16_t *dest_mask, uint16_t *src_mask, uint8_t } } -void LoRaPHY::intersect_channel_mask(const uint16_t *source, - uint16_t *destination, uint8_t size) -{ - if (!source || !destination || size == 0) { - return; - } - - for (uint8_t i = 0; i < size; i++) { - destination[i] &= source[i]; - } -} - -void LoRaPHY::fill_channel_mask_with_fsb(const uint16_t *expectation, - const uint16_t *fsb_mask, - uint16_t *destination, - uint8_t size) -{ - if (!expectation || !fsb_mask || !destination || size == 0) { - return; - } - - for (uint8_t i = 0; i < size; i++) { - destination[i] = expectation[i] & fsb_mask[i]; - } - -} - -void LoRaPHY::fill_channel_mask_with_value(uint16_t *channel_mask, - uint16_t value, uint8_t size) -{ - if (!channel_mask || size == 0) { - return; - } - - for (uint8_t i = 0; i < size; i++) { - channel_mask[i] = value; - } -} - void LoRaPHY::set_last_tx_done(uint8_t channel, bool joined, lorawan_time_t last_tx_done_time) { band_t *band_table = (band_t *) phy_params.bands.table; @@ -396,16 +356,13 @@ uint8_t LoRaPHY::verify_link_ADR_req(verify_adr_params_t *verify_params, if (status != 0) { // Verify channel datarate - if (verify_channel_DR(phy_params.max_channel_cnt, verify_params->channel_mask, - datarate, phy_params.min_tx_datarate, - phy_params.max_tx_datarate, phy_params.channels.channel_list) - == false) { + if (verify_channel_DR(verify_params->channel_mask, datarate) == false) { status &= 0xFD; // Datarate KO } // Verify tx power if (val_in_range(tx_power, phy_params.max_tx_power, - phy_params.min_tx_power) == 0) { + phy_params.min_tx_power) == false) { // Verify if the maximum TX power is exceeded if (phy_params.max_tx_power > tx_power) { // Apply maximum TX power. Accept TX power. @@ -1140,8 +1097,8 @@ uint8_t LoRaPHY::dl_channel_request(uint8_t channel_id, uint32_t rx1_frequency) uint8_t status = 0x03; // Verify if the frequency is supported - uint8_t band = lookup_band_for_frequency(rx1_frequency); - if (verify_frequency_for_band(rx1_frequency, band) == false) { + int band = lookup_band_for_frequency(rx1_frequency); + if (band < 0) { status &= 0xFE; } @@ -1343,7 +1300,7 @@ lorawan_status_t LoRaPHY::add_channel(const channel_params_t *new_channel, // Default channels don't accept all values if (id < phy_params.default_channel_cnt) { // Validate the datarate range for min: must be DR_0 - if (new_channel->dr_range.fields.min > phy_params.min_tx_datarate) { + if (new_channel->dr_range.fields.min != DR_0) { dr_invalid = true; } diff --git a/features/lorawan/lorastack/phy/LoRaPHY.h b/features/lorawan/lorastack/phy/LoRaPHY.h index 5b4ed32b8b..42c45b9575 100644 --- a/features/lorawan/lorastack/phy/LoRaPHY.h +++ b/features/lorawan/lorastack/phy/LoRaPHY.h @@ -535,26 +535,6 @@ public: //Verifiers protected: LoRaPHY(); - /** - * Sets the intersection of source and destination channel masks - * into the destination. - */ - void intersect_channel_mask(const uint16_t *source, uint16_t *destination, - uint8_t size); - - /** - * Fills channel mask array based upon the provided FSB mask - */ - void fill_channel_mask_with_fsb(const uint16_t *expectation, - const uint16_t *fsb_mask, - uint16_t *channel_mask, uint8_t size); - - /** - * Fills channel mask array with a given value - */ - void fill_channel_mask_with_value(uint16_t *channel_mask, - uint16_t value, uint8_t size); - /** * Looks up corresponding band for a frequency. Returns -1 if not in any band. */ @@ -573,8 +553,7 @@ protected: /** * Verifies, if a datarate is available on an active channel. */ - bool verify_channel_DR(uint8_t nbChannels, uint16_t* channelsMask, int8_t dr, - int8_t minDr, int8_t maxDr, channel_params_t* channels); + bool verify_channel_DR(uint16_t* channelsMask, int8_t dr); /** * Disables a channel in a given channels mask. @@ -615,16 +594,6 @@ protected: uint8_t verify_link_ADR_req(verify_adr_params_t* verify_params, int8_t* dr, int8_t* tx_pow, uint8_t* nb_rep); - /** - * Computes the symbol time for LoRa modulation. - */ - double compute_symb_timeout_lora(uint8_t phy_dr, uint32_t bandwidth ); - - /** - * Computes the symbol time for FSK modulation. - */ - double compute_symb_timeout_fsk(uint8_t phy_dr); - /** * Computes the RX window timeout and the RX window offset. */ @@ -658,6 +627,18 @@ protected: bool is_datarate_supported(const int8_t datarate) const; +private: + + /** + * Computes the symbol time for LoRa modulation. + */ + double compute_symb_timeout_lora(uint8_t phy_dr, uint32_t bandwidth ); + + /** + * Computes the symbol time for FSK modulation. + */ + double compute_symb_timeout_fsk(uint8_t phy_dr); + protected: LoRaRadio *_radio; LoRaWANTimeHandler *_lora_time; diff --git a/features/lorawan/lorastack/phy/LoRaPHYAU915.cpp b/features/lorawan/lorastack/phy/LoRaPHYAU915.cpp index 357d382844..97d80016f4 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYAU915.cpp +++ b/features/lorawan/lorastack/phy/LoRaPHYAU915.cpp @@ -615,10 +615,32 @@ lorawan_status_t LoRaPHYAU915::set_next_channel(channel_selection_params_t* next uint8_t LoRaPHYAU915::apply_DR_offset(int8_t dr, int8_t dr_offset) { - int8_t datarate = datarate_offsets_AU915[dr][dr_offset]; - - if (datarate < 0) { - datarate = DR_0; - } - return datarate; + return datarate_offsets_AU915[dr][dr_offset]; +} + +void LoRaPHYAU915::intersect_channel_mask(const uint16_t *source, + uint16_t *destination, uint8_t size) +{ + for (uint8_t i = 0; i < size; i++) { + destination[i] &= source[i]; + } +} + +void LoRaPHYAU915::fill_channel_mask_with_fsb(const uint16_t *expectation, + const uint16_t *fsb_mask, + uint16_t *destination, + uint8_t size) +{ + for (uint8_t i = 0; i < size; i++) { + destination[i] = expectation[i] & fsb_mask[i]; + } + +} + +void LoRaPHYAU915::fill_channel_mask_with_value(uint16_t *channel_mask, + uint16_t value, uint8_t size) +{ + for (uint8_t i = 0; i < size; i++) { + channel_mask[i] = value; + } } diff --git a/features/lorawan/lorastack/phy/LoRaPHYAU915.h b/features/lorawan/lorastack/phy/LoRaPHYAU915.h index 1db1ff227c..27add455d9 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYAU915.h +++ b/features/lorawan/lorastack/phy/LoRaPHYAU915.h @@ -76,6 +76,28 @@ public: virtual uint8_t apply_DR_offset(int8_t dr, int8_t dr_offset); +private: + + /** + * Sets the intersection of source and destination channel masks + * into the destination. + */ + void intersect_channel_mask(const uint16_t *source, uint16_t *destination, + uint8_t size); + + /** + * Fills channel mask array based upon the provided FSB mask + */ + void fill_channel_mask_with_fsb(const uint16_t *expectation, + const uint16_t *fsb_mask, + uint16_t *channel_mask, uint8_t size); + + /** + * Fills channel mask array with a given value + */ + void fill_channel_mask_with_value(uint16_t *channel_mask, + uint16_t value, uint8_t size); + private: /*! diff --git a/features/lorawan/lorastack/phy/LoRaPHYCN470.cpp b/features/lorawan/lorastack/phy/LoRaPHYCN470.cpp index 6a004eb9e5..777677765a 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYCN470.cpp +++ b/features/lorawan/lorastack/phy/LoRaPHYCN470.cpp @@ -220,7 +220,7 @@ LoRaPHYCN470::LoRaPHYCN470() } // Initialize the channels default mask - for (uint8_t i = 0; i < CN470_MAX_NB_CHANNELS; i++) { + for (uint8_t i = 0; i < CN470_CHANNEL_MASK_SIZE; i++) { default_channel_mask[i] = 0xFFFF & fsb_mask[i]; } diff --git a/features/lorawan/lorastack/phy/LoRaPHYUS915.cpp b/features/lorawan/lorastack/phy/LoRaPHYUS915.cpp index a531de055b..95d52d212d 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYUS915.cpp +++ b/features/lorawan/lorastack/phy/LoRaPHYUS915.cpp @@ -676,11 +676,33 @@ void LoRaPHYUS915::set_tx_cont_mode(cw_mode_params_t* params, uint32_t given_fre uint8_t LoRaPHYUS915::apply_DR_offset(int8_t dr, int8_t dr_offset) { - int8_t datarate = datarate_offsets_US915[dr][dr_offset]; + return datarate_offsets_US915[dr][dr_offset]; +} - if (datarate < 0) { - datarate = DR_0; + +void LoRaPHYUS915::intersect_channel_mask(const uint16_t *source, + uint16_t *destination, uint8_t size) +{ + for (uint8_t i = 0; i < size; i++) { + destination[i] &= source[i]; + } +} + +void LoRaPHYUS915::fill_channel_mask_with_fsb(const uint16_t *expectation, + const uint16_t *fsb_mask, + uint16_t *destination, + uint8_t size) +{ + for (uint8_t i = 0; i < size; i++) { + destination[i] = expectation[i] & fsb_mask[i]; } - return datarate; +} + +void LoRaPHYUS915::fill_channel_mask_with_value(uint16_t *channel_mask, + uint16_t value, uint8_t size) +{ + for (uint8_t i = 0; i < size; i++) { + channel_mask[i] = value; + } } diff --git a/features/lorawan/lorastack/phy/LoRaPHYUS915.h b/features/lorawan/lorastack/phy/LoRaPHYUS915.h index 2c883ae69d..577611ba9c 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYUS915.h +++ b/features/lorawan/lorastack/phy/LoRaPHYUS915.h @@ -80,6 +80,26 @@ public: private: + /** + * Sets the intersection of source and destination channel masks + * into the destination. + */ + void intersect_channel_mask(const uint16_t *source, uint16_t *destination, + uint8_t size); + + /** + * Fills channel mask array based upon the provided FSB mask + */ + void fill_channel_mask_with_fsb(const uint16_t *expectation, + const uint16_t *fsb_mask, + uint16_t *channel_mask, uint8_t size); + + /** + * Fills channel mask array with a given value + */ + void fill_channel_mask_with_value(uint16_t *channel_mask, + uint16_t value, uint8_t size); + int8_t limit_tx_power(int8_t tx_power, int8_t max_band_tx_power, int8_t datarate); diff --git a/features/lorawan/lorawan_types.h b/features/lorawan/lorawan_types.h index 6f57c3c061..186eda07a1 100644 --- a/features/lorawan/lorawan_types.h +++ b/features/lorawan/lorawan_types.h @@ -101,6 +101,8 @@ typedef enum lorawan_status { LORAWAN_STATUS_NO_ACTIVE_SESSIONS = -1017, /**< Services not started - No active session */ LORAWAN_STATUS_IDLE = -1018, /**< Services started - Idle at the moment */ #if defined(LORAWAN_COMPLIANCE_TEST) + //Deprecated - will replace the code -1019 with something + //else in future. LORAWAN_STATUS_COMPLIANCE_TEST_ON = -1019, /**< Compliance test - is on-going */ #endif LORAWAN_STATUS_DUTYCYCLE_RESTRICTED = -1020, /**< Transmission will continue after duty cycle backoff*/ @@ -663,7 +665,7 @@ typedef struct { /** * The SNR for the received packet. */ - uint8_t snr; + int8_t snr; /** * A boolean to mark if the meta data is stale */ diff --git a/features/lorawan/system/lorawan_data_structures.h b/features/lorawan/system/lorawan_data_structures.h index 038248fa8d..fcf9d88f35 100644 --- a/features/lorawan/system/lorawan_data_structures.h +++ b/features/lorawan/system/lorawan_data_structures.h @@ -666,7 +666,7 @@ typedef struct { /*! * The SNR of the received packet. */ - uint8_t snr; + int8_t snr; /*! * The receive window. * @@ -838,9 +838,6 @@ typedef enum device_states { DEVICE_STATE_SENDING, DEVICE_STATE_AWAITING_ACK, DEVICE_STATE_STATUS_CHECK, -#if defined(LORAWAN_COMPLIANCE_TEST) - DEVICE_STATE_COMPLIANCE_TEST, -#endif DEVICE_STATE_SHUTDOWN } device_states_t; @@ -1284,117 +1281,4 @@ typedef struct { } loramac_protocol_params; - -#if defined(LORAWAN_COMPLIANCE_TEST) - -typedef struct { - /*! - * MLME-Request type. - */ - mlme_type_t type; - - mlme_cw_tx_mode_t cw_tx_mode; -} loramac_mlme_req_t; - -typedef struct { - /*! - * Compliance test request - */ - mcps_type_t type; - - /*! - * Frame port field. Must be set if the payload is not empty. Use the - * application-specific frame port values: [1...223]. - * - * LoRaWAN Specification V1.0.2, chapter 4.3.2. - */ - uint8_t fport; - - /*! - * Uplink datarate, if ADR is off. - */ - int8_t data_rate; - /*! - * The number of trials to transmit the frame, if the LoRaMAC layer did not - * receive an acknowledgment. The MAC performs a datarate adaptation - * according to the LoRaWAN Specification V1.0.2, chapter 18.4, as in - * the following table: - * - * Transmission nb | Data Rate - * ----------------|----------- - * 1 (first) | DR - * 2 | DR - * 3 | max(DR-1,0) - * 4 | max(DR-1,0) - * 5 | max(DR-2,0) - * 6 | max(DR-2,0) - * 7 | max(DR-3,0) - * 8 | max(DR-3,0) - * - * Note that if nb_trials is set to 1 or 2, the MAC will not decrease - * the datarate, if the LoRaMAC layer did not receive an acknowledgment. - */ - uint8_t nb_trials; - - /** Payload data - * - * A pointer to the buffer of the frame payload. - */ - uint8_t f_buffer[LORAMAC_PHY_MAXPAYLOAD]; - - /** Payload size - * - * The size of the frame payload. - */ - uint16_t f_buffer_size; - -} loramac_compliance_test_req_t; - -/** LoRaWAN compliance tests support data - * - */ -typedef struct compliance_test { - /** Is test running - * - */ - bool running; - /** State of test - * - */ - uint8_t state; - /** Is TX confirmed - * - */ - bool is_tx_confirmed; - /** Port used by the application - * - */ - uint8_t app_port; - /** Maximum size of data used by application - * - */ - uint8_t app_data_size; - /** Data provided by application - * - */ - uint8_t app_data_buffer[MBED_CONF_LORA_TX_MAX_SIZE]; - /** Downlink counter - * - */ - uint16_t downlink_counter; - /** Is link check required - * - */ - bool link_check; - /** Demodulation margin - * - */ - uint8_t demod_margin; - /** Number of gateways - * - */ - uint8_t nb_gateways; -} compliance_test_t; -#endif - #endif /* LORAWAN_SYSTEM_LORAWAN_DATA_STRUCTURES_H_ */ diff --git a/features/mbedtls/targets/TARGET_NUVOTON/TARGET_M480/TARGET_NUMAKER_PFM_M487/mbedtls_device.h b/features/mbedtls/targets/TARGET_NUVOTON/TARGET_M480/mbedtls_device.h similarity index 100% rename from features/mbedtls/targets/TARGET_NUVOTON/TARGET_M480/TARGET_NUMAKER_PFM_M487/mbedtls_device.h rename to features/mbedtls/targets/TARGET_NUVOTON/TARGET_M480/mbedtls_device.h diff --git a/features/mbedtls/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/mbedtls_device.h b/features/mbedtls/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/mbedtls_device.h index dfbc82055e..4fafb6f580 100644 --- a/features/mbedtls/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/mbedtls_device.h +++ b/features/mbedtls/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/mbedtls_device.h @@ -22,8 +22,6 @@ #define MBEDTLS_AES_ALT -#define MBEDTLS_SHA256_ALT - #define MBEDTLS_SHA1_ALT #define MBEDTLS_MD5_ALT diff --git a/features/mbedtls/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/mbedtls_device.h b/features/mbedtls/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/mbedtls_device.h index dfbc82055e..4fafb6f580 100644 --- a/features/mbedtls/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/mbedtls_device.h +++ b/features/mbedtls/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/mbedtls_device.h @@ -22,8 +22,6 @@ #define MBEDTLS_AES_ALT -#define MBEDTLS_SHA256_ALT - #define MBEDTLS_SHA1_ALT #define MBEDTLS_MD5_ALT diff --git a/features/mbedtls/targets/TARGET_STM/TARGET_STM32F7/TARGET_NUCLEO_F756ZG/mbedtls_device.h b/features/mbedtls/targets/TARGET_STM/TARGET_STM32F7/TARGET_NUCLEO_F756ZG/mbedtls_device.h index 8382789dfb..ddce19c470 100644 --- a/features/mbedtls/targets/TARGET_STM/TARGET_STM32F7/TARGET_NUCLEO_F756ZG/mbedtls_device.h +++ b/features/mbedtls/targets/TARGET_STM/TARGET_STM32F7/TARGET_NUCLEO_F756ZG/mbedtls_device.h @@ -23,8 +23,6 @@ #define MBEDTLS_AES_ALT #define MBEDTLS_SHA1_ALT - -#define MBEDTLS_SHA256_ALT #define MBEDTLS_MD5_ALT #endif /* MBEDTLS_DEVICE_H */ diff --git a/features/nanostack/sal-stack-nanostack/mbed_lib.json b/features/nanostack/sal-stack-nanostack/mbed_lib.json index 56620466a1..b69dd1c4f1 100644 --- a/features/nanostack/sal-stack-nanostack/mbed_lib.json +++ b/features/nanostack/sal-stack-nanostack/mbed_lib.json @@ -13,6 +13,9 @@ }, "NCS36510": { "nanostack.configuration": "lowpan_router" + }, + "TB_SENSE_12": { + "nanostack.configuration": "lowpan_router" } } } diff --git a/features/nanostack/targets/TARGET_Silicon_Labs/TARGET_SL_RAIL/NanostackRfPhyEfr32.cpp b/features/nanostack/targets/TARGET_Silicon_Labs/TARGET_SL_RAIL/NanostackRfPhyEfr32.cpp index 7ada01adaa..329ccca021 100644 --- a/features/nanostack/targets/TARGET_Silicon_Labs/TARGET_SL_RAIL/NanostackRfPhyEfr32.cpp +++ b/features/nanostack/targets/TARGET_Silicon_Labs/TARGET_SL_RAIL/NanostackRfPhyEfr32.cpp @@ -1275,3 +1275,9 @@ static void radioEventHandler(RAIL_Handle_t railHandle, } while (events != 0); } + +NanostackRfPhy &NanostackRfPhy::get_default_instance() +{ + static NanostackRfPhyEfr32 rf_phy; + return rf_phy; +} diff --git a/features/netsocket/InternetSocket.cpp b/features/netsocket/InternetSocket.cpp index da7573986e..948e25374a 100644 --- a/features/netsocket/InternetSocket.cpp +++ b/features/netsocket/InternetSocket.cpp @@ -21,8 +21,8 @@ using namespace mbed; InternetSocket::InternetSocket() : _stack(0), _socket(0), _timeout(osWaitForever), - _readers(0), _writers(0), _factory_allocated(false), - _pending(0) + _readers(0), _writers(0), _pending(0), + _factory_allocated(false) { } diff --git a/features/netsocket/SocketAddress.cpp b/features/netsocket/SocketAddress.cpp index b83c690fca..3e42619a5e 100644 --- a/features/netsocket/SocketAddress.cpp +++ b/features/netsocket/SocketAddress.cpp @@ -19,29 +19,11 @@ #include "NetworkStack.h" #include #include +#include "ip4string.h" #include "ip6string.h" -static bool ipv4_is_valid(const char *addr) -{ - int i = 0; - - // Check each digit for [0-9.] - for (; addr[i]; i++) { - if (!(addr[i] >= '0' && addr[i] <= '9') && addr[i] != '.') { - return false; - } - } - - // Ending with '.' garuntees host - if (i > 0 && addr[i - 1] == '.') { - return false; - } - - return true; -} - static bool ipv6_is_valid(const char *addr) { // Check each digit for [0-9a-fA-F:] @@ -62,48 +44,6 @@ static bool ipv6_is_valid(const char *addr) return colons >= 2; } -static void ipv4_from_address(uint8_t *bytes, const char *addr) -{ - int count = 0; - int i = 0; - - for (; count < NSAPI_IPv4_BYTES; count++) { - unsigned d; - // Not using %hh, since it might be missing in newlib-based toolchains. - // See also: https://git.io/vxiw5 - int scanned = sscanf(&addr[i], "%u", &d); - if (scanned < 1) { - return; - } - - bytes[count] = static_cast(d); - - for (; addr[i] != '.'; i++) { - if (!addr[i]) { - return; - } - } - - i++; - } -} - -static void ipv6_from_address(uint8_t *bytes, const char *addr) -{ - stoip6(addr, strlen(addr), bytes); -} - -static void ipv4_to_address(char *addr, const uint8_t *bytes) -{ - sprintf(addr, "%d.%d.%d.%d", bytes[0], bytes[1], bytes[2], bytes[3]); -} - -static void ipv6_to_address(char *addr, const uint8_t *bytes) -{ - ip6tos(bytes, addr); -} - - SocketAddress::SocketAddress(nsapi_addr_t addr, uint16_t port) { _ip_address = NULL; @@ -137,13 +77,12 @@ bool SocketAddress::set_ip_address(const char *addr) delete[] _ip_address; _ip_address = NULL; - if (addr && ipv4_is_valid(addr)) { + if (addr && stoip4(addr, strlen(addr), _addr.bytes)) { _addr.version = NSAPI_IPv4; - ipv4_from_address(_addr.bytes, addr); return true; } else if (addr && ipv6_is_valid(addr)) { _addr.version = NSAPI_IPv6; - ipv6_from_address(_addr.bytes, addr); + stoip6(addr, strlen(addr), _addr.bytes); return true; } else { _addr = nsapi_addr_t(); @@ -186,9 +125,9 @@ const char *SocketAddress::get_ip_address() const if (!_ip_address) { _ip_address = new char[NSAPI_IP_SIZE]; if (_addr.version == NSAPI_IPv4) { - ipv4_to_address(_ip_address, _addr.bytes); + ip4tos(_addr.bytes, _ip_address); } else if (_addr.version == NSAPI_IPv6) { - ipv6_to_address(_ip_address, _addr.bytes); + ip6tos(_addr.bytes, _ip_address); } } diff --git a/features/netsocket/TCPSocket.cpp b/features/netsocket/TCPSocket.cpp index 00bac9a3f9..dc304070ee 100644 --- a/features/netsocket/TCPSocket.cpp +++ b/features/netsocket/TCPSocket.cpp @@ -265,7 +265,7 @@ TCPSocket *TCPSocket::accept(nsapi_error_t *error) ret = _stack->socket_accept(_socket, &socket, &address); if (0 == ret) { - TCPSocket *connection = new TCPSocket(); + connection = new TCPSocket(); connection->_lock.lock(); connection->_factory_allocated = true; // Destroy automatically on close() connection->_remote_peer = address; diff --git a/features/netsocket/mbed_lib.json b/features/netsocket/mbed_lib.json index 5de5a8884a..3575b47ebc 100644 --- a/features/netsocket/mbed_lib.json +++ b/features/netsocket/mbed_lib.json @@ -36,6 +36,9 @@ }, "NCS36510": { "nsapi.default-mesh-type": "LOWPAN" + }, + "TB_SENSE_12": { + "nsapi.default-mesh-type": "LOWPAN" } } } diff --git a/features/storage/TESTS/blockdevice/flashsim_block_device/main.cpp b/features/storage/TESTS/blockdevice/flashsim_block_device/main.cpp index 1ef0b5ac9c..5b75a00e56 100644 --- a/features/storage/TESTS/blockdevice/flashsim_block_device/main.cpp +++ b/features/storage/TESTS/blockdevice/flashsim_block_device/main.cpp @@ -34,6 +34,11 @@ static const uint8_t blank = 0xFF; // Simple test for all APIs void functionality_test() { + + uint8_t *dummy = new (std::nothrow) uint8_t[num_blocks * erase_size]; + TEST_SKIP_UNLESS_MESSAGE(dummy, "Not enough memory for test"); + delete[] dummy; + HeapBlockDevice heap_bd(num_blocks * erase_size, read_size, prog_size, erase_size); FlashSimBlockDevice bd(&heap_bd, blank); diff --git a/features/storage/blockdevice/MBRBlockDevice.cpp b/features/storage/blockdevice/MBRBlockDevice.cpp index e98152fea1..0d7e14ca28 100644 --- a/features/storage/blockdevice/MBRBlockDevice.cpp +++ b/features/storage/blockdevice/MBRBlockDevice.cpp @@ -73,6 +73,12 @@ static int partition_absolute( { // Allocate smallest buffer necessary to write MBR uint32_t buffer_size = std::max(bd->get_program_size(), sizeof(struct mbr_table)); + + // Prevent alignment issues + if(buffer_size % bd->get_program_size() != 0) { + buffer_size += bd->get_program_size() - (buffer_size % bd->get_program_size()); + } + uint8_t *buffer = new uint8_t[buffer_size]; // Check for existing MBR diff --git a/features/storage/filesystem/fat/FATFileSystem.h b/features/storage/filesystem/fat/FATFileSystem.h index ed9fedaef4..b12fc3044b 100644 --- a/features/storage/filesystem/fat/FATFileSystem.h +++ b/features/storage/filesystem/fat/FATFileSystem.h @@ -32,6 +32,8 @@ /** * FATFileSystem based on ChaN's Fat Filesystem library v0.8 + * + * Synchronization level: Thread safe */ class FATFileSystem : public mbed::FileSystem { public: diff --git a/features/storage/filesystem/littlefs/LittleFileSystem.h b/features/storage/filesystem/littlefs/LittleFileSystem.h index 57cd676563..ac65d06fed 100644 --- a/features/storage/filesystem/littlefs/LittleFileSystem.h +++ b/features/storage/filesystem/littlefs/LittleFileSystem.h @@ -24,6 +24,8 @@ /** * LittleFileSystem, a little filesystem + * + * Synchronization level: Thread safe */ class LittleFileSystem : public mbed::FileSystem { public: diff --git a/features/storage/nvstore/TESTS/nvstore/functionality/main.cpp b/features/storage/nvstore/TESTS/nvstore/functionality/main.cpp index 60c5b5509c..a58ae13310 100644 --- a/features/storage/nvstore/TESTS/nvstore/functionality/main.cpp +++ b/features/storage/nvstore/TESTS/nvstore/functionality/main.cpp @@ -26,7 +26,6 @@ #include #include #include -#include "mbed_stats.h" #if !NVSTORE_ENABLED #error [NOT_SUPPORTED] NVSTORE needs to be enabled for this test @@ -35,6 +34,7 @@ using namespace utest::v1; static const uint16_t max_test_keys = 20; +static const uint16_t max_possible_keys_threshold = 64; static const size_t basic_func_max_data_size = 128; @@ -44,11 +44,9 @@ static const int thr_test_max_data_size = 32; static const int thr_test_num_threads = 3; #if defined(__CORTEX_M23) || defined(__CORTEX_M33) -static const int thr_test_min_stack_size = 1280; -static const int thr_test_max_stack_size = 1280; +static const int thr_test_stack_size = 1280; #else -static const int thr_test_min_stack_size = 768; -static const int thr_test_max_stack_size = 1024; +static const int thr_test_stack_size = 1024; #endif typedef struct { @@ -63,8 +61,7 @@ static thread_test_data_t *thr_test_data; static const int race_test_num_threads = 4; static const int race_test_key = 1; static const int race_test_data_size = 128; -static const int race_test_min_stack_size = 768; -static const int race_test_max_stack_size = 1024; +static const int race_test_stack_size = 768; static bool nvstore_overlaps_code = false; @@ -81,9 +78,7 @@ static void nvstore_basic_functionality_test() uint16_t actual_len_bytes = 0; NVStore &nvstore = NVStore::get_instance(); uint16_t key; - - uint8_t *nvstore_testing_buf_set = new uint8_t[basic_func_max_data_size]; - uint8_t *nvstore_testing_buf_get = new uint8_t[basic_func_max_data_size]; + uint16_t max_possible_keys; int result; @@ -99,11 +94,20 @@ static void nvstore_basic_functionality_test() TEST_SKIP_UNLESS_MESSAGE(!nvstore_overlaps_code, "Test skipped. NVStore region overlaps code."); } + uint8_t *nvstore_testing_buf_set = new (std::nothrow) uint8_t[basic_func_max_data_size]; + uint8_t *nvstore_testing_buf_get = new (std::nothrow) uint8_t[basic_func_max_data_size]; + if (!nvstore_testing_buf_set || !nvstore_testing_buf_get) { + printf("Not enough heap space to run test. Test skipped\n"); + goto clean; + } + gen_random(nvstore_testing_buf_set, basic_func_max_data_size); - uint16_t max_possible_keys = nvstore.get_max_possible_keys(); + max_possible_keys = nvstore.get_max_possible_keys(); TEST_SKIP_UNLESS_MESSAGE(max_test_keys < max_possible_keys, "Not enough possible keys for test. Test skipped."); + TEST_SKIP_UNLESS_MESSAGE(max_possible_keys >= max_possible_keys_threshold, + "Max possible keys below threshold. Test skipped."); nvstore.set_max_keys(max_test_keys); TEST_ASSERT_EQUAL(max_test_keys, nvstore.get_max_keys()); @@ -387,46 +391,11 @@ static void nvstore_basic_functionality_test() result = nvstore.get(NVSTORE_NUM_PREDEFINED_KEYS + 1, 64, nvstore_testing_buf_get, actual_len_bytes); TEST_ASSERT_EQUAL(NVSTORE_NOT_FOUND, result); +clean: delete[] nvstore_testing_buf_set; delete[] nvstore_testing_buf_get; } -// This function calculates the stack size that needs to be allocated per thread in -// the multi-thread tests. Given minimal and maximal stack sizes, and based on the heap -// stats (automatically enabled in CI), the function checks whether each thread has at least -// the minimal stack size, otherwise it reduces the number of threads (something that may happen -// on low memory boards). -static void calc_thread_stack_size(int &num_threads, uint32_t min_size, uint32_t max_size, - uint32_t &stack_size) -{ - mbed_stats_heap_t heap_stats; - mbed_stats_heap_get(&heap_stats); - - // reserved size (along with all other fields in heap stats) will be zero if - // app is compiled without heap stats (typically local builds) - if (!heap_stats.reserved_size) { - stack_size = max_size; - printf("Heap stats disabled in this build, so test may fail due to insufficient heap size\n"); - printf("If this happens, please build the test with heap stats enabled (-DMBED_HEAP_STATS_ENABLED=1)\n"); - return; - } - - NVStore &nvstore = NVStore::get_instance(); - int page_size = nvstore.size() / nvstore.get_max_possible_keys(); - // Check if we can allocate enough stack size (per thread) for the current number of threads - while (num_threads) { - stack_size = (heap_stats.reserved_size - heap_stats.current_size) / num_threads - sizeof(rtos::Thread) - page_size; - - stack_size = std::min(stack_size, max_size); - if (stack_size >= min_size) { - return; - } - - // Got here - stack not sufficient per thread. Reduce number of threads - num_threads--; - } -} - static void thread_test_check_key(uint16_t key) { uint8_t get_buff[thr_test_max_data_size]; @@ -481,47 +450,66 @@ static void nvstore_multi_thread_test() { #ifdef MBED_CONF_RTOS_PRESENT int i; - int num_threads = thr_test_num_threads; - uint32_t stack_size; uint16_t size; uint16_t key; int ret; - - rtos::Thread **threads = new rtos::Thread*[num_threads]; + char *dummy; + uint16_t max_possible_keys; NVStore &nvstore = NVStore::get_instance(); TEST_SKIP_UNLESS_MESSAGE(!nvstore_overlaps_code, "Test skipped. NVStore region overlaps code."); + thr_test_data = 0; + rtos::Thread **threads = new (std::nothrow) rtos::Thread*[thr_test_num_threads]; + if (!threads) { + goto mem_fail; + } + memset(threads, 0, thr_test_num_threads * sizeof(rtos::Thread*)); + ret = nvstore.reset(); TEST_ASSERT_EQUAL(NVSTORE_SUCCESS, ret); - thr_test_data = new thread_test_data_t; + thr_test_data = new (std::nothrow) thread_test_data_t; + if (!thr_test_data) { + goto mem_fail; + } + + memset(thr_test_data, 0, sizeof(thread_test_data_t)); thr_test_data->max_keys = max_test_keys / 2; - uint16_t max_possible_keys = nvstore.get_max_possible_keys(); + max_possible_keys = nvstore.get_max_possible_keys(); TEST_SKIP_UNLESS_MESSAGE(thr_test_data->max_keys < max_possible_keys, "Not enough possible keys for test. Test skipped."); + TEST_SKIP_UNLESS_MESSAGE(max_possible_keys >= max_possible_keys_threshold, + "Max possible keys below threshold. Test skipped."); thr_test_data->stop_threads = false; for (key = 0; key < thr_test_data->max_keys; key++) { for (i = 0; i < thr_test_num_buffs; i++) { size = 1 + rand() % thr_test_max_data_size; thr_test_data->sizes[key][i] = size; - thr_test_data->buffs[key][i] = new uint8_t[size + 1]; + thr_test_data->buffs[key][i] = new (std::nothrow) uint8_t[size + 1]; + if (!thr_test_data->buffs[key][i]) { + goto mem_fail; + } gen_random(thr_test_data->buffs[key][i], size); } ret = nvstore.set(key, thr_test_data->sizes[key][0], thr_test_data->buffs[key][0]); TEST_ASSERT_EQUAL(NVSTORE_SUCCESS, ret); } - calc_thread_stack_size(num_threads, thr_test_min_stack_size, thr_test_max_stack_size, stack_size); - if (!num_threads) { - printf("Not enough heap space to run test. Test skipped\n"); - goto end; + dummy = new (std::nothrow) char[thr_test_num_threads * thr_test_stack_size]; + delete[] dummy; + if (!dummy) { + goto mem_fail; } - for (i = 0; i < num_threads; i++) { - threads[i] = new rtos::Thread((osPriority_t)((int)osPriorityBelowNormal - num_threads + i), stack_size); + for (i = 0; i < thr_test_num_threads; i++) { + threads[i] = new (std::nothrow) rtos::Thread((osPriority_t)((int)osPriorityBelowNormal - thr_test_num_threads + i), + thr_test_stack_size); + if (!threads[i]) { + goto mem_fail; + } threads[i]->start(callback(thread_test_worker)); } @@ -530,12 +518,6 @@ static void nvstore_multi_thread_test() wait_ms(1000); - for (i = 0; i < num_threads; i++) { - delete threads[i]; - } - - delete[] threads; - ret = nvstore.deinit(); TEST_ASSERT_EQUAL(NVSTORE_SUCCESS, ret); @@ -545,15 +527,32 @@ static void nvstore_multi_thread_test() for (key = 0; key < thr_test_data->max_keys; key++) { thread_test_check_key(key); } + goto clean; -end: - for (key = 0; key < thr_test_data->max_keys; key++) { - for (i = 0; i < thr_test_num_buffs; i++) { - delete[] thr_test_data->buffs[key][i]; +mem_fail: + printf("Not enough heap space to run test. Test skipped\n"); + +clean: + if (thr_test_data) { + thr_test_data->stop_threads = true; + wait_ms(1000); + + for (key = 0; key < thr_test_data->max_keys; key++) { + for (i = 0; i < thr_test_num_buffs; i++) { + delete[] thr_test_data->buffs[key][i]; + } } + + delete thr_test_data; } - delete thr_test_data; + if (threads) { + for (i = 0; i < thr_test_num_threads; i++) { + delete threads[i]; + } + + delete[] threads; + } nvstore.reset(); @@ -574,45 +573,68 @@ static void nvstore_race_test() { #ifdef MBED_CONF_RTOS_PRESENT int i; - uint32_t stack_size; uint16_t initial_buf_size; int ret; + int num_sets; rtos::Thread *threads[race_test_num_threads]; - uint8_t *get_buff, *buffs[race_test_num_threads]; - int num_threads = race_test_num_threads; + uint8_t *get_buff = 0, *buffs[race_test_num_threads]; uint16_t actual_len_bytes; + uint16_t max_possible_keys; + char *dummy; TEST_SKIP_UNLESS_MESSAGE(!nvstore_overlaps_code, "Test skipped. NVStore region overlaps code."); NVStore &nvstore = NVStore::get_instance(); + max_possible_keys = nvstore.get_max_possible_keys(); + TEST_SKIP_UNLESS_MESSAGE(max_possible_keys >= max_possible_keys_threshold, + "Max possible keys below threshold. Test skipped."); + ret = nvstore.reset(); TEST_ASSERT_EQUAL(NVSTORE_SUCCESS, ret); + memset(buffs, 0, sizeof(buffs)); + memset(threads, 0, sizeof(threads)); + initial_buf_size = std::min((nvstore.size() - race_test_data_size) / 2, (size_t) race_test_data_size); - uint8_t *initial_buf = new uint8_t[initial_buf_size]; - int num_sets = (nvstore.size() - race_test_data_size) / initial_buf_size; + uint8_t *initial_buf = new (std::nothrow) uint8_t[initial_buf_size]; + if (!initial_buf) { + goto mem_fail; + } + + num_sets = (nvstore.size() - race_test_data_size) / initial_buf_size; for (i = 0; i < num_sets; i++) { ret = nvstore.set(0, initial_buf_size, initial_buf); TEST_ASSERT_EQUAL(NVSTORE_SUCCESS, ret); } delete[] initial_buf; - get_buff = new uint8_t[race_test_data_size]; - - calc_thread_stack_size(num_threads, race_test_min_stack_size, race_test_max_stack_size, stack_size); - if (!num_threads) { - printf("Not enough heap space to run test. Test skipped\n"); - goto end; + get_buff = new (std::nothrow) uint8_t[race_test_data_size]; + if (!get_buff) { + goto mem_fail; } - for (i = 0; i < num_threads; i++) { - buffs[i] = new uint8_t[race_test_data_size]; + for (i = 0; i < race_test_num_threads; i++) { + buffs[i] = new (std::nothrow) uint8_t[race_test_data_size]; + if (!buffs[i]) { + goto mem_fail; + } gen_random(buffs[i], race_test_data_size); } - for (i = 0; i < num_threads; i++) { - threads[i] = new rtos::Thread((osPriority_t)((int)osPriorityBelowNormal - num_threads + i), stack_size); + for (i = 0; i < race_test_num_threads; i++) { + threads[i] = new (std::nothrow) rtos::Thread((osPriority_t)((int)osPriorityBelowNormal - race_test_num_threads + i), + race_test_stack_size); + if (!threads[i]) { + goto mem_fail; + } + + dummy = new (std::nothrow) char[race_test_stack_size]; + if (!dummy) { + goto mem_fail; + } + delete[] dummy; + threads[i]->start(callback(race_test_worker, (void *) buffs[i])); threads[i]->join(); } @@ -621,19 +643,23 @@ static void nvstore_race_test() TEST_ASSERT_EQUAL(NVSTORE_SUCCESS, ret); TEST_ASSERT_EQUAL(race_test_data_size, actual_len_bytes); - for (i = 0; i < num_threads; i++) { + for (i = 0; i < race_test_num_threads; i++) { if (!memcmp(buffs[i], get_buff, actual_len_bytes)) { break; } } - TEST_ASSERT_NOT_EQUAL(num_threads, i); + TEST_ASSERT_NOT_EQUAL(race_test_num_threads, i); - for (i = 0; i < num_threads; i++) { + goto clean; + +mem_fail: + printf("Not enough heap space to run test. Test skipped\n"); + +clean: + for (i = 0; i < race_test_num_threads; i++) { delete threads[i]; delete[] buffs[i]; } - -end: delete[] get_buff; #endif } diff --git a/hal/LowPowerTickerWrapper.cpp b/hal/LowPowerTickerWrapper.cpp index 70b5190d4b..dbeb850435 100644 --- a/hal/LowPowerTickerWrapper.cpp +++ b/hal/LowPowerTickerWrapper.cpp @@ -207,7 +207,14 @@ void LowPowerTickerWrapper::_timeout_handler() _pending_timeout = false; timestamp_t current = _intf->read(); - if (_ticker_match_interval_passed(_last_set_interrupt, current, _cur_match_time)) { + /* Add extra check for '_last_set_interrupt == _cur_match_time' + * + * When '_last_set_interrupt == _cur_match_time', _ticker_match_interval_passed sees it as + * one-round interval rather than just-pass, so add extra check for it. In rare cases, we + * may trap in _timeout_handler/_schedule_match loop. This check can break it. + */ + if ((_last_set_interrupt == _cur_match_time) || + _ticker_match_interval_passed(_last_set_interrupt, current, _cur_match_time)) { _intf->fire_interrupt(); } else { _schedule_match(current); @@ -223,7 +230,9 @@ bool LowPowerTickerWrapper::_match_check(timestamp_t current) if (!_pending_match) { return false; } - return _ticker_match_interval_passed(_last_set_interrupt, current, _cur_match_time); + /* Add extra check for '_last_set_interrupt == _cur_match_time' as above */ + return (_last_set_interrupt == _cur_match_time) || + _ticker_match_interval_passed(_last_set_interrupt, current, _cur_match_time); } uint32_t LowPowerTickerWrapper::_lp_ticks_to_us(uint32_t ticks) @@ -245,7 +254,7 @@ void LowPowerTickerWrapper::_schedule_match(timestamp_t current) } } - uint32_t cycles_until_match = (_cur_match_time - _last_set_interrupt) & _mask; + uint32_t cycles_until_match = (_cur_match_time - current) & _mask; bool too_close = cycles_until_match < _min_count_until_match; if (!_set_interrupt_allowed) { diff --git a/hal/mbed_sleep_manager.c b/hal/mbed_sleep_manager.c index 30e2d74837..03f678e826 100644 --- a/hal/mbed_sleep_manager.c +++ b/hal/mbed_sleep_manager.c @@ -14,18 +14,18 @@ * limitations under the License. */ -#include "mbed_assert.h" -#include "mbed_power_mgmt.h" -#include "mbed_critical.h" +#include "platform/mbed_assert.h" +#include "platform/mbed_power_mgmt.h" +#include "platform/mbed_critical.h" #include "sleep_api.h" -#include "mbed_error.h" -#include "mbed_debug.h" -#include "mbed_stats.h" +#include "platform/mbed_error.h" +#include "platform/mbed_debug.h" +#include "platform/mbed_stats.h" #include "us_ticker_api.h" #include "lp_ticker_api.h" #include #include -#include "mbed_stats.h" +#include "platform/mbed_stats.h" #if DEVICE_SLEEP diff --git a/hal/mbed_ticker_api.c b/hal/mbed_ticker_api.c index ad61c43659..5c9fc55bce 100644 --- a/hal/mbed_ticker_api.c +++ b/hal/mbed_ticker_api.c @@ -17,7 +17,7 @@ #include #include "hal/ticker_api.h" #include "platform/mbed_critical.h" -#include "mbed_assert.h" +#include "platform/mbed_assert.h" static void schedule_interrupt(const ticker_data_t *const ticker); static void update_present_time(const ticker_data_t *const ticker); @@ -47,7 +47,7 @@ static void initialize(const ticker_data_t *ticker) uint8_t frequency_shifts = 0; for (uint8_t i = 31; i > 0; --i) { - if ((1 << i) == frequency) { + if ((1U << i) == frequency) { frequency_shifts = i; break; } diff --git a/platform/FileBase.cpp b/platform/FileBase.cpp index ce0229bace..1c8c35a3fb 100644 --- a/platform/FileBase.cpp +++ b/platform/FileBase.cpp @@ -57,7 +57,7 @@ FileBase::~FileBase() } if (_default == this) { - _default == NULL; + _default = NULL; } _mutex->unlock(); diff --git a/platform/mbed_alloc_wrappers.cpp b/platform/mbed_alloc_wrappers.cpp index 00e2dd2e75..3b4caf077a 100644 --- a/platform/mbed_alloc_wrappers.cpp +++ b/platform/mbed_alloc_wrappers.cpp @@ -48,7 +48,15 @@ typedef struct { #ifdef MBED_HEAP_STATS_ENABLED static SingletonPtr malloc_stats_mutex; -static mbed_stats_heap_t heap_stats = {0, 0, 0, 0, 0}; +static mbed_stats_heap_t heap_stats = {0, 0, 0, 0, 0, 0, 0}; + +typedef struct { + size_t size; +}mbed_heap_overhead_t; + +#define MALLOC_HEADER_SIZE (sizeof(mbed_heap_overhead_t)) +#define MALLOC_HEADER_PTR(p) (mbed_heap_overhead_t *)((char *)(p) - MALLOC_HEADER_SIZE) +#define MALLOC_HEAP_TOTAL_SIZE(p) (((p)->size) & (~0x1)) #endif void mbed_stats_heap_get(mbed_stats_heap_t *stats) @@ -71,7 +79,6 @@ void mbed_stats_heap_get(mbed_stats_heap_t *stats) #if defined(TOOLCHAIN_GCC) - extern "C" { void *__real__malloc_r(struct _reent *r, size_t size); void *__real__memalign_r(struct _reent *r, size_t alignment, size_t bytes); @@ -106,6 +113,7 @@ extern "C" void *malloc_wrapper(struct _reent *r, size_t size, void *caller) if (heap_stats.current_size > heap_stats.max_size) { heap_stats.max_size = heap_stats.current_size; } + heap_stats.overhead_size += MALLOC_HEAP_TOTAL_SIZE(MALLOC_HEADER_PTR(alloc_info)) - size; } else { heap_stats.alloc_fail_cnt += 1; } @@ -178,10 +186,14 @@ extern "C" void free_wrapper(struct _reent *r, void *ptr, void *caller) alloc_info_t *alloc_info = NULL; if (ptr != NULL) { alloc_info = ((alloc_info_t *)ptr) - 1; - heap_stats.current_size -= alloc_info->size; + size_t user_size = alloc_info->size; + size_t alloc_size = MALLOC_HEAP_TOTAL_SIZE(MALLOC_HEADER_PTR(alloc_info)); + heap_stats.current_size -= user_size; heap_stats.alloc_cnt -= 1; + heap_stats.overhead_size -= (alloc_size - user_size); } __real__free_r(r, (void *)alloc_info); + malloc_stats_mutex->unlock(); #else // #ifdef MBED_HEAP_STATS_ENABLED __real__free_r(r, ptr); @@ -260,7 +272,6 @@ extern "C" { void free_wrapper(void *ptr, void *caller); } - extern "C" void *SUB_MALLOC(size_t size) { return malloc_wrapper(size, MBED_CALLER_ADDR()); @@ -284,6 +295,7 @@ extern "C" void *malloc_wrapper(size_t size, void *caller) if (heap_stats.current_size > heap_stats.max_size) { heap_stats.max_size = heap_stats.current_size; } + heap_stats.overhead_size += MALLOC_HEAP_TOTAL_SIZE(MALLOC_HEADER_PTR(alloc_info)) - size; } else { heap_stats.alloc_fail_cnt += 1; } @@ -322,7 +334,7 @@ extern "C" void *SUB_REALLOC(void *ptr, size_t size) // If the new buffer has been allocated copy the data to it // and free the old buffer - if (new_ptr != NULL) { + if ((new_ptr != NULL) && (ptr != NULL)) { uint32_t copy_size = (old_size < size) ? old_size : size; memcpy(new_ptr, (void *)ptr, copy_size); free(ptr); @@ -374,10 +386,14 @@ extern "C" void free_wrapper(void *ptr, void *caller) alloc_info_t *alloc_info = NULL; if (ptr != NULL) { alloc_info = ((alloc_info_t *)ptr) - 1; - heap_stats.current_size -= alloc_info->size; + size_t user_size = alloc_info->size; + size_t alloc_size = MALLOC_HEAP_TOTAL_SIZE(MALLOC_HEADER_PTR(alloc_info)); + heap_stats.current_size -= user_size; heap_stats.alloc_cnt -= 1; + heap_stats.overhead_size -= (alloc_size - user_size); } SUPER_FREE((void *)alloc_info); + malloc_stats_mutex->unlock(); #else // #ifdef MBED_HEAP_STATS_ENABLED SUPER_FREE(ptr); diff --git a/platform/mbed_error.c b/platform/mbed_error.c index 721d1e944d..d093987824 100644 --- a/platform/mbed_error.c +++ b/platform/mbed_error.c @@ -120,7 +120,7 @@ static mbed_error_status_t handle_error(mbed_error_status_t error_status, unsign error_count++; //Clear the context capturing buffer - memset(¤t_error_ctx, sizeof(mbed_error_ctx), 0); + memset(¤t_error_ctx, 0, sizeof(mbed_error_ctx)); //Capture error information current_error_ctx.error_status = error_status; current_error_ctx.error_address = (uint32_t)caller; @@ -279,7 +279,7 @@ mbed_error_status_t mbed_clear_all_errors(void) //Make sure we dont multiple clients resetting core_util_critical_section_enter(); //Clear the error and context capturing buffer - memset(&last_error_ctx, sizeof(mbed_error_ctx), 0); + memset(&last_error_ctx, 0, sizeof(mbed_error_ctx)); //reset error count to 0 error_count = 0; #if MBED_CONF_PLATFORM_ERROR_HIST_ENABLED diff --git a/platform/mbed_lib.json b/platform/mbed_lib.json index d0566349e8..6c9a03988c 100644 --- a/platform/mbed_lib.json +++ b/platform/mbed_lib.json @@ -70,6 +70,31 @@ "help": "Enable tracing of each memory call by invoking a callback on each memory operation. See mbed_mem_trace.h in the HAL API for more information", "value": false }, + "sys-stats-enabled": { + "macro_name": "MBED_SYS_STATS_ENABLED", + "help": "Set to 1 to enable system stats. When enabled the function mbed_stats_sys_get returns non-zero data. See mbed_stats.h for more information", + "value": null + }, + "stack-stats-enabled": { + "macro_name": "MBED_STACK_STATS_ENABLED", + "help": "Set to 1 to enable stack stats. When enabled the functions mbed_stats_stack_get and mbed_stats_stack_get_each return non-zero data. See mbed_stats.h for more information", + "value": null + }, + "cpu-stats-enabled": { + "macro_name": "MBED_CPU_STATS_ENABLED", + "help": "Set to 1 to enable cpu stats. When enabled the function mbed_stats_cpu_get returns non-zero data. See mbed_stats.h for more information", + "value": null + }, + "heap-stats-enabled": { + "macro_name": "MBED_HEAP_STATS_ENABLED", + "help": "Set to 1 to enable heap stats. When enabled the function mbed_stats_heap_get returns non-zero data. See mbed_stats.h for more information", + "value": null + }, + "thread-stats-enabled": { + "macro_name": "MBED_THREAD_STATS_ENABLED", + "help": "Set to 1 to enable thread stats. When enabled the function mbed_stats_thread_get_each returns non-zero data. See mbed_stats.h for more information", + "value": null + }, "error-decode-http-url-str": { "help": "HTTP URL string for ARM Mbed-OS Error Decode microsite", "value": "\"\\nFor more info, visit: https://armmbed.github.io/mbedos-error/?error=0x%08X\"" diff --git a/platform/mbed_poll.cpp b/platform/mbed_poll.cpp index 6d8341020d..868a1b8d06 100644 --- a/platform/mbed_poll.cpp +++ b/platform/mbed_poll.cpp @@ -20,8 +20,8 @@ #include "rtos/Thread.h" using namespace rtos; #else -#include "Timer.h" -#include "LowPowerTimer.h" +#include "drivers/Timer.h" +#include "drivers/LowPowerTimer.h" #endif namespace mbed { diff --git a/platform/mbed_power_mgmt.h b/platform/mbed_power_mgmt.h index 660e02e71d..a3e701af96 100644 --- a/platform/mbed_power_mgmt.h +++ b/platform/mbed_power_mgmt.h @@ -23,7 +23,7 @@ #ifndef MBED_POWER_MGMT_H #define MBED_POWER_MGMT_H -#include "sleep_api.h" +#include "hal/sleep_api.h" #include "mbed_toolchain.h" #include "hal/ticker_api.h" #include @@ -169,9 +169,9 @@ void sleep_manager_sleep_auto(void); static inline void sleep(void) { #if DEVICE_SLEEP -#if (MBED_CONF_RTOS_PRESENT == 0) || (DEVICE_STCLK_OFF_DURING_SLEEP == 0) || defined(MBED_TICKLESS) +#if (MBED_CONF_RTOS_PRESENT == 0) || (DEVICE_SYSTICK_CLK_OFF_DURING_SLEEP == 0) || defined(MBED_TICKLESS) sleep_manager_sleep_auto(); -#endif /* (MBED_CONF_RTOS_PRESENT == 0) || (DEVICE_STCLK_OFF_DURING_SLEEP == 0) || defined(MBED_TICKLESS) */ +#endif /* (MBED_CONF_RTOS_PRESENT == 0) || (DEVICE_SYSTICK_CLK_OFF_DURING_SLEEP == 0) || defined(MBED_TICKLESS) */ #endif /* DEVICE_SLEEP */ } diff --git a/platform/mbed_rtc_time.cpp b/platform/mbed_rtc_time.cpp index 0646a46a0a..fbc8db2b1b 100644 --- a/platform/mbed_rtc_time.cpp +++ b/platform/mbed_rtc_time.cpp @@ -33,6 +33,8 @@ static void (*_rtc_write)(time_t t) = rtc_write; #include "drivers/LowPowerTimer.h" +#define US_PER_SEC 1000000 + static SingletonPtr _rtc_lp_timer; static uint64_t _rtc_lp_base; static bool _rtc_enabled; @@ -50,7 +52,7 @@ static int _rtc_lpticker_isenabled(void) static time_t _rtc_lpticker_read(void) { - return (uint64_t)_rtc_lp_timer->read() + _rtc_lp_base; + return _rtc_lp_timer->read_high_resolution_us() / US_PER_SEC + _rtc_lp_base; } static void _rtc_lpticker_write(time_t t) diff --git a/platform/mbed_stats.h b/platform/mbed_stats.h index 4532041379..415be895c2 100644 --- a/platform/mbed_stats.h +++ b/platform/mbed_stats.h @@ -48,6 +48,7 @@ typedef struct { uint32_t reserved_size; /**< Current number of bytes allocated for the heap. */ uint32_t alloc_cnt; /**< Current number of allocations. */ uint32_t alloc_fail_cnt; /**< Number of failed allocations. */ + uint32_t overhead_size; /**< Overhead added to heap for stats. */ } mbed_stats_heap_t; /** diff --git a/platform/mbed_version.h b/platform/mbed_version.h index a300bc1bed..ef02e9997d 100644 --- a/platform/mbed_version.h +++ b/platform/mbed_version.h @@ -43,7 +43,7 @@ * * @note 99 is default value for development version (master branch) */ -#define MBED_PATCH_VERSION 0 +#define MBED_PATCH_VERSION 1 #define MBED_ENCODE_VERSION(major, minor, patch) ((major)*10000 + (minor)*100 + (patch)) diff --git a/requirements.txt b/requirements.txt index 379a061eed..3f6d5662d8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -15,6 +15,6 @@ pyelftools>=0.24 jsonschema>=2.6 future>=0.16.0 six>=1.11.0 -git+https://github.com/armmbed/manifest-tool.git@v1.4.5 -mbed-cloud-sdk==2.0.0 +git+https://github.com/armmbed/manifest-tool.git@v1.4.6 +mbed-cloud-sdk==2.0.1 icetea>=1.0.2,<2 diff --git a/rtos/TARGET_CORTEX/mbed_rtos_rtx.c b/rtos/TARGET_CORTEX/mbed_rtos_rtx.c index 6769df1ff4..4485a180be 100644 --- a/rtos/TARGET_CORTEX/mbed_rtos_rtx.c +++ b/rtos/TARGET_CORTEX/mbed_rtos_rtx.c @@ -25,9 +25,8 @@ osThreadAttr_t _main_thread_attr; -/** The main thread's stack size can be configured by the application, if not explicitly specified it'll default to 4K */ #ifndef MBED_CONF_APP_MAIN_STACK_SIZE -#define MBED_CONF_APP_MAIN_STACK_SIZE 4096 +#define MBED_CONF_APP_MAIN_STACK_SIZE MBED_CONF_RTOS_MAIN_THREAD_STACK_SIZE #endif MBED_ALIGN(8) char _main_stack[MBED_CONF_APP_MAIN_STACK_SIZE]; mbed_rtos_storage_thread_t _main_obj; diff --git a/rtos/TARGET_CORTEX/mbed_rtx_conf.h b/rtos/TARGET_CORTEX/mbed_rtx_conf.h index 3bc1ca8622..f0b2fc3984 100644 --- a/rtos/TARGET_CORTEX/mbed_rtx_conf.h +++ b/rtos/TARGET_CORTEX/mbed_rtx_conf.h @@ -27,26 +27,23 @@ /** Any access to RTX5 specific data structures used in common code should be wrapped in ifdef MBED_OS_BACKEND_RTX5 */ #define MBED_OS_BACKEND_RTX5 -/** The thread's stack size can be configured by the application, if not explicitly specified it'll default to 4K */ -#ifndef MBED_CONF_APP_THREAD_STACK_SIZE -#define MBED_CONF_APP_THREAD_STACK_SIZE 4096 -#endif - +#if defined(MBED_CONF_APP_THREAD_STACK_SIZE) #define OS_STACK_SIZE MBED_CONF_APP_THREAD_STACK_SIZE - -/** The timer thread's stack size can be configured by the application, if not explicitly specified, it'll default to 768 */ -#ifndef MBED_CONF_APP_TIMER_THREAD_STACK_SIZE -#define MBED_CONF_APP_TIMER_THREAD_STACK_SIZE 768 +#else +#define OS_STACK_SIZE MBED_CONF_RTOS_THREAD_STACK_SIZE #endif +#ifdef MBED_CONF_APP_TIMER_THREAD_STACK_SIZE #define OS_TIMER_THREAD_STACK_SIZE MBED_CONF_APP_TIMER_THREAD_STACK_SIZE - -/** The idle thread's stack size can be configured by the application, if not explicitly specified, it'll default to 512 */ -#ifndef MBED_CONF_APP_IDLE_THREAD_STACK_SIZE -#define MBED_CONF_APP_IDLE_THREAD_STACK_SIZE 512 +#else +#define OS_TIMER_THREAD_STACK_SIZE MBED_CONF_RTOS_TIMER_THREAD_STACK_SIZE #endif +#ifdef MBED_CONF_APP_IDLE_THREAD_STACK_SIZE #define OS_IDLE_THREAD_STACK_SIZE MBED_CONF_APP_IDLE_THREAD_STACK_SIZE +#else +#define OS_IDLE_THREAD_STACK_SIZE MBED_CONF_RTOS_IDLE_THREAD_STACK_SIZE +#endif #define OS_DYNAMIC_MEM_SIZE 0 diff --git a/rtos/TARGET_CORTEX/mbed_rtx_handlers.c b/rtos/TARGET_CORTEX/mbed_rtx_handlers.c index 8afa16c8fb..f0b2ad7402 100644 --- a/rtos/TARGET_CORTEX/mbed_rtx_handlers.c +++ b/rtos/TARGET_CORTEX/mbed_rtx_handlers.c @@ -55,8 +55,6 @@ __NO_RETURN void osRtxIdleThread(void *argument) __NO_RETURN uint32_t osRtxErrorNotify(uint32_t code, void *object_id) { - osThreadId_t tid = osThreadGetId(); - switch (code) { case osRtxErrorStackUnderflow: // Stack underflow detected for thread (thread_id=object_id) diff --git a/rtos/mbed_lib.json b/rtos/mbed_lib.json index f0a4667759..7714cdd743 100644 --- a/rtos/mbed_lib.json +++ b/rtos/mbed_lib.json @@ -1,7 +1,23 @@ { "name": "rtos", "config": { - "present": 1 + "present": 1, + "main-thread-stack-size": { + "help": "The size of the main thread's stack", + "value": 4096 + }, + "timer-thread-stack-size": { + "help": "The size of the timer thread's stack", + "value": 768 + }, + "idle-thread-stack-size": { + "help": "The size of the idle thread's stack", + "value": 512 + }, + "thread-stack-size": { + "help": "The default stack size of new threads", + "value": 4096 + } }, "macros": ["_RTE_"] } diff --git a/targets/TARGET_Analog_Devices/TARGET_ADUCM302X/TARGET_ADUCM3029/TARGET_EV_COG_AD3029LZ/device/system_ADuCM3029.c b/targets/TARGET_Analog_Devices/TARGET_ADUCM302X/TARGET_ADUCM3029/TARGET_EV_COG_AD3029LZ/device/system_ADuCM3029.c index 0308310abe..b7697925cf 100755 --- a/targets/TARGET_Analog_Devices/TARGET_ADUCM302X/TARGET_ADUCM3029/TARGET_EV_COG_AD3029LZ/device/system_ADuCM3029.c +++ b/targets/TARGET_Analog_Devices/TARGET_ADUCM302X/TARGET_ADUCM3029/TARGET_EV_COG_AD3029LZ/device/system_ADuCM3029.c @@ -259,8 +259,8 @@ void adi_system_EnableISRAM(bool bEnable) * \n * \n false :To disable retention during the hibernation. * \n - * @return : SUCCESS : Configured successfully. - * FAILURE : For invalid bank. + * @return : ADI_SYS_SUCCESS : Configured successfully. + * ADI_SYS_FAILURE : For invalid bank. * @note: Please note that respective linker file need to support the configuration. Only BANK-1 and BANK-2 of SRAM is valid. */ @@ -269,7 +269,7 @@ uint32_t adi_system_EnableRetention(ADI_SRAM_BANK eBank,bool bEnable) #ifdef ADI_DEBUG if((eBank != ADI_SRAM_BANK_1) && (eBank != ADI_SRAM_BANK_2)) { - return FAILURE; + return ADI_SYS_FAILURE; } #endif pADI_PMG0->PWRKEY = PWRKEY_VALUE_KEY; @@ -282,5 +282,5 @@ uint32_t adi_system_EnableRetention(ADI_SRAM_BANK eBank,bool bEnable) pADI_PMG0->SRAMRET &= ~((uint32_t)eBank >> 1); } - return SUCCESS; + return ADI_SYS_SUCCESS; } diff --git a/targets/TARGET_Analog_Devices/TARGET_ADUCM302X/TARGET_ADUCM3029/bsp/system_ADuCM3029.h b/targets/TARGET_Analog_Devices/TARGET_ADUCM302X/TARGET_ADUCM3029/bsp/system_ADuCM3029.h index d36a11ee65..5bdce4ec95 100755 --- a/targets/TARGET_Analog_Devices/TARGET_ADUCM302X/TARGET_ADUCM3029/bsp/system_ADuCM3029.h +++ b/targets/TARGET_Analog_Devices/TARGET_ADUCM302X/TARGET_ADUCM3029/bsp/system_ADuCM3029.h @@ -40,9 +40,12 @@ extern "C" { #endif /* __cplusplus */ /*! \cond PRIVATE */ -#define SUCCESS 0u - -#define FAILURE 1u +/*! System API function return codes */ +typedef enum +{ + ADI_SYS_SUCCESS = 0, /*!< No error detected. */ + ADI_SYS_FAILURE, /*!< The API call failed. */ +} ADI_SYS_RESULT; /* System clock constant */ #define __HFOSC 26000000u diff --git a/targets/TARGET_NORDIC/TARGET_NRF5x/qspi_api.c b/targets/TARGET_NORDIC/TARGET_NRF5x/qspi_api.c index 39e25df550..222f812018 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5x/qspi_api.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5x/qspi_api.c @@ -281,7 +281,7 @@ qspi_status_t qspi_command_transfer(qspi_t *obj, const qspi_command_t *command, ret_code_t ret_code; uint8_t data[8]; uint32_t data_size = tx_size + rx_size; - + nrf_qspi_cinstr_conf_t qspi_cinstr_config; qspi_cinstr_config.opcode = command->instruction.value; qspi_cinstr_config.io2_level = true; @@ -298,8 +298,10 @@ qspi_status_t qspi_command_transfer(qspi_t *obj, const qspi_command_t *command, } else { return QSPI_STATUS_INVALID_PARAMETER; } - for (uint32_t i = 0; i < (uint32_t)qspi_cinstr_config.length - 1; ++i) { - data[i] = ((uint8_t *)&command->address.value)[i]; + uint32_t address_size = (uint32_t)qspi_cinstr_config.length - 1; + uint8_t *address_bytes = (uint8_t *)&command->address.value; + for (uint32_t i = 0; i < address_size; ++i) { + data[i] = address_bytes[address_size - 1 - i]; } } else if (data_size < 9) { qspi_cinstr_config.length = (nrf_qspi_cinstr_len_t)(NRF_QSPI_CINSTR_LEN_1B + data_size); @@ -321,7 +323,7 @@ qspi_status_t qspi_command_transfer(qspi_t *obj, const qspi_command_t *command, // Data is sending as a normal SPI transmission so there is one buffer to send and receive data. ((uint8_t *)rx_data)[i] = data[i]; } - + return QSPI_STATUS_OK; } diff --git a/targets/TARGET_NUVOTON/TARGET_M2351/PeripheralNames.h b/targets/TARGET_NUVOTON/TARGET_M2351/PeripheralNames.h index d5ce69b3d4..e56c403a12 100644 --- a/targets/TARGET_NUVOTON/TARGET_M2351/PeripheralNames.h +++ b/targets/TARGET_NUVOTON/TARGET_M2351/PeripheralNames.h @@ -163,7 +163,7 @@ typedef enum { #endif // NOTE: board-specific - STDIO_UART = UART_3 + STDIO_UART = UART_0 } UARTName; diff --git a/targets/TARGET_NUVOTON/TARGET_M2351/PinNames.h b/targets/TARGET_NUVOTON/TARGET_M2351/PinNames.h index e8a378439d..03185b688e 100644 --- a/targets/TARGET_NUVOTON/TARGET_M2351/PinNames.h +++ b/targets/TARGET_NUVOTON/TARGET_M2351/PinNames.h @@ -94,15 +94,19 @@ typedef enum { } PinDirection; typedef enum { + /* Input pull mode */ PullNone = 0, PullDown, PullUp, - PushPull, + /* I/O mode */ + InputOnly, + PushPullOutput, OpenDrain, - Quasi, + QuasiBidirectional, - PullDefault = PullUp, + /* Default input pull mode */ + PullDefault = PullUp } PinMode; typedef enum { @@ -124,13 +128,13 @@ typedef enum { A1 = PB_10, A2 = PB_9, A3 = PB_8, - A4 = PB_7, - A5 = PB_6, + A4 = PB_4, + A5 = PB_5, D0 = PA_8, D1 = PA_9, - D2 = PB_5, - D3 = PB_4, + D2 = PB_7, + D3 = PB_6, D4 = PB_3, D5 = PB_2, D6 = PC_12, diff --git a/targets/TARGET_NUVOTON/TARGET_M2351/device/TOOLCHAIN_ARM_MICRO/M2351.sct b/targets/TARGET_NUVOTON/TARGET_M2351/device/TOOLCHAIN_ARM_MICRO/M2351.sct index d393d81492..e7de211e84 100644 --- a/targets/TARGET_NUVOTON/TARGET_M2351/device/TOOLCHAIN_ARM_MICRO/M2351.sct +++ b/targets/TARGET_NUVOTON/TARGET_M2351/device/TOOLCHAIN_ARM_MICRO/M2351.sct @@ -10,7 +10,7 @@ * Secure: 32KiB * Non-secure: 64KiB */ -#if defined(__DOMAIN_NS) && __DOMAIN_NS +#if defined(DOMAIN_NS) && DOMAIN_NS #ifndef MBED_APP_START #define MBED_APP_START 0x10040000 @@ -64,14 +64,14 @@ /* Initial/ISR stack size */ #if (! defined(NU_INITIAL_STACK_SIZE)) -#if defined(__DOMAIN_NS) && __DOMAIN_NS +#if defined(DOMAIN_NS) && DOMAIN_NS #define NU_INITIAL_STACK_SIZE 0x800 #else #define NU_INITIAL_STACK_SIZE 0x800 #endif #endif -#if defined(__DOMAIN_NS) && __DOMAIN_NS +#if defined(DOMAIN_NS) && DOMAIN_NS LR_IROM1 MBED_APP_START { diff --git a/targets/TARGET_NUVOTON/TARGET_M2351/device/TOOLCHAIN_ARM_STD/M2351.sct b/targets/TARGET_NUVOTON/TARGET_M2351/device/TOOLCHAIN_ARM_STD/M2351.sct index d393d81492..e7de211e84 100644 --- a/targets/TARGET_NUVOTON/TARGET_M2351/device/TOOLCHAIN_ARM_STD/M2351.sct +++ b/targets/TARGET_NUVOTON/TARGET_M2351/device/TOOLCHAIN_ARM_STD/M2351.sct @@ -10,7 +10,7 @@ * Secure: 32KiB * Non-secure: 64KiB */ -#if defined(__DOMAIN_NS) && __DOMAIN_NS +#if defined(DOMAIN_NS) && DOMAIN_NS #ifndef MBED_APP_START #define MBED_APP_START 0x10040000 @@ -64,14 +64,14 @@ /* Initial/ISR stack size */ #if (! defined(NU_INITIAL_STACK_SIZE)) -#if defined(__DOMAIN_NS) && __DOMAIN_NS +#if defined(DOMAIN_NS) && DOMAIN_NS #define NU_INITIAL_STACK_SIZE 0x800 #else #define NU_INITIAL_STACK_SIZE 0x800 #endif #endif -#if defined(__DOMAIN_NS) && __DOMAIN_NS +#if defined(DOMAIN_NS) && DOMAIN_NS LR_IROM1 MBED_APP_START { diff --git a/targets/TARGET_NUVOTON/TARGET_M2351/device/TOOLCHAIN_GCC_ARM/M2351.ld b/targets/TARGET_NUVOTON/TARGET_M2351/device/TOOLCHAIN_GCC_ARM/M2351.ld index 956901e5d4..185e5fa42e 100644 --- a/targets/TARGET_NUVOTON/TARGET_M2351/device/TOOLCHAIN_GCC_ARM/M2351.ld +++ b/targets/TARGET_NUVOTON/TARGET_M2351/device/TOOLCHAIN_GCC_ARM/M2351.ld @@ -12,7 +12,7 @@ * Secure: 32KiB * Non-secure: 64KiB */ -#if defined(__DOMAIN_NS) && __DOMAIN_NS +#if defined(DOMAIN_NS) && DOMAIN_NS #ifndef MBED_APP_START #define MBED_APP_START 0x10040000 @@ -50,7 +50,7 @@ #endif -#if defined(__DOMAIN_NS) && __DOMAIN_NS +#if defined(DOMAIN_NS) && DOMAIN_NS StackSize = 0x800; #else StackSize = 0x800; @@ -71,7 +71,7 @@ StackSize = 0x800; #endif -#if defined(__DOMAIN_NS) && __DOMAIN_NS +#if defined(DOMAIN_NS) && DOMAIN_NS MEMORY { @@ -192,7 +192,7 @@ SECTIONS KEEP(*(.eh_frame*)) } > FLASH -#if (! defined(__DOMAIN_NS)) || (! __DOMAIN_NS) +#if (! defined(DOMAIN_NS)) || (! DOMAIN_NS) /* Veneer$$CMSE : */ .gnu.sgstubs : { diff --git a/targets/TARGET_NUVOTON/TARGET_M2351/device/TOOLCHAIN_IAR/M2351.icf b/targets/TARGET_NUVOTON/TARGET_M2351/device/TOOLCHAIN_IAR/M2351.icf index cc591e7ca7..ab844f73ea 100644 --- a/targets/TARGET_NUVOTON/TARGET_M2351/device/TOOLCHAIN_IAR/M2351.icf +++ b/targets/TARGET_NUVOTON/TARGET_M2351/device/TOOLCHAIN_IAR/M2351.icf @@ -2,7 +2,7 @@ /*-Editor annotation file-*/ /* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_0.xml" */ -if (isdefinedsymbol(__DOMAIN_NS)) { +if (isdefinedsymbol(DOMAIN_NS)) { if (! isdefinedsymbol(MBED_APP_START)) { define symbol MBED_APP_START = 0x10040000; @@ -85,7 +85,7 @@ do not initialize { section .noinit }; place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; place in ROM_region { readonly }; -if (! isdefinedsymbol(__DOMAIN_NS)) { +if (! isdefinedsymbol(DOMAIN_NS)) { place at address mem:__ICFEDIT_region_NSCROM_start__ { readonly section Veneer$$CMSE }; } place at start of IRAM_region { block CSTACK }; diff --git a/targets/TARGET_NUVOTON/TARGET_M2351/gpio_api.c b/targets/TARGET_NUVOTON/TARGET_M2351/gpio_api.c index 9c83e28a5e..f4057366f5 100644 --- a/targets/TARGET_NUVOTON/TARGET_M2351/gpio_api.c +++ b/targets/TARGET_NUVOTON/TARGET_M2351/gpio_api.c @@ -51,6 +51,9 @@ void gpio_init(gpio_t *obj, PinName pin) } obj->mask = gpio_set(pin); + /* Default mode/direction */ + obj->mode = PullUp; + obj->direction = PIN_INPUT; } void gpio_mode(gpio_t *obj, PinMode mode) @@ -58,8 +61,45 @@ void gpio_mode(gpio_t *obj, PinMode mode) if (obj->pin == (PinName) NC) { return; } - - pin_mode(obj->pin, mode); + + switch (mode) { + case PullNone: + case PullDown: + case PullUp: + /* H/W doesn't support separate configuration for input pull mode/direction. + * We translate to input-only/push-pull output I/O mode dependent on direction. */ + obj->mode = (obj->direction == PIN_INPUT) ? InputOnly : PushPullOutput; + break; + + case QuasiBidirectional: + /* With quasi-bidirectional I/O mode, before digital input function is performed, + * the corresponding bit in GPIOx_DOUT must be set to 1. */ + obj->mode = QuasiBidirectional; + if (obj->direction == PIN_INPUT) { + gpio_write(obj, 1); + } + break; + + case InputOnly: + case PushPullOutput: + /* We may meet contradictory I/O mode/direction configuration. Favor I/O mode + * in the gpio_mode call here. */ + if (mode == InputOnly) { + obj->direction = PIN_INPUT; + obj->mode = InputOnly; + } else { + obj->direction = PIN_OUTPUT; + obj->mode = PushPullOutput; + } + break; + + default: + /* Allow for configuring other I/O modes directly */ + obj->mode = mode; + break; + } + + pin_mode(obj->pin, obj->mode); } void gpio_dir(gpio_t *obj, PinDirection direction) @@ -67,25 +107,36 @@ void gpio_dir(gpio_t *obj, PinDirection direction) if (obj->pin == (PinName) NC) { return; } - - uint32_t pin_index = NU_PINNAME_TO_PIN(obj->pin); - uint32_t port_index = NU_PINNAME_TO_PORT(obj->pin); - GPIO_T *gpio_base = NU_PORT_BASE(port_index); - - uint32_t mode_intern = GPIO_MODE_INPUT; - - switch (direction) { - case PIN_INPUT: - mode_intern = GPIO_MODE_INPUT; - break; - - case PIN_OUTPUT: - mode_intern = GPIO_MODE_OUTPUT; + + obj->direction = direction; + + switch (obj->mode) { + case PullNone: + case PullDown: + case PullUp: + /* H/W doesn't support separate configuration for input pull mode/direction. + * We translate to input-only/push-pull output I/O mode dependent on direction. */ + obj->mode = (obj->direction == PIN_INPUT) ? InputOnly : PushPullOutput; break; + case QuasiBidirectional: + /* With quasi-bidirectional I/O mode, before digital input function is performed, + * the corresponding bit in GPIOx_DOUT must be set to 1. */ + if (obj->direction == PIN_INPUT) { + gpio_write(obj, 1); + } + break; + + case InputOnly: + case PushPullOutput: + /* We may meet contradictory I/O mode/direction configuration. Favor direction + * in the gpio_dir call here. */ + obj->mode = (obj->direction == PIN_INPUT) ? InputOnly : PushPullOutput; + break; + default: - return; + break; } - - GPIO_SetMode(gpio_base, 1 << pin_index, mode_intern); + + pin_mode(obj->pin, obj->mode); } diff --git a/targets/TARGET_NUVOTON/TARGET_M2351/gpio_object.h b/targets/TARGET_NUVOTON/TARGET_M2351/gpio_object.h index 6437ac617b..d8c2e870eb 100644 --- a/targets/TARGET_NUVOTON/TARGET_M2351/gpio_object.h +++ b/targets/TARGET_NUVOTON/TARGET_M2351/gpio_object.h @@ -29,8 +29,10 @@ extern "C" { #endif typedef struct { - PinName pin; - uint32_t mask; + PinName pin; + uint32_t mask; + PinDirection direction; + PinMode mode; } gpio_t; static inline void gpio_write(gpio_t *obj, int value) diff --git a/targets/TARGET_NUVOTON/TARGET_M2351/lp_ticker.c b/targets/TARGET_NUVOTON/TARGET_M2351/lp_ticker.c index 8e0daf379f..10f7adbf15 100644 --- a/targets/TARGET_NUVOTON/TARGET_M2351/lp_ticker.c +++ b/targets/TARGET_NUVOTON/TARGET_M2351/lp_ticker.c @@ -101,8 +101,6 @@ void lp_ticker_init(void) /* By HAL spec, ticker_init allows the ticker to keep counting and disables the * ticker interrupt. */ lp_ticker_disable_interrupt(); - lp_ticker_clear_interrupt(); - NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); return; } ticker_inited = 1; @@ -162,23 +160,7 @@ void lp_ticker_init(void) void lp_ticker_free(void) { - TIMER_T *timer_base = (TIMER_T *) NU_MODBASE(TIMER_MODINIT.modname); - - /* Stop counting */ - TIMER_Stop(timer_base); - wait_us((NU_US_PER_SEC / NU_TMRCLK_PER_SEC) * 3); - - /* Wait for timer to stop counting and unset active flag */ - while((timer_base->CTL & TIMER_CTL_ACTSTS_Msk)); - - /* Disable wakeup */ - TIMER_DisableWakeup(timer_base); - wait_us((NU_US_PER_SEC / NU_TMRCLK_PER_SEC) * 3); - /* Disable interrupt */ - TIMER_DisableInt(timer_base); - wait_us((NU_US_PER_SEC / NU_TMRCLK_PER_SEC) * 3); - NVIC_DisableIRQ(TIMER_MODINIT.irq_n); /* Disable IP clock @@ -203,6 +185,10 @@ timestamp_t lp_ticker_read() void lp_ticker_set_interrupt(timestamp_t timestamp) { + /* Clear any previously pending interrupts */ + lp_ticker_clear_interrupt(); + NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); + /* In continuous mode, counter will be reset to zero with the following sequence: * 1. Stop counting * 2. Configure new CMP value diff --git a/targets/TARGET_NUVOTON/TARGET_M2351/pinmap.c b/targets/TARGET_NUVOTON/TARGET_M2351/pinmap.c index d72e9e3b43..d1fa0bc383 100644 --- a/targets/TARGET_NUVOTON/TARGET_M2351/pinmap.c +++ b/targets/TARGET_NUVOTON/TARGET_M2351/pinmap.c @@ -41,31 +41,40 @@ void pin_mode(PinName pin, PinMode mode) GPIO_T *gpio_base = NU_PORT_BASE(port_index); uint32_t mode_intern = GPIO_MODE_INPUT; - + switch (mode) { - case PullUp: + case InputOnly: mode_intern = GPIO_MODE_INPUT; break; - - case PullDown: - case PullNone: - // NOTE: Not support - return; - - case PushPull: + + case PushPullOutput: mode_intern = GPIO_MODE_OUTPUT; break; - + case OpenDrain: mode_intern = GPIO_MODE_OPEN_DRAIN; break; - - case Quasi: + + case QuasiBidirectional: mode_intern = GPIO_MODE_QUASI; break; + + default: + /* H/W doesn't support separate configuration for input pull mode/direction. + * We expect upper layer would have translated input pull mode/direction + * to I/O mode */ + return; } - + GPIO_SetMode(gpio_base, 1 << pin_index, mode_intern); + + /* Invalid combinations of PinMode/PinDirection + * + * We assume developer would avoid the following combinations of PinMode/PinDirection + * which are invalid: + * 1. InputOnly/PIN_OUTPUT + * 2. PushPullOutput/PIN_INPUT + */ } #if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) diff --git a/targets/TARGET_NUVOTON/TARGET_M2351/us_ticker.c b/targets/TARGET_NUVOTON/TARGET_M2351/us_ticker.c index a8034561fc..2f81310e7c 100644 --- a/targets/TARGET_NUVOTON/TARGET_M2351/us_ticker.c +++ b/targets/TARGET_NUVOTON/TARGET_M2351/us_ticker.c @@ -75,8 +75,6 @@ void us_ticker_init(void) /* By HAL spec, ticker_init allows the ticker to keep counting and disables the * ticker interrupt. */ us_ticker_disable_interrupt(); - us_ticker_clear_interrupt(); - NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); return; } ticker_inited = 1; @@ -125,16 +123,7 @@ void us_ticker_init(void) void us_ticker_free(void) { - TIMER_T *timer_base = (TIMER_T *) NU_MODBASE(TIMER_MODINIT.modname); - - /* Stop counting */ - TIMER_Stop(timer_base); - - /* Wait for timer to stop counting and unset active flag */ - while((timer_base->CTL & TIMER_CTL_ACTSTS_Msk)); - /* Disable interrupt */ - TIMER_DisableInt(timer_base); NVIC_DisableIRQ(TIMER_MODINIT.irq_n); /* Disable IP clock @@ -159,6 +148,10 @@ uint32_t us_ticker_read() void us_ticker_set_interrupt(timestamp_t timestamp) { + /* Clear any previously pending interrupts */ + us_ticker_clear_interrupt(); + NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); + /* In continuous mode, counter will be reset to zero with the following sequence: * 1. Stop counting * 2. Configure new CMP value diff --git a/targets/TARGET_NUVOTON/TARGET_M451/PinNames.h b/targets/TARGET_NUVOTON/TARGET_M451/PinNames.h index 4599c86ca9..577ff8d28c 100644 --- a/targets/TARGET_NUVOTON/TARGET_M451/PinNames.h +++ b/targets/TARGET_NUVOTON/TARGET_M451/PinNames.h @@ -55,15 +55,19 @@ typedef enum { } PinDirection; typedef enum { + /* Input pull mode */ PullNone = 0, PullDown, PullUp, - PushPull, + /* I/O mode */ + InputOnly, + PushPullOutput, OpenDrain, - Quasi, + QuasiBidirectional, - PullDefault = PullUp, + /* Default input pull mode */ + PullDefault = PullUp } PinMode; typedef enum { diff --git a/targets/TARGET_NUVOTON/TARGET_M451/gpio_api.c b/targets/TARGET_NUVOTON/TARGET_M451/gpio_api.c index 27589ccc39..f3ce3fe477 100644 --- a/targets/TARGET_NUVOTON/TARGET_M451/gpio_api.c +++ b/targets/TARGET_NUVOTON/TARGET_M451/gpio_api.c @@ -51,6 +51,9 @@ void gpio_init(gpio_t *obj, PinName pin) } obj->mask = gpio_set(pin); + /* Default mode/direction */ + obj->mode = PullUp; + obj->direction = PIN_INPUT; } void gpio_mode(gpio_t *obj, PinMode mode) @@ -58,8 +61,45 @@ void gpio_mode(gpio_t *obj, PinMode mode) if (obj->pin == (PinName) NC) { return; } - - pin_mode(obj->pin, mode); + + switch (mode) { + case PullNone: + case PullDown: + case PullUp: + /* H/W doesn't support separate configuration for input pull mode/direction. + * We translate to input-only/push-pull output I/O mode dependent on direction. */ + obj->mode = (obj->direction == PIN_INPUT) ? InputOnly : PushPullOutput; + break; + + case QuasiBidirectional: + /* With quasi-bidirectional I/O mode, before digital input function is performed, + * the corresponding bit in GPIOx_DOUT must be set to 1. */ + obj->mode = QuasiBidirectional; + if (obj->direction == PIN_INPUT) { + gpio_write(obj, 1); + } + break; + + case InputOnly: + case PushPullOutput: + /* We may meet contradictory I/O mode/direction configuration. Favor I/O mode + * in the gpio_mode call here. */ + if (mode == InputOnly) { + obj->direction = PIN_INPUT; + obj->mode = InputOnly; + } else { + obj->direction = PIN_OUTPUT; + obj->mode = PushPullOutput; + } + break; + + default: + /* Allow for configuring other I/O modes directly */ + obj->mode = mode; + break; + } + + pin_mode(obj->pin, obj->mode); } void gpio_dir(gpio_t *obj, PinDirection direction) @@ -67,25 +107,36 @@ void gpio_dir(gpio_t *obj, PinDirection direction) if (obj->pin == (PinName) NC) { return; } - - uint32_t pin_index = NU_PINNAME_TO_PIN(obj->pin); - uint32_t port_index = NU_PINNAME_TO_PORT(obj->pin); - GPIO_T *gpio_base = NU_PORT_BASE(port_index); - - uint32_t mode_intern = GPIO_MODE_INPUT; - - switch (direction) { - case PIN_INPUT: - mode_intern = GPIO_MODE_INPUT; - break; - - case PIN_OUTPUT: - mode_intern = GPIO_MODE_OUTPUT; + + obj->direction = direction; + + switch (obj->mode) { + case PullNone: + case PullDown: + case PullUp: + /* H/W doesn't support separate configuration for input pull mode/direction. + * We translate to input-only/push-pull output I/O mode dependent on direction. */ + obj->mode = (obj->direction == PIN_INPUT) ? InputOnly : PushPullOutput; break; + case QuasiBidirectional: + /* With quasi-bidirectional I/O mode, before digital input function is performed, + * the corresponding bit in GPIOx_DOUT must be set to 1. */ + if (obj->direction == PIN_INPUT) { + gpio_write(obj, 1); + } + break; + + case InputOnly: + case PushPullOutput: + /* We may meet contradictory I/O mode/direction configuration. Favor direction + * in the gpio_dir call here. */ + obj->mode = (obj->direction == PIN_INPUT) ? InputOnly : PushPullOutput; + break; + default: - return; + break; } - - GPIO_SetMode(gpio_base, 1 << pin_index, mode_intern); + + pin_mode(obj->pin, obj->mode); } diff --git a/targets/TARGET_NUVOTON/TARGET_M451/gpio_object.h b/targets/TARGET_NUVOTON/TARGET_M451/gpio_object.h index 282bae437b..6337fd5cd0 100644 --- a/targets/TARGET_NUVOTON/TARGET_M451/gpio_object.h +++ b/targets/TARGET_NUVOTON/TARGET_M451/gpio_object.h @@ -28,8 +28,10 @@ extern "C" { #endif typedef struct { - PinName pin; - uint32_t mask; + PinName pin; + uint32_t mask; + PinDirection direction; + PinMode mode; } gpio_t; static inline void gpio_write(gpio_t *obj, int value) diff --git a/targets/TARGET_NUVOTON/TARGET_M451/lp_ticker.c b/targets/TARGET_NUVOTON/TARGET_M451/lp_ticker.c index 5a09e84a3d..c723e77cb1 100644 --- a/targets/TARGET_NUVOTON/TARGET_M451/lp_ticker.c +++ b/targets/TARGET_NUVOTON/TARGET_M451/lp_ticker.c @@ -76,8 +76,6 @@ void lp_ticker_init(void) /* By HAL spec, ticker_init allows the ticker to keep counting and disables the * ticker interrupt. */ lp_ticker_disable_interrupt(); - lp_ticker_clear_interrupt(); - NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); return; } ticker_inited = 1; @@ -128,23 +126,7 @@ void lp_ticker_init(void) void lp_ticker_free(void) { - TIMER_T *timer_base = (TIMER_T *) NU_MODBASE(TIMER_MODINIT.modname); - - /* Stop counting */ - TIMER_Stop(timer_base); - wait_us((NU_US_PER_SEC / NU_TMRCLK_PER_SEC) * 3); - - /* Wait for timer to stop counting and unset active flag */ - while((timer_base->CTL & TIMER_CTL_ACTSTS_Msk)); - - /* Disable wakeup */ - TIMER_DisableWakeup(timer_base); - wait_us((NU_US_PER_SEC / NU_TMRCLK_PER_SEC) * 3); - /* Disable interrupt */ - TIMER_DisableInt(timer_base); - wait_us((NU_US_PER_SEC / NU_TMRCLK_PER_SEC) * 3); - NVIC_DisableIRQ(TIMER_MODINIT.irq_n); /* Disable IP clock */ @@ -166,6 +148,10 @@ timestamp_t lp_ticker_read() void lp_ticker_set_interrupt(timestamp_t timestamp) { + /* Clear any previously pending interrupts */ + lp_ticker_clear_interrupt(); + NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); + /* In continuous mode, counter will be reset to zero with the following sequence: * 1. Stop counting * 2. Configure new CMP value diff --git a/targets/TARGET_NUVOTON/TARGET_M451/pinmap.c b/targets/TARGET_NUVOTON/TARGET_M451/pinmap.c index 274c07fe25..214f7fc6be 100644 --- a/targets/TARGET_NUVOTON/TARGET_M451/pinmap.c +++ b/targets/TARGET_NUVOTON/TARGET_M451/pinmap.c @@ -55,29 +55,38 @@ void pin_mode(PinName pin, PinMode mode) GPIO_T *gpio_base = NU_PORT_BASE(port_index); uint32_t mode_intern = GPIO_MODE_INPUT; - + switch (mode) { - case PullUp: + case InputOnly: mode_intern = GPIO_MODE_INPUT; break; - - case PullDown: - case PullNone: - // NOTE: Not support - return; - - case PushPull: + + case PushPullOutput: mode_intern = GPIO_MODE_OUTPUT; break; - + case OpenDrain: mode_intern = GPIO_MODE_OPEN_DRAIN; break; - - case Quasi: + + case QuasiBidirectional: mode_intern = GPIO_MODE_QUASI; break; + + default: + /* H/W doesn't support separate configuration for input pull mode/direction. + * We expect upper layer would have translated input pull mode/direction + * to I/O mode */ + return; } - + GPIO_SetMode(gpio_base, 1 << pin_index, mode_intern); + + /* Invalid combinations of PinMode/PinDirection + * + * We assume developer would avoid the following combinations of PinMode/PinDirection + * which are invalid: + * 1. InputOnly/PIN_OUTPUT + * 2. PushPullOutput/PIN_INPUT + */ } diff --git a/targets/TARGET_NUVOTON/TARGET_M451/us_ticker.c b/targets/TARGET_NUVOTON/TARGET_M451/us_ticker.c index 0fadea09de..c04d4a940e 100644 --- a/targets/TARGET_NUVOTON/TARGET_M451/us_ticker.c +++ b/targets/TARGET_NUVOTON/TARGET_M451/us_ticker.c @@ -52,8 +52,6 @@ void us_ticker_init(void) /* By HAL spec, ticker_init allows the ticker to keep counting and disables the * ticker interrupt. */ us_ticker_disable_interrupt(); - us_ticker_clear_interrupt(); - NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); return; } ticker_inited = 1; @@ -93,16 +91,7 @@ void us_ticker_init(void) void us_ticker_free(void) { - TIMER_T *timer_base = (TIMER_T *) NU_MODBASE(TIMER_MODINIT.modname); - - /* Stop counting */ - TIMER_Stop(timer_base); - - /* Wait for timer to stop counting and unset active flag */ - while((timer_base->CTL & TIMER_CTL_ACTSTS_Msk)); - /* Disable interrupt */ - TIMER_DisableInt(timer_base); NVIC_DisableIRQ(TIMER_MODINIT.irq_n); /* Disable IP clock */ @@ -124,6 +113,10 @@ uint32_t us_ticker_read() void us_ticker_set_interrupt(timestamp_t timestamp) { + /* Clear any previously pending interrupts */ + us_ticker_clear_interrupt(); + NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); + /* In continuous mode, counter will be reset to zero with the following sequence: * 1. Stop counting * 2. Configure new CMP value diff --git a/targets/TARGET_NUVOTON/TARGET_M480/PinNames.h b/targets/TARGET_NUVOTON/TARGET_M480/PinNames.h index 816d5ece49..d23085835f 100644 --- a/targets/TARGET_NUVOTON/TARGET_M480/PinNames.h +++ b/targets/TARGET_NUVOTON/TARGET_M480/PinNames.h @@ -55,15 +55,19 @@ typedef enum { } PinDirection; typedef enum { + /* Input pull mode */ PullNone = 0, PullDown, PullUp, - PushPull, + /* I/O mode */ + InputOnly, + PushPullOutput, OpenDrain, - Quasi, + QuasiBidirectional, - PullDefault = PullUp, + /* Default input pull mode */ + PullDefault = PullUp } PinMode; typedef enum { @@ -125,7 +129,11 @@ typedef enum { LED3 = LED_GREEN, LED4 = LED1, // No real LED. Just for passing ATS. // Button naming +#if TARGET_NUMAKER_PFM_M487 SW2 = PG_15, +#elif TARGET_NUMAKER_IOT_M487 + SW2 = PG_5, +#endif SW3 = PF_11, } PinName; diff --git a/targets/TARGET_NUVOTON/TARGET_M480/gpio_api.c b/targets/TARGET_NUVOTON/TARGET_M480/gpio_api.c index 9b7b15503e..e6deff1fa9 100644 --- a/targets/TARGET_NUVOTON/TARGET_M480/gpio_api.c +++ b/targets/TARGET_NUVOTON/TARGET_M480/gpio_api.c @@ -51,6 +51,9 @@ void gpio_init(gpio_t *obj, PinName pin) } obj->mask = gpio_set(pin); + /* Default mode/direction */ + obj->mode = PullUp; + obj->direction = PIN_INPUT; } void gpio_mode(gpio_t *obj, PinMode mode) @@ -59,7 +62,44 @@ void gpio_mode(gpio_t *obj, PinMode mode) return; } - pin_mode(obj->pin, mode); + switch (mode) { + case PullNone: + case PullDown: + case PullUp: + /* H/W doesn't support separate configuration for input pull mode/direction. + * We translate to input-only/push-pull output I/O mode dependent on direction. */ + obj->mode = (obj->direction == PIN_INPUT) ? InputOnly : PushPullOutput; + break; + + case QuasiBidirectional: + /* With quasi-bidirectional I/O mode, before digital input function is performed, + * the corresponding bit in GPIOx_DOUT must be set to 1. */ + obj->mode = QuasiBidirectional; + if (obj->direction == PIN_INPUT) { + gpio_write(obj, 1); + } + break; + + case InputOnly: + case PushPullOutput: + /* We may meet contradictory I/O mode/direction configuration. Favor I/O mode + * in the gpio_mode call here. */ + if (mode == InputOnly) { + obj->direction = PIN_INPUT; + obj->mode = InputOnly; + } else { + obj->direction = PIN_OUTPUT; + obj->mode = PushPullOutput; + } + break; + + default: + /* Allow for configuring other I/O modes directly */ + obj->mode = mode; + break; + } + + pin_mode(obj->pin, obj->mode); } void gpio_dir(gpio_t *obj, PinDirection direction) @@ -68,24 +108,35 @@ void gpio_dir(gpio_t *obj, PinDirection direction) return; } - uint32_t pin_index = NU_PINNAME_TO_PIN(obj->pin); - uint32_t port_index = NU_PINNAME_TO_PORT(obj->pin); - GPIO_T *gpio_base = NU_PORT_BASE(port_index); + obj->direction = direction; - uint32_t mode_intern = GPIO_MODE_INPUT; + switch (obj->mode) { + case PullNone: + case PullDown: + case PullUp: + /* H/W doesn't support separate configuration for input pull mode/direction. + * We translate to input-only/push-pull output I/O mode dependent on direction. */ + obj->mode = (obj->direction == PIN_INPUT) ? InputOnly : PushPullOutput; + break; + + case QuasiBidirectional: + /* With quasi-bidirectional I/O mode, before digital input function is performed, + * the corresponding bit in GPIOx_DOUT must be set to 1. */ + if (obj->direction == PIN_INPUT) { + gpio_write(obj, 1); + } + break; - switch (direction) { - case PIN_INPUT: - mode_intern = GPIO_MODE_INPUT; - break; + case InputOnly: + case PushPullOutput: + /* We may meet contradictory I/O mode/direction configuration. Favor direction + * in the gpio_dir call here. */ + obj->mode = (obj->direction == PIN_INPUT) ? InputOnly : PushPullOutput; + break; - case PIN_OUTPUT: - mode_intern = GPIO_MODE_OUTPUT; - break; - - default: - return; + default: + break; } - GPIO_SetMode(gpio_base, 1 << pin_index, mode_intern); + pin_mode(obj->pin, obj->mode); } diff --git a/targets/TARGET_NUVOTON/TARGET_M480/gpio_object.h b/targets/TARGET_NUVOTON/TARGET_M480/gpio_object.h index d4564d3795..76d079bf7c 100644 --- a/targets/TARGET_NUVOTON/TARGET_M480/gpio_object.h +++ b/targets/TARGET_NUVOTON/TARGET_M480/gpio_object.h @@ -28,8 +28,10 @@ extern "C" { #endif typedef struct { - PinName pin; - uint32_t mask; + PinName pin; + uint32_t mask; + PinDirection direction; + PinMode mode; } gpio_t; static inline void gpio_write(gpio_t *obj, int value) diff --git a/targets/TARGET_NUVOTON/TARGET_M480/lp_ticker.c b/targets/TARGET_NUVOTON/TARGET_M480/lp_ticker.c index 1811c72dfc..fe6a923cee 100644 --- a/targets/TARGET_NUVOTON/TARGET_M480/lp_ticker.c +++ b/targets/TARGET_NUVOTON/TARGET_M480/lp_ticker.c @@ -76,8 +76,6 @@ void lp_ticker_init(void) /* By HAL spec, ticker_init allows the ticker to keep counting and disables the * ticker interrupt. */ lp_ticker_disable_interrupt(); - lp_ticker_clear_interrupt(); - NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); return; } ticker_inited = 1; @@ -128,23 +126,7 @@ void lp_ticker_init(void) void lp_ticker_free(void) { - TIMER_T *timer_base = (TIMER_T *) NU_MODBASE(TIMER_MODINIT.modname); - - /* Stop counting */ - TIMER_Stop(timer_base); - wait_us((NU_US_PER_SEC / NU_TMRCLK_PER_SEC) * 3); - - /* Wait for timer to stop counting and unset active flag */ - while((timer_base->CTL & TIMER_CTL_ACTSTS_Msk)); - - /* Disable wakeup */ - TIMER_DisableWakeup(timer_base); - wait_us((NU_US_PER_SEC / NU_TMRCLK_PER_SEC) * 3); - /* Disable interrupt */ - TIMER_DisableInt(timer_base); - wait_us((NU_US_PER_SEC / NU_TMRCLK_PER_SEC) * 3); - NVIC_DisableIRQ(TIMER_MODINIT.irq_n); /* Disable IP clock */ @@ -166,6 +148,10 @@ timestamp_t lp_ticker_read() void lp_ticker_set_interrupt(timestamp_t timestamp) { + /* Clear any previously pending interrupts */ + lp_ticker_clear_interrupt(); + NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); + /* In continuous mode, counter will be reset to zero with the following sequence: * 1. Stop counting * 2. Configure new CMP value diff --git a/targets/TARGET_NUVOTON/TARGET_M480/pinmap.c b/targets/TARGET_NUVOTON/TARGET_M480/pinmap.c index 3e360a708e..2fe8540f3b 100644 --- a/targets/TARGET_NUVOTON/TARGET_M480/pinmap.c +++ b/targets/TARGET_NUVOTON/TARGET_M480/pinmap.c @@ -47,27 +47,36 @@ void pin_mode(PinName pin, PinMode mode) uint32_t mode_intern = GPIO_MODE_INPUT; switch (mode) { - case PullUp: - mode_intern = GPIO_MODE_INPUT; - break; + case InputOnly: + mode_intern = GPIO_MODE_INPUT; + break; - case PullDown: - case PullNone: - // NOTE: Not support - return; + case PushPullOutput: + mode_intern = GPIO_MODE_OUTPUT; + break; - case PushPull: - mode_intern = GPIO_MODE_OUTPUT; - break; + case OpenDrain: + mode_intern = GPIO_MODE_OPEN_DRAIN; + break; - case OpenDrain: - mode_intern = GPIO_MODE_OPEN_DRAIN; - break; + case QuasiBidirectional: + mode_intern = GPIO_MODE_QUASI; + break; - case Quasi: - mode_intern = GPIO_MODE_QUASI; - break; + default: + /* H/W doesn't support separate configuration for input pull mode/direction. + * We expect upper layer would have translated input pull mode/direction + * to I/O mode */ + return; } GPIO_SetMode(gpio_base, 1 << pin_index, mode_intern); + + /* Invalid combinations of PinMode/PinDirection + * + * We assume developer would avoid the following combinations of PinMode/PinDirection + * which are invalid: + * 1. InputOnly/PIN_OUTPUT + * 2. PushPullOutput/PIN_INPUT + */ } diff --git a/targets/TARGET_NUVOTON/TARGET_M480/us_ticker.c b/targets/TARGET_NUVOTON/TARGET_M480/us_ticker.c index 1441cf26b3..48624e308e 100644 --- a/targets/TARGET_NUVOTON/TARGET_M480/us_ticker.c +++ b/targets/TARGET_NUVOTON/TARGET_M480/us_ticker.c @@ -52,8 +52,6 @@ void us_ticker_init(void) /* By HAL spec, ticker_init allows the ticker to keep counting and disables the * ticker interrupt. */ us_ticker_disable_interrupt(); - us_ticker_clear_interrupt(); - NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); return; } ticker_inited = 1; @@ -93,16 +91,7 @@ void us_ticker_init(void) void us_ticker_free(void) { - TIMER_T *timer_base = (TIMER_T *) NU_MODBASE(TIMER_MODINIT.modname); - - /* Stop counting */ - TIMER_Stop(timer_base); - - /* Wait for timer to stop counting and unset active flag */ - while((timer_base->CTL & TIMER_CTL_ACTSTS_Msk)); - /* Disable interrupt */ - TIMER_DisableInt(timer_base); NVIC_DisableIRQ(TIMER_MODINIT.irq_n); /* Disable IP clock */ @@ -124,6 +113,10 @@ uint32_t us_ticker_read() void us_ticker_set_interrupt(timestamp_t timestamp) { + /* Clear any previously pending interrupts */ + us_ticker_clear_interrupt(); + NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); + /* In continuous mode, counter will be reset to zero with the following sequence: * 1. Stop counting * 2. Configure new CMP value diff --git a/targets/TARGET_NUVOTON/TARGET_NANO100/PinNames.h b/targets/TARGET_NUVOTON/TARGET_NANO100/PinNames.h index b443dabd38..4658f5261b 100644 --- a/targets/TARGET_NUVOTON/TARGET_NANO100/PinNames.h +++ b/targets/TARGET_NUVOTON/TARGET_NANO100/PinNames.h @@ -55,15 +55,18 @@ typedef enum { } PinDirection; typedef enum { + /* Input pull mode */ PullNone = 0, PullDown, PullUp, - PushPull, + /* I/O mode */ + InputOnly, + PushPullOutput, OpenDrain, - Quasi, - PullDefault = PullUp, + /* Default input pull mode */ + PullDefault = PullUp } PinMode; typedef enum { diff --git a/targets/TARGET_NUVOTON/TARGET_NANO100/gpio_api.c b/targets/TARGET_NUVOTON/TARGET_NANO100/gpio_api.c index ac7a896ee2..1398e8198f 100644 --- a/targets/TARGET_NUVOTON/TARGET_NANO100/gpio_api.c +++ b/targets/TARGET_NUVOTON/TARGET_NANO100/gpio_api.c @@ -48,6 +48,9 @@ void gpio_init(gpio_t *obj, PinName pin) } obj->mask = gpio_set(pin); + /* Default mode/direction */ + obj->mode = PullUp; + obj->direction = PIN_INPUT; } void gpio_mode(gpio_t *obj, PinMode mode) @@ -55,8 +58,37 @@ void gpio_mode(gpio_t *obj, PinMode mode) if (obj->pin == (PinName) NC) { return; } - - pin_mode(obj->pin, mode); + + switch (mode) { + case PullNone: + case PullDown: + case PullUp: + /* H/W doesn't support separate configuration for input pull mode/direction. + * We translate to input-only/push-pull output I/O mode dependent on direction. */ + obj->mode = (obj->direction == PIN_INPUT) ? InputOnly : PushPullOutput; + break; + + + case InputOnly: + case PushPullOutput: + /* We may meet contradictory I/O mode/direction configuration. Favor I/O mode + * in the gpio_mode call here. */ + if (mode == InputOnly) { + obj->direction = PIN_INPUT; + obj->mode = InputOnly; + } else { + obj->direction = PIN_OUTPUT; + obj->mode = PushPullOutput; + } + break; + + default: + /* Allow for configuring other I/O modes directly */ + obj->mode = mode; + break; + } + + pin_mode(obj->pin, obj->mode); } void gpio_dir(gpio_t *obj, PinDirection direction) @@ -64,25 +96,28 @@ void gpio_dir(gpio_t *obj, PinDirection direction) if (obj->pin == (PinName) NC) { return; } - - uint32_t pin_index = NU_PINNAME_TO_PIN(obj->pin); - uint32_t port_index = NU_PINNAME_TO_PORT(obj->pin); - GPIO_T *gpio_base = NU_PORT_BASE(port_index); - - uint32_t mode_intern = GPIO_PMD_INPUT; - - switch (direction) { - case PIN_INPUT: - mode_intern = GPIO_PMD_INPUT; + + obj->direction = direction; + + switch (obj->mode) { + case PullNone: + case PullDown: + case PullUp: + /* H/W doesn't support separate configuration for input pull mode/direction. + * We translate to input-only/push-pull output I/O mode dependent on direction. */ + obj->mode = (obj->direction == PIN_INPUT) ? InputOnly : PushPullOutput; break; - - case PIN_OUTPUT: - mode_intern = GPIO_PMD_OUTPUT; + + case InputOnly: + case PushPullOutput: + /* We may meet contradictory I/O mode/direction configuration. Favor direction + * in the gpio_dir call here. */ + obj->mode = (obj->direction == PIN_INPUT) ? InputOnly : PushPullOutput; break; - + default: - return; + break; } - - GPIO_SetMode(gpio_base, 1 << pin_index, mode_intern); + + pin_mode(obj->pin, obj->mode); } diff --git a/targets/TARGET_NUVOTON/TARGET_NANO100/gpio_object.h b/targets/TARGET_NUVOTON/TARGET_NANO100/gpio_object.h index e2458dc87b..957789c5a5 100644 --- a/targets/TARGET_NUVOTON/TARGET_NANO100/gpio_object.h +++ b/targets/TARGET_NUVOTON/TARGET_NANO100/gpio_object.h @@ -28,8 +28,10 @@ extern "C" { #endif typedef struct { - PinName pin; - uint32_t mask; + PinName pin; + uint32_t mask; + PinDirection direction; + PinMode mode; } gpio_t; static inline void gpio_write(gpio_t *obj, int value) diff --git a/targets/TARGET_NUVOTON/TARGET_NANO100/lp_ticker.c b/targets/TARGET_NUVOTON/TARGET_NANO100/lp_ticker.c index c2faafc856..41b1ec55d7 100644 --- a/targets/TARGET_NUVOTON/TARGET_NANO100/lp_ticker.c +++ b/targets/TARGET_NUVOTON/TARGET_NANO100/lp_ticker.c @@ -78,8 +78,6 @@ void lp_ticker_init(void) /* By HAL spec, ticker_init allows the ticker to keep counting and disables the * ticker interrupt. */ lp_ticker_disable_interrupt(); - lp_ticker_clear_interrupt(); - NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); return; } ticker_inited = 1; @@ -132,23 +130,7 @@ void lp_ticker_init(void) void lp_ticker_free(void) { - TIMER_T *timer_base = (TIMER_T *) NU_MODBASE(TIMER_MODINIT.modname); - - /* Stop counting */ - TIMER_Stop(timer_base); - wait_us((NU_US_PER_SEC / NU_TMRCLK_PER_SEC) * 3); - - /* Wait for timer to stop counting and unset active flag */ - while((timer_base->CTL & TIMER_CTL_TMR_ACT_Msk)); - - /* Disable wakeup */ - TIMER_DisableWakeup(timer_base); - wait_us((NU_US_PER_SEC / NU_TMRCLK_PER_SEC) * 3); - /* Disable interrupt */ - TIMER_DisableInt(timer_base); - wait_us((NU_US_PER_SEC / NU_TMRCLK_PER_SEC) * 3); - NVIC_DisableIRQ(TIMER_MODINIT.irq_n); /* Disable IP clock */ @@ -170,6 +152,10 @@ timestamp_t lp_ticker_read() void lp_ticker_set_interrupt(timestamp_t timestamp) { + /* Clear any previously pending interrupts */ + lp_ticker_clear_interrupt(); + NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); + /* In continuous mode, counter will be reset to zero with the following sequence: * 1. Stop counting * 2. Configure new CMP value diff --git a/targets/TARGET_NUVOTON/TARGET_NANO100/pinmap.c b/targets/TARGET_NUVOTON/TARGET_NANO100/pinmap.c index 59912a59df..137036abc1 100644 --- a/targets/TARGET_NUVOTON/TARGET_NANO100/pinmap.c +++ b/targets/TARGET_NUVOTON/TARGET_NANO100/pinmap.c @@ -44,30 +44,35 @@ void pin_mode(PinName pin, PinMode mode) uint32_t port_index = NU_PINNAME_TO_PORT(pin); GPIO_T *gpio_base = NU_PORT_BASE(port_index); - uint32_t mode_intern = GPIO_PMD_INPUT; - + uint32_t mode_intern; + switch (mode) { - case PullUp: + case InputOnly: mode_intern = GPIO_PMD_INPUT; break; - - case PullDown: - case PullNone: - // NOTE: Not support - return; - - case PushPull: + + case PushPullOutput: mode_intern = GPIO_PMD_OUTPUT; break; - + case OpenDrain: mode_intern = GPIO_PMD_OPEN_DRAIN; break; - case Quasi: - // NOTE: Not support - break; + default: + /* H/W doesn't support separate configuration for input pull mode/direction. + * We expect upper layer would have translated input pull mode/direction + * to I/O mode */ + return; } - + GPIO_SetMode(gpio_base, 1 << pin_index, mode_intern); + + /* Invalid combinations of PinMode/PinDirection + * + * We assume developer would avoid the following combinations of PinMode/PinDirection + * which are invalid: + * 1. InputOnly/PIN_OUTPUT + * 2. PushPullOutput/PIN_INPUT + */ } diff --git a/targets/TARGET_NUVOTON/TARGET_NANO100/us_ticker.c b/targets/TARGET_NUVOTON/TARGET_NANO100/us_ticker.c index 0c5160d839..67fbe28317 100644 --- a/targets/TARGET_NUVOTON/TARGET_NANO100/us_ticker.c +++ b/targets/TARGET_NUVOTON/TARGET_NANO100/us_ticker.c @@ -54,8 +54,6 @@ void us_ticker_init(void) /* By HAL spec, ticker_init allows the ticker to keep counting and disables the * ticker interrupt. */ us_ticker_disable_interrupt(); - us_ticker_clear_interrupt(); - NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); return; } ticker_inited = 1; @@ -95,16 +93,7 @@ void us_ticker_init(void) void us_ticker_free(void) { - TIMER_T *timer_base = (TIMER_T *) NU_MODBASE(TIMER_MODINIT.modname); - - /* Stop counting */ - TIMER_Stop(timer_base); - - /* Wait for timer to stop counting and unset active flag */ - while((timer_base->CTL & TIMER_CTL_TMR_ACT_Msk)); - /* Disable interrupt */ - TIMER_DisableInt(timer_base); NVIC_DisableIRQ(TIMER_MODINIT.irq_n); /* Disable IP clock */ @@ -126,6 +115,10 @@ uint32_t us_ticker_read() void us_ticker_set_interrupt(timestamp_t timestamp) { + /* Clear any previously pending interrupts */ + us_ticker_clear_interrupt(); + NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); + /* In continuous mode, counter will be reset to zero with the following sequence: * 1. Stop counting * 2. Configure new CMP value diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/PinNames.h b/targets/TARGET_NUVOTON/TARGET_NUC472/PinNames.h index 4beecb4b88..333ada6663 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/PinNames.h +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/PinNames.h @@ -55,15 +55,19 @@ typedef enum { } PinDirection; typedef enum { + /* Input pull mode */ PullNone = 0, PullDown, PullUp, - PushPull, + /* I/O mode */ + InputOnly, + PushPullOutput, OpenDrain, - Quasi, + QuasiBidirectional, - PullDefault = PullUp, + /* Default input pull mode */ + PullDefault = PullUp } PinMode; typedef enum { diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/gpio_api.c b/targets/TARGET_NUVOTON/TARGET_NUC472/gpio_api.c index 27589ccc39..f3ce3fe477 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/gpio_api.c +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/gpio_api.c @@ -51,6 +51,9 @@ void gpio_init(gpio_t *obj, PinName pin) } obj->mask = gpio_set(pin); + /* Default mode/direction */ + obj->mode = PullUp; + obj->direction = PIN_INPUT; } void gpio_mode(gpio_t *obj, PinMode mode) @@ -58,8 +61,45 @@ void gpio_mode(gpio_t *obj, PinMode mode) if (obj->pin == (PinName) NC) { return; } - - pin_mode(obj->pin, mode); + + switch (mode) { + case PullNone: + case PullDown: + case PullUp: + /* H/W doesn't support separate configuration for input pull mode/direction. + * We translate to input-only/push-pull output I/O mode dependent on direction. */ + obj->mode = (obj->direction == PIN_INPUT) ? InputOnly : PushPullOutput; + break; + + case QuasiBidirectional: + /* With quasi-bidirectional I/O mode, before digital input function is performed, + * the corresponding bit in GPIOx_DOUT must be set to 1. */ + obj->mode = QuasiBidirectional; + if (obj->direction == PIN_INPUT) { + gpio_write(obj, 1); + } + break; + + case InputOnly: + case PushPullOutput: + /* We may meet contradictory I/O mode/direction configuration. Favor I/O mode + * in the gpio_mode call here. */ + if (mode == InputOnly) { + obj->direction = PIN_INPUT; + obj->mode = InputOnly; + } else { + obj->direction = PIN_OUTPUT; + obj->mode = PushPullOutput; + } + break; + + default: + /* Allow for configuring other I/O modes directly */ + obj->mode = mode; + break; + } + + pin_mode(obj->pin, obj->mode); } void gpio_dir(gpio_t *obj, PinDirection direction) @@ -67,25 +107,36 @@ void gpio_dir(gpio_t *obj, PinDirection direction) if (obj->pin == (PinName) NC) { return; } - - uint32_t pin_index = NU_PINNAME_TO_PIN(obj->pin); - uint32_t port_index = NU_PINNAME_TO_PORT(obj->pin); - GPIO_T *gpio_base = NU_PORT_BASE(port_index); - - uint32_t mode_intern = GPIO_MODE_INPUT; - - switch (direction) { - case PIN_INPUT: - mode_intern = GPIO_MODE_INPUT; - break; - - case PIN_OUTPUT: - mode_intern = GPIO_MODE_OUTPUT; + + obj->direction = direction; + + switch (obj->mode) { + case PullNone: + case PullDown: + case PullUp: + /* H/W doesn't support separate configuration for input pull mode/direction. + * We translate to input-only/push-pull output I/O mode dependent on direction. */ + obj->mode = (obj->direction == PIN_INPUT) ? InputOnly : PushPullOutput; break; + case QuasiBidirectional: + /* With quasi-bidirectional I/O mode, before digital input function is performed, + * the corresponding bit in GPIOx_DOUT must be set to 1. */ + if (obj->direction == PIN_INPUT) { + gpio_write(obj, 1); + } + break; + + case InputOnly: + case PushPullOutput: + /* We may meet contradictory I/O mode/direction configuration. Favor direction + * in the gpio_dir call here. */ + obj->mode = (obj->direction == PIN_INPUT) ? InputOnly : PushPullOutput; + break; + default: - return; + break; } - - GPIO_SetMode(gpio_base, 1 << pin_index, mode_intern); + + pin_mode(obj->pin, obj->mode); } diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/gpio_object.h b/targets/TARGET_NUVOTON/TARGET_NUC472/gpio_object.h index d8894b8d06..719006bf13 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/gpio_object.h +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/gpio_object.h @@ -28,8 +28,10 @@ extern "C" { #endif typedef struct { - PinName pin; - uint32_t mask; + PinName pin; + uint32_t mask; + PinDirection direction; + PinMode mode; } gpio_t; static inline void gpio_write(gpio_t *obj, int value) diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/lp_ticker.c b/targets/TARGET_NUVOTON/TARGET_NUC472/lp_ticker.c index 1f55c08ca2..0b4f99e717 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/lp_ticker.c +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/lp_ticker.c @@ -76,8 +76,6 @@ void lp_ticker_init(void) /* By HAL spec, ticker_init allows the ticker to keep counting and disables the * ticker interrupt. */ lp_ticker_disable_interrupt(); - lp_ticker_clear_interrupt(); - NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); return; } ticker_inited = 1; @@ -127,23 +125,7 @@ void lp_ticker_init(void) void lp_ticker_free(void) { - TIMER_T *timer_base = (TIMER_T *) NU_MODBASE(TIMER_MODINIT.modname); - - /* Stop counting */ - TIMER_Stop(timer_base); - wait_us((NU_US_PER_SEC / NU_TMRCLK_PER_SEC) * 3); - - /* Wait for timer to stop counting and unset active flag */ - while((timer_base->CTL & TIMER_CTL_ACTSTS_Msk)); - - /* Disable wakeup */ - TIMER_DisableWakeup(timer_base); - wait_us((NU_US_PER_SEC / NU_TMRCLK_PER_SEC) * 3); - /* Disable interrupt */ - TIMER_DisableInt(timer_base); - wait_us((NU_US_PER_SEC / NU_TMRCLK_PER_SEC) * 3); - NVIC_DisableIRQ(TIMER_MODINIT.irq_n); /* Disable IP clock */ @@ -165,6 +147,10 @@ timestamp_t lp_ticker_read() void lp_ticker_set_interrupt(timestamp_t timestamp) { + /* Clear any previously pending interrupts */ + lp_ticker_clear_interrupt(); + NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); + /* In continuous mode, counter will be reset to zero with the following sequence: * 1. Stop counting * 2. Configure new CMP value diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/pinmap.c b/targets/TARGET_NUVOTON/TARGET_NUC472/pinmap.c index 274c07fe25..d12ca01eea 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/pinmap.c +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/pinmap.c @@ -54,30 +54,39 @@ void pin_mode(PinName pin, PinMode mode) uint32_t port_index = NU_PINNAME_TO_PORT(pin); GPIO_T *gpio_base = NU_PORT_BASE(port_index); - uint32_t mode_intern = GPIO_MODE_INPUT; - + uint32_t mode_intern; + switch (mode) { - case PullUp: + case InputOnly: mode_intern = GPIO_MODE_INPUT; break; - - case PullDown: - case PullNone: - // NOTE: Not support - return; - - case PushPull: + + case PushPullOutput: mode_intern = GPIO_MODE_OUTPUT; break; - + case OpenDrain: mode_intern = GPIO_MODE_OPEN_DRAIN; break; - - case Quasi: + + case QuasiBidirectional: mode_intern = GPIO_MODE_QUASI; break; + + default: + /* H/W doesn't support separate configuration for input pull mode/direction. + * We expect upper layer would have translated input pull mode/direction + * to I/O mode */ + return; } - + GPIO_SetMode(gpio_base, 1 << pin_index, mode_intern); + + /* Invalid combinations of PinMode/PinDirection + * + * We assume developer would avoid the following combinations of PinMode/PinDirection + * which are invalid: + * 1. InputOnly/PIN_OUTPUT + * 2. PushPullOutput/PIN_INPUT + */ } diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/us_ticker.c b/targets/TARGET_NUVOTON/TARGET_NUC472/us_ticker.c index 03e58bac60..78997c68a9 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/us_ticker.c +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/us_ticker.c @@ -52,8 +52,6 @@ void us_ticker_init(void) /* By HAL spec, ticker_init allows the ticker to keep counting and disables the * ticker interrupt. */ us_ticker_disable_interrupt(); - us_ticker_clear_interrupt(); - NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); return; } ticker_inited = 1; @@ -92,16 +90,7 @@ void us_ticker_init(void) void us_ticker_free(void) { - TIMER_T *timer_base = (TIMER_T *) NU_MODBASE(TIMER_MODINIT.modname); - - /* Stop counting */ - TIMER_Stop(timer_base); - - /* Wait for timer to stop counting and unset active flag */ - while((timer_base->CTL & TIMER_CTL_ACTSTS_Msk)); - /* Disable interrupt */ - TIMER_DisableInt(timer_base); NVIC_DisableIRQ(TIMER_MODINIT.irq_n); /* Disable IP clock */ @@ -123,6 +112,10 @@ uint32_t us_ticker_read() void us_ticker_set_interrupt(timestamp_t timestamp) { + /* Clear any previously pending interrupts */ + us_ticker_clear_interrupt(); + NVIC_ClearPendingIRQ(TIMER_MODINIT.irq_n); + /* In continuous mode, counter will be reset to zero with the following sequence: * 1. Stop counting * 2. Configure new CMP value diff --git a/targets/TARGET_NXP/TARGET_LPC11U6X/serial_api.c b/targets/TARGET_NXP/TARGET_LPC11U6X/serial_api.c index b897ebfacb..a046cb1e62 100644 --- a/targets/TARGET_NXP/TARGET_LPC11U6X/serial_api.c +++ b/targets/TARGET_NXP/TARGET_LPC11U6X/serial_api.c @@ -266,7 +266,7 @@ void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_b (parity == ParityForced1) || (parity == ParityForced0)); data_bits -= 5; - int parity_enable, parity_select; + int parity_enable = 0, parity_select = 0; switch (parity) { case ParityNone: parity_enable = 0; parity_select = 0; break; case ParityOdd : parity_enable = 1; parity_select = 0; break; @@ -274,7 +274,7 @@ void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_b case ParityForced1: parity_enable = 1; parity_select = 2; break; case ParityForced0: parity_enable = 1; parity_select = 3; break; default: - return; + break; } obj->uart->LCR = data_bits << 0 diff --git a/targets/TARGET_NXP/TARGET_LPC11XX_11CXX/serial_api.c b/targets/TARGET_NXP/TARGET_LPC11XX_11CXX/serial_api.c index 87b2ea39f4..084a6ff184 100644 --- a/targets/TARGET_NXP/TARGET_LPC11XX_11CXX/serial_api.c +++ b/targets/TARGET_NXP/TARGET_LPC11XX_11CXX/serial_api.c @@ -193,7 +193,7 @@ void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_b stop_bits -= 1; data_bits -= 5; - int parity_enable, parity_select; + int parity_enable = 0, parity_select = 0; switch (parity) { case ParityNone: parity_enable = 0; parity_select = 0; break; case ParityOdd : parity_enable = 1; parity_select = 0; break; @@ -201,7 +201,6 @@ void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_b case ParityForced1: parity_enable = 1; parity_select = 2; break; case ParityForced0: parity_enable = 1; parity_select = 3; break; default: - parity_enable = 0, parity_select = 0; break; } diff --git a/targets/TARGET_NXP/TARGET_LPC13XX/serial_api.c b/targets/TARGET_NXP/TARGET_LPC13XX/serial_api.c index 5020afc54b..34c0aaf29a 100644 --- a/targets/TARGET_NXP/TARGET_LPC13XX/serial_api.c +++ b/targets/TARGET_NXP/TARGET_LPC13XX/serial_api.c @@ -196,7 +196,7 @@ void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_b stop_bits -= 1; data_bits -= 5; - int parity_enable, parity_select; + int parity_enable = 0, parity_select = 0; switch (parity) { case ParityNone: parity_enable = 0; parity_select = 0; break; case ParityOdd : parity_enable = 1; parity_select = 0; break; diff --git a/targets/TARGET_NXP/TARGET_LPC15XX/serial_api.c b/targets/TARGET_NXP/TARGET_LPC15XX/serial_api.c index ab06380329..12e6be7b0b 100644 --- a/targets/TARGET_NXP/TARGET_LPC15XX/serial_api.c +++ b/targets/TARGET_NXP/TARGET_LPC15XX/serial_api.c @@ -203,7 +203,7 @@ void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_b stop_bits -= 1; data_bits -= 7; - int paritysel; + int paritysel = 0; switch (parity) { case ParityNone: paritysel = 0; break; case ParityEven: paritysel = 2; break; diff --git a/targets/TARGET_NXP/TARGET_LPC176X/serial_api.c b/targets/TARGET_NXP/TARGET_LPC176X/serial_api.c index 32da943249..b7c00c61b1 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/serial_api.c +++ b/targets/TARGET_NXP/TARGET_LPC176X/serial_api.c @@ -256,7 +256,7 @@ void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_b stop_bits -= 1; data_bits -= 5; - int parity_enable, parity_select; + int parity_enable = 0, parity_select = 0; switch (parity) { case ParityNone: parity_enable = 0; parity_select = 0; break; case ParityOdd : parity_enable = 1; parity_select = 0; break; @@ -264,7 +264,6 @@ void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_b case ParityForced1: parity_enable = 1; parity_select = 2; break; case ParityForced0: parity_enable = 1; parity_select = 3; break; default: - parity_enable = 0, parity_select = 0; break; } diff --git a/targets/TARGET_NXP/TARGET_LPC408X/TARGET_LPC4088/serial_api.c b/targets/TARGET_NXP/TARGET_LPC408X/TARGET_LPC4088/serial_api.c index 210353d11c..4eebc5b9ec 100644 --- a/targets/TARGET_NXP/TARGET_LPC408X/TARGET_LPC4088/serial_api.c +++ b/targets/TARGET_NXP/TARGET_LPC408X/TARGET_LPC4088/serial_api.c @@ -219,7 +219,7 @@ void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_b stop_bits -= 1; data_bits -= 5; - int parity_enable, parity_select; + int parity_enable = 0, parity_select = 0; switch (parity) { case ParityNone: parity_enable = 0; parity_select = 0; break; case ParityOdd : parity_enable = 1; parity_select = 0; break; diff --git a/targets/TARGET_NXP/TARGET_LPC408X/TARGET_LPC4088_DM/serial_api.c b/targets/TARGET_NXP/TARGET_LPC408X/TARGET_LPC4088_DM/serial_api.c index f3dd6c51b4..ce8a25c55c 100644 --- a/targets/TARGET_NXP/TARGET_LPC408X/TARGET_LPC4088_DM/serial_api.c +++ b/targets/TARGET_NXP/TARGET_LPC408X/TARGET_LPC4088_DM/serial_api.c @@ -206,7 +206,7 @@ void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_b stop_bits -= 1; data_bits -= 5; - int parity_enable, parity_select; + int parity_enable = 0, parity_select = 0; switch (parity) { case ParityNone: parity_enable = 0; parity_select = 0; break; case ParityOdd : parity_enable = 1; parity_select = 0; break; diff --git a/targets/TARGET_NXP/TARGET_LPC43XX/serial_api.c b/targets/TARGET_NXP/TARGET_LPC43XX/serial_api.c index 3ca5ba9338..bf246e3130 100644 --- a/targets/TARGET_NXP/TARGET_LPC43XX/serial_api.c +++ b/targets/TARGET_NXP/TARGET_LPC43XX/serial_api.c @@ -264,7 +264,7 @@ void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_b } data_bits -= 5; - int parity_enable, parity_select; + int parity_enable = 0, parity_select = 0; switch (parity) { case ParityNone: parity_enable = 0; parity_select = 0; break; case ParityOdd : parity_enable = 1; parity_select = 0; break; @@ -272,8 +272,7 @@ void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_b case ParityForced1: parity_enable = 1; parity_select = 2; break; case ParityForced0: parity_enable = 1; parity_select = 3; break; default: - error("Invalid serial parity setting"); - return; + break; } obj->uart->LCR = data_bits << 0 diff --git a/targets/TARGET_NXP/TARGET_LPC81X/serial_api.c b/targets/TARGET_NXP/TARGET_LPC81X/serial_api.c index fa5127d298..dc22cac896 100644 --- a/targets/TARGET_NXP/TARGET_LPC81X/serial_api.c +++ b/targets/TARGET_NXP/TARGET_LPC81X/serial_api.c @@ -188,7 +188,7 @@ void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_b stop_bits -= 1; data_bits -= 7; - int paritysel; + int paritysel = 0; switch (parity) { case ParityNone: paritysel = 0; break; case ParityEven: paritysel = 2; break; diff --git a/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_IMX/pwmout_api.c b/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_IMX/pwmout_api.c index 759aeded46..c79b1a56bb 100644 --- a/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_IMX/pwmout_api.c +++ b/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_IMX/pwmout_api.c @@ -23,12 +23,13 @@ #include "fsl_pwm.h" #include "PeripheralPins.h" -static float pwm_clock_mhz; +static float pwm_clock_mhz = 0; + /* Array of PWM peripheral base address. */ static PWM_Type *const pwm_addrs[] = PWM_BASE_PTRS; -extern void pwm_setup_clock(); +extern void pwm_setup(); extern uint32_t pwm_get_clock(); void pwmout_init(pwmout_t* obj, PinName pin) @@ -36,48 +37,57 @@ void pwmout_init(pwmout_t* obj, PinName pin) PWMName pwm = (PWMName)pinmap_peripheral(pin, PinMap_PWM); MBED_ASSERT(pwm != (PWMName)NC); - pwm_setup_clock(); + uint32_t pwm_base_clock; + uint32_t instance = (pwm >> PWM_SHIFT) & 0x7; + uint32_t module = (pwm >> PWM_MODULE_SHIFT) & 0x3; + uint32_t pwmchannel = pwm & 0x1; + pwm_config_t pwmInfo; + static uint32_t clkdiv; obj->pwm_name = pwm; - - uint32_t pwm_base_clock; pwm_base_clock = pwm_get_clock(); - float clkval = (float)pwm_base_clock / 1000000.0f; - uint32_t clkdiv = 0; - while (clkval > 1) { - clkdiv++; - clkval /= 2.0f; - if (clkdiv == 7) { - break; + + if (pwm_clock_mhz == 0) { + float clkval = (float)pwm_base_clock / 1000000.0f; + + while (clkval > 1) { + clkdiv++; + clkval /= 2.0f; + if (clkdiv == 7) { + break; + } } + pwm_clock_mhz = clkval; } - pwm_clock_mhz = clkval; - uint32_t instance = (pwm >> PWM_SHIFT) & 0x3; - uint32_t module = pwm >> PWM_MODULE_SHIFT; - uint8_t pwmchannel = pwm & 0x1; - pwm_config_t pwmInfo; + pwm_setup(instance); + /* Initialize PWM module */ PWM_GetDefaultConfig(&pwmInfo); pwmInfo.prescale = (pwm_clock_prescale_t)clkdiv; - /* Initialize PWM module */ + PWM_Init(pwm_addrs[instance], (pwm_submodule_t)module, &pwmInfo); - pwm_signal_param_t config = { + pwm_signal_param_t channel_config = { .level = kPWM_HighTrue, .dutyCyclePercent = 0, .deadtimeValue = 0 }; + if (pwmchannel == 0) { - config.pwmChannel = kPWM_PwmA; + channel_config.pwmChannel = kPWM_PwmA; } else { - config.pwmChannel = kPWM_PwmB; + channel_config.pwmChannel = kPWM_PwmB; } - // default to 20ms: standard for servos, and fine for e.g. brightness control - PWM_SetupPwm(pwm_addrs[instance], (pwm_submodule_t)module, &config, 1, kPWM_EdgeAligned, 50, pwm_base_clock); + // Setup the module signals to be low + PWM_SetupPwm(pwm_addrs[instance], (pwm_submodule_t)module, &channel_config, 1, kPWM_EdgeAligned, 50, pwm_base_clock); - PWM_StartTimer(pwm_addrs[instance], module); + /* Set the load okay bit for all submodules to load registers from their buffer */ + PWM_SetPwmLdok(pwm_addrs[instance], (1 << module), true); + + /* Start the timer for the sub-module */ + PWM_StartTimer(pwm_addrs[instance], (1 << module)); // Wire pinout pinmap_pinout(pin, PinMap_PWM); @@ -85,10 +95,10 @@ void pwmout_init(pwmout_t* obj, PinName pin) void pwmout_free(pwmout_t* obj) { - uint32_t instance = (obj->pwm_name >> PWM_SHIFT) & 0x3; - uint32_t module = obj->pwm_name >> PWM_MODULE_SHIFT; + uint32_t instance = (obj->pwm_name >> PWM_SHIFT) & 0x7; + uint32_t module = (obj->pwm_name >> PWM_MODULE_SHIFT) & 0x3; - PWM_Deinit(pwm_addrs[instance], (pwm_submodule_t)module); + PWM_StopTimer(pwm_addrs[instance], (1 << module)); } void pwmout_write(pwmout_t* obj, float value) @@ -99,9 +109,9 @@ void pwmout_write(pwmout_t* obj, float value) value = 1.0f; } - PWM_Type *base = pwm_addrs[(obj->pwm_name >> PWM_SHIFT) & 0x3]; - uint32_t module = obj->pwm_name >> PWM_MODULE_SHIFT; - uint32_t pwmchannel = obj->pwm_name & 0xF; + PWM_Type *base = pwm_addrs[(obj->pwm_name >> PWM_SHIFT) & 0x7]; + uint32_t module = (obj->pwm_name >> PWM_MODULE_SHIFT) & 0x3; + uint32_t pwmchannel = obj->pwm_name & 0x1; uint16_t pulseCnt = 0; pulseCnt = base->SM[module].VAL1; @@ -117,15 +127,14 @@ void pwmout_write(pwmout_t* obj, float value) } /* Set the load okay bit */ - PWM_SetPwmLdok(base, module, true); - + PWM_SetPwmLdok(base, (1 << module), true); } float pwmout_read(pwmout_t* obj) { - PWM_Type *base = pwm_addrs[(obj->pwm_name >> PWM_SHIFT) & 0x3]; - uint32_t module = obj->pwm_name >> PWM_MODULE_SHIFT; - uint32_t pwmchannel = obj->pwm_name & 0xF; + PWM_Type *base = pwm_addrs[(obj->pwm_name >> PWM_SHIFT) & 0x7]; + uint32_t module = (obj->pwm_name >> PWM_MODULE_SHIFT) & 0x3; + uint32_t pwmchannel = obj->pwm_name & 0x1; uint16_t count; uint16_t mod = (base->SM[module].VAL1) & PWM_VAL1_VAL1_MASK; @@ -157,12 +166,30 @@ void pwmout_period_ms(pwmout_t* obj, int ms) // Set the PWM period, keeping the duty cycle the same. void pwmout_period_us(pwmout_t* obj, int us) { - PWM_Type *base = pwm_addrs[(obj->pwm_name >> PWM_SHIFT) & 0x3]; - uint32_t module = obj->pwm_name >> PWM_MODULE_SHIFT; + PWM_Type *base = pwm_addrs[(obj->pwm_name >> PWM_SHIFT) & 0x7]; + uint32_t module = (obj->pwm_name >> PWM_MODULE_SHIFT) & 0x3; float dc = pwmout_read(obj); + uint32_t pwm_base_clock; + + pwm_base_clock = pwm_get_clock(); + uint32_t clkdiv = 0; + + pwm_clock_mhz = (float) pwm_base_clock / 1000000.0f; + uint32_t mod = (pwm_clock_mhz * (float) us) - 1; + while (mod > 0xFFFF) { + ++clkdiv; + pwm_clock_mhz /= 2.0f; + mod = (pwm_clock_mhz * (float) us) - 1; + if (clkdiv == 7) { + break; + } + } + uint32_t PRSC = base->SM[module].CTRL & ~PWM_CTRL_PRSC_MASK; + PRSC |= PWM_CTRL_PRSC(clkdiv); + base->SM[module].CTRL = PRSC; /* Indicates the end of the PWM period */ - base->SM[module].VAL1 = PWM_VAL1_VAL1((pwm_clock_mhz * (float)us) - 1); + base->SM[module].VAL1 = PWM_VAL1_VAL1(mod); pwmout_write(obj, dc); } @@ -179,9 +206,9 @@ void pwmout_pulsewidth_ms(pwmout_t* obj, int ms) void pwmout_pulsewidth_us(pwmout_t* obj, int us) { - PWM_Type *base = pwm_addrs[(obj->pwm_name >> PWM_SHIFT) & 0x3]; - uint32_t module = obj->pwm_name >> PWM_MODULE_SHIFT; - uint32_t pwmchannel = obj->pwm_name & 0xF; + PWM_Type *base = pwm_addrs[(obj->pwm_name >> PWM_SHIFT) & 0x7]; + uint32_t module = (obj->pwm_name >> PWM_MODULE_SHIFT) & 0x3; + uint32_t pwmchannel = obj->pwm_name & 0x1; uint32_t value = (uint32_t)(pwm_clock_mhz * (float)us); /* Setup the PWM dutycycle */ @@ -193,7 +220,7 @@ void pwmout_pulsewidth_us(pwmout_t* obj, int us) base->SM[module].VAL5 = value; } /* Set the load okay bit */ - PWM_SetPwmLdok(base, module, true); + PWM_SetPwmLdok(base, (1 << module), true); } #endif diff --git a/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_IMX/spi_api.c b/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_IMX/spi_api.c index 5795639d87..710d813813 100644 --- a/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_IMX/spi_api.c +++ b/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_IMX/spi_api.c @@ -107,15 +107,9 @@ static inline int spi_readable(spi_t * obj) int spi_master_write(spi_t *obj, int value) { - lpspi_transfer_t masterXfer; uint32_t rx_data; - masterXfer.txData = (uint8_t *)&value; - masterXfer.rxData = NULL; - masterXfer.dataSize = 1; - masterXfer.configFlags = kLPSPI_MasterPcs0 | kLPSPI_MasterPcsContinuous | kLPSPI_SlaveByteSwap; - - LPSPI_MasterTransferBlocking(spi_address[obj->instance], &masterXfer); + LPSPI_WriteData(spi_address[obj->instance], value); // wait rx buffer full while (!spi_readable(obj)); diff --git a/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_MIMXRT1050/TARGET_EVK/PeripheralNames.h b/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_MIMXRT1050/TARGET_EVK/PeripheralNames.h index cda975898e..93dce23ac9 100644 --- a/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_MIMXRT1050/TARGET_EVK/PeripheralNames.h +++ b/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_MIMXRT1050/TARGET_EVK/PeripheralNames.h @@ -52,14 +52,38 @@ typedef enum { #define PWM_SHIFT 8 typedef enum { - PWM_1 = (0 << PWM_SHIFT) | (0 << PWM_MODULE_SHIFT) | (0), // PWM1 Submodule 0 PWMA - PWM_2 = (0 << PWM_SHIFT) | (0 << PWM_MODULE_SHIFT) | (1), // PWM1 Submodule 0 PWMB - PWM_3 = (0 << PWM_SHIFT) | (1 << PWM_MODULE_SHIFT) | (0), // PWM1 Submodule 1 PWMA - PWM_4 = (0 << PWM_SHIFT) | (1 << PWM_MODULE_SHIFT) | (1), // PWM1 Submodule 1 PWMB - PWM_5 = (0 << PWM_SHIFT) | (2 << PWM_MODULE_SHIFT) | (0), // PWM1 Submodule 2 PWMA - PWM_6 = (0 << PWM_SHIFT) | (2 << PWM_MODULE_SHIFT) | (1), // PWM1 Submodule 2 PWMB - PWM_7 = (0 << PWM_SHIFT) | (3 << PWM_MODULE_SHIFT) | (0), // PWM1 Submodule 3 PWMA - PWM_8 = (0 << PWM_SHIFT) | (3 << PWM_MODULE_SHIFT) | (1), // PWM1 Submodule 3 PWMB + PWM_1 = (1 << PWM_SHIFT) | (0 << PWM_MODULE_SHIFT) | (0), // PWM1 Submodule 0 PWMA + PWM_2 = (1 << PWM_SHIFT) | (0 << PWM_MODULE_SHIFT) | (1), // PWM1 Submodule 0 PWMB + PWM_3 = (1 << PWM_SHIFT) | (1 << PWM_MODULE_SHIFT) | (0), // PWM1 Submodule 1 PWMA + PWM_4 = (1 << PWM_SHIFT) | (1 << PWM_MODULE_SHIFT) | (1), // PWM1 Submodule 1 PWMB + PWM_5 = (1 << PWM_SHIFT) | (2 << PWM_MODULE_SHIFT) | (0), // PWM1 Submodule 2 PWMA + PWM_6 = (1 << PWM_SHIFT) | (2 << PWM_MODULE_SHIFT) | (1), // PWM1 Submodule 2 PWMB + PWM_7 = (1 << PWM_SHIFT) | (3 << PWM_MODULE_SHIFT) | (0), // PWM1 Submodule 3 PWMA + PWM_8 = (1 << PWM_SHIFT) | (3 << PWM_MODULE_SHIFT) | (1), // PWM1 Submodule 3 PWMB + PWM_9 = (2 << PWM_SHIFT) | (0 << PWM_MODULE_SHIFT) | (0), // PWM2 Submodule 0 PWMA + PWM_10 = (2 << PWM_SHIFT) | (0 << PWM_MODULE_SHIFT) | (1), // PWM2 Submodule 0 PWMB + PWM_11 = (2 << PWM_SHIFT) | (1 << PWM_MODULE_SHIFT) | (0), // PWM2 Submodule 1 PWMA + PWM_12 = (2 << PWM_SHIFT) | (1 << PWM_MODULE_SHIFT) | (1), // PWM2 Submodule 1 PWMB + PWM_13 = (2 << PWM_SHIFT) | (2 << PWM_MODULE_SHIFT) | (0), // PWM2 Submodule 2 PWMA + PWM_14 = (2 << PWM_SHIFT) | (2 << PWM_MODULE_SHIFT) | (1), // PWM2 Submodule 2 PWMB + PWM_15 = (2 << PWM_SHIFT) | (3 << PWM_MODULE_SHIFT) | (0), // PWM2 Submodule 3 PWMA + PWM_16 = (2 << PWM_SHIFT) | (3 << PWM_MODULE_SHIFT) | (1), // PWM2 Submodule 3 PWMB + PWM_17 = (3 << PWM_SHIFT) | (0 << PWM_MODULE_SHIFT) | (0), // PWM3 Submodule 0 PWMA + PWM_18 = (3 << PWM_SHIFT) | (0 << PWM_MODULE_SHIFT) | (1), // PWM3 Submodule 0 PWMB + PWM_19 = (3 << PWM_SHIFT) | (1 << PWM_MODULE_SHIFT) | (0), // PWM3 Submodule 1 PWMA + PWM_20 = (3 << PWM_SHIFT) | (1 << PWM_MODULE_SHIFT) | (1), // PWM3 Submodule 1 PWMB + PWM_21 = (3 << PWM_SHIFT) | (2 << PWM_MODULE_SHIFT) | (0), // PWM3 Submodule 2 PWMA + PWM_22 = (3 << PWM_SHIFT) | (2 << PWM_MODULE_SHIFT) | (1), // PWM3 Submodule 2 PWMB + PWM_23 = (3 << PWM_SHIFT) | (3 << PWM_MODULE_SHIFT) | (0), // PWM3 Submodule 3 PWMA + PWM_24 = (3 << PWM_SHIFT) | (3 << PWM_MODULE_SHIFT) | (1), // PWM3 Submodule 3 PWMB + PWM_25 = (4 << PWM_SHIFT) | (0 << PWM_MODULE_SHIFT) | (0), // PWM4 Submodule 0 PWMA + PWM_26 = (4 << PWM_SHIFT) | (0 << PWM_MODULE_SHIFT) | (1), // PWM4 Submodule 0 PWMB + PWM_27 = (4 << PWM_SHIFT) | (1 << PWM_MODULE_SHIFT) | (0), // PWM4 Submodule 1 PWMA + PWM_28 = (4 << PWM_SHIFT) | (1 << PWM_MODULE_SHIFT) | (1), // PWM4 Submodule 1 PWMB + PWM_29 = (4 << PWM_SHIFT) | (2 << PWM_MODULE_SHIFT) | (0), // PWM4 Submodule 2 PWMA + PWM_30 = (4 << PWM_SHIFT) | (2 << PWM_MODULE_SHIFT) | (1), // PWM4 Submodule 2 PWMB + PWM_31 = (4 << PWM_SHIFT) | (3 << PWM_MODULE_SHIFT) | (0), // PWM4 Submodule 3 PWMA + PWM_32 = (4 << PWM_SHIFT) | (3 << PWM_MODULE_SHIFT) | (1) // PWM4 Submodule 3 PWMB } PWMName; #define ADC_INSTANCE_SHIFT 8 diff --git a/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_MIMXRT1050/TARGET_EVK/PeripheralPins.c b/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_MIMXRT1050/TARGET_EVK/PeripheralPins.c index fb5889835d..e155041366 100644 --- a/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_MIMXRT1050/TARGET_EVK/PeripheralPins.c +++ b/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_MIMXRT1050/TARGET_EVK/PeripheralPins.c @@ -88,6 +88,9 @@ const PinMap PinMap_SPI_SSEL[] = { const PinMap PinMap_PWM[] = { {GPIO_AD_B0_10, PWM_7, ((3U << DAISY_REG_VALUE_SHIFT) | (0x454 << DAISY_REG_SHIFT) | 1)}, {GPIO_AD_B0_11, PWM_8, ((3U << DAISY_REG_VALUE_SHIFT) | (0x464 << DAISY_REG_SHIFT) | 1)}, + {GPIO_AD_B1_08, PWM_25, ((1U << DAISY_REG_VALUE_SHIFT) | (0x494 << DAISY_REG_SHIFT) | 1)}, + {GPIO_SD_B0_00, PWM_1, ((1U << DAISY_REG_VALUE_SHIFT) | (0x458 << DAISY_REG_SHIFT) | 1)}, + {GPIO_SD_B0_01, PWM_2, ((1U << DAISY_REG_VALUE_SHIFT) | (0x468 << DAISY_REG_SHIFT) | 1)}, {NC , NC , 0} }; diff --git a/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_MIMXRT1050/TARGET_EVK/mbed_overrides.c b/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_MIMXRT1050/TARGET_EVK/mbed_overrides.c index d27ee85a34..a71d79604f 100644 --- a/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_MIMXRT1050/TARGET_EVK/mbed_overrides.c +++ b/targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_MIMXRT1050/TARGET_EVK/mbed_overrides.c @@ -16,6 +16,7 @@ #include "pinmap.h" #include "fsl_clock_config.h" #include "fsl_clock.h" +#include "fsl_xbara.h" #include "lpm.h" #define LPSPI_CLOCK_SOURCE_DIVIDER (7U) @@ -217,9 +218,35 @@ uint32_t i2c_get_clock() return ((CLOCK_GetFreq(kCLOCK_Usb1PllClk) / 8) / (LPI2C_CLOCK_SOURCE_DIVIDER + 1U)); } -void pwm_setup_clock() +void pwm_setup(uint32_t instance) { - /* Use default settings */ + /* Use default clock settings */ + /* Set the PWM Fault inputs to a low value */ + XBARA_Init(XBARA1); + + XBARA_SetSignalsConnection(XBARA1, kXBARA1_InputLogicHigh, kXBARA1_OutputFlexpwm1234Fault2); + XBARA_SetSignalsConnection(XBARA1, kXBARA1_InputLogicHigh, kXBARA1_OutputFlexpwm1234Fault3); + + switch (instance) { + case 1: + XBARA_SetSignalsConnection(XBARA1, kXBARA1_InputLogicHigh, kXBARA1_OutputFlexpwm1Fault0); + XBARA_SetSignalsConnection(XBARA1, kXBARA1_InputLogicHigh, kXBARA1_OutputFlexpwm1Fault1); + break; + case 2: + XBARA_SetSignalsConnection(XBARA1, kXBARA1_InputLogicHigh, kXBARA1_OutputFlexpwm2Fault0); + XBARA_SetSignalsConnection(XBARA1, kXBARA1_InputLogicHigh, kXBARA1_OutputFlexpwm2Fault1); + break; + case 3: + XBARA_SetSignalsConnection(XBARA1, kXBARA1_InputLogicHigh, kXBARA1_OutputFlexpwm3Fault0); + XBARA_SetSignalsConnection(XBARA1, kXBARA1_InputLogicHigh, kXBARA1_OutputFlexpwm3Fault1); + break; + case 4: + XBARA_SetSignalsConnection(XBARA1, kXBARA1_InputLogicHigh, kXBARA1_OutputFlexpwm4Fault0); + XBARA_SetSignalsConnection(XBARA1, kXBARA1_InputLogicHigh, kXBARA1_OutputFlexpwm4Fault1); + break; + default: + break; + } } uint32_t pwm_get_clock() diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/analogin_api.c b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/analogin_api.c index 44ce5b66cd..8a5237958a 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/analogin_api.c +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/analogin_api.c @@ -41,8 +41,11 @@ void analogin_init (analogin_t *obj, PinName pin) HAL_ADC_INIT_DAT HalADCInitDataTmp; PHAL_ADC_INIT_DAT pHalADCInitDataTmp = &HalADCInitDataTmp; /* To backup user config first */ - + +#if defined(CONFIG_MBED_ENABLED) _memset(&(obj->HalADCInitData), 0, sizeof(HAL_ADC_INIT_DAT)); +#endif + _memcpy(pHalADCInitDataTmp, &(obj->HalADCInitData), sizeof(HAL_ADC_INIT_DAT)); _memset(obj, 0x00, sizeof(analogin_t)); @@ -92,17 +95,13 @@ void analogin_init (analogin_t *obj, PinName pin) pSalADCHND->pUserCB = pSalADCMngtAdpt->pUserCB; /*To assign user callback pointers*/ - pSalADCMngtAdpt->pUserCB->pTXCB = pSalADCUserCBAdpt; - pSalADCMngtAdpt->pUserCB->pTXCCB = (pSalADCUserCBAdpt+1); - pSalADCMngtAdpt->pUserCB->pRXCB = (pSalADCUserCBAdpt+2); - pSalADCMngtAdpt->pUserCB->pRXCCB = (pSalADCUserCBAdpt+3); - pSalADCMngtAdpt->pUserCB->pRDREQCB = (pSalADCUserCBAdpt+4); - pSalADCMngtAdpt->pUserCB->pERRCB = (pSalADCUserCBAdpt+5); - pSalADCMngtAdpt->pUserCB->pDMATXCB = (pSalADCUserCBAdpt+6); - pSalADCMngtAdpt->pUserCB->pDMATXCCB = (pSalADCUserCBAdpt+7); - pSalADCMngtAdpt->pUserCB->pDMARXCB = (pSalADCUserCBAdpt+8); - pSalADCMngtAdpt->pUserCB->pDMARXCCB = (pSalADCUserCBAdpt+9); - + + pSalADCMngtAdpt->pUserCB->pRXCB = pSalADCUserCBAdpt; + pSalADCMngtAdpt->pUserCB->pRXCCB = (pSalADCUserCBAdpt+1); + pSalADCMngtAdpt->pUserCB->pERRCB = (pSalADCUserCBAdpt+2); + pSalADCMngtAdpt->pUserCB->pIDMARXCCB= (pSalADCUserCBAdpt+3); + pSalADCMngtAdpt->pUserCB->pDMARXCB = (pSalADCUserCBAdpt+4); + pSalADCMngtAdpt->pUserCB->pDMARXCCB = (pSalADCUserCBAdpt+5); /* Set ADC Device Number */ pSalADCHND->DevNum = adc_idx; @@ -136,9 +135,13 @@ float analogin_read(analogin_t *obj) uint8_t AnaloginIdx = 0; uint32_t AnalogDat = 0; +#if defined(CONFIG_MBED_ENABLED) //no auto-calibration implemented yet, uses hard coded calibrate uint32_t Offset = 0x2980; uint32_t AnalogDatFull = 0xAA00; +#else + uint32_t AnalogDatFull = 0; +#endif PSAL_ADC_MNGT_ADPT pSalADCMngtAdpt = NULL; PSAL_ADC_HND pSalADCHND = NULL; @@ -152,7 +155,12 @@ float analogin_read(analogin_t *obj) AnalogDat = AnaloginTmp[(AnaloginIdx/2)]; AnalogDat = (AnalogDat & AnaloginDatMsk); AnalogDat = (AnalogDat>>((u32)(16*(AnaloginIdx&0x01)))); + +#if defined(CONFIG_MBED_ENABLED) AnalogDat -= Offset; +#else + AnalogDatFull = 0xCE80; +#endif value = (float)(AnalogDat) / (float)(AnalogDatFull); return (float)value; diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/analogout_api.c b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/analogout_api.c index d69e12db05..2c33b63290 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/analogout_api.c +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/analogout_api.c @@ -26,6 +26,8 @@ #define DAC_POSITIVE_FULL_SCALE 0x7E0 #define DAC_NEGATIVE_FULL_SCALE 0x820 +extern void HalDACPinMuxInit(void *Data); +extern void HalDACPinMuxDeInit(void *Data); /** \brief analogout_init:\n * to initialize DAC diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_ARM_STD/lib_peripheral_mbed_arm.ar b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_ARM_STD/lib_peripheral_mbed_arm.ar index 7aff54937f..156f86a576 100644 Binary files a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_ARM_STD/lib_peripheral_mbed_arm.ar and b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_ARM_STD/lib_peripheral_mbed_arm.ar differ diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_ARM_STD/lib_wlan_mbed_arm.ar b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_ARM_STD/lib_wlan_mbed_arm.ar index 980575aa8b..0b2a03c1dd 100644 Binary files a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_ARM_STD/lib_wlan_mbed_arm.ar and b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_ARM_STD/lib_wlan_mbed_arm.ar differ diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_GCC_ARM/lib_peripheral_mbed_gcc.a b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_GCC_ARM/lib_peripheral_mbed_gcc.a index 2f6ab3f0c9..44b1a3c34f 100644 Binary files a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_GCC_ARM/lib_peripheral_mbed_gcc.a and b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_GCC_ARM/lib_peripheral_mbed_gcc.a differ diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_GCC_ARM/lib_wlan_mbed_gcc.a b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_GCC_ARM/lib_wlan_mbed_gcc.a index 312525c618..bcd22c4880 100644 Binary files a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_GCC_ARM/lib_wlan_mbed_gcc.a and b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_GCC_ARM/lib_wlan_mbed_gcc.a differ diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_IAR/lib_peripheral_mbed_iar.a b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_IAR/lib_peripheral_mbed_iar.a index e906f7fd12..84af9c1399 100644 Binary files a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_IAR/lib_peripheral_mbed_iar.a and b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_IAR/lib_peripheral_mbed_iar.a differ diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_IAR/lib_wlan_mbed_iar.a b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_IAR/lib_wlan_mbed_iar.a index a19c10c636..216b172d94 100644 Binary files a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_IAR/lib_wlan_mbed_iar.a and b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_IAR/lib_wlan_mbed_iar.a differ diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/platform_autoconf.h b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/platform_autoconf.h index 6613bbd524..5d3c7a03cb 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/platform_autoconf.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/platform_autoconf.h @@ -18,9 +18,7 @@ /* * Target Platform Selection */ -#define CONFIG_WITHOUT_MONITOR 1 - -#undef CONFIG_RTL8195A +#undef CONFIG_RTL8195A #define CONFIG_RTL8195A 1 #undef CONFIG_FPGA #undef CONFIG_RTL_SIM @@ -54,12 +52,21 @@ #undef CONFIG_IMAGE_AUTO_LOAD //#undef CONFIG_IMAGE_PAGE_LOAD //#define CONFIG_IMAGE_AUTO_LOAD 1 -#define CONFIG_BOOT_TO_UPGRADE_IMG2 1 + +#undef CONFIG_BOOT_TO_UPGRADE_IMG2 + #undef CONFIG_PERI_UPDATE_IMG #define CONFIG_BOOT_FROM_JTAG 1 #undef CONFIG_ALIGNMENT_EXCEPTION_ENABLE #define CONFIG_KERNEL 1 + #define PLATFORM_FREERTOS 1 +#define CONFIG_MBED_ENABLED 1 +#if defined(CONFIG_MBED_ENABLED) +#undef PLATFORM_FREERTOS +#define PLATFORM_CMSIS_RTOS 1 +#endif + #undef PLATFORM_UCOSII #undef PLATFORM_ECOS #undef CONFIG_TASK_SCHEDUL_DIS @@ -73,7 +80,11 @@ #define CONFIG_WDG 1 #undef CONFIG_WDG_NON #define CONFIG_WDG_NORMAL 1 -#define CONFIG_GDMA_EN 0 + +#undef CONFIG_WDG_TEST +#define CONFIG_WDG_MODULE 1 +#define CONFIG_GDMA_EN 1 + #define CONFIG_GDMA_NORMAL 1 #undef CONFIG_GDMA_TEST #define CONFIG_GDMA_MODULE 1 @@ -85,6 +96,7 @@ #define CONFIG_GPIO_NORMAL 1 #undef CONFIG_GPIO_TEST #define CONFIG_GPIO_MODULE 1 + #if defined(CONFIG_INIC) || (CONFIG_SDIOD) #define CONFIG_SDIO_DEVICE_EN 1 #define CONFIG_SDIO_DEVICE_NORMAL 1 @@ -107,6 +119,10 @@ #define DWC_HOST_ONLY 1 #define CONFIG_USB_HOST_ONLY 1 #endif + +#undef CONFIG_SDIO_HOST_EN +#undef CONFIG_USB_EN + #define CONFIG_SPI_COM_EN 1 #define CONFIG_SPI_COM_NORMAL 1 #undef CONFIG_SPI_COM_TEST @@ -121,24 +137,31 @@ #define CONFIG_I2C_MODULE 1 #undef CONFIG_DEBUG_LOG_I2C_HAL #undef CONFIG_PCM_EN -#undef CONFIG_I2S_EN -#undef CONFIG_I2S_NORMAL +#define CONFIG_I2S_EN 1 +#define CONFIG_I2S_NORMAL 1 #undef CONFIG_I2S_TEST -#undef CONFIG_I2S_MODULE +#define CONFIG_I2S_MODULE 1 + #undef CONFIG_DEBUG_LOG_I2S_HAL #undef CONFIG_NFC_EN #undef CONFIG_NFC_NORMAL #undef CONFIG_NFC_TEST #undef CONFIG_NFC_MODULE + +// power saving enable #define CONFIG_SOC_PS_EN 1 #define CONFIG_SOC_PS_NORMAL 1 #undef CONFIG_SOC_PS_TEST -//#define CONFIG_SOC_PS_MODULE 1 +#define CONFIG_SOC_PS_MODULE 1 + #define CONFIG_CRYPTO_EN 1 #define CONFIG_CRYPTO_NORMAL 1 #undef CONFIG_CRYPTO_TEST #define CONFIG_CRYPTO_MODULE 1 -#define CONFIG_MII_EN 1 + +//#define CONFIG_MII_EN 1 +#undef CONFIG_MII_EN + #define CONFIG_PWM_EN 1 #define CONFIG_PWM_NORMAL 1 #undef CONFIG_PWM_TEST @@ -186,19 +209,13 @@ #define CONFIG_UART_LOG_HISTORY 1 #undef CONFIG_CONSOLE_NORMALL_MODE #define CONFIG_CONSOLE_VERIFY_MODE 1 -#undef CONFIG_DEBUG_LOG + +//#undef CONFIG_DEBUG_LOG +#define CONFIG_DEBUG_LOG 1 + #define CONFIG_DEBUG_ERR_MSG 1 #undef CONFIG_DEBUG_WARN_MSG #undef CONFIG_DEBUG_INFO_MSG - -/* - * < SDK Option Config - */ -//#undef CONFIG_MBED_ENABLED -#ifdef CONFIG_MBED_ENABLED -#undef PLATFORM_FREERTOS -#define PLATFORM_CMSIS_RTOS 1 -#endif #undef CONFIG_APP_DEMO /* diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/platform_opts.h b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/platform_opts.h index c8beb5447f..e67a675caa 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/platform_opts.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/platform_opts.h @@ -37,8 +37,9 @@ limitations under the License. #define SUPPORT_INTERACTIVE_MODE 0//on/off wifi_interactive_mode #define CONFIG_LOG_SERVICE_LOCK 0 -#define CONFIG_LOG_USE_HS_UART 0 //command/log via highspeed uart -#define CONFIG_LOG_USE_I2C 0 //command/log via I2C +#define CONFIG_ATCMD_MP 0 //support MP AT command +#define USE_MODE 1 //for test + #endif /** @@ -65,6 +66,7 @@ limitations under the License. */ #define AP_SETTING_SECTOR 0x000FE000 #define UART_SETTING_SECTOR 0x000FC000 +#define SPI_SETTING_SECTOR 0x000FC000 #define FAST_RECONNECT_DATA (0x80000 - 0x1000) /** @@ -75,6 +77,8 @@ limitations under the License. #define CONFIG_LWIP_LAYER 1 #define CONFIG_INIT_NET 1 //init lwip layer when start up #define CONFIG_WIFI_IND_USE_THREAD 0 // wifi indicate worker thread +#define CONFIG_ENABLE_AP_POLLING_CLIENT_ALIVE 1 // on or off AP POLLING CLIENT + //on/off relative commands in log service #define CONFIG_SSL_CLIENT 0 @@ -95,6 +99,11 @@ limitations under the License. /* For WPS and P2P */ #define CONFIG_ENABLE_WPS 0 #define CONFIG_ENABLE_P2P 0 + +#if CONFIG_ENABLE_WPS +#define CONFIG_ENABLE_WPS_DISCOVERY 1 +#endif + #if CONFIG_ENABLE_P2P #define CONFIG_ENABLE_WPS_AP 1 #undef CONFIG_WIFI_IND_USE_THREAD @@ -104,6 +113,17 @@ limitations under the License. #error "If CONFIG_ENABLE_P2P, need to define CONFIG_ENABLE_WPS_AP 1" #endif +/* For SSL/TLS */ +#define CONFIG_USE_POLARSSL 0 +#define CONFIG_USE_MBEDTLS 1 +#if ((CONFIG_USE_POLARSSL == 0) && (CONFIG_USE_MBEDTLS == 0)) || ((CONFIG_USE_POLARSSL == 1) && (CONFIG_USE_MBEDTLS == 1)) +#undef CONFIG_USE_POLARSSL +#define CONFIG_USE_POLARSSL 1 +#undef CONFIG_USE_MBEDTLS +#define CONFIG_USE_MBEDTLS 0 + +#endif + /* For Simple Link */ #define CONFIG_INCLUDE_SIMPLE_CONFIG 1 @@ -125,6 +145,9 @@ limitations under the License. #endif //end of #if CONFIG_WLAN /*******************************************************************************/ +/* For LWIP configuration */ +#define CONFIG_LWIP_DHCP_COARSE_TIMER 60 + /** * For Ethernet configurations */ @@ -166,6 +189,10 @@ limitations under the License. #endif /******************End of iNIC configurations*******************/ + +/* for CoAP example*/ +#define CONFIG_EXAMPLE_COAP 0 + /* For aj_basic_example */ #define CONFIG_EXAMPLE_AJ_BASIC 0 @@ -214,6 +241,12 @@ limitations under the License. /* For http download example */ #define CONFIG_EXAMPLE_HTTP_DOWNLOAD 0 +/* For httpc example */ +#define CONFIG_EXAMPLE_HTTPC 0 + +/* For httpd example */ +#define CONFIG_EXAMPLE_HTTPD 0 + /* For tcp keepalive example */ #define CONFIG_EXAMPLE_TCP_KEEPALIVE 0 @@ -232,6 +265,96 @@ limitations under the License. #define FATFS_DISK_SD 1 #define CONFIG_EXAMPLE_CODEC_SGTL5000 1 #endif +/* For audio mp3 pcm example */ +#define CONFIG_EXAMPLE_AUDIO_MP3 0 +#if CONFIG_EXAMPLE_AUDIO_MP3 +#define FATFS_DISK_SD 1 +#define CONFIG_EXAMPLE_MP3_STREAM_SGTL5000 1 +#endif + +/* For audio m4a example */ +#define CONFIG_EXAMPLE_AUDIO_M4A 0 +#if CONFIG_EXAMPLE_AUDIO_M4A +#define CONFIG_EXAMPLE_M4A_FROM_HTTP 1 // 1: From HTTP, 0: From SDCARD +#define FATFS_DISK_SD 1 +#undef CONFIG_INCLUDE_SIMPLE_CONFIG +#define CONFIG_INCLUDE_SIMPLE_CONFIG 0 +#undef SUPPORT_MP_MODE +#define SUPPORT_MP_MODE 0 +#if (CONFIG_EXAMPLE_M4A_FROM_HTTP == 0) +#undef CONFIG_WLAN +#define CONFIG_WLAN 0 +#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT +#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 +#undef SUPPORT_LOG_SERVICE +#define SUPPORT_LOG_SERVICE 0 +#else +#undef FAST_RECONNECT_DATA +#define FAST_RECONNECT_DATA (0x200000-0x1000) +#endif +#endif + +/* For audio m4a example */ +#define CONFIG_EXAMPLE_AUDIO_M4A_SELFPARSE 0 +#if CONFIG_EXAMPLE_AUDIO_M4A_SELFPARSE +#define FATFS_DISK_SD 1 +#undef CONFIG_INCLUDE_SIMPLE_CONFIG +#define CONFIG_INCLUDE_SIMP LE_CONFIG 0 +#undef SUPPORT_MP_MODE +#define SUPPORT_MP_MODE 0 +#undef CONFIG_WLAN +#define CONFIG_WLAN 0 +#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT +#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 +#undef SUPPORT_LOG_SERVICE +#define SUPPORT_LOG_SERVICE 0 +#endif + +/* For m4a,mp3 combined example */ +#define CONFIG_EXAMPLE_AUDIO_M4A_MP3 0 +#if CONFIG_EXAMPLE_AUDIO_M4A_MP3 +#define FATFS_DISK_SD 1 +#undef CONFIG_WLAN +#define CONFIG_WLAN 0 +#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT +#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 +#undef CONFIG_INCLUDE_SIMPLE_CONFIG +#define CONFIG_INCLUDE_SIMPLE_CONFIG 0 +#undef SUPPORT_LOG_SERVICE +#define SUPPORT_LOG_SERVICE 0 +#undef SUPPORT_MP_MODE +#define SUPPORT_MP_MODE 0 +#endif + +/* For audio amr example */ +#define CONFIG_EXAMPLE_AUDIO_AMR 0 +#if CONFIG_EXAMPLE_AUDIO_AMR +#define FATFS_DISK_SD 1 +#undef CONFIG_WLAN +#define CONFIG_WLAN 0 +#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT +#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 +#undef CONFIG_INCLUDE_SIMPLE_CONFIG +#define CONFIG_INCLUDE_SIMPLE_CONFIG 0 +#endif + +/* For audio HLS example */ +#define CONFIG_EXAMPLE_AUDIO_HLS 0 +#if CONFIG_EXAMPLE_AUDIO_HLS +#define FATFS_DISK_SD 1 +#undef FAST_RECONNECT_DATA +#define FAST_RECONNECT_DATA (0x200000-0x1000) +#undef CONFIG_INCLUDE_SIMPLE_CONFIG +#define CONFIG_INCLUDE_SIMPLE_CONFIG 0 +#undef SUPPORT_MP_MODE +#define SUPPORT_MP_MODE 0 +#endif + +/*Foe alc audio dsp firmware upgrade */ +#define CONFIG_EXAMPLE_ALC_DSP_FW_UPGRADE 0 + +/*Foe audio pcm upload */ +#define CONFIG_EXAMPLE_AUDIO_PCM_UPLOAD 0 /* For UART Module AT command example */ #define CONFIG_EXAMPLE_UART_ATCMD 0 @@ -250,15 +373,50 @@ limitations under the License. #define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 #endif +/* For SPI Module AT command example */ +#define CONFIG_EXAMPLE_SPI_ATCMD 0 + +#if CONFIG_EXAMPLE_SPI_ATCMD +#undef FREERTOS_PMU_TICKLESS_PLL_RESERVED +#define FREERTOS_PMU_TICKLESS_PLL_RESERVED 1 +#undef CONFIG_OTA_UPDATE +#define CONFIG_OTA_UPDATE 1 +#undef CONFIG_TRANSPORT +#define CONFIG_TRANSPORT 1 +#undef LOG_SERVICE_BUFLEN +#define LOG_SERVICE_BUFLEN 1600 +#undef CONFIG_LOG_SERVICE_LOCK +#define CONFIG_LOG_SERVICE_LOCK 1 +#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT +#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 +#endif #define CONFIG_EXAMPLE_MEDIA_SS 0 -#define CONFIG_EXAMPLE_MEDIA_MS 0 +#define CONFIG_EXAMPLE_MEDIA_MS 0 #define CONFIG_EXAMPLE_MEDIA_AUDIO_FROM_RTP 0 + +//Defines for mp3 streaming over wifi, default output through alc5651 +#define CONFIG_EXAMPLE_MP3_STREAM_RTP 0 + +#if CONFIG_EXAMPLE_MP3_STREAM_RTP +#undef CONFIG_EXAMPLE_MEDIA_AUDIO_FROM_RTP +#define CONFIG_EXAMPLE_MEDIA_AUDIO_FROM_RTP 1 +#undef CONFIG_INCLUDE_SIMPLE_CONFIG +#define CONFIG_INCLUDE_SIMPLE_CONFIG 0 +//Set this flag to 1 in case sgtl5000 to be used else alc5651 will be used +#define CONFIG_EXAMPLE_MP3_STREAM_SGTL5000 0 +#endif + // Use media source/sink example -#if (CONFIG_EXAMPLE_MEDIA_SS==1) || (CONFIG_EXAMPLE_MEDIA_MS==1) + +#if (CONFIG_EXAMPLE_MEDIA_SS==1) || (CONFIG_EXAMPLE_MEDIA_AUDIO_FROM_RTP) + #undef CONFIG_INCLUDE_SIMPLE_CONFIG #define CONFIG_INCLUDE_SIMPLE_CONFIG 0 #define CONFIG_ENABLE_WPS 0 -#endif +#endif + +/* For ISP AT COMMAND config*/ +#define CONFIG_ISP 0 /* For Mjpeg capture example*/ #define CONFIG_EXAMPLE_MJPEG_CAPTURE 0 @@ -266,6 +424,17 @@ limitations under the License. #define FATFS_DISK_SD 1 #endif +/* For DCT example*/ +#define CONFIG_EXAMPLE_DCT 0 + +/* For audio flash mp3 pcm example */ +#define CONFIG_EXAMPLE_FLASH_MP3 0 +#if CONFIG_EXAMPLE_FLASH_MP3 +#define FATFS_DISK_FLASH 1 +#define CONFIG_EXAMPLE_MP3_STREAM_SGTL5000 1 + +#endif + /****************** For EAP method example *******************/ #define CONFIG_EXAMPLE_EAP 0 @@ -279,6 +448,9 @@ limitations under the License. #if CONFIG_ENABLE_PEAP || CONFIG_ENABLE_TLS || CONFIG_ENABLE_TTLS #define CONFIG_ENABLE_EAP + +#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT + #define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 #endif @@ -292,6 +464,11 @@ limitations under the License. /* For usb mass storage example */ #define CONFIG_EXAMPLE_USB_MASS_STORAGE 0 +/* For vendor specific example */ +#define CONFIG_EXAMPLE_USB_VENDOR_SPECIFIC 0 + +#define CONFIG_EXAMPLE_USB_ISOC_DEVICE 0 + /* For FATFS example*/ #define CONFIG_EXAMPLE_FATFS 0 #if CONFIG_EXAMPLE_FATFS @@ -300,8 +477,9 @@ limitations under the License. // fatfs version #define FATFS_R_10C // fatfs disk interface -#define FATFS_DISK_USB 0 -#define FATFS_DISK_SD 1 +#define FATFS_DISK_USB 0 +#define FATFS_DISK_SD 1 +#define FATFS_DISK_FLASH 0 #endif #endif @@ -380,7 +558,42 @@ in lwip_opt.h for support uart adapter*/ /* For ssl server example */ #define CONFIG_EXAMPLE_SSL_SERVER 0 +/*For timelapse example */ +#define CONFIG_EXAMPLE_TIMELAPSE 0 +#if CONFIG_EXAMPLE_TIMELAPSE +#define CONFIG_USE_HTTP_SERVER 0 +#if CONFIG_USE_HTTP_SERVER +#undef CONFIG_INCLUDE_SIMPLE_CONFIG +#define CONFIG_INCLUDE_SIMPLE_CONFIG 0 +#define CONFIG_ENABLE_WPS 0 +#else +#undef CONFIG_INCLUDE_SIMPLE_CONFIG +#define CONFIG_INCLUDE_SIMPLE_CONFIG 0 +#define CONFIG_ENABLE_WPS 0 +#define CONFIG_FATFS_EN 1 +#define FATFS_R_10C +#define FATFS_DISK_SD 1 +#endif +#endif + /* For ota update http example */ #define CONFIG_EXAMPLE_OTA_HTTP 0 +/* For Amazon AWS IoT example */ +#define CONFIG_EXAMPLE_AMAZON_AWS_IOT 0 +#define CONFIG_EXAMPLE_AMAZON_ALEXA 0 + +/*For wifi roaming example*/ +#define CONFIG_EXAMPLE_WIFI_ROAMING 0 +#if CONFIG_QQ_LINK +#define FATFS_R_10C +#define FATFS_DISK_USB 0 +#define FATFS_DISK_SD 1 +#endif +#if CONFIG_ENABLE_WPS +#define WPS_CONNECT_RETRY_COUNT 4 +#define WPS_CONNECT_RETRY_INTERVAL 5000 // in ms +#endif +#define AUTO_RECONNECT_COUNT 8 +#define AUTO_RECONNECT_INTERVAL 5 // in sec #endif diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/rtl8195a_init.c b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/rtl8195a_init.c index 4e7b39657d..1b1e581826 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/rtl8195a_init.c +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/rtl8195a_init.c @@ -14,6 +14,8 @@ * limitations under the License. */ #include "rtl8195a.h" +#include "basic_types.h" +#include "hal_common.h" #if defined(__CC_ARM) || \ (defined (__ARMCC_VERSION) && __ARMCC_VERSION >= 6010050) @@ -67,15 +69,20 @@ extern uint8_t __bss_dram_end__[]; extern VECTOR_Func NewVectorTable[]; extern void SystemCoreClockUpdate(void); +extern VOID En32KCalibration(VOID); extern void PLAT_Start(void); extern void PLAT_Main(void); IMAGE2_START_RAM_FUN_SECTION +__USED + const RAM_START_FUNCTION gImage2EntryFun0 = { PLAT_Start }; IMAGE2_VALID_PATTEN_SECTION +__USED + const uint8_t IMAGE2_SIGNATURE[20] = { 'R', 'T', 'K', 'W', 'i', 'n', 0x0, 0xff, (FW_VERSION&0xff), ((FW_VERSION >> 8)&0xff), @@ -166,11 +173,119 @@ void TRAP_HardFaultHandler_Patch(void) #endif extern _LONG_CALL_ void * __rtl_memset_v1_00(void * m , int c , size_t n); +_WEAK void SDIO_Device_Off(void) +{ + /* Disable Clock for SDIO function */ + ACTCK_SDIOD_CCTRL(OFF); + + /* SDIO Function Disable */ + SDIOD_ON_FCTRL(OFF); + SDIOD_OFF_FCTRL(OFF); + // SDIO Pin Mux off + SDIOD_PIN_FCTRL(OFF); +} + +void SYSPlatformInit(void) +{ +#ifdef CONFIG_CHIP_A_CUT + //Set SPS lower voltage + HAL_WRITE32(SYSTEM_CTRL_BASE, REG_SYS_EFUSE_SYSCFG0, (HAL_READ32(SYSTEM_CTRL_BASE, REG_SYS_EFUSE_SYSCFG0)&0xf0ffffff)); +#else // B-Cut & C-Cut + //Set SPS lower voltage + HAL_WRITE32(SYSTEM_CTRL_BASE, REG_SYS_EFUSE_SYSCFG0, ((HAL_READ32(SYSTEM_CTRL_BASE, REG_SYS_EFUSE_SYSCFG0)&0xf0ffffff)|0x6000000)); +#endif + + //xtal buffer driving current + HAL_WRITE32(SYSTEM_CTRL_BASE, REG_SYS_XTAL_CTRL1, + ((HAL_READ32(SYSTEM_CTRL_BASE, REG_SYS_XTAL_CTRL1)&(~(BIT_MASK_SYS_XTAL_DRV_RF1< 10000) { /*Delay 100ms*/ + //DiagPrintf("32K linear Calibration Fail!!\n"); + flag = 0; + break; + } + } + } + } +} // Image2 Entry Function void PLAT_Init(void) { - uint32_t val; - // Overwrite vector table NewVectorTable[2] = (VECTOR_Func) TRAP_NMIHandler; #if defined ( __ICCARM__ ) @@ -185,25 +300,18 @@ void PLAT_Init(void) __rtl_memset_v1_00((void *)__bss_dtcm_start__, 0, __bss_dtcm_end__ - __bss_dtcm_start__); __rtl_memset_v1_00((void *)__bss_dram_start__, 0, __bss_dram_end__ - __bss_dram_start__); - extern HAL_TIMER_OP_EXT HalTimerOpExt; - __rtl_memset_v1_00((void *)&HalTimerOpExt, 0, sizeof(HalTimerOpExt)); - __rtl_memset_v1_00((void *)&HalTimerOp, 0, sizeof(HalTimerOp)); + HAL_WRITE32(SYSTEM_CTRL_BASE, REG_OSC32K_CTRL, (HAL_READ32(SYSTEM_CTRL_BASE, REG_OSC32K_CTRL)|BIT17|BIT18)); + HalDelayUs(40); +#ifdef CONFIG_TIMER_MODULE + // Re-init G-Timer HAL Function pointer with ROM Patch + if (HalCommonInit() != HAL_OK) { + DBG_8195A("Hal Common Init Failed.\n"); + } +#endif - HalTimerOpInit_Patch(&HalTimerOp); SystemCoreClockUpdate(); - // Set SPS lower voltage - val = __RTK_CTRL_READ32(REG_SYS_EFUSE_SYSCFG0); - val &= 0xf0ffffff; - val |= 0x6000000; - __RTK_CTRL_WRITE32(REG_SYS_EFUSE_SYSCFG0, val); - - // xtal buffer driving current - val = __RTK_CTRL_READ32(REG_SYS_XTAL_CTRL1); - val &= ~(BIT_MASK_SYS_XTAL_DRV_RF1 << BIT_SHIFT_SYS_XTAL_DRV_RF1); - val |= BIT_SYS_XTAL_DRV_RF1(1); - __RTK_CTRL_WRITE32(REG_SYS_XTAL_CTRL1, val); - + SYSPlatformInit(); // Initialize SPIC, then disable it for power saving. if ((HAL_PERI_ON_READ32(REG_SOC_FUNC_EN) & BIT_SOC_FLASH_EN) != 0) { SpicNVMCalLoadAll(); @@ -212,11 +320,19 @@ void PLAT_Init(void) } #ifdef CONFIG_TIMER_MODULE + + OSC_32_LINEAR_CALIBRATION(10); + HalDelayUs(40); + Calibration32k(); #endif +#ifdef CONFIG_SOC_PS_MODULE + InitSoCPM(); +#endif + #ifndef CONFIG_SDIO_DEVICE_EN - SDIO_DEV_Disable(); + SDIO_Device_Off(); #endif // Enter App start function diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/rtl8195a_trap.h b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/rtl8195a_trap.h index e3a8327459..c59b4534d9 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/rtl8195a_trap.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/rtl8195a_trap.h @@ -18,10 +18,6 @@ typedef void (*VECTOR_Func)(void *data); -typedef struct { - void (*RamStartFun)(void); -} RAM_START_FUNCTION; - typedef struct { void (*RamStartFun)(void); void (*RamWakeupFun)(void); diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/gpio_api.c b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/gpio_api.c index d7845c6b7d..832b1595a6 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/gpio_api.c +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/gpio_api.c @@ -20,6 +20,8 @@ #include "gpio_api.h" +extern void HAL_GPIO_DeInit(HAL_GPIO_PIN *GPIO_Pin); + // convert Mbed pin mode to HAL Pin Mode const u8 GPIO_InPinMode[] = { DIN_PULL_NONE, // PullNone @@ -193,10 +195,18 @@ void gpio_pull_ctrl(gpio_t *obj, PinMode pull_type) HAL_GPIO_PullCtrl((u32) obj->pin, (u32)pull_type); } - void gpio_deinit(gpio_t *obj) { HAL_GPIO_DeInit(&obj->hal_pin); } +int gpio_is_connected(const gpio_t *obj) +{ + if(obj->pin != (PinName)NC){ + return 1; + } else { + return 0; + } +} + #endif diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/gpio_irq_api.c b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/gpio_irq_api.c index 8b97503b23..c00b9ba369 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/gpio_irq_api.c +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/gpio_irq_api.c @@ -19,6 +19,8 @@ #if CONFIG_GPIO_EN #include "gpio_irq_api.h" +extern void HAL_GPIO_DeInit(HAL_GPIO_PIN *GPIO_Pin); + int gpio_irq_init(gpio_irq_t *obj, PinName pin, gpio_irq_handler handler, uint32_t id) { uint32_t pin_name; diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/i2c_api.c b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/i2c_api.c index 1783034d67..6f5fe376a5 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/i2c_api.c +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/i2c_api.c @@ -15,7 +15,6 @@ */ #include - #include "objects.h" #include "PinNames.h" #include "hal_i2c.h" @@ -79,7 +78,7 @@ static SAL_I2C_TRANSFER_BUF i2crxtranbuf[4]; extern u32 ConfigDebugErr; extern u32 ConfigDebuginfo; void i2c_init(i2c_t *obj, PinName sda, PinName scl) -{ +{ int i2c_sel; int i2c_idx; PSAL_I2C_MNGT_ADPT pSalI2CMngtAdpt = NULL; @@ -230,9 +229,9 @@ void i2c_frequency(i2c_t *obj, int hz) inline int i2c_start(i2c_t *obj) { - memset(address_save_int , 0, sizeof(address_save_int)); - memset(Byte_count , 0, sizeof(Byte_count)); - memset(address_save, 0, sizeof(address_save)); + _memset(address_save_int , 0, sizeof(address_save_int)); + _memset(Byte_count , 0, sizeof(Byte_count)); + _memset(address_save, 0, sizeof(address_save)); return 0; } @@ -279,7 +278,7 @@ int i2c_read(i2c_t *obj, int address, char *data, int length, int stop) } else { /* Calculate user time out parameters */ I2CInTOTcnt = 300; - if ((I2CInTOTcnt != 0) && (I2CInTOTcnt != I2C_TIMEOOUT_ENDLESS)) { + if ((I2CInTOTcnt != 0) && (I2CInTOTcnt != I2C_TIMEOUT_ENDLESS)) { InTimeoutCount = (I2CInTOTcnt*1000/TIMER_TICK_US); InStartCount = HalTimerOp.HalTimerReadCount(1); } @@ -345,7 +344,7 @@ int i2c_write(i2c_t *obj, int address, const char *data, int length, int stop) } else { /* Calculate user time out parameters */ I2CInTOTcnt = 300; - if ((I2CInTOTcnt != 0) && (I2CInTOTcnt != I2C_TIMEOOUT_ENDLESS)) { + if ((I2CInTOTcnt != 0) && (I2CInTOTcnt != I2C_TIMEOUT_ENDLESS)) { InTimeoutCount = (I2CInTOTcnt*1000/TIMER_TICK_US); InStartCount = HalTimerOp.HalTimerReadCount(1); } @@ -458,7 +457,7 @@ void i2c_slave_address(i2c_t *obj, int idx, uint32_t address, uint32_t mask) pSalI2CMngtAdpt = &(obj->SalI2CMngtAdpt); pSalI2CHND = &(pSalI2CMngtAdpt->pSalHndPriv->SalI2CHndPriv); address = (address & 0xFE ) >>1; - + uint16_t i2c_user_addr = (uint16_t) address; if (i2c_target_addr[pSalI2CHND->DevNum] != i2c_user_addr) { @@ -528,7 +527,7 @@ int i2c_slave_read(i2c_t *obj, char *data, int length) } else { /* Calculate user time out parameters */ I2CInTOTcnt = 300; - if ((I2CInTOTcnt != 0) && (I2CInTOTcnt != I2C_TIMEOOUT_ENDLESS)) { + if ((I2CInTOTcnt != 0) && (I2CInTOTcnt != I2C_TIMEOUT_ENDLESS)) { InTimeoutCount = (I2CInTOTcnt*1000/TIMER_TICK_US); InStartCount = HalTimerOp.HalTimerReadCount(1); } diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/log_uart_api.h b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/log_uart_api.h index c88af28772..1c252ec6c1 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/log_uart_api.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/log_uart_api.h @@ -1,10 +1,10 @@ /* mbed Microcontroller Library * Copyright (c) 2013-2016 Realtek Semiconductor Corp. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software @@ -12,11 +12,12 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ #ifndef LOG_UART_API_H #define LOG_UART_API_H +#if defined(CONFIG_PLATFORM_8195A) && (CONFIG_PLATFORM_8195A == 1) #include "device.h" #include "serial_api.h" #include "hal_log_uart.h" @@ -25,43 +26,305 @@ extern "C" { #endif -typedef void (*loguart_irq_handler)(uint32_t id, LOG_UART_INT_ID event); +/** @addtogroup log_uart LOG_UART + * @ingroup hal + * @brief log_uart functions + * @{ + */ +///@name Ameba1 Only +///@{ + +/****************************************************** + * Type Definitions + ******************************************************/ +/** Log uart irq handler function pointer type + * + * @param id : The argument for log uart interrupt handler + * @param event : The log uart interrupt indication ID. More details is shown in hal_log_uart.h + */ +typedef void (*loguart_irq_handler)(uint32_t id, LOG_UART_INT_ID event); typedef struct log_uart_s log_uart_t; -int32_t log_uart_init (log_uart_t *obj, int baudrate, int data_bits, SerialParity parity, int stop_bits); +/****************************************************** + * Function Declarations + ******************************************************/ +/** + * @brief Initialize Realtek log uart. + * Initialize the required parts of the log uart. + * i.e. baudrate, data bits, parity, etc. + * @param[in] obj: The address of log uart object. + * @param[in] baudrate: Baud rate of the log uart object. + * @param[in] data_bits: Data bits of the log uart object. + * @param[in] parity: Parity type of the log uart object + - ParityNone, - Do not use parity + - ParityOdd, - Use odd parity + - ParityEven, - Use even parity + - ParityForced1, - Use even parity, the same as ParityEven + - ParityForced0 - Use odd parity, the same as ParityOdd + * @param[in] stop_bits: The number of stop bits for the log uart object. + * @return 0 if initialization is successful, -1 otherwise + */ +int32_t log_uart_init(log_uart_t *obj, int baudrate, int data_bits, SerialParity parity, int stop_bits); + +/** + * @brief Release the resources related to Realtek log uart. + + * @param[in] obj: The address of log uart object. + * @return None + */ void log_uart_free(log_uart_t *obj); + +/** + * @brief Set the baud rate of log uart. + + * @param[in] obj: The address of log uart object. + * @param[in] baudrate: Baud rate of the log uart object. + * @return None + */ void log_uart_baud(log_uart_t *obj, int baudrate); + +/** + * @brief Set parameters for log uart. + * including data bits, parity type and stop bits + + * @param[in] obj: The address of log uart object. + * @param[in] data_bits: Data bits of log uart object. + * @param[in] parity: Parity type of the log uart object + - ParityNone, - Do not use parity + - ParityOdd, - Use odd parity + - ParityEven, - Use even parity + - ParityForced1, - Use even parity, the same as ParityEven + - ParityForced0 - Use odd parity, the same as ParityOdd + * @param[in] stop_bits: The number of stop bits for the log uart object. + * @return None + */ void log_uart_format(log_uart_t *obj, int data_bits, SerialParity parity, int stop_bits); + +/** + * @brief Set irq handler for log uart. + * @param[in] obj: The address of log uart object. + * @param[in] handler: The interrupt handler for log uart. + * @param[in] id: The argument for log uart interrupt handler. + * @return None + */ void log_uart_irq_handler(log_uart_t *obj, loguart_irq_handler handler, uint32_t id); + +/** + * @brief Enable/disable the specific irq indication ID. + * @param[in] obj: The address of log uart object. + * @param[in] irq: The log uart interrupt indication ID which will be enabled/disabled. + * @param[in] enable: 1 enable, 0 disable + * @return None + */ void log_uart_irq_set(log_uart_t *obj, LOG_UART_INT_ID irq, uint32_t enable); + +/** + * @brief Read one character from log uart. + This function will block untill the log uart gets something to read + * @param[in] obj: The address of log uart object. + * @return the character read from log uart + */ char log_uart_getc(log_uart_t *obj); + +/** + * @brief Write one character to log uart. + This function will block untill the data is successfully written to log uart + * @param[in] obj: The address of log uart object. + * @param[in] c: The one byte data to be written to log uart. + * @return None + */ void log_uart_putc(log_uart_t *obj, char c); + +/** + * @brief Check whether log uart is ready to read data + * @param[in] obj: The address of log uart object. + * @return 1 if there is data at log uart to be read, 0 otherwise + */ int log_uart_readable(log_uart_t *obj); + +/** + * @brief Check whether log uart is ready to write data + * @param[in] obj: The address of log uart object. + * @return 1 if log uart is ready for writing, 0 otherwise + */ int log_uart_writable(log_uart_t *obj); + +/** + * @brief Clear both data at log uart + This function will clear data in both TX FIFO and RX FIFO of log uart + * @param[in] obj: The address of log uart object. + * @return None + */ void log_uart_clear(log_uart_t *obj); + +/** + * @brief Clear TX FIFO of log uart + * @param[in] obj: The address of log uart object. + * @return None + */ void log_uart_clear_tx(log_uart_t *obj); + +/** + * @brief Clear RX FIFO of log uart + * @param[in] obj: The address of log uart object. + * @return None + */ void log_uart_clear_rx(log_uart_t *obj); + +/** + * @brief Set break control for log uart + * @param[in] obj: The address of log uart object. + * @return None + */ void log_uart_break_set(log_uart_t *obj); + +/** + * @brief Clear break control for log uart + * @param[in] obj: The address of log uart object. + * @return None + */ void log_uart_break_clear(log_uart_t *obj); + +/** + * @brief Set the handler for complete TX + * @param[in] obj: The address of log uart object. + * @param[in] handler: The function which is called when log uart has finished transmitting data. + * @param[in] id: The parameter for handler. + * @return None + */ void log_uart_tx_comp_handler(log_uart_t *obj, void *handler, uint32_t id); + +/** + * @brief Set the handler for complete RX + * @param[in] obj: The address of log uart object. + * @param[in] handler: The function which is called when log uart has finished receving data + * @param[in] id: The parameter for handler. + * @return None + */ void log_uart_rx_comp_handler(log_uart_t *obj, void *handler, uint32_t id); + +/** + * @brief Set the handler for line status + * @param[in] obj: The address of log uart object. + * @param[in] handler: The function which is called when log uart gets an line status indication ID. + * @param[in] id: The parameter for handler. + * @return None + */ void log_uart_line_status_handler(log_uart_t *obj, void *handler, uint32_t id); -int32_t log_uart_recv (log_uart_t *obj, char *prxbuf, uint32_t len, uint32_t timeout_ms); -int32_t log_uart_send (log_uart_t *obj, char *ptxbuf, uint32_t len, uint32_t timeout_ms); -int32_t log_uart_recv_stream (log_uart_t *obj, char *prxbuf, uint32_t len); -int32_t log_uart_send_stream (log_uart_t *obj, char *ptxbuf, uint32_t len); -int32_t log_uart_recv_stream_timeout (log_uart_t *obj, char *prxbuf, uint32_t len, + +/** + * @brief Read data from log uart in blocking mode. + * @param[in] obj: The address of log uart object. + * @param[out] prxbuf: The buffer to store received data. + * @param[in] len: The maximum length of data to be read + * @param[in] timeout_ms: Blocking time in ms. + * @return the length of received data in bytes + */ +int32_t log_uart_recv(log_uart_t *obj, char *prxbuf, uint32_t len, uint32_t timeout_ms); + +/** + * @brief Send data to log uart in blocking mode + * @param[in] obj: The address of log uart object. + * @param[in] ptxbuf: Data buffer to be sent to log uart + * @param[in] len: Length of data to be sent to log uart + * @param[in] timeout_ms: Blocking time in ms. + * @return the length of sent data in bytes + */ +int32_t log_uart_send(log_uart_t *obj, char *ptxbuf, uint32_t len, uint32_t timeout_ms); + +/** + * @brief Read data from log uart in interrupt mode(Non-blocking) + * @param[in] obj: The address of log uart object. + * @param[out] prxbuf: The buffer to store received data. + * @param[in] len: The maximum length of data to be read + * @return 0 if success + */ +int32_t log_uart_recv_stream(log_uart_t *obj, char *prxbuf, uint32_t len); + +/** + * @brief Send data to log uart in interrupt mode(Non-blocking) + * @param[in] obj: The address of log uart object. + * @param[in] ptxbuf: Data buffer to be sent to log uart + * @param[in] len: Length of data to be sent to log uart + * @return 0 if success + */ +int32_t log_uart_send_stream(log_uart_t *obj, char *ptxbuf, uint32_t len); + +/** + * @brief Read data from log uart with a given timeout in interrupt mode(Non-blocking) + * @param[in] obj: The address of log uart object. + * @param[out] prxbuf: The buffer to store received data. + * @param[in] len: The maximum length of data to be read + * @param[in] timeout_ms: The timeout for reading data in ms + * @param[in] force_cs: User callback function + * @return the length in Byte of received data before timeout, or error (< 0) + */ +int32_t log_uart_recv_stream_timeout(log_uart_t *obj, char *prxbuf, uint32_t len, uint32_t timeout_ms, void *force_cs); -int32_t log_uart_send_stream_abort (log_uart_t *obj); -int32_t log_uart_recv_stream_abort (log_uart_t *obj); -void log_uart_disable (log_uart_t *obj); -void log_uart_enable (log_uart_t *obj); + +/** + * @brief Abort interrupt mode of sending data + * @param[in] obj: The address of log uart object. + * @return the length of data sent to log uart. + */ +int32_t log_uart_send_stream_abort(log_uart_t *obj); + +/** + * @brief Abort interrupt mode of receiving data + * @param[in] obj: The address of log uart object. + * @return the length of data received from log uart. + */ +int32_t log_uart_recv_stream_abort(log_uart_t *obj); + +/** + * @brief Disable log uart + * @param[in] obj: The address of log uart object. + * @return None. + */ +void log_uart_disable(log_uart_t *obj); + +/** + * @brief Enable log uart + * @param[in] obj: The address of log uart object. + * @return None. + */ +void log_uart_enable(log_uart_t *obj); + +/** + * @brief Read Line-Status register + * @return value: + * - Bit 0: RX Data Ready + * - Bit 1: Overrun Error + * - Bit 2: Parity Error + * - Bit 3: Framing Error + * - Bit 4: Break Interrupt (received data input is held in 0 state for a longer than a full word tx time) + * - Bit 5: TX FIFO empty (THR empty) + * - Bit 6: TX FIFO empty (THR & TSR both empty) + * - Bit 7: Receiver FIFO Error (parity error, framing error or break indication) + */ uint8_t log_uart_raed_lsr(log_uart_t *obj); + +/** + * @brief Read Modem-Status register + * @return value: + * - Bit 0: DCTS, The CTS line has changed its state + * - Bit 1: DDSR, The DSR line has changed its state + * - Bit 2: TERI, RI line has changed its state from low to high state + * - Bit 3: DDCD, DCD line has changed its state + * - Bit 4: Complement of the CTS input + * - Bit 5: Complement of the DSR input + * - Bit 6: Complement of the RI input + * - Bit 7: Complement of the DCD input + */ uint8_t log_uart_raed_msr(log_uart_t *obj); +///@} +/*\@}*/ + #ifdef __cplusplus } #endif +#endif //CONFIG_PLATFORM_8195A #endif // end of "#ifndef LOG_UART_API_H" diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/port_api.c b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/port_api.c index a181d88c08..0cd3b703fc 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/port_api.c +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/port_api.c @@ -142,7 +142,7 @@ void port_mode(port_t *obj, PinMode mode) break; } if (obj->mask & (1 << i)) { // If the pin is used - pin_mode(obj->pin_def[i], mode); + pin_mode((PinName)obj->pin_def[i], mode); } } } diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/serial_api.c b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/serial_api.c index 46f2dde5fc..b91e9f6771 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/serial_api.c +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/serial_api.c @@ -73,13 +73,17 @@ static HAL_GDMA_OP UartGdmaOp; #ifdef CONFIG_MBED_ENABLED #include "log_uart_api.h" + #include "hal_log_uart.h" + int stdio_uart_inited = 0; serial_t stdio_uart; log_uart_t stdio_uart_log; + static uint32_t serial_log_irq_ids; static uart_irq_handler log_irq_handler; static uint32_t serial_log_irq_en; + #endif static void SerialTxDoneCallBack(VOID *pAdapter); diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/spi_api.c b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/spi_api.c index b1e9109800..032d6117bb 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/spi_api.c +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/spi_api.c @@ -16,7 +16,7 @@ #include "objects.h" #include "spi_api.h" - +#include "spi_ex_api.h" #include "PinNames.h" #include "pinmap.h" #include "hal_ssi.h" @@ -32,6 +32,11 @@ void spi_tx_done_callback(VOID *obj); void spi_rx_done_callback(VOID *obj); void spi_bus_tx_done_callback(VOID *obj); +#ifdef CONFIG_GDMA_EN +HAL_GDMA_OP SpiGdmaOp; +#endif + +uint8_t SPI0_IS_AS_SLAVE = 0; //TODO: Load default Setting: It should be loaded from external setting file. extern const DW_SSI_DEFAULT_SETTING SpiDefaultSetting; @@ -73,10 +78,12 @@ void spi_init (spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName sse _memset((void*)obj, 0, sizeof(spi_t)); obj->state = 0; - /* SsiClockDivider doesn't support odd number */ + uint32_t SystemClock = SystemGetCpuClk(); + uint32_t MaxSsiFreq = (SystemClock >> 2) >> 1; - DBG_SSI_INFO("SystemClock: %d\n", SystemGetCpuClk()); - DBG_SSI_INFO("MaxSsiFreq : %d\n", SystemGetCpuClk() >> 3); + /* SsiClockDivider doesn't support odd number */ + DBG_SSI_INFO("SystemClock: %d\n", SystemClock); + DBG_SSI_INFO("MaxSsiFreq : %d\n", MaxSsiFreq); ssi_mosi = pinmap_peripheral(mosi, PinMap_SSI_MOSI); ssi_miso = pinmap_peripheral(miso, PinMap_SSI_MISO); @@ -119,7 +126,23 @@ void spi_init (spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName sse DBG_SSI_ERR(ANSI_COLOR_RED"spi_init(): SPI %x init fails.\n"ANSI_COLOR_RESET,pHalSsiAdaptor->Index); return; } - osDelay(1); + + pHalSsiAdaptor->TxCompCallback = spi_tx_done_callback; + pHalSsiAdaptor->TxCompCbPara = (void*)obj; + pHalSsiAdaptor->RxCompCallback = spi_rx_done_callback; + pHalSsiAdaptor->RxCompCbPara = (void*)obj; + pHalSsiAdaptor->TxIdleCallback = spi_bus_tx_done_callback; + pHalSsiAdaptor->TxIdleCbPara = (void*)obj; + +#ifdef CONFIG_GDMA_EN + HalGdmaOpInit((VOID*)&SpiGdmaOp); + pHalSsiAdaptor->DmaConfig.pHalGdmaOp = &SpiGdmaOp; + pHalSsiAdaptor->DmaConfig.pRxHalGdmaAdapter = &obj->spi_gdma_adp_rx; + pHalSsiAdaptor->DmaConfig.pTxHalGdmaAdapter = &obj->spi_gdma_adp_tx; + obj->dma_en = 0; + pHalSsiAdaptor->HaveTxChannel = 0; + pHalSsiAdaptor->HaveRxChannel = 0; +#endif } void spi_free (spi_t *obj) @@ -129,6 +152,17 @@ void spi_free (spi_t *obj) HalSsiDeInit(pHalSsiAdaptor); SPI0_MULTI_CS_CTRL(OFF); + +#ifdef CONFIG_GDMA_EN + if (obj->dma_en & SPI_DMA_RX_EN) { + HalSsiRxGdmaDeInit(pHalSsiAdaptor); + } + + if (obj->dma_en & SPI_DMA_TX_EN) { + HalSsiTxGdmaDeInit(pHalSsiAdaptor); + } + obj->dma_en = 0; +#endif } void spi_format (spi_t *obj, int bits, int mode, int slave) @@ -183,6 +217,7 @@ void spi_format (spi_t *obj, int bits, int mode, int slave) if (pHalSsiAdaptor->Index == 0) { pHalSsiAdaptor->Role = SSI_SLAVE; pHalSsiAdaptor->SlaveOutputEnable = SLV_TXD_ENABLE; // <-- Slave only + SPI0_IS_AS_SLAVE = 1; DBG_SSI_INFO("SPI0 is as slave\n"); } else { DBG_SSI_ERR("The SPI%d cannot work as Slave mode, only SPI0 does.\r\n", pHalSsiAdaptor->Index); @@ -247,10 +282,12 @@ int spi_master_block_write(spi_t *obj, const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length, char write_fill) { int total = (tx_length > rx_length) ? tx_length : rx_length; + int i; + char out, in; - for (int i = 0; i < total; i++) { - char out = (i < tx_length) ? tx_buffer[i] : write_fill; - char in = spi_master_write(obj, out); + for (i = 0; i < total; i++) { + out = (i < tx_length) ? tx_buffer[i] : write_fill; + in = spi_master_write(obj, out); if (i < rx_length) { rx_buffer[i] = in; } @@ -296,3 +333,40 @@ int spi_busy (spi_t *obj) } +// Bus Idle: Real TX done, TX FIFO empty and bus shift all data out already +void spi_bus_tx_done_callback(VOID *obj) +{ + spi_t *spi_obj = (spi_t *)obj; + spi_irq_handler handler; + + if (spi_obj->bus_tx_done_handler) { + handler = (spi_irq_handler)spi_obj->bus_tx_done_handler; + handler(spi_obj->bus_tx_done_irq_id, (SpiIrq)0); + } +} + +void spi_tx_done_callback(VOID *obj) +{ + spi_t *spi_obj = (spi_t *)obj; + spi_irq_handler handler; + + if (spi_obj->state & SPI_STATE_TX_BUSY) { + spi_obj->state &= ~SPI_STATE_TX_BUSY; + if (spi_obj->irq_handler) { + handler = (spi_irq_handler)spi_obj->irq_handler; + handler(spi_obj->irq_id, SpiTxIrq); + } + } +} + +void spi_rx_done_callback(VOID *obj) +{ + spi_t *spi_obj = (spi_t *)obj; + spi_irq_handler handler; + + spi_obj->state &= ~SPI_STATE_RX_BUSY; + if (spi_obj->irq_handler) { + handler = (spi_irq_handler)spi_obj->irq_handler; + handler(spi_obj->irq_id, SpiRxIrq); + } +} diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/spi_ex_api.h b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/spi_ex_api.h new file mode 100644 index 0000000000..e80a4981ec --- /dev/null +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/spi_ex_api.h @@ -0,0 +1,244 @@ +/* mbed Microcontroller Library + * Copyright (c) 2013-2016 Realtek Semiconductor Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MBED_SPI_EXT_API_H +#define MBED_SPI_EXT_API_H + +#include "device.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @addtogroup spi_ex SPI_EX + * @ingroup hal + * @brief spi extended functions + * @{ + */ + +///@name Ameba Common +///@{ + +#define SPI_DMA_RX_EN (1<<0) +#define SPI_DMA_TX_EN (1<<1) + +enum { + SPI_SCLK_IDLE_LOW=0, // the SCLK is Low when SPI is inactive + SPI_SCLK_IDLE_HIGH=2 // the SCLK is High when SPI is inactive +}; + +// SPI Master mode: for continuous transfer, how the CS toggle: +enum { + SPI_CS_TOGGLE_EVERY_FRAME=0, // let SCPH=0 then the CS toggle every frame + SPI_CS_TOGGLE_START_STOP=1 // let SCPH=1 the CS toggle at start and stop +}; + +enum { + SPI_SCLK_TOGGLE_MIDDLE=0, // Serial Clk toggle at middle of 1st data bit and latch data at 1st Clk edge + SPI_SCLK_TOGGLE_START=1 // Serial Clk toggle at start of 1st data bit and latch data at 2nd Clk edge +}; + +typedef enum { + CS_0 = 0, + CS_1 = 1, + CS_2 = 2, + CS_3 = 3, + CS_4 = 4, + CS_5 = 5, + CS_6 = 6, + CS_7 = 7 +}ChipSelect; + + +#define SPI_STATE_READY 0x00 +#define SPI_STATE_RX_BUSY (1<<1) +#define SPI_STATE_TX_BUSY (1<<2) + +typedef enum { + SpiRxIrq, + SpiTxIrq +} SpiIrq; + +typedef void (*spi_irq_handler)(uint32_t id, SpiIrq event); + +/** + * @brief Set SPI interrupt handler if needed. + * @param obj: spi object define in application software. + * @param handler: interrupt callback function + * @param id: interrupt callback parameter + * @retval none + */ +void spi_irq_hook(spi_t *obj, spi_irq_handler handler, uint32_t id); + +/** + * @brief Set SPI interrupt bus tx done handler if needed. + * @param obj: spi object define in application software. + * @param handler: interrupt bus tx done callback function + * @param id: interrupt callback parameter + * @retval none + */ +void spi_bus_tx_done_irq_hook(spi_t *obj, spi_irq_handler handler, uint32_t id); + +/** + * @brief Slave device to flush tx fifo. + * @param obj: spi slave object define in application software. + * @note : It will discard all data in both tx fifo and rx fifo + */ +void spi_slave_flush_fifo(spi_t * obj); + +/** + * @brief slave recv target length data use interrupt mode. + * @param obj: spi slave object define in application software. + * @param rx_buffer: buffer to save data read from SPI FIFO. + * @param length: number of data bytes to be read. + * @retval : stream init status + */ +int32_t spi_slave_read_stream(spi_t *obj, char *rx_buffer, uint32_t length); + +/** + * @brief slave send target length data use interrupt mode. + * @param obj: spi slave object define in application software. + * @param tx_buffer: buffer to be written to Tx FIFO. + * @param length: number of data bytes to be send. + * @retval : stream init status + */ +int32_t spi_slave_write_stream(spi_t *obj, char *tx_buffer, uint32_t length); + +/** + * @brief master recv target length data use interrupt mode. + * @param obj: spi master object define in application software. + * @param rx_buffer: buffer to save data read from SPI FIFO. + * @param length: number of data bytes to be read. + * @retval : stream init status + */ +int32_t spi_master_read_stream(spi_t *obj, char *rx_buffer, uint32_t length); + +/** + * @brief master send target length data use interrupt mode. + * @param obj: spi master object define in application software. + * @param tx_buffer: buffer to be written to Tx FIFO. + * @param length: number of data bytes to be send. + * @retval : stream init status + */ +int32_t spi_master_write_stream(spi_t *obj, char *tx_buffer, uint32_t length); + +/** + * @brief master send & recv target length data use interrupt mode. + * @param obj: spi master object define in application software. + * @param tx_buffer: buffer to be written to Tx FIFO. + * @param rx_buffer: buffer to save data read from SPI FIFO. + * @param length: number of data bytes to be send & recv. + * @retval : stream init status + */ +int32_t spi_master_write_read_stream(spi_t *obj, char *tx_buffer, char *rx_buffer, uint32_t length); + +/** + * @brief slave recv target length data use interrupt mode and timeout mechanism. + * @param obj: spi slave object define in application software. + * @param rx_buffer: buffer to save data read from SPI FIFO. + * @param length: number of data bytes to be read. + * @param timeout_ms: timeout waiting time. + * @retval : number of bytes read already + */ +int32_t spi_slave_read_stream_timeout(spi_t *obj, char *rx_buffer, uint32_t length, uint32_t timeout_ms); + +/** + * @brief slave recv target length data use interrupt mode and stop if the spi bus is idle. + * @param obj: spi slave object define in application software. + * @param rx_buffer: buffer to save data read from SPI FIFO. + * @param length: number of data bytes to be read. + * @retval : number of bytes read already + */ +int32_t spi_slave_read_stream_terminate(spi_t *obj, char *rx_buffer, uint32_t length); + +//#ifdef CONFIG_GDMA_EN +/** + * @brief slave recv target length data use DMA mode. + * @param obj: spi slave object define in application software. + * @param rx_buffer: buffer to save data read from SPI FIFO. + * @param length: number of data bytes to be read. + * @retval : stream init status + */ +int32_t spi_slave_read_stream_dma(spi_t *obj, char *rx_buffer, uint32_t length); + +/** + * @brief slave send target length data use DMA mode. + * @param obj: spi slave object define in application software. + * @param tx_buffer: buffer to be written to Tx FIFO. + * @param length: number of data bytes to be send. + * @retval : stream init status + */ +int32_t spi_slave_write_stream_dma(spi_t *obj, char *tx_buffer, uint32_t length); + +/** + * @brief master send & recv target length data use DMA mode. + * @param obj: spi master object define in application software. + * @param tx_buffer: buffer to be written to Tx FIFO. + * @param rx_buffer: buffer to save data read from SPI FIFO. + * @param length: number of data bytes to be send & recv. + * @retval : stream init status + */ +int32_t spi_master_write_read_stream_dma(spi_t * obj, char * tx_buffer, char * rx_buffer, uint32_t length); + +/** + * @brief master recv target length data use DMA mode. + * @param obj: spi master object define in application software. + * @param rx_buffer: buffer to save data read from SPI FIFO. + * @param length: number of data bytes to be read. + * @retval : stream init status + * @note : DMA or Interrupt mode can be used to TX dummy data + */ +int32_t spi_master_read_stream_dma(spi_t *obj, char *rx_buffer, uint32_t length); + +/** + * @brief master send target length data use DMA mode. + * @param obj: spi master object define in application software. + * @param tx_buffer: buffer to be written to Tx FIFO. + * @param length: number of data bytes to be send. + * @retval : stream init status + */ +int32_t spi_master_write_stream_dma(spi_t *obj, char *tx_buffer, uint32_t length); + +/** + * @brief slave recv target length data use DMA mode and timeout mechanism. + * @param obj: spi slave object define in application software. + * @param rx_buffer: buffer to save data read from SPI FIFO. + * @param length: number of data bytes to be read. + * @param timeout_ms: timeout waiting time. + * @retval : number of bytes read already + */ +int32_t spi_slave_read_stream_dma_timeout(spi_t *obj, char *rx_buffer, uint32_t length, uint32_t timeout_ms); + +/** + * @brief slave recv target length data use DMA mode and stop if the spi bus is idle. + * @param obj: spi slave object define in application software. + * @param rx_buffer: buffer to save data read from SPI FIFO. + * @param length: number of data bytes to be read. + * @retval : number of bytes read already + */ +int32_t spi_slave_read_stream_dma_terminate(spi_t * obj, char * rx_buffer, uint32_t length); +//#endif + +///@} + +/*\@}*/ + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/timer_api.c b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/timer_api.c index a82fe441e8..c67a2045fb 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/timer_api.c +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/timer_api.c @@ -76,7 +76,7 @@ void gtimer_init (gtimer_t *obj, uint32_t tid) pTimerAdapter->TimerIrqPriority = 0; pTimerAdapter->TimerLoadValueUs = 0xFFFFFFFF; // Just a whatever value pTimerAdapter->TimerMode = USER_DEFINED; - + HalTimerInit ((VOID*) pTimerAdapter); } diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/timer_api.h b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/timer_api.h index 7ad983c26e..33c61a3761 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/timer_api.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/timer_api.h @@ -29,7 +29,7 @@ enum { TIMER3 = 5, // GTimer 5, share with PWM_2 TIMER4 = 0, // GTimer 0, share with software-RTC functions - GTIMER_MAX = 5 + GTIMER_MAX = 5 }; void gtimer_init (gtimer_t *obj, uint32_t tid); diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/trng_api.c b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/trng_api.c index 5dd1b92faa..c708c2318b 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/trng_api.c +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/trng_api.c @@ -27,7 +27,7 @@ void trng_init(trng_t *obj) { _memset((void *)obj, 0, sizeof(trng_t)); - analogin_init(&obj->tradcng, ADC0); + analogin_init(&obj->tradcng, (PinName)ADC0); obj->inited = 1; } diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/us_ticker.c b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/us_ticker.c index 81bff2a2fa..40cb05c136 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/us_ticker.c +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/us_ticker.c @@ -97,7 +97,7 @@ void us_ticker_set_interrupt(timestamp_t timestamp) HalTimerOp.HalTimerDis((u32)TimerAdapter.TimerId); HalTimerOpExt.HalTimerReLoad((u32)TimerAdapter.TimerId, TimerAdapter.TimerLoadValueUs); - HalTimerOpExt.HalTimerSync(SYS_TIM_ID); + //HalTimerOpExt.HalTimerSync(SYS_TIM_ID); HalTimerOp.HalTimerEn((u32)TimerAdapter.TimerId); } @@ -107,7 +107,7 @@ void us_ticker_fire_interrupt(void) HalTimerOp.HalTimerDis((u32)TimerAdapter.TimerId); HalTimerOpExt.HalTimerReLoad((u32)TimerAdapter.TimerId, TimerAdapter.TimerLoadValueUs); - HalTimerOpExt.HalTimerSync(SYS_TIM_ID); + //HalTimerOpExt.HalTimerSync(SYS_TIM_ID); HalTimerOp.HalTimerEn((u32)TimerAdapter.TimerId); } diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/rtw_emac.cpp b/targets/TARGET_Realtek/TARGET_AMEBA/rtw_emac.cpp index 5b243a623e..6580b83e2a 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/rtw_emac.cpp +++ b/targets/TARGET_Realtek/TARGET_AMEBA/rtw_emac.cpp @@ -76,6 +76,7 @@ bool RTW_EMAC::get_hwaddr(uint8_t *addr) const } else { printf("Get HW address failed\r\n"); } + return true; } void RTW_EMAC::set_hwaddr(const uint8_t *addr) diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/platform/platform_stdlib.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/platform/platform_stdlib.h index c6dfcf1f69..d3b7499fc1 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/platform/platform_stdlib.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/platform/platform_stdlib.h @@ -16,272 +16,41 @@ #ifndef __PLATFORM_STDLIB_H__ #define __PLATFORM_STDLIB_H__ -#define USE_CLIB_PATCH 0 -#if defined (__GNUC__) -/* build rom should set USE_RTL_ROM_CLIB=0 */ -#ifndef CONFIG_MBED_ENABLED -#include -#endif +#ifdef __cplusplus +extern "C" { #endif -#ifdef CONFIG_BUILD_ROM -#define USE_RTL_ROM_CLIB 0 -#else -#define BUFFERED_PRINTF 0 -#ifndef CONFIG_MBED_ENABLED -#define USE_RTL_ROM_CLIB 1 -#else -#define USE_RTL_ROM_CLIB 0 -#endif +#if defined(CONFIG_PLATFORM_8195A)+\ + defined(CONFIG_PLATFORM_8711B)+\ + defined(CONFIG_PLATFORM_8721D)+\ + defined(CONFIG_PLATFORM_8195BHP)+\ + defined(USE_STM322xG_EVAL)+\ + defined(USE_STM324xG_EVAL)+\ + defined(STM32F10X_XL) > 1 + #error "Cannot define two or more platform at one time" #endif #if defined(CONFIG_PLATFORM_8195A) -#if defined (__IARSTDLIB__) - #include - #include - #include - #include - #include "diag.h" - - #define strsep(str, delim) _strsep(str, delim) -#elif defined (__CC_ARM) - #include - #include - #include - #include - #include "diag.h" - #define strsep(str, delim) _strsep(str, delim) - #define _memset(dst, val, sz) memset(dst, val, sz) -#else - #include - #include - #include - #include "diag.h" - #include "strproc.h" - #include "basic_types.h" - #include "hal_misc.h" - #if USE_RTL_ROM_CLIB - #include "rtl_lib.h" - #endif - - #undef printf - #undef sprintf - #undef snprintf - #undef atoi - #undef memcmp - #undef memcpy - #undef memset - #undef strcmp - #undef strcpy - #undef strlen - #undef strncmp - #undef strncpy - #undef strsep - #undef strtok - #if USE_RTL_ROM_CLIB - #undef memchr - #undef memmove - #undef strcat - #undef strchr - #undef strncat - #undef strstr - #endif - - #if USE_RTL_ROM_CLIB -#if BUFFERED_PRINTF - extern int buffered_printf(const char* fmt, ...); - #define printf buffered_printf -#else - #define printf rtl_printf -#endif - #define sprintf rtl_sprintf - #define snprintf rtl_snprintf - #define memchr rtl_memchr - #define memcmp rtl_memcmp - #define memcpy rtl_memcpy - #define memmove rtl_memmove - #define memset rtl_memset - #define strcat rtl_strcat - #define strchr rtl_strchr - #define strcmp(s1, s2) rtl_strcmp((const char *)s1, (const char *)s2) - #define strcpy rtl_strcpy - #define strlen(str) rtl_strlen((const char *)str) - #define strncat rtl_strncat - #define strncmp(s1, s2, n) rtl_strncmp((const char *)s1, (const char *)s2, n) - #define strncpy rtl_strncpy - #define strstr rtl_strstr - #define strsep rtl_strsep - #define strtok rtl_strtok - #else - #if USE_CLIB_PATCH - extern int DiagSscanfPatch(const char *buf, const char *fmt, ...); - extern char* DiagStrtokPatch(char *str, const char* delim); - extern char* DiagStrstrPatch(char *string, char *substring); - extern int DiagSnPrintfPatch(char *buf, size_t size, const char *fmt, ...); - extern u32 DiagPrintfPatch(const char *fmt, ...); - extern u32 DiagSPrintfPatch(u8 *buf, const char *fmt, ...); - #define printf DiagPrintfPatch - #define sprintf DiagSPrintfPatch - #define snprintf DiagSnPrintfPatch - #define strstr(a, b) DiagStrstrPatch((char *)(a), (char *)(b)) - #define strtok DiagStrtokPatch - #else - #define printf DiagPrintf - #define sprintf(fmt, arg...) DiagSPrintf((u8*)fmt, ##arg) - #if defined (__GNUC__) - #define snprintf DiagSnPrintf // NULL function - #define strstr(str1, str2) prvStrStr(str1, str2) // NULL function - #endif - #define strtok(str, delim) _strsep(str, delim) - #endif - #define memcmp(dst, src, sz) _memcmp(dst, src, sz) - #define memcpy(dst, src, sz) _memcpy(dst, src, sz) - #define memset(dst, val, sz) _memset(dst, val, sz) - #define strchr(s, c) _strchr(s, c) // for B-cut ROM - #define strcmp(str1, str2) prvStrCmp((const unsigned char *) str1, (const unsigned char *) str2) - #define strcpy(dest, src) _strcpy(dest, src) - #define strlen(str) prvStrLen((const unsigned char *) str) - #define strncmp(str1, str2, cnt) _strncmp(str1, str2, cnt) - #define strncpy(dest, src, count) _strncpy(dest, src, count) - #define strsep(str, delim) _strsep(str, delim) - #endif - - #define atoi(str) prvAtoi(str) - #define strpbrk(cs, ct) _strpbrk(cs, ct) // for B-cut ROM - - #if USE_CLIB_PATCH - #undef sscanf - #define sscanf DiagSscanfPatch - #else - #if defined (__GNUC__) - #undef sscanf //_sscanf - //extern int DiagSscanfPatch(const char *buf, const char *fmt, ...); - //#define sscanf DiagSscanfPatch - #define sscanf sscanf // use libc sscanf - #endif - #endif -#endif // defined (__IARSTDLIB__) - -// -// memory management -// -#ifndef CONFIG_MBED_ENABLED -extern void *pvPortMalloc( size_t xWantedSize ); -extern void vPortFree( void *pv ); -#define malloc pvPortMalloc -#define free vPortFree -#endif + #include "platform_stdlib_rtl8195a.h" #elif defined (CONFIG_PLATFORM_8711B) - -#if defined (__IARSTDLIB__) - #include - #include - #include - #include - #include /* va_list */ - #include "diag.h" - - #define strsep(str, delim) _strsep(str, delim) -#else - #include - #include - #include - #include /* va_list */ - #include "diag.h" - #include "strproc.h" - #include "memproc.h" - #include "basic_types.h" -#if USE_RTL_ROM_CLIB - #include "rtl_lib.h" - #include "rom_libc_string.h" -#endif - - #undef printf - #undef sprintf - #undef snprintf - #undef memchr - #undef memcmp - #undef memcpy - #undef memset - #undef memmove - #undef strcmp - #undef strcpy - #undef strlen - #undef strncmp - #undef strncpy - #undef strsep - #undef strtok - #undef strcat - #undef strchr - #undef strncat - #undef strstr - #undef atol - #undef atoi - #undef strpbrk - -#if USE_RTL_ROM_CLIB -#if BUFFERED_PRINTF - extern int buffered_printf(const char* fmt, ...); - #define printf buffered_printf -#else - #define printf rtl_printf -#endif - #define sprintf rtl_sprintf - #define snprintf rtl_snprintf - #define vsnprintf rtl_vsnprintf -#else - #define printf DiagPrintf - #define sprintf(fmt, arg...) DiagSPrintf((u8*)fmt, ##arg) - #define snprintf DiagSnPrintf // NULL function - #define vsnprintf(buf, size, fmt, ap) VSprintf(buf, fmt, ap) -#endif - #define memchr __rtl_memchr_v1_00 - #define memcmp(dst, src, sz) _memcmp(dst, src, sz) - #define memcpy(dst, src, sz) _memcpy(dst, src, sz) - #define memmove __rtl_memmove_v1_00 - #define memset(dst, val, sz) _memset(dst, val, sz) - - #define strchr(s, c) _strchr(s, c) // for B-cut ROM - #define strcmp(str1, str2) prvStrCmp((const unsigned char *) str1, (const unsigned char *) str2) - #define strcpy(dest, src) _strcpy(dest, src) - #define strlen(str) prvStrLen((const unsigned char *) str) - #define strsep(str, delim) _strsep(str, delim) - #define strstr(str1, str2) prvStrStr(str1, str2) // NULL function - #define strtok(str, delim) prvStrtok(str, delim)//_strsep(str, delim) - #define strcat __rtl_strcat_v1_00 - - #define strncmp(str1, str2, cnt) _strncmp(str1, str2, cnt) - #define strncpy(dest, src, count) _strncpy(dest, src, count) - #define strncat __rtl_strncat_v1_00 - - #define atol(str) strtol(str,NULL,10) - #define atoi(str) prvAtoi(str) - #define strpbrk(cs, ct) _strpbrk(cs, ct) // for B-cut ROM -#if defined (__GNUC__) - #undef sscanf - #define sscanf _sscanf_patch - #define rand Rand -#endif - //extern int _sscanf_patch(const char *buf, const char *fmt, ...); - //#define sscanf _sscanf_patch - - -#endif // defined (__IARSTDLIB__) - -// -// memory management -// -extern void *pvPortMalloc( size_t xWantedSize ); -extern void vPortFree( void *pv ); -#define malloc pvPortMalloc -#define free vPortFree + #include "platform_stdlib_rtl8711b.h" +#elif defined (CONFIG_PLATFORM_8721D) + #include "platform_stdlib_rtl8721d.h" +#elif defined(CONFIG_PLATFORM_8195BHP) + #include "platform_stdlib_rtl8195bhp.h" #elif defined(USE_STM322xG_EVAL) || defined(USE_STM324xG_EVAL) || defined(STM32F10X_XL) - #include - #include - #include - #include + #include "platform_stdlib_stm32.h" +#elif defined (CONFIG_PLATFORM_8710C) + #include "platform_stdlib_rtl8710c.h" +#else + #error "Undefined Platform stdlib" #endif +#if (CONFIG_PLATFORM_AMEBA_X == 0) +#include "basic_types.h" +#endif +#ifdef __cplusplus +} +#endif #endif //__PLATFORM_STDLIB_H__ - diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/platform/platform_stdlib_rtl8195a.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/platform/platform_stdlib_rtl8195a.h new file mode 100644 index 0000000000..84ee1c4727 --- /dev/null +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/platform/platform_stdlib_rtl8195a.h @@ -0,0 +1,166 @@ +#ifndef PLATFORM_STDLIB_RTL8195A_H +#define PLATFORM_STDLIB_RTL8195A_H + +#define USE_CLIB_PATCH 0 + +#if defined (__GNUC__) + /* build rom should set USE_RTL_ROM_CLIB=0 */ + #if !defined(CONFIG_MBED_ENABLED) + #include + #endif +#endif + +#if defined(CONFIG_BUILD_ROM) || defined(CONFIG_MBED_ENABLED) + #define USE_RTL_ROM_CLIB 0 +#else + #define BUFFERED_PRINTF 0 + #define USE_RTL_ROM_CLIB 1 +#endif + +#if defined (__IARSTDLIB__) + #include + #include + #include + #include + #include "diag.h" + + #define strsep(str, delim) _strsep(str, delim) +#elif defined (__CC_ARM) + #include + #include + #include + #include + #include "diag.h" + #define strsep(str, delim) _strsep(str, delim) +#elif defined (CONFIG_MBED_ENABLED) + #include + #include + #include + #include + #include "diag.h" + + #define strsep(str, delim) _strsep(str, delim) +#else + #include + #include + #include + #include "diag.h" + #include "strproc.h" + #include "basic_types.h" + #include "hal_misc.h" + #if USE_RTL_ROM_CLIB + #include "rtl_lib.h" + #endif + + #undef printf + #undef sprintf + #undef snprintf + #undef atoi + #undef memcmp + #undef memcpy + #undef memset + #undef strcmp + #undef strcpy + #undef strlen + #undef strncmp + #undef strncpy + #undef strsep + #undef strtok + #if USE_RTL_ROM_CLIB + #undef memchr + #undef memmove + #undef strcat + #undef strchr + #undef strncat + #undef strstr + #endif + + #if USE_RTL_ROM_CLIB + #if BUFFERED_PRINTF + extern int buffered_printf(const char* fmt, ...); + #define printf buffered_printf + #else + #define printf rtl_printf + #endif + + #define sprintf rtl_sprintf + #define snprintf rtl_snprintf + #define memchr rtl_memchr + #define memcmp rtl_memcmp + #define memcpy rtl_memcpy + #define memmove rtl_memmove + #define memset rtl_memset + #define strcat rtl_strcat + #define strchr rtl_strchr + #define strcmp(s1, s2) rtl_strcmp((const char *)s1, (const char *)s2) + #define strcpy rtl_strcpy + #define strlen(str) rtl_strlen((const char *)str) + #define strncat rtl_strncat + #define strncmp(s1, s2, n) rtl_strncmp((const char *)s1, (const char *)s2, n) + #define strncpy rtl_strncpy + #define strstr rtl_strstr + #define strsep rtl_strsep + #define strtok rtl_strtok + #else + #if USE_CLIB_PATCH + extern int DiagSscanfPatch(const char *buf, const char *fmt, ...); + extern char* DiagStrtokPatch(char *str, const char* delim); + extern char* DiagStrstrPatch(char *string, char *substring); + extern int DiagSnPrintfPatch(char *buf, size_t size, const char *fmt, ...); + extern u32 DiagPrintfPatch(const char *fmt, ...); + extern u32 DiagSPrintfPatch(u8 *buf, const char *fmt, ...); + #define printf DiagPrintfPatch + #define sprintf DiagSPrintfPatch + #define snprintf DiagSnPrintfPatch + #define strstr(a, b) DiagStrstrPatch((char *)(a), (char *)(b)) + #define strtok DiagStrtokPatch + #else + #define printf DiagPrintf + #define sprintf(fmt, arg...) DiagSPrintf((u8*)fmt, ##arg) + #if defined (__GNUC__) + #define snprintf DiagSnPrintf // NULL function + #define strstr(str1, str2) prvStrStr(str1, str2) // NULL function + #endif + #define strtok(str, delim) _strsep(str, delim) + #endif + #define memcmp(dst, src, sz) _memcmp(dst, src, sz) + #define memcpy(dst, src, sz) _memcpy(dst, src, sz) + #define memset(dst, val, sz) _memset(dst, val, sz) + #define strchr(s, c) _strchr(s, c) // for B-cut ROM + #define strcmp(str1, str2) prvStrCmp((const unsigned char *) str1, (const unsigned char *) str2) + #define strcpy(dest, src) _strcpy(dest, src) + #define strlen(str) prvStrLen((const unsigned char *) str) + #define strncmp(str1, str2, cnt) _strncmp(str1, str2, cnt) + #define strncpy(dest, src, count) _strncpy(dest, src, count) + #define strsep(str, delim) _strsep(str, delim) + #endif + + #define atoi(str) prvAtoi(str) + #define strpbrk(cs, ct) _strpbrk(cs, ct) // for B-cut ROM + + #if USE_CLIB_PATCH + #undef sscanf + #define sscanf DiagSscanfPatch + #else + #if defined (__GNUC__) + #undef sscanf //_sscanf + //extern int DiagSscanfPatch(const char *buf, const char *fmt, ...); + //#define sscanf DiagSscanfPatch + #define sscanf sscanf // use libc sscanf + #endif + #endif +#endif // defined (__IARSTDLIB__) + +// +// memory management +// +#if defined(CONFIG_MBED_ENABLED) + //use libc memory functions +#else + extern void *pvPortMalloc( size_t xWantedSize ); + extern void vPortFree( void *pv ); + #define malloc pvPortMalloc + #define free vPortFree +#endif + +#endif // PLATFORM_STDLIB_RTL8195A_H diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/wifi/wifi_conf.c b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/wifi/wifi_conf.c deleted file mode 100644 index 4902ada864..0000000000 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/wifi/wifi_conf.c +++ /dev/null @@ -1,1967 +0,0 @@ -/* Copyright (c) 2013-2016 Realtek Semiconductor Corp. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -//#include -//#include -#include -#include -#include -#include -#include "tcpip.h" -#include -#ifndef CONFIG_MBED_ENABLED -#include // -#endif -#if CONFIG_EXAMPLE_WLAN_FAST_CONNECT || CONFIG_JD_SMART -#include "wlan_fast_connect/example_wlan_fast_connect.h" -#endif -#if CONFIG_EXAMPLE_UART_ATCMD -#include "at_cmd/atcmd_wifi.h" -#endif -extern u32 GlobalDebugEnable; -#define WIFI_CONF_MSG(...) do {\ - if (GlobalDebugEnable) \ - printf("\r" __VA_ARGS__);\ -}while(0) - -#if CONFIG_INIC_EN -extern int inic_start(void); -extern int inic_stop(void); -#endif - -/****************************************************** - * Constants - ******************************************************/ -#define SCAN_USE_SEMAPHORE 0 - -#define RTW_JOIN_TIMEOUT 15000 - -#define JOIN_ASSOCIATED (uint32_t)(1 << 0) -#define JOIN_AUTHENTICATED (uint32_t)(1 << 1) -#define JOIN_LINK_READY (uint32_t)(1 << 2) -#define JOIN_SECURITY_COMPLETE (uint32_t)(1 << 3) -#define JOIN_COMPLETE (uint32_t)(1 << 4) -#define JOIN_NO_NETWORKS (uint32_t)(1 << 5) -#define JOIN_WRONG_SECURITY (uint32_t)(1 << 6) -#define JOIN_HANDSHAKE_DONE (uint32_t)(1 << 7) -#define JOIN_SIMPLE_CONFIG (uint32_t)(1 << 8) -#define JOIN_AIRKISS (uint32_t)(1 << 9) - -/****************************************************** - * Type Definitions - ******************************************************/ - -/****************************************************** - * Variables Declarations - ******************************************************/ -#if !defined(CONFIG_MBED_ENABLED) -extern struct netif xnetif[NET_IF_NUM]; -#endif -/****************************************************** - * Variables Definitions - ******************************************************/ -static internal_scan_handler_t scan_result_handler_ptr = {0, 0, 0, RTW_FALSE, 0, 0, 0, 0, 0}; -static internal_join_result_t* join_user_data; -#ifdef CONFIG_MBED_ENABLED -static rtw_mode_t wifi_mode = RTW_MODE_STA; -#else -extern rtw_mode_t wifi_mode; -#endif -int error_flag = RTW_UNKNOWN; -uint32_t rtw_join_status; -#if ATCMD_VER == ATVER_2 -extern unsigned char dhcp_mode_sta; -#endif - -/****************************************************** - * Variables Definitions - ******************************************************/ - -#ifndef WLAN0_NAME - #define WLAN0_NAME "wlan0" -#endif -#ifndef WLAN1_NAME - #define WLAN1_NAME "wlan1" -#endif -/* Give default value if not defined */ -#ifndef NET_IF_NUM -#ifdef CONFIG_CONCURRENT_MODE -#define NET_IF_NUM 2 -#else -#define NET_IF_NUM 1 -#endif -#endif - -/*Static IP ADDRESS*/ -#ifndef IP_ADDR0 -#define IP_ADDR0 192 -#define IP_ADDR1 168 -#define IP_ADDR2 1 -#define IP_ADDR3 80 -#endif - -/*NETMASK*/ -#ifndef NETMASK_ADDR0 -#define NETMASK_ADDR0 255 -#define NETMASK_ADDR1 255 -#define NETMASK_ADDR2 255 -#define NETMASK_ADDR3 0 -#endif - -/*Gateway Address*/ -#ifndef GW_ADDR0 -#define GW_ADDR0 192 -#define GW_ADDR1 168 -#define GW_ADDR2 1 -#define GW_ADDR3 1 -#endif - -/*Static IP ADDRESS*/ -#ifndef AP_IP_ADDR0 -#define AP_IP_ADDR0 192 -#define AP_IP_ADDR1 168 -#define AP_IP_ADDR2 43 -#define AP_IP_ADDR3 1 -#endif - -/*NETMASK*/ -#ifndef AP_NETMASK_ADDR0 -#define AP_NETMASK_ADDR0 255 -#define AP_NETMASK_ADDR1 255 -#define AP_NETMASK_ADDR2 255 -#define AP_NETMASK_ADDR3 0 -#endif - -/*Gateway Address*/ -#ifndef AP_GW_ADDR0 -#define AP_GW_ADDR0 192 -#define AP_GW_ADDR1 168 -#define AP_GW_ADDR2 43 -#define AP_GW_ADDR3 1 -#endif - -/****************************************************** - * Function Definitions - ******************************************************/ - -#if CONFIG_WLAN -//----------------------------------------------------------------------------// -static int wifi_connect_local(rtw_network_info_t *pWifi) -{ - int ret = 0; - - if(is_promisc_enabled()) - promisc_set(0, NULL, 0); - - /* lock 4s to forbid suspend under linking */ - rtw_wakelock_timeout(4 *1000); - - if(!pWifi) return -1; - switch(pWifi->security_type){ - case RTW_SECURITY_OPEN: - ret = wext_set_key_ext(WLAN0_NAME, IW_ENCODE_ALG_NONE, NULL, 0, 0, 0, 0, NULL, 0); - break; - case RTW_SECURITY_WEP_PSK: - case RTW_SECURITY_WEP_SHARED: - ret = wext_set_auth_param(WLAN0_NAME, IW_AUTH_80211_AUTH_ALG, IW_AUTH_ALG_SHARED_KEY); - if(ret == 0) - ret = wext_set_key_ext(WLAN0_NAME, IW_ENCODE_ALG_WEP, NULL, pWifi->key_id, 1 /* set tx key */, 0, 0, pWifi->password, pWifi->password_len); - break; - case RTW_SECURITY_WPA_TKIP_PSK: - case RTW_SECURITY_WPA2_TKIP_PSK: - ret = wext_set_auth_param(WLAN0_NAME, IW_AUTH_80211_AUTH_ALG, IW_AUTH_ALG_OPEN_SYSTEM); - if(ret == 0) - ret = wext_set_key_ext(WLAN0_NAME, IW_ENCODE_ALG_TKIP, NULL, 0, 0, 0, 0, NULL, 0); - if(ret == 0) - ret = wext_set_passphrase(WLAN0_NAME, pWifi->password, pWifi->password_len); - break; - case RTW_SECURITY_WPA_AES_PSK: - case RTW_SECURITY_WPA2_AES_PSK: - case RTW_SECURITY_WPA2_MIXED_PSK: - case RTW_SECURITY_WPA_WPA2_MIXED: - ret = wext_set_auth_param(WLAN0_NAME, IW_AUTH_80211_AUTH_ALG, IW_AUTH_ALG_OPEN_SYSTEM); - if(ret == 0) - ret = wext_set_key_ext(WLAN0_NAME, IW_ENCODE_ALG_CCMP, NULL, 0, 0, 0, 0, NULL, 0); - if(ret == 0) - ret = wext_set_passphrase(WLAN0_NAME, pWifi->password, pWifi->password_len); - break; - default: - ret = -1; - WIFI_CONF_MSG("\n\rWIFICONF: security type(0x%x) is not supported.\n\r", pWifi->security_type); - break; - } - if(ret == 0) - ret = wext_set_ssid(WLAN0_NAME, pWifi->ssid.val, pWifi->ssid.len); - return ret; -} - -static int wifi_connect_bssid_local(rtw_network_info_t *pWifi) -{ - int ret = 0; - u8 bssid[12] = {0}; - - if(is_promisc_enabled()) - promisc_set(0, NULL, 0); - - /* lock 4s to forbid suspend under linking */ - rtw_wakelock_timeout(4 *1000); - - if(!pWifi) return -1; - switch(pWifi->security_type){ - case RTW_SECURITY_OPEN: - ret = wext_set_key_ext(WLAN0_NAME, IW_ENCODE_ALG_NONE, NULL, 0, 0, 0, 0, NULL, 0); - break; - case RTW_SECURITY_WEP_PSK: - case RTW_SECURITY_WEP_SHARED: - ret = wext_set_auth_param(WLAN0_NAME, IW_AUTH_80211_AUTH_ALG, IW_AUTH_ALG_SHARED_KEY); - if(ret == 0) - ret = wext_set_key_ext(WLAN0_NAME, IW_ENCODE_ALG_WEP, NULL, pWifi->key_id, 1 /* set tx key */, 0, 0, pWifi->password, pWifi->password_len); - break; - case RTW_SECURITY_WPA_TKIP_PSK: - case RTW_SECURITY_WPA2_TKIP_PSK: - ret = wext_set_auth_param(WLAN0_NAME, IW_AUTH_80211_AUTH_ALG, IW_AUTH_ALG_OPEN_SYSTEM); - if(ret == 0) - ret = wext_set_key_ext(WLAN0_NAME, IW_ENCODE_ALG_TKIP, NULL, 0, 0, 0, 0, NULL, 0); - if(ret == 0) - ret = wext_set_passphrase(WLAN0_NAME, pWifi->password, pWifi->password_len); - break; - case RTW_SECURITY_WPA_AES_PSK: - case RTW_SECURITY_WPA2_AES_PSK: - case RTW_SECURITY_WPA2_MIXED_PSK: - ret = wext_set_auth_param(WLAN0_NAME, IW_AUTH_80211_AUTH_ALG, IW_AUTH_ALG_OPEN_SYSTEM); - if(ret == 0) - ret = wext_set_key_ext(WLAN0_NAME, IW_ENCODE_ALG_CCMP, NULL, 0, 0, 0, 0, NULL, 0); - if(ret == 0) - ret = wext_set_passphrase(WLAN0_NAME, pWifi->password, pWifi->password_len); - break; - default: - ret = -1; - WIFI_CONF_MSG("\n\rWIFICONF: security type(0x%x) is not supported.\n\r", pWifi->security_type); - break; - } - if(ret == 0){ - memcpy(bssid, pWifi->bssid.octet, ETH_ALEN); - if(pWifi->ssid.len){ - bssid[ETH_ALEN] = '#'; - bssid[ETH_ALEN + 1] = '@'; - memcpy(bssid + ETH_ALEN + 2, &pWifi, sizeof(pWifi)); - } - ret = wext_set_bssid(WLAN0_NAME, bssid); - } - return ret; -} - -void wifi_rx_beacon_hdl( char* buf, int buf_len, int flags, void* userdata) { - //printf("Beacon!\n"); -} - - -static void wifi_no_network_hdl(char* buf, int buf_len, int flags, void* userdata) -{ - if(join_user_data!=NULL) - rtw_join_status = JOIN_NO_NETWORKS; -} - -static void wifi_connected_hdl( char* buf, int buf_len, int flags, void* userdata) -{ -#ifdef CONFIG_ENABLE_EAP - if(get_eap_phase()){ - rtw_join_status = JOIN_COMPLETE | JOIN_SECURITY_COMPLETE | JOIN_ASSOCIATED | JOIN_AUTHENTICATED | JOIN_LINK_READY; - return; - } -#endif /* CONFIG_ENABLE_EAP */ - - if((join_user_data!=NULL)&&((join_user_data->network_info.security_type == RTW_SECURITY_OPEN) || - (join_user_data->network_info.security_type == RTW_SECURITY_WEP_PSK) || - (join_user_data->network_info.security_type == RTW_SECURITY_WEP_SHARED))){ - rtw_join_status = JOIN_COMPLETE | JOIN_SECURITY_COMPLETE | JOIN_ASSOCIATED | JOIN_AUTHENTICATED | JOIN_LINK_READY; - rtw_up_sema(&join_user_data->join_sema); - }else if((join_user_data!=NULL)&&((join_user_data->network_info.security_type == RTW_SECURITY_WPA2_AES_PSK) )){ - rtw_join_status = JOIN_COMPLETE | JOIN_SECURITY_COMPLETE | JOIN_ASSOCIATED | JOIN_AUTHENTICATED | JOIN_LINK_READY; - } -} -static void wifi_handshake_done_hdl( char* buf, int buf_len, int flags, void* userdata) -{ - rtw_join_status = JOIN_COMPLETE | JOIN_SECURITY_COMPLETE | JOIN_ASSOCIATED | JOIN_AUTHENTICATED | JOIN_LINK_READY|JOIN_HANDSHAKE_DONE; - if(join_user_data != NULL) - rtw_up_sema(&join_user_data->join_sema); -} - -static void wifi_disconn_hdl( char* buf, int buf_len, int flags, void* userdata) -{ - if(join_user_data != NULL){ - if(join_user_data->network_info.security_type == RTW_SECURITY_OPEN){ - - if(rtw_join_status == JOIN_NO_NETWORKS) - error_flag = RTW_NONE_NETWORK; - - }else if(join_user_data->network_info.security_type == RTW_SECURITY_WEP_PSK){ - - if(rtw_join_status == JOIN_NO_NETWORKS) - error_flag = RTW_NONE_NETWORK; - - else if(rtw_join_status == 0) - error_flag = RTW_CONNECT_FAIL; - - }else if(join_user_data->network_info.security_type == RTW_SECURITY_WPA2_AES_PSK){ - - if(rtw_join_status ==JOIN_NO_NETWORKS) - error_flag = RTW_NONE_NETWORK; - - else if(rtw_join_status == 0) - error_flag = RTW_CONNECT_FAIL; - - else if(rtw_join_status == (JOIN_COMPLETE | JOIN_SECURITY_COMPLETE | JOIN_ASSOCIATED | JOIN_AUTHENTICATED | JOIN_LINK_READY)) - error_flag = RTW_WRONG_PASSWORD; - } - - }else{ - if(error_flag == RTW_NO_ERROR) //wifi_disconn_hdl will be dispatched one more time after join_user_data = NULL add by frankie - error_flag = RTW_UNKNOWN; - } - - if(join_user_data != NULL) - rtw_up_sema(&join_user_data->join_sema); - //printf("\r\nWiFi Disconnect. Error flag is %d.\n", error_flag); -} - -#if CONFIG_EXAMPLE_WLAN_FAST_CONNECT || CONFIG_JD_SMART -#define WLAN0_NAME "wlan0" - -void restore_wifi_info_to_flash() -{ - - struct wlan_fast_reconnect * data_to_flash; - u32 channel = 0; - u8 index = 0; - u8 *ifname[1] = {WLAN0_NAME}; - rtw_wifi_setting_t setting; - //struct security_priv *psecuritypriv = &padapter->securitypriv; - //WLAN_BSSID_EX *pcur_bss = pmlmepriv->cur_network.network; - - data_to_flash = (struct wlan_fast_reconnect *)rtw_zmalloc(sizeof(struct wlan_fast_reconnect)); - - if(data_to_flash && p_write_reconnect_ptr){ - if(wifi_get_setting((const char*)ifname[0],&setting) || setting.mode == RTW_MODE_AP){ - WIFI_CONF_MSG("\r\n %s():wifi_get_setting fail or ap mode", __func__); - return; - } - channel = setting.channel; - - rtw_memset(psk_essid[index], 0, sizeof(psk_essid[index])); - strncpy(psk_essid[index], setting.ssid, strlen(setting.ssid)); - switch(setting.security_type){ - case RTW_SECURITY_OPEN: - rtw_memset(psk_passphrase[index], 0, sizeof(psk_passphrase[index])); - rtw_memset(wpa_global_PSK[index], 0, sizeof(wpa_global_PSK[index])); - data_to_flash->security_type = RTW_SECURITY_OPEN; - break; - case RTW_SECURITY_WEP_PSK: - channel |= (setting.key_idx) << 28; - rtw_memset(psk_passphrase[index], 0, sizeof(psk_passphrase[index])); - rtw_memset(wpa_global_PSK[index], 0, sizeof(wpa_global_PSK[index])); - rtw_memcpy(psk_passphrase[index], setting.password, sizeof(psk_passphrase[index])); - data_to_flash->security_type = RTW_SECURITY_WEP_PSK; - break; - case RTW_SECURITY_WPA_TKIP_PSK: - data_to_flash->security_type = RTW_SECURITY_WPA_TKIP_PSK; - break; - case RTW_SECURITY_WPA2_AES_PSK: - data_to_flash->security_type = RTW_SECURITY_WPA2_AES_PSK; - break; - default: - break; - } - - memcpy(data_to_flash->psk_essid, psk_essid[index], sizeof(data_to_flash->psk_essid)); - if (strlen(psk_passphrase64) == 64) { - memcpy(data_to_flash->psk_passphrase, psk_passphrase64, sizeof(data_to_flash->psk_passphrase)); - } else { - memcpy(data_to_flash->psk_passphrase, psk_passphrase[index], sizeof(data_to_flash->psk_passphrase)); - } - memcpy(data_to_flash->wpa_global_PSK, wpa_global_PSK[index], sizeof(data_to_flash->wpa_global_PSK)); - memcpy(&(data_to_flash->channel), &channel, 4); - - //call callback function in user program - p_write_reconnect_ptr((u8 *)data_to_flash, sizeof(struct wlan_fast_reconnect)); - - } - if(data_to_flash) - rtw_free(data_to_flash); -} - -#endif - -//----------------------------------------------------------------------------// -int wifi_connect( - char *ssid, - rtw_security_t security_type, - char *password, - int ssid_len, - int password_len, - int key_id, - void *semaphore) -{ - _sema join_semaphore; - rtw_result_t result = RTW_SUCCESS; - u8 wep_hex = 0; - u8 wep_pwd[14] = {0}; - - if(rtw_join_status & JOIN_SIMPLE_CONFIG || rtw_join_status & JOIN_AIRKISS){ - return RTW_ERROR; - } - - rtw_join_status = 0;//clear for last connect status - error_flag = RTW_UNKNOWN ;//clear for last connect status - if ( ( ( ( password_len > RTW_MAX_PSK_LEN ) || - ( password_len < RTW_MIN_PSK_LEN ) ) && - ( ( security_type == RTW_SECURITY_WPA_TKIP_PSK ) || - ( security_type == RTW_SECURITY_WPA_AES_PSK ) || - ( security_type == RTW_SECURITY_WPA2_AES_PSK ) || - ( security_type == RTW_SECURITY_WPA2_TKIP_PSK ) || - ( security_type == RTW_SECURITY_WPA2_MIXED_PSK ) ) )) { - error_flag = RTW_WRONG_PASSWORD; - return RTW_INVALID_KEY; - } - - if ((security_type == RTW_SECURITY_WEP_PSK)|| - (security_type ==RTW_SECURITY_WEP_SHARED)) { - if ((password_len != 5) && (password_len != 13) && - (password_len != 10)&& (password_len != 26)) { - error_flag = RTW_WRONG_PASSWORD; - return RTW_INVALID_KEY; - } else { - - if(password_len == 10) { - - u32 p[5] = {0}; - u8 i = 0; - sscanf((const char*)password, "%02lx%02lx%02lx%02lx%02lx", &p[0], &p[1], &p[2], &p[3], &p[4]); - for(i=0; i< 5; i++) - wep_pwd[i] = (u8)p[i]; - wep_pwd[5] = '\0'; - password_len = 5; - wep_hex = 1; - } else if (password_len == 26) { - u32 p[13] = {0}; - u8 i = 0; - sscanf((const char*)password, "%02lx%02lx%02lx%02lx%02lx%02lx%02lx"\ - "%02lx%02lx%02lx%02lx%02lx%02lx", &p[0], &p[1], &p[2], &p[3], &p[4],\ - &p[5], &p[6], &p[7], &p[8], &p[9], &p[10], &p[11], &p[12]); - for(i=0; i< 13; i++) - wep_pwd[i] = (u8)p[i]; - wep_pwd[13] = '\0'; - password_len = 13; - wep_hex = 1; - } - } - } - - internal_join_result_t *join_result = (internal_join_result_t *)rtw_zmalloc(sizeof(internal_join_result_t)); - if(!join_result) { - return RTW_NOMEM; - } - - join_result->network_info.ssid.len = ssid_len > 32 ? 32 : ssid_len; - rtw_memcpy(join_result->network_info.ssid.val, ssid, ssid_len); - - join_result->network_info.password_len = password_len; - if(password_len) { - /* add \0 to the end */ - join_result->network_info.password = rtw_zmalloc(password_len + 1); - if(!join_result->network_info.password) { - result = RTW_NOMEM; - goto error; - } - if (0 == wep_hex) - rtw_memcpy(join_result->network_info.password, password, password_len); - else - rtw_memcpy(join_result->network_info.password, wep_pwd, password_len); - - } - - join_result->network_info.security_type = security_type; - join_result->network_info.key_id = key_id; - - if(semaphore == NULL) { - rtw_init_sema( &join_result->join_sema, 0 ); - if(!join_result->join_sema){ - result = RTW_NORESOURCE; - goto error; - } - join_semaphore = join_result->join_sema; - } else { - join_result->join_sema = semaphore; - } - wifi_reg_event_handler(WIFI_EVENT_NO_NETWORK,wifi_no_network_hdl,NULL); - wifi_reg_event_handler(WIFI_EVENT_CONNECT, wifi_connected_hdl, NULL); - wifi_reg_event_handler(WIFI_EVENT_DISCONNECT, wifi_disconn_hdl, NULL); - wifi_reg_event_handler(WIFI_EVENT_FOURWAY_HANDSHAKE_DONE, wifi_handshake_done_hdl, NULL); - - wifi_connect_local(&join_result->network_info); - - join_user_data = join_result; - - if(semaphore == NULL) { -// for eap connection, timeout should be longer (default value in wpa_supplicant: 60s) -#ifdef CONFIG_ENABLE_EAP - if(get_eap_phase()){ - if(rtw_down_timeout_sema( &join_result->join_sema, 60000 ) == RTW_FALSE) { - WIFI_CONF_MSG("RTW API: Join bss timeout\r\n"); - if(password_len) { - rtw_free(join_result->network_info.password); - } - result = RTW_TIMEOUT; - goto error; - } else { - if(wifi_is_connected_to_ap( ) != RTW_SUCCESS) { - result = RTW_ERROR; - goto error; - } - } - } - else -#endif - if(rtw_down_timeout_sema( &join_result->join_sema, RTW_JOIN_TIMEOUT ) == RTW_FALSE) { - WIFI_CONF_MSG("RTW API: Join bss timeout\r\n"); - if(password_len) { - rtw_free(join_result->network_info.password); - } - result = RTW_TIMEOUT; - goto error; - } else { - if(join_result->network_info.password_len) { - rtw_free(join_result->network_info.password); - } - if(wifi_is_connected_to_ap( ) != RTW_SUCCESS) { - result = RTW_ERROR; - goto error; - } - } - } - - result = RTW_SUCCESS; - -#if CONFIG_EXAMPLE_WLAN_FAST_CONNECT || CONFIG_JD_SMART - restore_wifi_info_to_flash(); -#endif - -error: - if(semaphore == NULL){ - rtw_free_sema( &join_semaphore); - } - join_user_data = NULL; - rtw_free((u8*)join_result); - wifi_unreg_event_handler(WIFI_EVENT_CONNECT, wifi_connected_hdl); - wifi_unreg_event_handler(WIFI_EVENT_NO_NETWORK,wifi_no_network_hdl); - wifi_unreg_event_handler(WIFI_EVENT_FOURWAY_HANDSHAKE_DONE, wifi_handshake_done_hdl); - return result; -} - -int wifi_connect_bssid( - unsigned char bssid[ETH_ALEN], - char *ssid, - rtw_security_t security_type, - char *password, - int bssid_len, - int ssid_len, - int password_len, - int key_id, - void *semaphore) -{ - _sema join_semaphore; - rtw_result_t result = RTW_SUCCESS; - - if(rtw_join_status & JOIN_SIMPLE_CONFIG || rtw_join_status & JOIN_AIRKISS){ - return RTW_ERROR; - } - - rtw_join_status = 0;//clear for last connect status - error_flag = RTW_UNKNOWN;//clear for last connect status - internal_join_result_t *join_result = (internal_join_result_t *)rtw_zmalloc(sizeof(internal_join_result_t)); - if(!join_result) { - return RTW_NOMEM; - } - if(ssid_len && ssid){ - join_result->network_info.ssid.len = ssid_len > 32 ? 32 : ssid_len; - rtw_memcpy(join_result->network_info.ssid.val, ssid, ssid_len); - } - rtw_memcpy(join_result->network_info.bssid.octet, bssid, bssid_len); - - if ( ( ( ( password_len > RTW_MAX_PSK_LEN ) || - ( password_len < RTW_MIN_PSK_LEN ) ) && - ( ( security_type == RTW_SECURITY_WPA_TKIP_PSK ) || - ( security_type == RTW_SECURITY_WPA_AES_PSK ) || - ( security_type == RTW_SECURITY_WPA2_AES_PSK ) || - ( security_type == RTW_SECURITY_WPA2_TKIP_PSK ) || - ( security_type == RTW_SECURITY_WPA2_MIXED_PSK ) ) )|| - (((password_len != 5)&& (password_len != 13))&& - ((security_type == RTW_SECURITY_WEP_PSK)|| - (security_type ==RTW_SECURITY_WEP_SHARED ) ))) { - return RTW_INVALID_KEY; - } - join_result->network_info.password_len = password_len; - if(password_len) { - /* add \0 to the end */ - join_result->network_info.password = rtw_zmalloc(password_len + 1); - if(!join_result->network_info.password) { - return RTW_NOMEM; - } - rtw_memcpy(join_result->network_info.password, password, password_len); - } - - join_result->network_info.security_type = security_type; - join_result->network_info.key_id = key_id; - - if(semaphore == NULL) { - rtw_init_sema( &join_result->join_sema, 0 ); - if(!join_result->join_sema){ - return RTW_NORESOURCE; - } - join_semaphore = join_result->join_sema; - } else { - join_result->join_sema = semaphore; - } - wifi_reg_event_handler(WIFI_EVENT_NO_NETWORK,wifi_no_network_hdl,NULL); - wifi_reg_event_handler(WIFI_EVENT_CONNECT, wifi_connected_hdl, NULL); - wifi_reg_event_handler(WIFI_EVENT_DISCONNECT, wifi_disconn_hdl, NULL); - wifi_reg_event_handler(WIFI_EVENT_FOURWAY_HANDSHAKE_DONE, wifi_handshake_done_hdl, NULL); - - wifi_connect_bssid_local(&join_result->network_info); - - join_user_data = join_result; - - if(semaphore == NULL) { - if(rtw_down_timeout_sema( &join_result->join_sema, RTW_JOIN_TIMEOUT ) == RTW_FALSE) { - WIFI_CONF_MSG("RTW API: Join bss timeout\r\n"); - if(password_len) { - rtw_free(join_result->network_info.password); - } - rtw_free((u8*)join_result); - rtw_free_sema( &join_semaphore); - result = RTW_TIMEOUT; - goto error; - } else { - rtw_free_sema( &join_semaphore ); - if(join_result->network_info.password_len) { - rtw_free(join_result->network_info.password); - } - rtw_free((u8*)join_result); - if( wifi_is_connected_to_ap( ) != RTW_SUCCESS) { - result = RTW_ERROR; - goto error; - } - } - } - - result = RTW_SUCCESS; - -#if CONFIG_EXAMPLE_WLAN_FAST_CONNECT || CONFIG_JD_SMART - restore_wifi_info_to_flash(); -#endif - -error: - join_user_data = NULL; - wifi_unreg_event_handler(WIFI_EVENT_CONNECT, wifi_connected_hdl); - wifi_unreg_event_handler(WIFI_EVENT_NO_NETWORK,wifi_no_network_hdl); - wifi_unreg_event_handler(WIFI_EVENT_FOURWAY_HANDSHAKE_DONE, wifi_handshake_done_hdl); - return result; -} - -int wifi_disconnect(void) -{ - int ret = 0; - - //set MAC address last byte to 1 since driver will filter the mac with all 0x00 or 0xff - //add extra 2 zero byte for check of #@ in wext_set_bssid() - const __u8 null_bssid[ETH_ALEN + 2] = {0, 0, 0, 0, 0, 1, 0, 0}; - - if (wext_set_bssid(WLAN0_NAME, null_bssid) < 0){ - WIFI_CONF_MSG("\n\rWEXT: Failed to set bogus BSSID to disconnect"); - ret = -1; - } - return ret; -} - -//----------------------------------------------------------------------------// -int wifi_is_connected_to_ap( void ) -{ - return rltk_wlan_is_connected_to_ap(); -} - -//----------------------------------------------------------------------------// -int wifi_is_up(rtw_interface_t interface) -{ - if(interface == RTW_AP_INTERFACE) { - if(wifi_mode == RTW_MODE_STA_AP) { - return rltk_wlan_running(WLAN1_IDX); - } - } - - return rltk_wlan_running(WLAN0_IDX); -} - -int wifi_is_ready_to_transceive(rtw_interface_t interface) -{ - switch ( interface ) - { - case RTW_AP_INTERFACE: - return ( wifi_is_up(interface) == RTW_TRUE ) ? RTW_SUCCESS : RTW_ERROR; - - case RTW_STA_INTERFACE: - switch ( error_flag) - { - case RTW_NO_ERROR: - return RTW_SUCCESS; - - default: - return RTW_ERROR; - } - default: - return RTW_ERROR; - } -} - -//----------------------------------------------------------------------------// -int wifi_set_mac_address(char * mac) -{ - char buf[13+17+1]; - rtw_memset(buf, 0, sizeof(buf)); - snprintf(buf, 13+17, "write_mac %s", mac); - return wext_private_command(WLAN0_NAME, buf, 0); -} - -int wifi_get_mac_address(char * mac) -{ - int ret = 0; - char buf[32]; - rtw_memset(buf, 0, sizeof(buf)); - rtw_memcpy(buf, "read_mac", 8); - ret = wext_private_command_with_retval(WLAN0_NAME, buf, buf, 32); - strcpy(mac, buf); - return ret; -} - -//----------------------------------------------------------------------------// -int wifi_enable_powersave(void) -{ - return wext_enable_powersave(WLAN0_NAME, 1, 1); -} - -int wifi_disable_powersave(void) -{ - return wext_disable_powersave(WLAN0_NAME); -} - -#if 0 //Not ready -//----------------------------------------------------------------------------// -int wifi_get_txpower(int *poweridx) -{ - int ret = 0; - char buf[11]; - - rtw_memset(buf, 0, sizeof(buf)); - rtw_memcpy(buf, "txpower", 11); - ret = wext_private_command_with_retval(WLAN0_NAME, buf, buf, 11); - sscanf(buf, "%d", poweridx); - - return ret; -} - -int wifi_set_txpower(int poweridx) -{ - int ret = 0; - char buf[24]; - - rtw_memset(buf, 0, sizeof(buf)); - snprintf(buf, 24, "txpower patha=%d", poweridx); - ret = wext_private_command(WLAN0_NAME, buf, 0); - - return ret; -} -#endif - -//----------------------------------------------------------------------------// -int wifi_get_associated_client_list(void * client_list_buffer, uint16_t buffer_length) -{ - const char * ifname = WLAN0_NAME; - int ret = 0; - char buf[25]; - - if(wifi_mode == RTW_MODE_STA_AP) { - ifname = WLAN1_NAME; - } - - rtw_memset(buf, 0, sizeof(buf)); - snprintf(buf, 25, "get_client_list %x", client_list_buffer); - ret = wext_private_command(ifname, buf, 0); - - return ret; -} - -//----------------------------------------------------------------------------// -int wifi_get_ap_info(rtw_bss_info_t * ap_info, rtw_security_t* security) -{ - const char * ifname = WLAN0_NAME; - int ret = 0; - char buf[24]; - - if(wifi_mode == RTW_MODE_STA_AP) { - ifname = WLAN1_NAME; - } - - rtw_memset(buf, 0, sizeof(buf)); - snprintf(buf, 24, "get_ap_info %x", ap_info); - ret = wext_private_command(ifname, buf, 0); - - snprintf(buf, 24, "get_security"); - ret = wext_private_command_with_retval(ifname, buf, buf, 24); - sscanf(buf, "%lu", security); - - return ret; -} - -int wifi_get_drv_ability(uint32_t *ability) -{ - return wext_get_drv_ability(WLAN0_NAME, ability); -} - -//----------------------------------------------------------------------------// -int wifi_set_country(rtw_country_code_t country_code) -{ - int ret; - - ret = wext_set_country(WLAN0_NAME, country_code); - - return ret; -} - -//----------------------------------------------------------------------------// -int wifi_set_channel_plan(uint8_t channel_plan) -{ - const char * ifname = WLAN0_NAME; - int ret = 0; - char buf[24]; - - rtw_memset(buf, 0, sizeof(buf)); - snprintf(buf, 24, "set_ch_plan %x", channel_plan); - ret = wext_private_command(ifname, buf, 0); - return ret; -} - -//----------------------------------------------------------------------------// -int wifi_get_rssi(int *pRSSI) -{ - return wext_get_rssi(WLAN0_NAME, pRSSI); -} - -//----------------------------------------------------------------------------// -int wifi_set_channel(int channel) -{ - return wext_set_channel(WLAN0_NAME, channel); -} - -int wifi_get_channel(int *channel) -{ - return wext_get_channel(WLAN0_NAME, (u8*)channel); -} - -//----------------------------------------------------------------------------// -int wifi_register_multicast_address(rtw_mac_t *mac) -{ - return wext_register_multicast_address(WLAN0_NAME, mac); -} - -int wifi_unregister_multicast_address(rtw_mac_t *mac) -{ - return wext_unregister_multicast_address(WLAN0_NAME, mac); -} - -//----------------------------------------------------------------------------// -void wifi_set_mib(void) -{ - // adaptivity - wext_set_adaptivity(RTW_ADAPTIVITY_DISABLE); -} - -//----------------------------------------------------------------------------// -int wifi_rf_on(void) -{ - int ret; - ret = rltk_wlan_rf_on(); - return ret; -} - -//----------------------------------------------------------------------------// -int wifi_rf_off(void) -{ - int ret; - ret = rltk_wlan_rf_off(); - return ret; -} - -//----------------------------------------------------------------------------// -int wifi_on(rtw_mode_t mode) -{ - int ret = 1; - int timeout = 20; - int idx; - int devnum = 1; - static int event_init = 0; - - if(rltk_wlan_running(WLAN0_IDX)) { - WIFI_CONF_MSG("\n\rWIFI is already running"); - return 1; - } - - if(event_init == 0){ - init_event_callback_list(); - event_init = 1; - } - - wifi_mode = mode; - - if(mode == RTW_MODE_STA_AP) - devnum = 2; - - // set wifi mib - wifi_set_mib(); - WIFI_CONF_MSG("\n\rInitializing WIFI ..."); - for(idx=0;idxBSSID.octet, (*result_ptr)->BSSID.octet)){ - if((*result_ptr)->signal_strength > scan_result_handler_ptr.pap_details[i]->signal_strength){ - temp = scan_result_handler_ptr.pap_details[i]; - for(j = i-1; j >= 0; j--){ - if(scan_result_handler_ptr.pap_details[j]->signal_strength >= (*result_ptr)->signal_strength) - break; - else - scan_result_handler_ptr.pap_details[j+1] = scan_result_handler_ptr.pap_details[j]; - } - scan_result_handler_ptr.pap_details[j+1] = temp; - scan_result_handler_ptr.pap_details[j+1]->signal_strength = (*result_ptr)->signal_strength; - } - memset(*result_ptr, 0, sizeof(rtw_scan_result_t)); - return; - } - } - - scan_result_handler_ptr.scan_cnt++; - - if(scan_result_handler_ptr.scan_cnt > scan_result_handler_ptr.max_ap_size){ - scan_result_handler_ptr.scan_cnt = scan_result_handler_ptr.max_ap_size; - if((*result_ptr)->signal_strength > scan_result_handler_ptr.pap_details[scan_result_handler_ptr.max_ap_size-1]->signal_strength){ - rtw_memcpy(scan_result_handler_ptr.pap_details[scan_result_handler_ptr.max_ap_size-1], *result_ptr, sizeof(rtw_scan_result_t)); - temp = scan_result_handler_ptr.pap_details[scan_result_handler_ptr.max_ap_size -1]; - }else - return; - }else{ - rtw_memcpy(&scan_result_handler_ptr.ap_details[scan_result_handler_ptr.scan_cnt-1], *result_ptr, sizeof(rtw_scan_result_t)); - } - - for(i=0; i< scan_result_handler_ptr.scan_cnt-1; i++){ - if((*result_ptr)->signal_strength > scan_result_handler_ptr.pap_details[i]->signal_strength) - break; - } - insert_pos = i; - - for(i = scan_result_handler_ptr.scan_cnt-1; i>insert_pos; i--) - scan_result_handler_ptr.pap_details[i] = scan_result_handler_ptr.pap_details[i-1]; - - if(temp != NULL) - scan_result_handler_ptr.pap_details[insert_pos] = temp; - else - scan_result_handler_ptr.pap_details[insert_pos] = &scan_result_handler_ptr.ap_details[scan_result_handler_ptr.scan_cnt-1]; - rtw_memset(*result_ptr, 0, sizeof(rtw_scan_result_t)); -} - -void wifi_scan_done_hdl( char* buf, int buf_len, int flags, void* userdata) -{ - int i = 0; - rtw_scan_handler_result_t scan_result_report; - - for(i=0; ibuf, pscan_buf->buf_len, flags); - }else{ - wifi_reg_event_handler(WIFI_EVENT_SCAN_RESULT_REPORT, wifi_scan_each_report_hdl, NULL); - wifi_reg_event_handler(WIFI_EVENT_SCAN_DONE, wifi_scan_done_hdl, NULL); - ret = wext_set_scan(WLAN0_NAME, NULL, 0, flags); - } - - if(ret == 0) { - if(result_ptr != NULL){ - ret = wext_get_scan(WLAN0_NAME, pscan_buf->buf, pscan_buf->buf_len); - } - } - else if(ret == -1){ - if(result_ptr == NULL){ - wifi_unreg_event_handler(WIFI_EVENT_SCAN_RESULT_REPORT, wifi_scan_each_report_hdl); - wifi_unreg_event_handler(WIFI_EVENT_SCAN_DONE, wifi_scan_done_hdl); - } - } - return ret; -} - -int wifi_scan_networks_with_ssid(int (results_handler)(char*buf, int buflen, char *ssid, void *user_data), - OUT void* user_data, IN int scan_buflen, IN char* ssid, IN int ssid_len) -{ - int scan_cnt = 0, add_cnt = 0; - scan_buf_arg scan_buf; - int ret; - - scan_buf.buf_len = scan_buflen; - scan_buf.buf = (char*)rtw_malloc(scan_buf.buf_len); - if(!scan_buf.buf){ - WIFI_CONF_MSG("\n\rERROR: Can't malloc memory(%d)", scan_buf.buf_len); - return RTW_NOMEM; - } - //set ssid - memset(scan_buf.buf, 0, scan_buf.buf_len); - memcpy(scan_buf.buf, &ssid_len, sizeof(int)); - memcpy(scan_buf.buf+sizeof(int), ssid, ssid_len); - - //Scan channel - scan_cnt = wifi_scan(RTW_SCAN_TYPE_ACTIVE, RTW_BSS_TYPE_ANY, &scan_buf); - if(scan_cnt < 0){ - WIFI_CONF_MSG("\n\rERROR: wifi scan failed"); - ret = RTW_ERROR; - }else{ - if(NULL == results_handler) - { - int plen = 0; - while(plen < scan_buf.buf_len){ - int len, rssi, ssid_len, i, security_mode; - int wps_password_id; - char *mac, *ssid; - //u8 *security_mode; - printf("\n\r"); - // len - len = (int)*(scan_buf.buf + plen); - printf("len = %d,\t", len); - // check end - if(len == 0) break; - // mac - mac = scan_buf.buf + plen + 1; - printf("mac = "); - for(i=0; i<6; i++) - printf("%02x ", (u8)*(mac+i)); - printf(",\t"); - // rssi - rssi = *(int*)(scan_buf.buf + plen + 1 + 6); - printf(" rssi = %d,\t", rssi); - // security_mode - security_mode = (int)*(scan_buf.buf + plen + 1 + 6 + 4); - switch (security_mode) { - case IW_ENCODE_ALG_NONE: - printf("sec = open ,\t"); - break; - case IW_ENCODE_ALG_WEP: - printf("sec = wep ,\t"); - break; - case IW_ENCODE_ALG_CCMP: - printf("sec = wpa/wpa2,\t"); - break; - } - // password id - wps_password_id = (int)*(scan_buf.buf + plen + 1 + 6 + 4 + 1); - printf("wps password id = %d,\t", wps_password_id); - - printf("channel = %d,\t", *(scan_buf.buf + plen + 1 + 6 + 4 + 1 + 1)); - // ssid - ssid_len = len - 1 - 6 - 4 - 1 - 1 - 1; - ssid = scan_buf.buf + plen + 1 + 6 + 4 + 1 + 1 + 1; - printf("ssid = "); - for(i=0; i 0) - { - rtw_msleep_os(20); - count --; - } - if(count == 0){ - WIFI_CONF_MSG("\n\r[%d]WiFi: Scan is running. Wait 2s timeout.", rtw_get_current_time()); - return RTW_TIMEOUT; - } - } - scan_result_handler_ptr.scan_start_time = rtw_get_current_time(); - scan_result_handler_ptr.scan_running = 1; -#endif - - scan_result_handler_ptr.gscan_result_handler = results_handler; - - scan_result_handler_ptr.max_ap_size = max_ap_size; - scan_result_handler_ptr.ap_details = (rtw_scan_result_t*)rtw_zmalloc(max_ap_size*sizeof(rtw_scan_result_t)); - if(scan_result_handler_ptr.ap_details == NULL){ - goto err_exit; - } - rtw_memset(scan_result_handler_ptr.ap_details, 0, max_ap_size*sizeof(rtw_scan_result_t)); - - scan_result_handler_ptr.pap_details = (rtw_scan_result_t**)rtw_zmalloc(max_ap_size*sizeof(rtw_scan_result_t*)); - if(scan_result_handler_ptr.pap_details == NULL) - goto error2_with_result_ptr; - rtw_memset(scan_result_handler_ptr.pap_details, 0, max_ap_size); - - scan_result_handler_ptr.scan_cnt = 0; - - scan_result_handler_ptr.scan_complete = RTW_FALSE; - scan_result_handler_ptr.user_data = user_data; - - if (wifi_scan( RTW_SCAN_COMMAMD<<4 | RTW_SCAN_TYPE_ACTIVE, RTW_BSS_TYPE_ANY, NULL) != RTW_SUCCESS) - { - goto error1_with_result_ptr; - } - - return RTW_SUCCESS; - -error1_with_result_ptr: - rtw_free((u8*)scan_result_handler_ptr.pap_details); - scan_result_handler_ptr.pap_details = NULL; - -error2_with_result_ptr: - rtw_free((u8*)scan_result_handler_ptr.ap_details); - scan_result_handler_ptr.ap_details = NULL; - -err_exit: - rtw_memset((void *)&scan_result_handler_ptr, 0, sizeof(scan_result_handler_ptr)); - return RTW_ERROR; -} -//----------------------------------------------------------------------------// -int wifi_set_pscan_chan(__u8 * channel_list,__u8 * pscan_config, __u8 length) -{ - if(channel_list) - return wext_set_pscan_channel(WLAN0_NAME, channel_list, pscan_config, length); - else - return -1; -} - -//----------------------------------------------------------------------------// -int wifi_get_setting(const char *ifname, rtw_wifi_setting_t *pSetting) -{ - int ret = 0; - int mode = 0; - unsigned short security = 0; - - memset(pSetting, 0, sizeof(rtw_wifi_setting_t)); - if(wext_get_mode(ifname, &mode) < 0) - ret = -1; - - switch(mode) { - case IW_MODE_MASTER: - pSetting->mode = RTW_MODE_AP; - break; - case IW_MODE_INFRA: - default: - pSetting->mode = RTW_MODE_STA; - break; - //default: - //printf("\r\n%s(): Unknown mode %d\n", __func__, mode); - //break; - } - - if(wext_get_ssid(ifname, pSetting->ssid) < 0) - ret = -1; - if(wext_get_channel(ifname, &pSetting->channel) < 0) - ret = -1; - if(wext_get_enc_ext(ifname, &security, &pSetting->key_idx, pSetting->password) < 0) - ret = -1; - - switch(security){ - case IW_ENCODE_ALG_NONE: - pSetting->security_type = RTW_SECURITY_OPEN; - break; - case IW_ENCODE_ALG_WEP: - pSetting->security_type = RTW_SECURITY_WEP_PSK; - break; - case IW_ENCODE_ALG_TKIP: - pSetting->security_type = RTW_SECURITY_WPA_TKIP_PSK; - break; - case IW_ENCODE_ALG_CCMP: - pSetting->security_type = RTW_SECURITY_WPA2_AES_PSK; - break; - default: - break; - } - - if(security == IW_ENCODE_ALG_TKIP || security == IW_ENCODE_ALG_CCMP) - if(wext_get_passphrase(ifname, pSetting->password) < 0) - ret = -1; - - return ret; -} -//----------------------------------------------------------------------------// -int wifi_show_setting(const char *ifname, rtw_wifi_setting_t *pSetting) -{ - int ret = 0; - - printf("\n\r\nWIFI %s Setting:",ifname); - printf("\n\r=============================="); - - switch(pSetting->mode) { - case RTW_MODE_AP: -#if CONFIG_EXAMPLE_UART_ATCMD - at_printf("\r\nAP,"); -#endif - printf("\n\r MODE => AP"); - break; - case RTW_MODE_STA: -#if CONFIG_EXAMPLE_UART_ATCMD - at_printf("\r\nSTA,"); -#endif - printf("\n\r MODE => STATION"); - break; - default: -#if CONFIG_EXAMPLE_UART_ATCMD - at_printf("\r\nUNKNOWN,"); -#endif - printf("\n\r MODE => UNKNOWN"); - } -#if CONFIG_EXAMPLE_UART_ATCMD - at_printf("%s,%d,", pSetting->ssid, pSetting->channel); -#endif - printf("\n\r SSID => %s", pSetting->ssid); - printf("\n\r CHANNEL => %d", pSetting->channel); - - switch(pSetting->security_type) { - case RTW_SECURITY_OPEN: -#if CONFIG_EXAMPLE_UART_ATCMD - at_printf("OPEN,"); -#endif - printf("\n\r SECURITY => OPEN"); - break; - case RTW_SECURITY_WEP_PSK: -#if CONFIG_EXAMPLE_UART_ATCMD - at_printf("WEP,%d,", pSetting->key_idx); -#endif - printf("\n\r SECURITY => WEP"); - printf("\n\r KEY INDEX => %d", pSetting->key_idx); - break; - case RTW_SECURITY_WPA_TKIP_PSK: -#if CONFIG_EXAMPLE_UART_ATCMD - at_printf("TKIP,"); -#endif - printf("\n\r SECURITY => TKIP"); - break; - case RTW_SECURITY_WPA2_AES_PSK: -#if CONFIG_EXAMPLE_UART_ATCMD - at_printf("AES,"); -#endif - printf("\n\r SECURITY => AES"); - break; - default: -#if CONFIG_EXAMPLE_UART_ATCMD - at_printf("UNKNOWN,"); -#endif - printf("\n\r SECURITY => UNKNOWN"); - } - -#if CONFIG_EXAMPLE_UART_ATCMD - at_printf("%s,", pSetting->password); -#endif - printf("\n\r PASSWORD => %s", pSetting->password); - printf("\n\r"); - - return ret; -} - -//----------------------------------------------------------------------------// -int wifi_set_network_mode(rtw_network_mode_t mode) -{ - if((mode == RTW_NETWORK_B) || (mode == RTW_NETWORK_BG) || (mode == RTW_NETWORK_BGN)) - return rltk_wlan_wireless_mode((unsigned char) mode); - - return -1; -} - -int wifi_set_wps_phase(unsigned char is_trigger_wps) -{ - return rltk_wlan_set_wps_phase(is_trigger_wps); -} - -//----------------------------------------------------------------------------// -int wifi_set_promisc(rtw_rcr_level_t enabled, void (*callback)(unsigned char*, unsigned int, void*), unsigned char len_used) -{ - return promisc_set(enabled, callback, len_used); -} - -void wifi_enter_promisc_mode(){ - int mode = 0; - unsigned char ssid[33]; - - if(wifi_mode == RTW_MODE_STA_AP){ - wifi_off(); - rtw_msleep_os(20); - wifi_on(RTW_MODE_PROMISC); - }else{ - wext_get_mode(WLAN0_NAME, &mode); - - switch(mode) { - case IW_MODE_MASTER: //In AP mode - //rltk_wlan_deinit(); - wifi_off();//modified by Chris Yang for iNIC - rtw_msleep_os(20); - //rltk_wlan_init(0, RTW_MODE_PROMISC); - //rltk_wlan_start(0); - wifi_on(RTW_MODE_PROMISC); - break; - case IW_MODE_INFRA: //In STA mode - if(wext_get_ssid(WLAN0_NAME, ssid) > 0) - wifi_disconnect(); - } - } -} - -int wifi_restart_ap( - unsigned char *ssid, - rtw_security_t security_type, - unsigned char *password, - int ssid_len, - int password_len, - int channel) -{ - unsigned char idx = 0; -#if !defined(CONFIG_MBED_ENABLED) - ip_addr_t ipaddr; - ip_addr_t netmask; - ip_addr_t gw; - struct netif * pnetif = &xnetif[0]; -#endif -#ifdef CONFIG_CONCURRENT_MODE - rtw_wifi_setting_t setting; - int sta_linked = 0; -#endif - - if(rltk_wlan_running(WLAN1_IDX)){ - idx = 1; - } - - // stop dhcp server -#ifndef CONFIG_MBED_ENABLED - dhcps_deinit(); -#endif - -#ifdef CONFIG_CONCURRENT_MODE - if(idx > 0){ - sta_linked = wifi_get_setting(WLAN0_NAME, &setting); - wifi_off(); - rtw_msleep_os(20); - wifi_on(RTW_MODE_STA_AP); - } - else -#endif - { -#if !defined(CONFIG_MBED_ENABLED) - IP4_ADDR(&ipaddr, GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3); - IP4_ADDR(&netmask, NETMASK_ADDR0, NETMASK_ADDR1 , NETMASK_ADDR2, NETMASK_ADDR3); - IP4_ADDR(&gw, GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3); - netif_set_addr(pnetif, &ipaddr, &netmask,&gw); -#endif - wifi_off(); - rtw_msleep_os(20); - wifi_on(RTW_MODE_AP); - } - // start ap - if(wifi_start_ap((char*)ssid, security_type, (char*)password, ssid_len, password_len, channel) < 0) { - WIFI_CONF_MSG("\n\rERROR: Operation failed!"); - return -1; - } - -#if (INCLUDE_uxTaskGetStackHighWaterMark == 1) - printf("\r\nWebServer Thread: High Water Mark is %ld\n", uxTaskGetStackHighWaterMark(NULL)); -#endif -#ifdef CONFIG_CONCURRENT_MODE - // connect to ap if wlan0 was linked with ap - if(idx > 0 && sta_linked == 0){ -#if CONFIG_DHCP_CLIENT - int ret; -#endif - printf("\r\nAP: ssid=%s", (char*)setting.ssid); - printf("\r\nAP: security_type=%d", setting.security_type); - printf("\r\nAP: password=%s", (char*)setting.password); - printf("\r\nAP: key_idx =%d\n", setting.key_idx); -#if CONFIG_DHCP_CLIENT - ret = -#endif - wifi_connect((char*)setting.ssid, - setting.security_type, - (char*)setting.password, - strlen((char*)setting.ssid), - strlen((char*)setting.password), - setting.key_idx, - NULL); -#if CONFIG_DHCP_CLIENT - if(ret == RTW_SUCCESS) { - /* Start DHCPClient */ - LwIP_DHCP(0, DHCP_START); - } -#endif - } -#endif -#if (INCLUDE_uxTaskGetStackHighWaterMark == 1) - printf("\r\nWebServer Thread: High Water Mark is %ld\n", uxTaskGetStackHighWaterMark(NULL)); -#endif -#if !defined(CONFIG_MBED_ENABLED) - // start dhcp server - dhcps_init(&xnetif[idx]); -#endif - return 0; -} - -#if CONFIG_AUTO_RECONNECT -struct task_struct g_wifi_auto_reconnect_task; - -extern void (*p_wlan_autoreconnect_hdl)(rtw_security_t, char*, int, char*, int, int); - -struct wifi_autoreconnect_param { - rtw_security_t security_type; - char *ssid; - int ssid_len; - char *password; - int password_len; - int key_id; -}; - -static void wifi_autoreconnect_thread(void *param) -{ -#if !defined(CONFIG_MBED_ENABLED) && CONFIG_LWIP_LAYER - int ret = RTW_ERROR; -#endif - struct wifi_autoreconnect_param *reconnect_param = (struct wifi_autoreconnect_param *) param; - WIFI_CONF_MSG("\n\rauto reconnect ...\n"); -#if !defined(CONFIG_MBED_ENABLED) && CONFIG_LWIP_LAYER - ret = -#endif - wifi_connect(reconnect_param->ssid, - reconnect_param->security_type, - reconnect_param->password, - reconnect_param->ssid_len, - reconnect_param->password_len, - reconnect_param->key_id, - NULL); -#if !defined(CONFIG_MBED_ENABLED) && CONFIG_LWIP_LAYER - if(ret == RTW_SUCCESS) { -#if ATCMD_VER == ATVER_2 - if (dhcp_mode_sta == 2){ - struct netif * pnetif = &xnetif[0]; - LwIP_UseStaticIP(pnetif); - dhcps_init(pnetif); - } - else -#endif - { - LwIP_DHCP(0, DHCP_START); -#if LWIP_AUTOIP - uint8_t *ip = LwIP_GetIP(&xnetif[0]); - if((ip[0] == 0) && (ip[1] == 0) && (ip[2] == 0) && (ip[3] == 0)) { - WIFI_CONF_MSG("\n\nIPv4 AUTOIP ..."); - LwIP_AUTOIP(&xnetif[0]); - } -#endif - } - } -#endif - rtw_delete_task(&g_wifi_auto_reconnect_task); -} - -void wifi_autoreconnect_hdl(rtw_security_t security_type, - char *ssid, int ssid_len, - char *password, int password_len, - int key_id) -{ - static struct wifi_autoreconnect_param param; - param.security_type = security_type; - param.ssid = ssid; - param.ssid_len = ssid_len; - param.password = password; - param.password_len = password_len; - param.key_id = key_id; - - if(!rtw_create_task(&g_wifi_auto_reconnect_task,"wifi_autoreconnect",512,TASK_PRORITY_IDEL+1,wifi_autoreconnect_thread, ¶m)) - WIFI_CONF_MSG("\n\rTCP ERROR: Create TCP server task failed."); -} - -int wifi_config_autoreconnect(__u8 mode, __u8 retry_times, __u16 timeout) -{ - p_wlan_autoreconnect_hdl = wifi_autoreconnect_hdl; - return wext_set_autoreconnect(WLAN0_NAME, mode, retry_times, timeout); -} - -int wifi_set_autoreconnect(__u8 mode) -{ - p_wlan_autoreconnect_hdl = wifi_autoreconnect_hdl; - return wifi_config_autoreconnect(mode, 3, 5);//default retry 3 times, timeout 5 seconds -} - -int wifi_get_autoreconnect(__u8 *mode) -{ - return wext_get_autoreconnect(WLAN0_NAME, mode); -} -#endif - -#ifdef CONFIG_CUSTOM_IE -/* - * Example for custom ie - * - * u8 test_1[] = {221, 2, 2, 2}; - * u8 test_2[] = {221, 2, 1, 1}; - * rtw_custom_ie_t buf[2] = {{test_1, PROBE_REQ}, - * {test_2, PROBE_RSP | BEACON}}; - * u8 buf_test2[] = {221, 2, 1, 3} ; - * rtw_custom_ie_t buf_update = {buf_test2, PROBE_REQ}; - * - * add ie list - * static void cmd_add_ie(int argc, char **argv) - * { - * wifi_add_custom_ie((void *)buf, 2); - * } - * - * update current ie - * static void cmd_update_ie(int argc, char **argv) - * { - * wifi_update_custom_ie(&buf_update, 2); - * } - * - * delete all ie - * static void cmd_del_ie(int argc, char **argv) - * { - * wifi_del_custom_ie(); - * } - */ - -int wifi_add_custom_ie(void *cus_ie, int ie_num) -{ - return wext_add_custom_ie(WLAN0_NAME, cus_ie, ie_num); -} - - -int wifi_update_custom_ie(void *cus_ie, int ie_index) -{ - return wext_update_custom_ie(WLAN0_NAME, cus_ie, ie_index); -} - -int wifi_del_custom_ie() -{ - return wext_del_custom_ie(WLAN0_NAME); -} - -#endif - -#ifdef CONFIG_PROMISC -extern void promisc_init_packet_filter(void); -extern int promisc_add_packet_filter(u8 filter_id, rtw_packet_filter_pattern_t *patt, rtw_packet_filter_rule_t rule); -extern int promisc_enable_packet_filter(u8 filter_id); -extern int promisc_disable_packet_filter(u8 filter_id); -extern int promisc_remove_packet_filter(u8 filter_id); -void wifi_init_packet_filter() -{ - promisc_init_packet_filter(); -} - -int wifi_add_packet_filter(unsigned char filter_id, rtw_packet_filter_pattern_t *patt, rtw_packet_filter_rule_t rule) -{ - return promisc_add_packet_filter(filter_id, patt, rule); -} - -int wifi_enable_packet_filter(unsigned char filter_id) -{ - return promisc_enable_packet_filter(filter_id); -} - -int wifi_disable_packet_filter(unsigned char filter_id) -{ - return promisc_disable_packet_filter(filter_id); -} - -int wifi_remove_packet_filter(unsigned char filter_id) -{ - return promisc_remove_packet_filter(filter_id); -} -#endif - -#ifdef CONFIG_AP_MODE -int wifi_enable_forwarding(void) -{ - return wext_enable_forwarding(WLAN0_NAME); -} - -int wifi_disable_forwarding(void) -{ - return wext_disable_forwarding(WLAN0_NAME); -} -#endif - -/* API to set flag for concurrent mode wlan1 issue_deauth when channel switched by wlan0 - * usage: wifi_set_ch_deauth(0) -> wlan0 wifi_connect -> wifi_set_ch_deauth(1) - */ -#ifdef CONFIG_CONCURRENT_MODE -int wifi_set_ch_deauth(__u8 enable) -{ - return wext_set_ch_deauth(WLAN1_NAME, enable); -} -#endif - -void wifi_set_indicate_mgnt(int enable) -{ - wext_set_indicate_mgnt(enable); - return; -} - -//----------------------------------------------------------------------------// -#endif //#if CONFIG_WLAN - diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/wifi/wifi_conf.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/wifi/wifi_conf.h index 21bd4fa97c..d858751333 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/wifi/wifi_conf.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/wifi/wifi_conf.h @@ -12,26 +12,31 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - ****************************************************************************** - * @file wifi_conf.h - * @author - * @version - * @brief This file provides user interface for Wi-Fi station and AP mode configuration - * base on the functionalities provided by Realtek Wi-Fi driver. - ****************************************************************************** */ + +/** + ****************************************************************************** + * @file wifi_conf.h + * @author + * @version + * @brief This file provides user interface for Wi-Fi station and AP mode configuration + * base on the functionalities provided by Realtek Wi-Fi driver. + ****************************************************************************** + */ #ifndef __WIFI_API_H #define __WIFI_API_H -#include "osdep_service.h" -#include "wifi_constants.h" -#include "wifi_structures.h" -#include "wifi_util.h" -#include "wifi_ind.h" -#ifndef CONFIG_MBED_ENABLED +/** @addtogroup nic NIC + * @ingroup wlan + * @brief NIC functions + * @{ + */ + +#include "wifi_constants.h" +#include "wifi_structures.h" +#include "wifi_util.h" +#include "wifi_ind.h" #include -#endif #ifdef __cplusplus extern "C" { @@ -44,7 +49,15 @@ #define RTW_ENABLE_API_INFO #ifdef RTW_ENABLE_API_INFO - #define RTW_API_INFO(args) do {printf args;} while(0) +#if defined(CONFIG_MBED_ENABLED) + extern __u32 GlobalDebugEnable; + #define RTW_API_INFO(...) do {\ + if (GlobalDebugEnable) \ + printf(__VA_ARGS__);\ + }while(0) +#else + #define RTW_API_INFO printf +#endif #else #define RTW_API_INFO(args) #endif @@ -225,18 +238,6 @@ int wifi_is_up(rtw_interface_t interface); * RTW_STA_INTERFACE, RTW_AP_INTERFACE * @return RTW_SUCCESS : if the interface is ready to * transceive ethernet packets - * @return RTW_NOTFOUND : no AP with a matching SSID was - * found - * @return RTW_NOT_AUTHENTICATED: a matching AP was found but - * it won't let you - * authenticate. This can - * occur if this device is - * in the block list on the - * AP. - * @return RTW_NOT_KEYED: the device has authenticated and - * associated but has not completed - * the key exchange. This can occur - * if the passphrase is incorrect. * @return RTW_ERROR : if the interface is not ready to * transceive ethernet packets */ @@ -297,6 +298,14 @@ int wifi_set_txpower(int poweridx); */ int wifi_get_associated_client_list(void * client_list_buffer, unsigned short buffer_length); +/** + * @brief Get connected AP's BSSID + * @param[out] bssid : the location where the AP BSSID will be stored + * @return RTW_SUCCESS : if result was successfully get + * @return RTW_ERROR : if result was not successfully get + */ +int wifi_get_ap_bssid(unsigned char *bssid); + /** * @brief Get the SoftAP information. * @param[out] ap_info: The location where the AP info will be stored. @@ -314,6 +323,15 @@ int wifi_get_ap_info(rtw_bss_info_t * ap_info, rtw_security_t* security); */ int wifi_set_country(rtw_country_code_t country_code); +/** + * @brief retrieved sta mode MAX data rate. + * @param[out] inidata_rate: MAX data rate. + * @return RTW_SUCCESS: If the INIDATA_RATE is successfully retrieved. + * @return RTW_ERROR: If the INIDATA_RATE is not retrieved. + * note: inidata_rate = 2 * (data rate), you need inidata_rate/2.0 to get the real rate + */ +int wifi_get_sta_max_data_rate(__u8 * inidata_rate); + /** * @brief Retrieve the latest RSSI value. * @param[out] pRSSI: Points to the integer to store the RSSI value gotten from driver. @@ -362,11 +380,21 @@ int wifi_register_multicast_address(rtw_mac_t *mac); int wifi_unregister_multicast_address(rtw_mac_t *mac); /** - * @brief Disable the adaptivity mode. + * @brief Setup the adaptivity mode. + * You can replace this weak function by the same name funcation to setup adaptivity mode you want. * @param None * @return If the function succeeds, the return value is 0. */ -void wifi_set_mib(void); +_WEAK void wifi_set_mib(void); + +/** + * @brief Setup country code. + * You can replace this weak function by the same name funcation to setup country code you want. + * @param None + * @return If the function succeeds, the return value is 0. + */ +//----------------------------------------------------------------------------// +_WEAK void wifi_set_country_code(void); /** * @brief Enable Wi-Fi RF. @@ -620,19 +648,31 @@ Set the network mode according to the data rate its supported. */ int wifi_set_network_mode(rtw_network_mode_t mode); +/** + * @brief Get the network mode. + * Driver works in BGN mode in default after driver initialization. This function is used to + * get the current wireless network mode for station mode. + * @param[in] pmode: Network mode to get. + * @return RTW_SUCCESS or RTW_ERROR. + */ +int wifi_get_network_mode(rtw_network_mode_t *pmode); + /** * @brief Set the chip to start or stop the promiscuous mode. - * @param[in] enabled: enabled can be set 0, 1 and 2. if enabled is zero, disable the promisc, else enable the promisc. + * @param[in] enabled: enabled can be set 0, 1, 2, 3 and 4. if enabled is zero, disable the promisc, else enable the promisc. * - 0 means disable the promisc. - * - 1 means enable the promisc. - * - 2 means enable the promisc special for length is used. + * - 1 means enable the promisc special for all ethernet frames. + * - 2 means enable the promisc special for Broadcast/Multicast ethernet frames. + * - 3 means enable the promisc special for all 802.11 frames. + * - 4 means enable the promisc special for Broadcast/Multicast 802.11 frames. * @param[in] callback: the callback function which will * receive and process the netowork data. - * @param[in] len_used: specify if the the promisc length is used. - * If len_used set to 1, packet length will be saved and transferred to callback function. + * @param[in] len_used: specify if the the promisc data length is used. + * If len_used set to 1, packet(frame data) length will be saved and transferred to callback function. * * @return RTW_SUCCESS or RTW_ERROR * @note This function can be used to implement vendor specified simple configure. + * @note To fetch Ethernet frames, the len_used should be set to 1 */ int wifi_set_promisc(rtw_rcr_level_t enabled, void (*callback)(unsigned char*, unsigned int, void*), unsigned char len_used); @@ -726,7 +766,6 @@ int wifi_get_autoreconnect(__u8 *mode); */ int wifi_get_last_error(void); - #ifdef CONFIG_CUSTOM_IE #ifndef BIT #define BIT(x) ((__u32)1 << (x)) @@ -742,7 +781,7 @@ enum CUSTOM_IE_TYPE{ PROBE_RSP = BIT(1), BEACON = BIT(2), }; -typedef uint32_t rtw_custom_ie_type_t; +typedef __u32 rtw_custom_ie_type_t; #endif /* _CUSTOM_IE_TYPE_ */ /* ie format @@ -837,13 +876,79 @@ int wifi_disable_packet_filter(unsigned char filter_id); int wifi_remove_packet_filter(unsigned char filter_id); #endif +/** + * @brief Get antenna infomation. + * @param[in] antenna: Points to store the antenna value gotten from driver, 0: main, 1: aux. + * @return 0 if success, otherwise return -1. + */ +#ifdef CONFIG_ANTENNA_DIVERSITY +int wifi_get_antenna_info(unsigned char *antenna); +#endif // #ifdef CONFIG_ANTENNA_DIVERSITY + void wifi_set_indicate_mgnt(int enable); +/** + * @brief Get the information of MP driver + * @param[out] ability : 0x1 stand for mp driver, and 0x0 stand for normal driver + * @return RTW_SUCCESS + */ +int wifi_get_drv_ability(uint32_t *ability); + +/** + * @brief Set channel plan into flash/efuse, must reboot after setting channel plan + * @param[in] channel_plan : the value of channel plan, define in wifi_constants.h + * @return RTW_SUCCESS or RTW_ERROR + */ +int wifi_set_channel_plan(uint8_t channel_plan); + +/** + * @brief Get channel plan from calibration section + * @param[out] channel_plan : point to the value of channel plan, define in wifi_constants.h + * @return RTW_SUCCESS or RTW_ERROR + */ +int wifi_get_channel_plan(uint8_t *channel_plan); + +#ifdef CONFIG_AP_MODE +/** + * @brief Enable packets forwarding in ap mode + * @return RTW_SUCCESS + */ +int wifi_enable_forwarding(void); + +/** + * @brief Disable packets forwarding in ap mode + * @return RTW_SUCCESS + */ +int wifi_disable_forwarding(void); +#endif + +#ifdef CONFIG_CONCURRENT_MODE +/** + * @brief Set flag for concurrent mode wlan1 issue_deauth when channel switched by wlan0 + * usage: wifi_set_ch_deauth(0) -> wlan0 wifi_connect -> wifi_set_ch_deauth(1) + * @param[in] enable : 0 for disable and 1 for enable + * @return RTW_SUCCESS + */ +int wifi_set_ch_deauth(__u8 enable); +#endif + +///@name Ameba1 Only +///@{ +/** + * @brief enable AP sending QoS Null0 Data to poll Sta be alive + * @param[in] enabled: enabled can be set to 0,1. + * - 0 means enable. + * - 1 means disable. + * @return None + */ +void wifi_set_ap_polling_sta(__u8 enabled); +///@} #ifdef __cplusplus } #endif +/*\@}*/ + #endif // __WIFI_API_H //----------------------------------------------------------------------------// - diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/wifi/wifi_ind.c b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/wifi/wifi_ind.c deleted file mode 100644 index e794ee81d4..0000000000 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/wifi/wifi_ind.c +++ /dev/null @@ -1,274 +0,0 @@ -/****************************************************************************** - * Copyright (c) 2013-2016 Realtek Semiconductor Corp. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -#include "wifi/wifi_ind.h" -#include "wifi/wifi_conf.h" -#include "osdep_service.h" -#include "platform_stdlib.h" - -/****************************************************** - * Constants - ******************************************************/ - -#define WIFI_INDICATE_MSG 0 -#define WIFI_MANAGER_STACKSIZE 1300 -#define WIFI_MANAGER_PRIORITY (0) //Actual priority is 4 since calling rtw_create_task -#define WIFI_MANAGER_Q_SZ 8 - -#define WIFI_EVENT_MAX_ROW 3 -/****************************************************** - * Globals - ******************************************************/ - -static event_list_elem_t event_callback_list[WIFI_EVENT_MAX][WIFI_EVENT_MAX_ROW]; -#if CONFIG_WIFI_IND_USE_THREAD -static rtw_worker_thread_t wifi_worker_thread; -#endif - -//----------------------------------------------------------------------------// -#if CONFIG_WIFI_IND_USE_THREAD -static rtw_result_t rtw_send_event_to_worker(int event_cmd, char *buf, int buf_len, int flags) -{ - rtw_event_message_t message; - int i; - rtw_result_t ret = RTW_SUCCESS; - char *local_buf = NULL; - - if(event_cmd >= WIFI_EVENT_MAX) - return RTW_BADARG; - - for(i = 0; i < WIFI_EVENT_MAX_ROW; i++){ - if(event_callback_list[event_cmd][i].handler == NULL) - continue; - - message.function = (event_handler_t)event_callback_list[event_cmd][i].handler; - message.buf_len = buf_len; - if(buf_len){ - local_buf = (char*)pvPortMalloc(buf_len); - if(local_buf == NULL) - return RTW_NOMEM; - memcpy(local_buf, buf, buf_len); - //printf("\n!!!!!Allocate %p(%d) for evcmd %d\n", local_buf, buf_len, event_cmd); - } - message.buf = local_buf; - message.flags = flags; - message.user_data = event_callback_list[event_cmd][i].handler_user_data; - - ret = rtw_push_to_xqueue(&wifi_worker_thread.event_queue, &message, 0); - if(ret != RTW_SUCCESS){ - if(local_buf){ - printf("\r\nrtw_send_event_to_worker: enqueue cmd %d failed and free %p(%d)\n", event_cmd, local_buf, buf_len); - vPortFree(local_buf); - } - break; - } - } - return ret; -} -#else -static rtw_result_t rtw_indicate_event_handle(int event_cmd, char *buf, int buf_len, int flags) -{ - rtw_event_handler_t handle = NULL; - int i; - - if(event_cmd >= WIFI_EVENT_MAX) - return RTW_BADARG; - - for(i = 0; i < WIFI_EVENT_MAX_ROW; i++){ - handle = event_callback_list[event_cmd][i].handler; - if(handle == NULL) - continue; - handle(buf, buf_len, flags, event_callback_list[event_cmd][i].handler_user_data); - } - - return RTW_SUCCESS; -} -#endif - -void wifi_indication( rtw_event_indicate_t event, char *buf, int buf_len, int flags) -{ - // - // If upper layer application triggers additional operations on receiving of wext_wlan_indicate, - // please strictly check current stack size usage (by using uxTaskGetStackHighWaterMark() ) - // , and tries not to share the same stack with wlan driver if remaining stack space is - // not available for the following operations. - // ex: using semaphore to notice another thread. - switch(event) - { - case WIFI_EVENT_DISCONNECT: -#if(WIFI_INDICATE_MSG==1) - printf("\n\r %s():Disconnection indication received", __FUNCTION__); -#endif - break; - case WIFI_EVENT_CONNECT: - // For WPA/WPA2 mode, indication of connection does not mean data can be - // correctly transmitted or received. Data can be correctly transmitted or - // received only when 4-way handshake is done. - // Please check WIFI_EVENT_FOURWAY_HANDSHAKE_DONE event -#if(WIFI_INDICATE_MSG==1) - // Sample: return mac address - if(buf != NULL && buf_len == 6) - { - printf("\n\r%s():Connect indication received: %02x:%02x:%02x:%02x:%02x:%02x", __FUNCTION__, - buf[0],buf[1],buf[2],buf[3],buf[4],buf[5]); - } -#endif - break; - case WIFI_EVENT_FOURWAY_HANDSHAKE_DONE: -#if(WIFI_INDICATE_MSG==1) - if(buf != NULL) - { - if(buf_len == strlen(IW_EXT_STR_FOURWAY_DONE)) - printf("\n\r%s():%s", __FUNCTION__, buf); - } -#endif - break; - case WIFI_EVENT_SCAN_RESULT_REPORT: -#if(WIFI_INDICATE_MSG==1) - printf("\n\r%s(): WIFI_EVENT_SCAN_RESULT_REPORT\n", __func__); -#endif - break; - case WIFI_EVENT_SCAN_DONE: -#if(WIFI_INDICATE_MSG==1) - printf("\n\r%s(): WIFI_EVENT_SCAN_DONE\n", __func__); -#endif - break; - case WIFI_EVENT_RECONNECTION_FAIL: -#if(WIFI_INDICATE_MSG==1) - if(buf != NULL){ - if(buf_len == strlen(IW_EXT_STR_RECONNECTION_FAIL)) - printf("\n\r%s", buf); - } -#endif - break; - case WIFI_EVENT_NO_NETWORK: -#if(WIFI_INDICATE_MSG==1) - printf("\n\r%s(): WIFI_EVENT_NO_NETWORK\n", __func__); -#endif - break; - case WIFI_EVENT_RX_MGNT: -#if(WIFI_INDICATE_MSG==1) - printf("\n\r%s(): WIFI_EVENT_RX_MGNT\n", __func__); -#endif - break; -#if CONFIG_ENABLE_P2P - case WIFI_EVENT_SEND_ACTION_DONE: -#if(WIFI_INDICATE_MSG==1) - printf("\n\r%s(): WIFI_EVENT_SEND_ACTION_DONE\n", __func__); -#endif - break; -#endif //CONFIG_ENABLE_P2P - case WIFI_EVENT_STA_ASSOC: -#if(WIFI_INDICATE_MSG==1) - printf("\n\r%s(): WIFI_EVENT_STA_ASSOC\n", __func__); -#endif - break; - case WIFI_EVENT_STA_DISASSOC: -#if(WIFI_INDICATE_MSG==1) - printf("\n\r%s(): WIFI_EVENT_STA_DISASSOC\n", __func__); -#endif - break; -#ifdef CONFIG_WPS - case WIFI_EVENT_STA_WPS_START: -#if(WIFI_INDICATE_MSG==1) - printf("\n\r%s(): WIFI_EVENT_STA_WPS_START\n", __func__); -#endif - break; - case WIFI_EVENT_WPS_FINISH: -#if(WIFI_INDICATE_MSG==1) - printf("\n\r%s(): WIFI_EVENT_WPS_FINISH\n", __func__); -#endif - break; - case WIFI_EVENT_EAPOL_RECVD: -#if(WIFI_INDICATE_MSG==1) - printf("\n\r%s(): WIFI_EVENT_EAPOL_RECVD\n", __func__); -#endif - break; -#endif - case WIFI_EVENT_BEACON_AFTER_DHCP: -#if(WIFI_INDICATE_MSG==1) - printf("\n\r%s(): WIFI_EVENT_BEACON_AFTER_DHCP\n", __func__); -#endif - break; - } - -#if CONFIG_INIC_EN - inic_indicate_event(event, buf, buf_len, flags); -#endif//CONFIG_INIC_EN - -#if CONFIG_WIFI_IND_USE_THREAD - rtw_send_event_to_worker(event, buf, buf_len, flags); -#else - rtw_indicate_event_handle(event, buf, buf_len, flags); -#endif -} - -void wifi_reg_event_handler(unsigned int event_cmds, rtw_event_handler_t handler_func, void *handler_user_data) -{ - int i = 0, j = 0; - if(event_cmds < WIFI_EVENT_MAX){ - for(i=0; i < WIFI_EVENT_MAX_ROW; i++){ - if(event_callback_list[event_cmds][i].handler == NULL){ - for(j=0; j - -// Add extra interfaces to make release sdk able to determine promisc API linking -void promisc_deinit(void *padapter) -{ -#ifdef CONFIG_PROMISC - _promisc_deinit(padapter); -#endif -} - -int promisc_recv_func(void *padapter, void *rframe) -{ - // Never reach here if not define CONFIG_PROMISC -#ifdef CONFIG_PROMISC - return _promisc_recv_func(padapter, rframe); -#else - return 0; -#endif -} - -int promisc_set(rtw_rcr_level_t enabled, void (*callback)(unsigned char*, unsigned int, void*), unsigned char len_used) -{ -#ifdef CONFIG_PROMISC - return _promisc_set(enabled, callback, len_used); -#else - return -1; -#endif -} - -unsigned char is_promisc_enabled(void) -{ -#ifdef CONFIG_PROMISC - return _is_promisc_enabled(); -#else - return 0; -#endif -} - -int promisc_get_fixed_channel(void *fixed_bssid, u8 *ssid, int *ssid_length) -{ -#ifdef CONFIG_PROMISC - return _promisc_get_fixed_channel(fixed_bssid, ssid, ssid_length); -#else - return 0; -#endif -} -// End of Add extra interfaces - -struct eth_frame { - struct eth_frame *prev; - struct eth_frame *next; - unsigned char da[6]; - unsigned char sa[6]; - unsigned int len; - unsigned char type; - signed char rssi; -}; - -#if CONFIG_INIC_CMD_RSP -#if defined(__IAR_SYSTEMS_ICC__) -#pragma pack(1) -#endif -struct inic_eth_frame { - unsigned char da[6]; - unsigned char sa[6]; - unsigned int len; - unsigned char type; -}; -#if defined(__IAR_SYSTEMS_ICC__) -#pragma pack() -#endif - -static struct inic_eth_frame *inic_frame, *inic_frame_tail = NULL; -static int inic_frame_cnt = 0; -#define MAX_INIC_FRAME_NUM 50 //maximum packets for each channel -extern void inic_c2h_msg(const char *atcmd, char status, char *msg, u16 msg_len); -#endif - -struct eth_buffer { - struct eth_frame *head; - struct eth_frame *tail; -}; - -static struct eth_buffer eth_buffer; - -#ifdef CONFIG_PROMISC -#define MAX_PACKET_FILTER_INFO 5 -#define FILTER_ID_INIT_VALUE 10 -rtw_packet_filter_info_t paff_array[MAX_PACKET_FILTER_INFO]={{0}, {0}, {0}, {0}, {0}}; -static u8 packet_filter_enable_num = 0; - -void promisc_init_packet_filter() -{ - int i = 0; - for(i=0; ioffset; - paff_array[i].patt.mask_size = patt->mask_size; - paff_array[i].patt.mask = rtw_malloc(patt->mask_size); - memcpy(paff_array[i].patt.mask, patt->mask, patt->mask_size); - paff_array[i].patt.pattern= rtw_malloc(patt->mask_size); - memcpy(paff_array[i].patt.pattern, patt->pattern, patt->mask_size); - - paff_array[i].rule = rule; - paff_array[i].enable = 0; - - return 0; -} - -int promisc_enable_packet_filter(u8 filter_id) -{ - int i = 0; - while(i < MAX_PACKET_FILTER_INFO){ - if(paff_array[i].filter_id == filter_id) - break; - i++; - } - - if(i == MAX_PACKET_FILTER_INFO) - return -1; - - paff_array[i].enable = 1; - packet_filter_enable_num++; - return 0; -} - -int promisc_disable_packet_filter(u8 filter_id) -{ - int i = 0; - while(i < MAX_PACKET_FILTER_INFO){ - if(paff_array[i].filter_id == filter_id) - break; - i++; - } - - if(i == MAX_PACKET_FILTER_INFO) - return -1; - - paff_array[i].enable = 0; - packet_filter_enable_num--; - return 0; -} - -int promisc_remove_packet_filter(u8 filter_id) -{ - int i = 0; - while(i < MAX_PACKET_FILTER_INFO){ - if(paff_array[i].filter_id == filter_id) - break; - i++; - } - - if(i == MAX_PACKET_FILTER_INFO) - return -1; - - paff_array[i].filter_id = FILTER_ID_INIT_VALUE; - paff_array[i].enable = 0; - paff_array[i].rule = 0; - if(paff_array[i].patt.mask){ - rtw_mfree((void *) paff_array[i].patt.mask, paff_array[i].patt.mask_size); - paff_array[i].patt.mask = NULL; - } - - if(paff_array[i].patt.pattern){ - rtw_mfree((void *) paff_array[i].patt.pattern, paff_array[i].patt.mask_size); - paff_array[i].patt.pattern = NULL; - } - paff_array[i].patt.mask_size = 0; - return 0; -} -#endif - -/* Make callback simple to prevent latency to wlan rx when promiscuous mode */ -static void promisc_callback(unsigned char *buf, unsigned int len, void* userdata) -{ - struct eth_frame *frame = (struct eth_frame *) rtw_malloc(sizeof(struct eth_frame)); - - if(frame) { - frame->prev = NULL; - frame->next = NULL; - memcpy(frame->da, buf, 6); - memcpy(frame->sa, buf+6, 6); - frame->len = len; - frame->rssi = ((ieee80211_frame_info_t *)userdata)->rssi; - _lock lock; - _irqL irqL; - rtw_enter_critical(&lock, &irqL); - - if(eth_buffer.tail) { - eth_buffer.tail->next = frame; - frame->prev = eth_buffer.tail; - eth_buffer.tail = frame; - } - else { - eth_buffer.head = frame; - eth_buffer.tail = frame; - } - - rtw_exit_critical(&lock, &irqL); - } -} - -struct eth_frame* retrieve_frame(void) -{ - struct eth_frame *frame = NULL; - - _lock lock; - _irqL irqL; - rtw_enter_critical(&lock, &irqL); - - if(eth_buffer.head) { - frame = eth_buffer.head; - - if(eth_buffer.head->next) { - eth_buffer.head = eth_buffer.head->next; - eth_buffer.head->prev = NULL; - } - else { - eth_buffer.head = NULL; - eth_buffer.tail = NULL; - } - } - - rtw_exit_critical(&lock, &irqL); - - return frame; -} - -static void promisc_test(int duration, unsigned char len_used) -{ - int ch; - unsigned int start_time; - struct eth_frame *frame; - eth_buffer.head = NULL; - eth_buffer.tail = NULL; - - wifi_enter_promisc_mode(); - wifi_set_promisc(RTW_PROMISC_ENABLE, promisc_callback, len_used); - - for(ch = 1; ch <= 13; ch ++) { - if(wifi_set_channel(ch) == 0) - printf("\n\n\rSwitch to channel(%d)", ch); - - start_time = rtw_get_current_time(); - - while(1) { - unsigned int current_time = rtw_get_current_time(); - - if(rtw_systime_to_ms(current_time - start_time) < (unsigned int)duration) { - frame = retrieve_frame(); - - if(frame) { - int i; - printf("\n\rDA:"); - for(i = 0; i < 6; i ++) - printf(" %02x", frame->da[i]); - printf(", SA:"); - for(i = 0; i < 6; i ++) - printf(" %02x", frame->sa[i]); - printf(", len=%d", frame->len); - printf(", RSSI=%d", frame->rssi); -#if CONFIG_INIC_CMD_RSP - if(inic_frame_tail){ - if(inic_frame_cnt < MAX_INIC_FRAME_NUM){ - memcpy(inic_frame_tail->da, frame->da, 6); - memcpy(inic_frame_tail->sa, frame->sa, 6); - inic_frame_tail->len = frame->len; - inic_frame_tail++; - inic_frame_cnt++; - } - } -#endif - rtw_mfree((void *) frame, sizeof(struct eth_frame)); - } - else - rtw_mdelay_os(1); //delay 1 tick - } - else - break; - } -#if CONFIG_INIC_CMD_RSP - if(inic_frame){ - inic_c2h_msg("ATWM", RTW_SUCCESS, (char *)inic_frame, sizeof(struct inic_eth_frame)*inic_frame_cnt); - memset(inic_frame, '\0', sizeof(struct inic_eth_frame)*MAX_INIC_FRAME_NUM); - inic_frame_tail = inic_frame; - inic_frame_cnt = 0; - rtw_msleep_os(10); - } -#endif - } - - wifi_set_promisc(RTW_PROMISC_DISABLE, NULL, 0); - - while((frame = retrieve_frame()) != NULL) - rtw_mfree((void *) frame, sizeof(struct eth_frame)); -} - -static void promisc_callback_all(unsigned char *buf, unsigned int len, void* userdata) -{ - struct eth_frame *frame = (struct eth_frame *) rtw_malloc(sizeof(struct eth_frame)); - - if(frame) { - frame->prev = NULL; - frame->next = NULL; - memcpy(frame->da, buf+4, 6); - memcpy(frame->sa, buf+10, 6); - frame->len = len; - /* - * type is the first byte of Frame Control Field of 802.11 frame - * If the from/to ds information is needed, type could be reused as follows: - * frame->type = ((((ieee80211_frame_info_t *)userdata)->i_fc & 0x0100) == 0x0100) ? 2 : 1; - * 1: from ds; 2: to ds - */ - frame->type = *buf; - frame->rssi = ((ieee80211_frame_info_t *)userdata)->rssi; - - _lock lock; - _irqL irqL; - rtw_enter_critical(&lock, &irqL); - - - if(eth_buffer.tail) { - eth_buffer.tail->next = frame; - frame->prev = eth_buffer.tail; - eth_buffer.tail = frame; - } - else { - eth_buffer.head = frame; - eth_buffer.tail = frame; - } - - rtw_exit_critical(&lock, &irqL); - } -} -static void promisc_test_all(int duration, unsigned char len_used) -{ - int ch; - unsigned int start_time; - struct eth_frame *frame; - eth_buffer.head = NULL; - eth_buffer.tail = NULL; - - wifi_enter_promisc_mode(); - wifi_set_promisc(RTW_PROMISC_ENABLE_2, promisc_callback_all, len_used); - - for(ch = 1; ch <= 13; ch ++) { - if(wifi_set_channel(ch) == 0) - printf("\n\n\rSwitch to channel(%d)", ch); - - start_time = rtw_get_current_time(); - - while(1) { - unsigned int current_time = rtw_get_current_time(); - - if(rtw_systime_to_ms(current_time - start_time) < (unsigned int)duration) { - frame = retrieve_frame(); - - if(frame) { - int i; - printf("\n\rTYPE: 0x%x, ", frame->type); - printf("DA:"); - for(i = 0; i < 6; i ++) - printf(" %02x", frame->da[i]); - printf(", SA:"); - for(i = 0; i < 6; i ++) - printf(" %02x", frame->sa[i]); - printf(", len=%d", frame->len); - printf(", RSSI=%d", frame->rssi); -#if CONFIG_INIC_CMD_RSP - if(inic_frame_tail){ - if(inic_frame_cnt < MAX_INIC_FRAME_NUM){ - memcpy(inic_frame_tail->da, frame->da, 6); - memcpy(inic_frame_tail->sa, frame->sa, 6); - inic_frame_tail->len = frame->len; - inic_frame_tail->type = frame->type; - inic_frame_tail++; - inic_frame_cnt++; - } - } -#endif - rtw_mfree((void *) frame, sizeof(struct eth_frame)); - } - else - rtw_mdelay_os(1); //delay 1 tick - } - else - break; - } -#if CONFIG_INIC_CMD_RSP - if(inic_frame){ - inic_c2h_msg("ATWM", RTW_SUCCESS, (char *)inic_frame, sizeof(struct inic_eth_frame)*inic_frame_cnt); - memset(inic_frame, '\0', sizeof(struct inic_eth_frame)*MAX_INIC_FRAME_NUM); - inic_frame_tail = inic_frame; - inic_frame_cnt = 0; - rtw_msleep_os(10); - } -#endif - } - - wifi_set_promisc(RTW_PROMISC_DISABLE, NULL, 0); - - while((frame = retrieve_frame()) != NULL) - rtw_mfree((void *) frame, sizeof(struct eth_frame)); -} - -void cmd_promisc(int argc, char **argv) -{ - int duration; -#if CONFIG_INIC_CMD_RSP - inic_frame_tail = inic_frame = rtw_malloc(sizeof(struct inic_eth_frame)*MAX_INIC_FRAME_NUM); - if(inic_frame == NULL){ - inic_c2h_msg("ATWM", RTW_BUFFER_UNAVAILABLE_TEMPORARY, NULL, 0); - return; - } -#endif - #ifdef CONFIG_PROMISC - wifi_init_packet_filter(); - #endif - if((argc == 2) && ((duration = atoi(argv[1])) > 0)) - //promisc_test(duration, 0); - promisc_test_all(duration, 0); - else if((argc == 3) && ((duration = atoi(argv[1])) > 0) && (strcmp(argv[2], "with_len") == 0)) - promisc_test(duration, 1); - else - printf("\n\rUsage: %s DURATION_SECONDS [with_len]", argv[0]); -#if CONFIG_INIC_CMD_RSP - if(inic_frame) - rtw_mfree(inic_frame, sizeof(struct inic_eth_frame)*MAX_INIC_FRAME_NUM); - inic_frame_tail = NULL; - inic_frame_cnt = 0; -#endif -} -#endif //#if CONFIG_WLAN - diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/wifi/wifi_util.c b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/wifi/wifi_util.c deleted file mode 100644 index e35fef0d0c..0000000000 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/wifi/wifi_util.c +++ /dev/null @@ -1,1344 +0,0 @@ -/****************************************************************************** - * Copyright (c) 2013-2016 Realtek Semiconductor Corp. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ -#include -#include -#include -#include -#include - -extern u32 GlobalDebugEnable; -#define WIFI_UTIL_MSG(...) do {\ - if (GlobalDebugEnable) \ - printf("\r" __VA_ARGS__);\ -}while(0) - -int iw_ioctl(const char *ifname, unsigned long request, struct iwreq *pwrq) -{ - memcpy(pwrq->ifr_name, ifname, 5); - return rltk_wlan_control(request, (void *) pwrq); -} - -int wext_get_ssid(const char *ifname, __u8 *ssid) -{ - struct iwreq iwr; - int ret = 0; - - memset(&iwr, 0, sizeof(iwr)); - iwr.u.essid.pointer = ssid; - iwr.u.essid.length = 32; - - if (iw_ioctl(ifname, SIOCGIWESSID, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCGIWESSID] ssid = NULL, not connected"); //do not use perror - ret = -1; - } else { - ret = iwr.u.essid.length; - if (ret > 32) - ret = 32; - /* Some drivers include nul termination in the SSID, so let's - * remove it here before further processing. WE-21 changes this - * to explicitly require the length _not_ to include nul - * termination. */ - if (ret > 0 && ssid[ret - 1] == '\0') - ret--; - ssid[ret] = '\0'; - } - - return ret; -} - -int wext_set_ssid(const char *ifname, const __u8 *ssid, __u16 ssid_len) -{ - struct iwreq iwr; - int ret = 0; - - memset(&iwr, 0, sizeof(iwr)); - iwr.u.essid.pointer = (void *) ssid; - iwr.u.essid.length = ssid_len; - iwr.u.essid.flags = (ssid_len != 0); - - if (iw_ioctl(ifname, SIOCSIWESSID, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCSIWESSID] error"); - ret = -1; - } - - return ret; -} - -int wext_set_bssid(const char *ifname, const __u8 *bssid) -{ - struct iwreq iwr; - int ret = 0; - - memset(&iwr, 0, sizeof(iwr)); - iwr.u.ap_addr.sa_family = ARPHRD_ETHER; - memcpy(iwr.u.ap_addr.sa_data, bssid, ETH_ALEN); - - if(bssid[ETH_ALEN]=='#' && bssid[ETH_ALEN + 1]=='@'){ - memcpy(iwr.u.ap_addr.sa_data + ETH_ALEN, bssid + ETH_ALEN, 6); - } - - if (iw_ioctl(ifname, SIOCSIWAP, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCSIWAP] error"); - ret = -1; - } - - return ret; -} - -int is_broadcast_ether_addr(const unsigned char *addr) -{ - return (addr[0] & addr[1] & addr[2] & addr[3] & addr[4] & addr[5]) == 0xff; -} - -int wext_set_auth_param(const char *ifname, __u16 idx, __u32 value) -{ - struct iwreq iwr; - int ret = 0; - - memset(&iwr, 0, sizeof(iwr)); - iwr.u.param.flags = idx & IW_AUTH_INDEX; - iwr.u.param.value = value; - - if (iw_ioctl(ifname, SIOCSIWAUTH, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rWEXT: SIOCSIWAUTH(param %d value 0x%x) failed)", idx, value); - } - - return ret; -} - -int wext_set_key_ext(const char *ifname, __u16 alg, const __u8 *addr, int key_idx, int set_tx, const __u8 *seq, __u16 seq_len, __u8 *key, __u16 key_len) -{ - struct iwreq iwr; - int ret = 0; - struct iw_encode_ext *ext; - - ext = (struct iw_encode_ext *) rtw_malloc(sizeof(struct iw_encode_ext) + key_len); - if (ext == NULL) - return -1; - else - memset(ext, 0, sizeof(struct iw_encode_ext) + key_len); - - memset(&iwr, 0, sizeof(iwr)); - iwr.u.encoding.flags = key_idx + 1; - iwr.u.encoding.flags |= IW_ENCODE_TEMP; - iwr.u.encoding.pointer = ext; - iwr.u.encoding.length = sizeof(struct iw_encode_ext) + key_len; - - if (alg == IW_ENCODE_DISABLED) - iwr.u.encoding.flags |= IW_ENCODE_DISABLED; - - if (addr == NULL || is_broadcast_ether_addr(addr)) - ext->ext_flags |= IW_ENCODE_EXT_GROUP_KEY; - - if (set_tx) - ext->ext_flags |= IW_ENCODE_EXT_SET_TX_KEY; - - ext->addr.sa_family = ARPHRD_ETHER; - - if (addr) - memcpy(ext->addr.sa_data, addr, ETH_ALEN); - else - memset(ext->addr.sa_data, 0xff, ETH_ALEN); - - if (key && key_len) { - memcpy(ext->key, key, key_len); - ext->key_len = key_len; - } - - ext->alg = alg; - - if (seq && seq_len) { - ext->ext_flags |= IW_ENCODE_EXT_RX_SEQ_VALID; - memcpy(ext->rx_seq, seq, seq_len); - } - - if (iw_ioctl(ifname, SIOCSIWENCODEEXT, &iwr) < 0) { - ret = -2; - WIFI_UTIL_MSG("\n\rioctl[SIOCSIWENCODEEXT] set key fail"); - } - - rtw_free(ext); - return ret; -} - -int wext_get_enc_ext(const char *ifname, __u16 *alg, __u8 *key_idx, __u8 *passphrase) -{ - struct iwreq iwr; - int ret = 0; - struct iw_encode_ext *ext; - - ext = (struct iw_encode_ext *) rtw_malloc(sizeof(struct iw_encode_ext) + 16); - if (ext == NULL) - return -1; - else - memset(ext, 0, sizeof(struct iw_encode_ext) + 16); - - iwr.u.encoding.pointer = ext; - - if (iw_ioctl(ifname, SIOCGIWENCODEEXT, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCGIWENCODEEXT] error"); - ret = -1; - } - else - { - *alg = ext->alg; - if(key_idx) - *key_idx = (__u8)iwr.u.encoding.flags; - if(passphrase) - memcpy(passphrase, ext->key, ext->key_len); - } - - if (ext != NULL) - rtw_free(ext); - - return ret; -} - -int wext_set_passphrase(const char *ifname, const __u8 *passphrase, __u16 passphrase_len) -{ - struct iwreq iwr; - int ret = 0; - - memset(&iwr, 0, sizeof(iwr)); - iwr.u.passphrase.pointer = (void *) passphrase; - iwr.u.passphrase.length = passphrase_len; - iwr.u.passphrase.flags = (passphrase_len != 0); - - if (iw_ioctl(ifname, SIOCSIWPRIVPASSPHRASE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCSIWESSID+0x1f] error"); - ret = -1; - } - - return ret; -} - -int wext_get_passphrase(const char *ifname, __u8 *passphrase) -{ - struct iwreq iwr; - int ret = 0; - - memset(&iwr, 0, sizeof(iwr)); - iwr.u.passphrase.pointer = (void *) passphrase; - - if (iw_ioctl(ifname, SIOCGIWPRIVPASSPHRASE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCGIWPRIVPASSPHRASE] error"); - ret = -1; - } - else { - ret = iwr.u.passphrase.length; - passphrase[ret] = '\0'; - } - - return ret; -} - -#if 0 -int wext_set_mac_address(const char *ifname, char * mac) -{ - char buf[13+17+1]; - rtw_memset(buf, 0, sizeof(buf)); - snprintf(buf, 13+17, "write_mac %s", mac); - return wext_private_command(ifname, buf, 0); -} - -int wext_get_mac_address(const char *ifname, char * mac) -{ - int ret = 0; - char buf[32]; - - rtw_memset(buf, 0, sizeof(buf)); - rtw_memcpy(buf, "read_mac", 8); - ret = wext_private_command_with_retval(ifname, buf, buf, 32); - strcpy(mac, buf); - return ret; -} -#endif - -int wext_enable_powersave(const char *ifname, __u8 ips_mode, __u8 lps_mode) -{ - struct iwreq iwr; - int ret = 0; - __u16 pindex = 0; - __u8 *para = NULL; - int cmd_len = 0; - - memset(&iwr, 0, sizeof(iwr)); - cmd_len = sizeof("pm_set"); - - // Encode parameters as TLV (type, length, value) format - para = rtw_malloc( 7 + (1+1+1) + (1+1+1) ); - if(para == NULL) return -1; - - snprintf((char*)para, cmd_len, "pm_set"); - pindex = 7; - - para[pindex++] = 0; // type 0 for ips - para[pindex++] = 1; - para[pindex++] = ips_mode; - - para[pindex++] = 1; // type 1 for lps - para[pindex++] = 1; - para[pindex++] = lps_mode; - - iwr.u.data.pointer = para; - iwr.u.data.length = pindex; - - if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCSIWPRIVAPESSID] error"); - ret = -1; - } - - rtw_free(para); - return ret; -} - -int wext_disable_powersave(const char *ifname) -{ - struct iwreq iwr; - int ret = 0; - __u16 pindex = 0; - __u8 *para = NULL; - int cmd_len = 0; - - memset(&iwr, 0, sizeof(iwr)); - cmd_len = sizeof("pm_set"); - - // Encode parameters as TLV (type, length, value) format - para = rtw_malloc( 7 + (1+1+1) + (1+1+1) ); - if(para == NULL) return -1; - - snprintf((char*)para, cmd_len, "pm_set"); - pindex = 7; - - para[pindex++] = 0; // type 0 for ips - para[pindex++] = 1; - para[pindex++] = 0; // ips = 0 - - para[pindex++] = 1; // type 1 for lps - para[pindex++] = 1; - para[pindex++] = 0; // lps = 0 - - iwr.u.data.pointer = para; - iwr.u.data.length = pindex; - - if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCSIWPRIVAPESSID] error"); - ret = -1; - } - - rtw_free(para); - return ret; - -} - -int wext_set_tdma_param(const char *ifname, __u8 slot_period, __u8 rfon_period_len_1, __u8 rfon_period_len_2, __u8 rfon_period_len_3) -{ - struct iwreq iwr; - int ret = 0; - __u16 pindex = 0; - __u8 *para = NULL; - int cmd_len = 0; - - memset(&iwr, 0, sizeof(iwr)); - cmd_len = sizeof("pm_set"); - - // Encode parameters as TLV (type, length, value) format - para = rtw_malloc( 7 + (1+1+4) ); - - snprintf((char*)para, cmd_len, "pm_set"); - pindex = 7; - - para[pindex++] = 2; // type 2 tdma param - para[pindex++] = 4; - para[pindex++] = slot_period; - para[pindex++] = rfon_period_len_1; - para[pindex++] = rfon_period_len_2; - para[pindex++] = rfon_period_len_3; - - iwr.u.data.pointer = para; - iwr.u.data.length = pindex; - - if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCSIWPRIVAPESSID] error"); - ret = -1; - } - - rtw_free(para); - return ret; -} - -int wext_set_lps_dtim(const char *ifname, __u8 lps_dtim) -{ - struct iwreq iwr; - int ret = 0; - __u16 pindex = 0; - __u8 *para = NULL; - int cmd_len = 0; - - memset(&iwr, 0, sizeof(iwr)); - cmd_len = sizeof("pm_set"); - - // Encode parameters as TLV (type, length, value) format - para = rtw_malloc( 7 + (1+1+1) ); - - snprintf((char*)para, cmd_len, "pm_set"); - pindex = 7; - - para[pindex++] = 3; // type 3 lps dtim - para[pindex++] = 1; - para[pindex++] = lps_dtim; - - iwr.u.data.pointer = para; - iwr.u.data.length = pindex; - - if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCSIWPRIVAPESSID] error"); - ret = -1; - } - - rtw_free(para); - return ret; -} - -int wext_get_lps_dtim(const char *ifname, __u8 *lps_dtim) -{ - - struct iwreq iwr; - int ret = 0; - __u16 pindex = 0; - __u8 *para = NULL; - int cmd_len = 0; - - memset(&iwr, 0, sizeof(iwr)); - cmd_len = sizeof("pm_get"); - - // Encode parameters as TLV (type, length, value) format - para = rtw_malloc( 7 + (1+1+1) ); - - snprintf((char*)para, cmd_len, "pm_get"); - pindex = 7; - - para[pindex++] = 3; // type 3 for lps dtim - para[pindex++] = 1; - para[pindex++] = 0; - - iwr.u.data.pointer = para; - iwr.u.data.length = pindex; - - if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCSIWPRIVAPESSID] error"); - ret = -1; - goto exit; - } - - //get result at the beginning of iwr.u.data.pointer - if((para[0]==3)&&(para[1]==1)) - *lps_dtim = para[2]; - else - WIFI_UTIL_MSG("\n\r%s error", __func__); - -exit: - rtw_free(para); - - return ret; -} - -int wext_set_tos_value(const char *ifname, __u8 *tos_value) -{ - struct iwreq iwr; - int ret = 0; - __u8 *para = NULL; - int cmd_len = sizeof("set_tos_value"); - - memset(&iwr, 0, sizeof(iwr)); - - para = rtw_malloc(cmd_len + 4); - snprintf((char*)para, cmd_len, "set_tos_value"); - - if (*tos_value >= 0 && *tos_value <=32){ - *(para + cmd_len) = 0x4f; - *(para + cmd_len+1) = 0xa4; - *(para + cmd_len+2) = 0; - *(para + cmd_len+3) = 0; - } - else if(*tos_value > 32 && *tos_value <=96){ - *(para + cmd_len) = 0x2b; - *(para + cmd_len+1) = 0xa4; - *(para + cmd_len+2) = 0; - *(para + cmd_len+3) = 0; - } - else if(*tos_value > 96 && *tos_value <= 160){ - *(para + cmd_len) = 0x22; - *(para + cmd_len+1) = 0x43; - *(para + cmd_len+2) = 0x5e; - *(para + cmd_len+3) = 0; - } - else if(*tos_value > 160){ - *(para + cmd_len) = 0x22; - *(para + cmd_len+1) = 0x32; - *(para + cmd_len+2) = 0x2f; - *(para + cmd_len+3) = 0; - } - - iwr.u.data.pointer = para; - iwr.u.data.length = cmd_len + 4; - - if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rwext_set_tos_value():ioctl[SIOCDEVPRIVATE] error"); - ret = -1; - } - - rtw_free(para); - return ret; -} - -int wext_get_tx_power(const char *ifname, __u8 *poweridx) -{ - struct iwreq iwr; - int ret = 0; - __u8 *para = NULL; - int cmd_len = sizeof("get_tx_power"); - - memset(&iwr, 0, sizeof(iwr)); - //Tx power size : 20 Bytes - //CCK 1M,2M,5.5M,11M : 4 Bytes - //OFDM 6M, 9M, 12M, 18M, 24M, 36M 48M, 54M : 8 Bytes - //MCS 0~7 : 8 Bytes - para = rtw_malloc(cmd_len + 20); - snprintf((char*)para, cmd_len, "get_tx_power"); - - iwr.u.data.pointer = para; - iwr.u.data.length = cmd_len + 20; - if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rwext_get_tx_power():ioctl[SIOCDEVPRIVATE] error"); - ret = -1; - } - - memcpy(poweridx,(__u8 *)(iwr.u.data.pointer),20); - rtw_free(para); - return ret; -} - -#if 0 -int wext_set_txpower(const char *ifname, int poweridx) -{ - int ret = 0; - char buf[24]; - - rtw_memset(buf, 0, sizeof(buf)); - snprintf(buf, 24, "txpower patha=%d", poweridx); - ret = wext_private_command(ifname, buf, 0); - - return ret; -} - -int wext_get_associated_client_list(const char *ifname, void * client_list_buffer, uint16_t buffer_length) -{ - int ret = 0; - char buf[25]; - - rtw_memset(buf, 0, sizeof(buf)); - snprintf(buf, 25, "get_client_list %x", client_list_buffer); - ret = wext_private_command(ifname, buf, 0); - - return ret; -} - -int wext_get_ap_info(const char *ifname, rtw_bss_info_t * ap_info, rtw_security_t* security) -{ - int ret = 0; - char buf[24]; - - rtw_memset(buf, 0, sizeof(buf)); - snprintf(buf, 24, "get_ap_info %x", ap_info); - ret = wext_private_command(ifname, buf, 0); - - snprintf(buf, 24, "get_security"); - ret = wext_private_command_with_retval(ifname, buf, buf, 24); - sscanf(buf, "%d", security); - - return ret; -} -#endif - -int wext_set_mode(const char *ifname, int mode) -{ - struct iwreq iwr; - int ret = 0; - - memset(&iwr, 0, sizeof(iwr)); - iwr.u.mode = mode; - if (iw_ioctl(ifname, SIOCSIWMODE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCSIWMODE] error"); - ret = -1; - } - - return ret; -} - -int wext_get_mode(const char *ifname, int *mode) -{ - struct iwreq iwr; - int ret = 0; - - memset(&iwr, 0, sizeof(iwr)); - - if (iw_ioctl(ifname, SIOCGIWMODE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCGIWMODE] error"); - ret = -1; - } - else - *mode = iwr.u.mode; - - return ret; -} - -int wext_set_ap_ssid(const char *ifname, const __u8 *ssid, __u16 ssid_len) -{ - struct iwreq iwr; - int ret = 0; - - memset(&iwr, 0, sizeof(iwr)); - iwr.u.essid.pointer = (void *) ssid; - iwr.u.essid.length = ssid_len; - iwr.u.essid.flags = (ssid_len != 0); - - if (iw_ioctl(ifname, SIOCSIWPRIVAPESSID, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCSIWPRIVAPESSID] error"); - ret = -1; - } - - return ret; -} - -int wext_set_country(const char *ifname, rtw_country_code_t country_code) -{ - struct iwreq iwr; - int ret = 0; - - memset(&iwr, 0, sizeof(iwr)); - - iwr.u.param.value = country_code; - - if (iw_ioctl(ifname, SIOCSIWPRIVCOUNTRY, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCSIWPRIVCOUNTRY] error"); - ret = -1; - } - return ret; -} - -int wext_get_rssi(const char *ifname, int *rssi) -{ - struct iwreq iwr; - int ret = 0; - - memset(&iwr, 0, sizeof(iwr)); - - if (iw_ioctl(ifname, SIOCGIWSENS, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCGIWSENS] error"); - ret = -1; - } else { - *rssi = 0 - iwr.u.sens.value; - } - return ret; -} - -int wext_set_pscan_channel(const char *ifname, __u8 *ch, __u8 *pscan_config, __u8 length) -{ - struct iwreq iwr; - int ret = 0; - __u8 *para = NULL; - int i =0; - - memset(&iwr, 0, sizeof(iwr)); - //Format of para:function_name num_channel chan1... pscan_config1 ... - para = rtw_malloc((length + length + 1) + 12);//size:num_chan + num_time + length + function_name - if(para == NULL) return -1; - - //Cmd - snprintf((char*)para, 12, "PartialScan"); - //length - *(para+12) = length; - for(i = 0; i < length; i++){ - *(para + 13 + i)= *(ch + i); - *((__u16*) (para + 13 + length + i))= *(pscan_config + i); - } - - iwr.u.data.pointer = para; - iwr.u.data.length = (length + length + 1) + 12; - if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rwext_set_pscan_channel():ioctl[SIOCDEVPRIVATE] error"); - ret = -1; - } - rtw_free(para); - return ret; -} -int wext_set_channel(const char *ifname, __u8 ch) -{ - struct iwreq iwr; - int ret = 0; - - memset(&iwr, 0, sizeof(iwr)); - iwr.u.freq.m = 0; - iwr.u.freq.e = 0; - iwr.u.freq.i = ch; - - if (iw_ioctl(ifname, SIOCSIWFREQ, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCSIWFREQ] error"); - ret = -1; - } - - return ret; -} - -int wext_get_channel(const char *ifname, __u8 *ch) -{ - struct iwreq iwr; - int ret = 0; - - memset(&iwr, 0, sizeof(iwr)); - - if (iw_ioctl(ifname, SIOCGIWFREQ, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCGIWFREQ] error"); - ret = -1; - } - else - *ch = iwr.u.freq.i; - - return ret; -} - -int wext_register_multicast_address(const char *ifname, rtw_mac_t *mac) -{ - int ret = 0; - char buf[32]; - - rtw_memset(buf, 0, sizeof(buf)); - snprintf(buf, 32, "reg_multicast "MAC_FMT, MAC_ARG(mac->octet)); - ret = wext_private_command(ifname, buf, 0); - - return ret; -} - -int wext_unregister_multicast_address(const char *ifname, rtw_mac_t *mac) -{ - int ret = 0; - char buf[35]; - - rtw_memset(buf, 0, sizeof(buf)); - snprintf(buf, 35, "reg_multicast -d "MAC_FMT, MAC_ARG(mac->octet)); - ret = wext_private_command(ifname, buf, 0); - - return ret; -} - -int wext_set_scan(const char *ifname, char *buf, __u16 buf_len, __u16 flags) -{ - struct iwreq iwr; - int ret = 0; - - memset(&iwr, 0, sizeof(iwr)); -#if 0 //for scan_with_ssid - if(buf) - memset(buf, 0, buf_len); -#endif - iwr.u.data.pointer = buf; - iwr.u.data.flags = flags; - iwr.u.data.length = buf_len; - if (iw_ioctl(ifname, SIOCSIWSCAN, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCSIWSCAN] error"); - ret = -1; - } - return ret; -} - -int wext_get_scan(const char *ifname, char *buf, __u16 buf_len) -{ - struct iwreq iwr; - int ret = 0; - - iwr.u.data.pointer = buf; - iwr.u.data.length = buf_len; - if (iw_ioctl(ifname, SIOCGIWSCAN, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCGIWSCAN] error"); - ret = -1; - }else - ret = iwr.u.data.flags; - return ret; -} - -int wext_private_command_with_retval(const char *ifname, char *cmd, char *ret_buf, int ret_len) -{ - struct iwreq iwr; - int ret = 0; - size_t buf_size; - char *buf; - - buf_size = 128; - if(strlen(cmd) >= buf_size) - buf_size = strlen(cmd) + 1; // 1 : '\0' - buf = (char*)rtw_malloc(buf_size); - if(!buf){ - WIFI_UTIL_MSG("\n\rWEXT: Can't malloc memory"); - return -1; - } - memset(buf, 0, buf_size); - strcpy(buf, cmd); - memset(&iwr, 0, sizeof(iwr)); - iwr.u.data.pointer = buf; - iwr.u.data.length = buf_size; - iwr.u.data.flags = 0; - - if ((ret = iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr)) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCDEVPRIVATE] error. ret=%d\n", ret); - } - if(ret_buf){ - if(ret_len > iwr.u.data.length) - ret_len = iwr.u.data.length; - rtw_memcpy(ret_buf, (char *) iwr.u.data.pointer, ret_len); - } - rtw_free(buf); - return ret; -} - -int wext_private_command(const char *ifname, char *cmd, int show_msg) -{ - struct iwreq iwr; - int ret = 0; - size_t buf_size; - char *buf; - - u8 cmdname[17] = {0}; // IFNAMSIZ+1 - - sscanf(cmd, "%16s", cmdname); - if((strcmp((const char *)cmdname, "config_get") == 0) - || (strcmp((const char *)cmdname, "config_set") == 0) - || (strcmp((const char *)cmdname, "efuse_get") == 0) - || (strcmp((const char *)cmdname, "efuse_set") == 0) - || (strcmp((const char *)cmdname, "mp_psd") == 0)) - buf_size = 2600;//2600 for config_get rmap,0,512 (or realmap) - else - buf_size = 512; - - if (strlen(cmd) >= buf_size) - buf_size = strlen(cmd) + 1; // 1 : '\0' - buf = (char*)rtw_malloc(buf_size); - if (!buf) { - WIFI_UTIL_MSG("\n\rWEXT: Can't malloc memory"); - return -1; - } - memset(buf, 0, buf_size); - strcpy(buf, cmd); - memset(&iwr, 0, sizeof(iwr)); - iwr.u.data.pointer = buf; - iwr.u.data.length = buf_size; - iwr.u.data.flags = 0; - - if ((ret = iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr)) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCDEVPRIVATE] error. ret=%d\n", ret); - } - if (show_msg && iwr.u.data.length) { - if(iwr.u.data.length > buf_size) - WIFI_UTIL_MSG("\n\rWEXT: Malloc memory is not enough"); - WIFI_UTIL_MSG("\n\rPrivate Message: %s", (char *) iwr.u.data.pointer); - } - rtw_free(buf); - return ret; -} - -void wext_wlan_indicate(unsigned int cmd, union iwreq_data *wrqu, char *extra) -{ - unsigned char null_mac[6] = {0}; - - switch(cmd) - { - case SIOCGIWAP: - if(wrqu->ap_addr.sa_family == ARPHRD_ETHER) - { - if(!memcmp(wrqu->ap_addr.sa_data, null_mac, sizeof(null_mac))) - wifi_indication(WIFI_EVENT_DISCONNECT, NULL, 0, 0); - else - wifi_indication(WIFI_EVENT_CONNECT, wrqu->ap_addr.sa_data, sizeof(null_mac), 0); - } - break; - - case IWEVCUSTOM: - if(extra) - { - if(!memcmp(IW_EXT_STR_FOURWAY_DONE, extra, strlen(IW_EXT_STR_FOURWAY_DONE))) - wifi_indication(WIFI_EVENT_FOURWAY_HANDSHAKE_DONE, extra, strlen(IW_EXT_STR_FOURWAY_DONE), 0); - else if(!memcmp(IW_EXT_STR_RECONNECTION_FAIL, extra, strlen(IW_EXT_STR_RECONNECTION_FAIL))) - wifi_indication(WIFI_EVENT_RECONNECTION_FAIL, extra, strlen(IW_EXT_STR_RECONNECTION_FAIL), 0); - else if(!memcmp(IW_EVT_STR_NO_NETWORK, extra, strlen(IW_EVT_STR_NO_NETWORK))) - wifi_indication(WIFI_EVENT_NO_NETWORK, extra, strlen(IW_EVT_STR_NO_NETWORK), 0); -#if CONFIG_ENABLE_P2P || defined(CONFIG_AP_MODE) - else if(!memcmp(IW_EVT_STR_STA_ASSOC, extra, strlen(IW_EVT_STR_STA_ASSOC))) - wifi_indication(WIFI_EVENT_STA_ASSOC, wrqu->data.pointer, wrqu->data.length, 0); - else if(!memcmp(IW_EVT_STR_STA_DISASSOC, extra, strlen(IW_EVT_STR_STA_DISASSOC))) - wifi_indication(WIFI_EVENT_STA_DISASSOC, wrqu->addr.sa_data, sizeof(null_mac), 0); - else if(!memcmp(IW_EVT_STR_SEND_ACTION_DONE, extra, strlen(IW_EVT_STR_SEND_ACTION_DONE))) - wifi_indication(WIFI_EVENT_SEND_ACTION_DONE, NULL, 0, wrqu->data.flags); -#endif - } - break; - case SIOCGIWSCAN: - if(wrqu->data.pointer == NULL) - wifi_indication(WIFI_EVENT_SCAN_DONE, NULL, 0, 0); - else - wifi_indication(WIFI_EVENT_SCAN_RESULT_REPORT, wrqu->data.pointer, wrqu->data.length, 0); - break; - case IWEVMGNTRECV: - wifi_indication(WIFI_EVENT_RX_MGNT, wrqu->data.pointer, wrqu->data.length, wrqu->data.flags); - break; -#ifdef REPORT_STA_EVENT - case IWEVREGISTERED: - if(wrqu->addr.sa_family == ARPHRD_ETHER) - wifi_indication(WIFI_EVENT_STA_ASSOC, wrqu->addr.sa_data, sizeof(null_mac), 0); - break; - case IWEVEXPIRED: - if(wrqu->addr.sa_family == ARPHRD_ETHER) - wifi_indication(WIFI_EVENT_STA_DISASSOC, wrqu->addr.sa_data, sizeof(null_mac), 0); - break; -#endif - default: - break; - - } - -} - - -int wext_send_eapol(const char *ifname, char *buf, __u16 buf_len, __u16 flags) -{ - struct iwreq iwr; - int ret = 0; - - memset(&iwr, 0, sizeof(iwr)); - iwr.u.data.pointer = buf; - iwr.u.data.length = buf_len; - iwr.u.data.flags = flags; - if (iw_ioctl(ifname, SIOCSIWEAPOLSEND, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCSIWEAPOLSEND] error"); - ret = -1; - } - return ret; -} - -int wext_send_mgnt(const char *ifname, char *buf, __u16 buf_len, __u16 flags) -{ - struct iwreq iwr; - int ret = 0; - - memset(&iwr, 0, sizeof(iwr)); - iwr.u.data.pointer = buf; - iwr.u.data.length = buf_len; - iwr.u.data.flags = flags; - if (iw_ioctl(ifname, SIOCSIWMGNTSEND, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCSIWMGNTSEND] error"); - ret = -1; - } - return ret; -} - -int wext_set_gen_ie(const char *ifname, char *buf, __u16 buf_len, __u16 flags) -{ - struct iwreq iwr; - int ret = 0; - - memset(&iwr, 0, sizeof(iwr)); - iwr.u.data.pointer = buf; - iwr.u.data.length = buf_len; - iwr.u.data.flags = flags; - if (iw_ioctl(ifname, SIOCSIWGENIE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rioctl[SIOCSIWGENIE] error"); - ret = -1; - } - return ret; -} - -int wext_set_autoreconnect(const char *ifname, __u8 mode, __u8 retry_times, __u16 timeout) -{ - struct iwreq iwr; - int ret = 0; - __u8 *para = NULL; - int cmd_len = 0; - - memset(&iwr, 0, sizeof(iwr)); - cmd_len = sizeof("SetAutoRecnt"); - para = rtw_malloc((4) + cmd_len);//size:para_len+cmd_len - if(para == NULL) return -1; - - //Cmd - snprintf((char*)para, cmd_len, "SetAutoRecnt"); - //length - *(para+cmd_len) = mode; //para1 - *(para+cmd_len+1) = retry_times; //para2 - *(para+cmd_len+2) = timeout; //para3 - - iwr.u.data.pointer = para; - iwr.u.data.length = (4) + cmd_len; - if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rwext_set_autoreconnect():ioctl[SIOCDEVPRIVATE] error"); - ret = -1; - } - rtw_free(para); - return ret; -} - -int wext_get_autoreconnect(const char *ifname, __u8 *mode) -{ - struct iwreq iwr; - int ret = 0; - __u8 *para = NULL; - int cmd_len = 0; - - memset(&iwr, 0, sizeof(iwr)); - cmd_len = sizeof("GetAutoRecnt"); - para = rtw_malloc(cmd_len);//size:para_len+cmd_len - //Cmd - snprintf((char*)para, cmd_len, "GetAutoRecnt"); - //length - - iwr.u.data.pointer = para; - iwr.u.data.length = cmd_len; - if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rwext_get_autoreconnect():ioctl[SIOCDEVPRIVATE] error"); - ret = -1; - } - *mode = *(__u8 *)(iwr.u.data.pointer); - rtw_free(para); - return ret; -} - -int wext_get_drv_ability(const char *ifname, __u32 *ability) -{ - int ret = 0; - char * buf = (char *)rtw_zmalloc(33); - if(buf == NULL) return -1; - - snprintf(buf, 33, "get_drv_ability %x", (unsigned int)ability); - ret = wext_private_command(ifname, buf, 0); - - rtw_free(buf); - return ret; -} - -#ifdef CONFIG_CUSTOM_IE -int wext_add_custom_ie(const char *ifname, void *cus_ie, int ie_num) -{ - struct iwreq iwr; - int ret = 0; - __u8 *para = NULL; - int cmd_len = 0; - if(ie_num <= 0 || !cus_ie){ - WIFI_UTIL_MSG("\n\rwext_add_custom_ie():wrong parameter"); - ret = -1; - return ret; - } - memset(&iwr, 0, sizeof(iwr)); - cmd_len = sizeof("SetCusIE"); - para = rtw_malloc((4)* 2 + cmd_len);//size:addr len+cmd_len - if(para == NULL) return -1; - - //Cmd - snprintf(para, cmd_len, "SetCusIE"); - //addr length - *(__u32 *)(para + cmd_len) = (__u32)cus_ie; //ie addr - //ie_num - *(__u32 *)(para + cmd_len + 4) = ie_num; //num of ie - - iwr.u.data.pointer = para; - iwr.u.data.length = (4)* 2 + cmd_len;// 2 input - if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rwext_add_custom_ie():ioctl[SIOCDEVPRIVATE] error"); - ret = -1; - } - rtw_free(para); - - return ret; -} - -int wext_update_custom_ie(const char *ifname, void * cus_ie, int ie_index) -{ - struct iwreq iwr; - int ret = 0; - __u8 *para = NULL; - int cmd_len = 0; - if(ie_index <= 0 || !cus_ie){ - WIFI_UTIL_MSG("\n\rwext_update_custom_ie():wrong parameter"); - ret = -1; - return ret; - } - memset(&iwr, 0, sizeof(iwr)); - cmd_len = sizeof("UpdateIE"); - para = rtw_malloc((4)* 2 + cmd_len);//size:addr len+cmd_len - if(para == NULL) return -1; - - //Cmd - snprintf(para, cmd_len, "UpdateIE"); - //addr length - *(__u32 *)(para + cmd_len) = (__u32)cus_ie; //ie addr - //ie_index - *(__u32 *)(para + cmd_len + 4) = ie_index; //num of ie - - iwr.u.data.pointer = para; - iwr.u.data.length = (4)* 2 + cmd_len;// 2 input - if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rwext_update_custom_ie():ioctl[SIOCDEVPRIVATE] error"); - ret = -1; - } - rtw_free(para); - - return ret; - -} - -int wext_del_custom_ie(const char *ifname) -{ - struct iwreq iwr; - int ret = 0; - __u8 *para = NULL; - int cmd_len = 0; - - memset(&iwr, 0, sizeof(iwr)); - cmd_len = sizeof("DelIE"); - para = rtw_malloc(cmd_len);//size:addr len+cmd_len - //Cmd - snprintf(para, cmd_len, "DelIE"); - - iwr.u.data.pointer = para; - iwr.u.data.length = cmd_len; - if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rwext_del_custom_ie():ioctl[SIOCDEVPRIVATE] error"); - ret = -1; - } - rtw_free(para); - - return ret; - - -} - -#endif - -#ifdef CONFIG_AP_MODE -int wext_enable_forwarding(const char *ifname) -{ - struct iwreq iwr; - int ret = 0; - __u8 *para = NULL; - int cmd_len = 0; - - memset(&iwr, 0, sizeof(iwr)); - cmd_len = sizeof("forwarding_set"); - para = rtw_malloc(cmd_len + 1); - if(para == NULL) return -1; - - // forwarding_set 1 - snprintf((char *) para, cmd_len, "forwarding_set"); - *(para + cmd_len) = '1'; - - iwr.u.essid.pointer = para; - iwr.u.essid.length = cmd_len + 1; - - if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rwext_enable_forwarding(): ioctl[SIOCDEVPRIVATE] error"); - ret = -1; - } - - rtw_free(para); - return ret; -} - -int wext_disable_forwarding(const char *ifname) -{ - struct iwreq iwr; - int ret = 0; - __u8 *para = NULL; - int cmd_len = 0; - - memset(&iwr, 0, sizeof(iwr)); - cmd_len = sizeof("forwarding_set"); - para = rtw_malloc(cmd_len + 1); - if(para == NULL) return -1; - - // forwarding_set 0 - snprintf((char *) para, cmd_len, "forwarding_set"); - *(para + cmd_len) = '0'; - - iwr.u.essid.pointer = para; - iwr.u.essid.length = cmd_len + 1; - - if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { - WIFI_UTIL_MSG("\n\rwext_disable_forwarding(): ioctl[SIOCDEVPRIVATE] error"); - ret = -1; - } - - rtw_free(para); - return ret; - -} -#endif - -#ifdef CONFIG_CONCURRENT_MODE -int wext_set_ch_deauth(const char *ifname, __u8 enable) -{ - int ret = 0; - char * buf = (char *)rtw_zmalloc(16); - if(buf == NULL) return -1; - - snprintf(buf, 16, "SetChDeauth %d", enable); - ret = wext_private_command(ifname, buf, 0); - - rtw_free(buf); - return ret; -} -#endif - -int wext_set_adaptivity(rtw_adaptivity_mode_t adaptivity_mode) -{ - extern u8 rtw_adaptivity_en; - extern u8 rtw_adaptivity_mode; - - switch(adaptivity_mode){ - case RTW_ADAPTIVITY_NORMAL: - rtw_adaptivity_en = 1; // enable adaptivity - rtw_adaptivity_mode = RTW_ADAPTIVITY_MODE_NORMAL; - break; - case RTW_ADAPTIVITY_CARRIER_SENSE: - rtw_adaptivity_en = 1; // enable adaptivity - rtw_adaptivity_mode = RTW_ADAPTIVITY_MODE_CARRIER_SENSE; - break; - case RTW_ADAPTIVITY_DISABLE: - default: - rtw_adaptivity_en = 0; //disable adaptivity - break; - } - return 0; -} - -int wext_set_adaptivity_th_l2h_ini(__u8 l2h_threshold) -{ - extern s8 rtw_adaptivity_th_l2h_ini; - rtw_adaptivity_th_l2h_ini = (__s8)l2h_threshold; - return 0; -} - -int wext_get_auto_chl(const char *ifname, unsigned char *channel_set, unsigned char channel_num) -{ - int ret = -1; - int channel = 0; - wext_disable_powersave(ifname); - if((channel = rltk_get_auto_chl(ifname,channel_set,channel_num)) != 0 ) - ret = channel; - wext_enable_powersave(ifname, 1, 1); - return ret; -} - -int wext_set_sta_num(unsigned char ap_sta_num) -{ - return rltk_set_sta_num(ap_sta_num); -} - -int wext_del_station(const char *ifname, unsigned char* hwaddr) -{ - return rltk_del_station(ifname, hwaddr); -} - -extern struct list_head *mf_list_head; -int wext_init_mac_filter(void) -{ - if (mf_list_head != NULL){ - return -1; - } - - mf_list_head = (struct list_head *)rtw_malloc(sizeof(struct list_head)); - if(mf_list_head == NULL){ - WIFI_UTIL_MSG("\n\r[ERROR] %s : can't allocate mf_list_head",__func__); - return -1; - } - - INIT_LIST_HEAD(mf_list_head); - - return 0; -} - -int wext_deinit_mac_filter(void) -{ - if (mf_list_head == NULL){ - return -1; - } - struct list_head *iterator; - rtw_mac_filter_list_t *item; - list_for_each(iterator, mf_list_head) { - item = list_entry(iterator, rtw_mac_filter_list_t, node); - list_del(iterator); - rtw_free(item); - item = NULL; - iterator = mf_list_head; - } - - rtw_free(mf_list_head); - mf_list_head = NULL; - return 0; -} - -int wext_add_mac_filter(unsigned char* hwaddr) -{ - if(mf_list_head == NULL){ - return -1; - } - - rtw_mac_filter_list_t *mf_list_new; - mf_list_new = (rtw_mac_filter_list_t *)rtw_malloc(sizeof(rtw_mac_filter_list_t)); - if(mf_list_new == NULL){ - WIFI_UTIL_MSG("\n\r[ERROR] %s : can't allocate mf_list_new",__func__); - return -1; - } - memcpy(mf_list_new->mac_addr,hwaddr,6); - list_add(&(mf_list_new->node), mf_list_head); - - return 0; -} - -int wext_del_mac_filter(unsigned char* hwaddr) -{ - if (mf_list_head == NULL){ - return -1; - } - - struct list_head *iterator; - rtw_mac_filter_list_t *item; - list_for_each(iterator, mf_list_head) { - item = list_entry(iterator, rtw_mac_filter_list_t, node); - if (memcmp(item->mac_addr, hwaddr, 6) == 0) { - list_del(iterator); - rtw_free(item); - item = NULL; - return 0; - } - } - return -1; -} - -extern void rtw_set_indicate_mgnt(int enable); -void wext_set_indicate_mgnt(int enable) -{ - rtw_set_indicate_mgnt(enable); - return; -} - diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/wifi/wifi_util.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/wifi/wifi_util.h index 3333fcf6bc..2a1e8da67b 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/wifi/wifi_util.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/api/wifi/wifi_util.h @@ -28,6 +28,8 @@ extern "C" { int wext_get_ssid(const char *ifname, __u8 *ssid); int wext_set_ssid(const char *ifname, const __u8 *ssid, __u16 ssid_len); +int wext_set_bssid(const char *ifname, const __u8 *bssid); +int wext_get_bssid(const char *ifname, __u8 *bssid); int wext_set_auth_param(const char *ifname, __u16 idx, __u32 value); int wext_set_key_ext(const char *ifname, __u16 alg, const __u8 *addr, int key_idx, int set_tx, const __u8 *seq, __u16 seq_len, __u8 *key, __u16 key_len); int wext_get_enc_ext(const char *ifname, __u16 *alg, __u8 *key_idx, __u8 *passphrase); diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/autoconf.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/autoconf.h index 3d69fff618..ddfed02ebe 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/autoconf.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/autoconf.h @@ -14,7 +14,6 @@ * limitations under the License. ******************************************************************************/ - #ifndef WLANCONFIG_H #define WLANCONFIG_H @@ -22,19 +21,42 @@ * Include user defined options first. Anything not defined in these files * will be set to standard values. Override anything you dont like! */ -#if defined(CONFIG_PLATFORM_8195A) || defined(CONFIG_PLATFORM_8711B) || defined(CONFIG_HARDWARE_8188F) #include "platform_opts.h" -#endif -#if defined(CONFIG_PLATFORM_8195A) || defined(CONFIG_PLATFORM_8711B) -#define CONFIG_PLATFORM_AMEBA_X +#if defined(CONFIG_PLATFORM_8195A) || defined(CONFIG_PLATFORM_8711B) || defined(CONFIG_PLATFORM_8721D) || defined(CONFIG_PLATFORM_8195BHP) +#ifndef CONFIG_PLATFORM_AMEBA_X +#define CONFIG_PLATFORM_AMEBA_X 1 #endif - -#if !defined(CONFIG_PLATFORM_AMEBA_X) -#define PLATFORM_FREERTOS 1 -#define CONFIG_GSPI_HCI #else -#define CONFIG_LX_HCI +#define CONFIG_PLATFORM_AMEBA_X 0 +#endif + +#if (CONFIG_PLATFORM_AMEBA_X == 1) + #if defined(CONFIG_PLATFORM_8195BHP) + #define CONFIG_AXI_HCI + #else + #define CONFIG_LX_HCI + #endif +#else + #define PLATFORM_FREERTOS 1 + #ifdef USE_SDIO_INTERFACE + #define CONFIG_SDIO_HCI + #else + #define CONFIG_GSPI_HCI +#endif +#endif // #if (CONFIG_PLATFORM_AMEBA_X == 1) + +#if defined(CONFIG_HARDWARE_8188F) || defined(CONFIG_HARDWARE_8192E)|| defined(CONFIG_HARDWARE_8723D) || defined(CONFIG_HARDWARE_8821C) || defined(CONFIG_PLATFORM_8195BHP) || defined(CONFIG_HARDWARE_8188E) || defined(CONFIG_PLATFORM_8721D) +#define CONFIG_FW_C2H_PKT +#define PHYDM_LINUX_CODING_STYLE 1 +#else +#define PHYDM_LINUX_CODING_STYLE 0 +#endif + +#if (PHYDM_LINUX_CODING_STYLE == 1) +#define PHYDM_NEW_INTERFACE 1 +#else +#define PHYDM_NEW_INTERFACE 0 #endif #ifndef CONFIG_INIC_EN @@ -51,20 +73,20 @@ #define RTW_NOTCH_FILTER 0 #define CONFIG_EMBEDDED_FWIMG #define CONFIG_PHY_SETTING_WITH_ODM -#if !defined(CONFIG_PLATFORM_AMEBA_X) +#if (CONFIG_PLATFORM_AMEBA_X == 0) #define CONFIG_ODM_REFRESH_RAMASK #define HAL_MAC_ENABLE 1 #define HAL_BB_ENABLE 1 #define HAL_RF_ENABLE 1 #endif -#if defined(CONFIG_PLATFORM_AMEBA_X) +#if (CONFIG_PLATFORM_AMEBA_X == 1) /* Patch when dynamic mechanism is not ready */ //#define CONFIG_DM_PATCH #endif //#define CONFIG_DEBUG //#define CONFIG_DEBUG_RTL871X -#if defined(CONFIG_PLATFORM_AMEBA_X) +#if (CONFIG_PLATFORM_AMEBA_X == 1) #define CONFIG_MEM_MONITOR MEM_MONITOR_SIMPLE #define WLAN_INTF_DBG 0 //#define CONFIG_DEBUG_DYNAMIC @@ -81,15 +103,20 @@ //#define CONFIG_DONT_CARE_TP //#define CONFIG_HIGH_TP //#define CONFIG_MEMORY_ACCESS_ALIGNED -#ifndef PLATFORM_CMSIS_RTOS // unsupported feature #define CONFIG_POWER_SAVING -#endif #ifdef CONFIG_POWER_SAVING #define CONFIG_IPS #define CONFIG_LPS //#define CONFIG_LPS_LCLK +#if (CONFIG_PLATFORM_AMEBA_X == 0) +#ifdef CONFIG_LPS_LCLK + #define CONFIG_DETECT_CPWM_BY_POLLING + #define LPS_RPWM_WAIT_MS 300 +#endif +#else #define CONFIG_LPS_32K #define TDMA_POWER_SAVING +#endif #define CONFIG_WAIT_PS_ACK #endif @@ -105,8 +132,12 @@ #define RX_AMSDU 0 #endif -#if defined(CONFIG_PLATFORM_AMEBA_X) - #if !defined(CONFIG_PLATFORM_8711B) +#if defined(CONFIG_PLATFORM_8711B) + #define CONFIG_FW_C2H_PKT +#endif + +#if (CONFIG_PLATFORM_AMEBA_X == 1) + #if defined(CONFIG_PLATFORM_8195A) #define CONFIG_USE_TCM_HEAP 1 /* USE TCM HEAP */ #endif #define CONFIG_RECV_TASKLET_THREAD @@ -126,7 +157,7 @@ #error "CONFIG_ISR_THREAD_MODE_POLLING and CONFIG_ISR_THREAD_MODE_INTERRUPT are mutually exclusive. " #endif -#if defined(CONFIG_PLATFORM_AMEBA_X) +#if (CONFIG_PLATFORM_AMEBA_X == 1) /* CRC DMEM optimized mode consume 1k less SRM memory consumption */ #define CRC_IMPLEMENTATION_MODE CRC_IMPLEMENTATION_DMEM_OPTIMIZED #endif @@ -136,7 +167,7 @@ #define AES_IMPLEMENTATION_MODE AES_IMPLEMENTATION_DMEM_OPTIMIZED #define USE_SKB_AS_XMITBUF 1 -#if defined(CONFIG_PLATFORM_AMEBA_X) +#if (CONFIG_PLATFORM_AMEBA_X == 1) #define USE_XMIT_EXTBUFF 1 #else #define USE_XMIT_EXTBUFF 0 @@ -149,7 +180,7 @@ #define NOT_SUPPORT_VHT #define NOT_SUPPORT_40M #define NOT_SUPPORT_80M -#ifndef CONFIG_PLATFORM_8711B +#if defined(CONFIG_PLATFORM_8195A) #define NOT_SUPPORT_BBSWING #endif #define NOT_SUPPORT_OLD_CHANNEL_PLAN @@ -164,7 +195,7 @@ #define CONFIG_AUTO_RECONNECT 1 #define ENABLE_HWPDN_PIN #define SUPPORT_SCAN_BUF 1 -#if !defined(CONFIG_PLATFORM_AMEBA_X) +#if (CONFIG_PLATFORM_AMEBA_X == 0) #define BE_I_CUT 1 #endif @@ -175,7 +206,6 @@ //#define CONFIG_WPA2_PREAUTH #define PSK_SUPPORT_TKIP 1 #endif -//#define AP_PSK_SUPPORT_TKIP /* For promiscuous mode */ #define CONFIG_PROMISC @@ -190,7 +220,7 @@ // for probe request with custom vendor specific IE #define CONFIG_CUSTOM_IE -#if !defined(CONFIG_PLATFORM_AMEBA_X) +#if (CONFIG_PLATFORM_AMEBA_X == 0) /* For multicast */ #define CONFIG_MULTICAST #endif @@ -201,20 +231,11 @@ #if defined(CONFIG_PLATFORM_8195A) #define CONFIG_RUNTIME_PORT_SWITCH #endif - #if defined(CONFIG_HARDWARE_8188F) - #define NET_IF_NUM 2 - #else #define NET_IF_NUM ((CONFIG_ETHERNET) + (CONFIG_WLAN) + 1) - #endif #else - #if defined(CONFIG_HARDWARE_8188F) - #define NET_IF_NUM 1 - #else #define NET_IF_NUM ((CONFIG_ETHERNET) + (CONFIG_WLAN)) - #endif #endif - /****************** For EAP auth configurations *******************/ #define CONFIG_TLS 0 #define CONFIG_PEAP 0 @@ -222,15 +243,17 @@ // DO NOT change the below config of EAP #ifdef PRE_CONFIG_EAP +#undef CONFIG_TLS #define CONFIG_TLS 1 +#undef CONFIG_PEAP #define CONFIG_PEAP 1 +#undef CONFIG_TTLS #define CONFIG_TTLS 1 #endif // enable 1X code in lib_wlan as default (increase 380 bytes) -#ifndef PLATFORM_CMSIS_RTOS // unsupported feature #define CONFIG_EAP -#endif + #if CONFIG_TLS || CONFIG_PEAP || CONFIG_TTLS #define EAP_REMOVE_UNUSED_CODE 1 #endif @@ -268,7 +291,7 @@ #define CONFIG_AP_MODE extern unsigned char g_user_ap_sta_num; #define USER_AP_STA_NUM g_user_ap_sta_num -#if defined(CONFIG_PLATFORM_AMEBA_X) +#if (CONFIG_PLATFORM_AMEBA_X == 1) #define AP_STA_NUM 3 //2014/10/27 modify to 3 #define USE_DEDICATED_BCN_TX 0 #if USE_DEDICATED_BCN_TX @@ -284,7 +307,7 @@ extern unsigned int g_ap_sta_num; #define CONFIG_AP_POLLING_CLIENT_ALIVE #endif #define CONFIG_NATIVEAP_MLME -#if defined(CONFIG_PLATFORM_AMEBA_X) +#if (CONFIG_PLATFORM_AMEBA_X == 1) #define CONFIG_INTERRUPT_BASED_TXBCN #endif #ifdef CONFIG_INTERRUPT_BASED_TXBCN @@ -292,14 +315,14 @@ extern unsigned int g_ap_sta_num; #define CONFIG_INTERRUPT_BASED_TXBCN_BCN_OK_ERR #endif // #define CONFIG_GK_REKEY -#if !defined(CONFIG_PLATFORM_AMEBA_X) +#if (CONFIG_PLATFORM_AMEBA_X == 0) #define USE_DEDICATED_BCN_TX 1 #endif #if CONFIG_INIC_EN // #define REPORT_STA_EVENT //useless #endif #else -#if !defined(CONFIG_PLATFORM_AMEBA_X) +#if (CONFIG_PLATFORM_AMEBA_X == 0) #define USE_DEDICATED_BCN_TX 0 #endif #endif @@ -308,14 +331,14 @@ extern unsigned int g_ap_sta_num; #error "If CONFIG_GK_REKEY when CONFIG_AP_MODE, need to CONFIG_MULTIPLE_WPA_STA" #endif -#if !defined(CONFIG_PLATFORM_AMEBA_X) +#if (CONFIG_PLATFORM_AMEBA_X == 0) #if !defined(CONFIG_AP_MODE) && defined(CONFIG_CONCURRENT_MODE) #error "If CONFIG_CONCURRENT_MODEE, need to CONFIG_AP_MODE" #endif #endif /* For efuse or flash config */ -#if defined(CONFIG_PLATFORM_AMEBA_X) +#if (CONFIG_PLATFORM_AMEBA_X == 1) #define CONFIG_RW_PHYSICAL_EFUSE 0 // Mask efuse user blocks #define CONFIG_HIDE_PROTECT_EFUSE 1 #define CONFIG_ADAPTOR_INFO_CACHING_FLASH 1 @@ -333,7 +356,7 @@ extern unsigned int g_ap_sta_num; #define MP_DRIVER 1 #define CONFIG_MP_IWPRIV_SUPPORT // #define HAL_EFUSE_MEMORY - #if defined(CONFIG_PLATFORM_AMEBA_X) + #if (CONFIG_PLATFORM_AMEBA_X == 1) #define MP_REG_TEST #endif #else @@ -342,10 +365,19 @@ extern unsigned int g_ap_sta_num; //Control wifi mcu function #define CONFIG_LITTLE_WIFI_MCU_FUNCTION_THREAD #define CONFIG_ODM_REFRESH_RAMASK + //#define CONFIG_ANTENNA_DIVERSITY + //#define CONFIG_BT_COEXIST #endif #endif // #ifdef CONFIG_MP_INCLUDED -#if defined(CONFIG_PLATFORM_AMEBA_X) +#ifdef CONFIG_BT_COEXIST + #undef NOT_SUPPORT_BT + #define CONFIG_BT_MAILBOX + #define CONFIG_BT_EFUSE + //#define CONFIG_BT_TWO_ANTENNA +#endif + +#if (CONFIG_PLATFORM_AMEBA_X == 1) #if defined(CONFIG_PLATFORM_8195A) #undef CONFIG_RTL8195A #define CONFIG_RTL8195A @@ -363,9 +395,109 @@ extern unsigned int g_ap_sta_num; #define CONFIG_MOVE_PSK_TO_ROM #define CONFIG_WOWLAN #define CONFIG_TRAFFIC_PROTECT + #define CONFIG_FABVERSION_UMC 1 + #if (CONFIG_INIC_EN == 1) + #undef CONFIG_PROMISC + #undef CONFIG_WPS + #undef CONFIG_AP_MODE + #undef CONFIG_NATIVEAP_MLME + #undef CONFIG_INTERRUPT_BASED_TXBCN + #undef CONFIG_INTERRUPT_BASED_TXBCN_BCN_OK_ERR + #undef USE_DEDICATED_BCN_TX + //#undef SUPPORT_SCAN_BUF + #undef CONFIG_CONCURRENT_MODE + #undef CONFIG_AUTO_RECONNECT + #endif + #endif + #if defined(CONFIG_PLATFORM_8721D) + #ifndef CONFIG_RTL8721D + #define CONFIG_RTL8721D + #endif + #undef NOT_SUPPORT_5G + #undef CONFIG_ADAPTOR_INFO_CACHING_FLASH + #define CONFIG_ADAPTOR_INFO_CACHING_FLASH 0 + #define CONFIG_EFUSE_SEPARATE + #define CONFIG_WOWLAN + #define CONFIG_TRAFFIC_PROTECT + #define SUPPORT_5G_CHANNEL 1 + #define DBG_DM_DIG 0 // DebugComponents: bit0 + //#define CONFIG_SUPPORT_DYNAMIC_TXPWR //rtw_phydm_fill_desc_dpt todo + #if (CONFIG_INIC_EN == 1) + #undef CONFIG_PROMISC + #undef CONFIG_WPS + #undef CONFIG_AP_MODE + #undef CONFIG_NATIVEAP_MLME + #undef CONFIG_INTERRUPT_BASED_TXBCN + #undef CONFIG_INTERRUPT_BASED_TXBCN_BCN_OK_ERR + #undef USE_DEDICATED_BCN_TX + //#undef SUPPORT_SCAN_BUF + #undef CONFIG_CONCURRENT_MODE + #undef CONFIG_AUTO_RECONNECT + #endif + #endif + #if defined(CONFIG_PLATFORM_8195BHP) + #define CONFIG_RTL8195B + #undef CONFIG_EAP +// #undef CONFIG_ADAPTOR_INFO_CACHING_FLASH +// #define CONFIG_ADAPTOR_INFO_CACHING_FLASH 0 + #undef CHECK_FLASH_VALID_MASK + #define CHECK_FLASH_VALID_MASK 0 + #undef CHECK_EFUSE_VALID_MASK + #define CHECK_EFUSE_VALID_MASK 0 + #undef CONFIG_RW_PHYSICAL_EFUSE + #define CONFIG_RW_PHYSICAL_EFUSE 1 // efuse_get realraw + #undef NOT_SUPPORT_5G + #undef NOT_SUPPORT_VHT + #undef NOT_SUPPORT_40M + #undef NOT_SUPPORT_80M + #define CONFIG_BW_80 + #define CONFIG_80211AC_VHT + #undef CONFIG_IPS +// #define CONFIG_NO_FW + #define CONFIG_EX_FW_BIN + #define LOAD_FW_HEADER_FROM_DRIVER +// #define RTW_IQK_FW_OFFLOAD + #define CONFIG_PHY_CAPABILITY_QUERY + #define CONFIG_FW_C2H_PKT + #define RTK_AC_SUPPORT + #define PHYDM_NEW_INTERFACE 1 + #define CONFIG_ISR_THREAD_MODE_INTERRUPT /* Wlan IRQ Interrupt Mode*/ +// #define CONFIG_WLAN_RF_CNTL + #define SUPPORT_5G_CHANNEL 1 + #define SUPPORTABLITY_PHYDMLIZE 1 + #define CONFIG_DFS + #ifdef CONFIG_DFS + #define CONFIG_DFS_ACTION + #endif + #undef CONFIG_RF_GAIN_OFFSET + + #define DBG_DM_DIG 0 // DebugComponents: bit0 +// #define CONFIG_DEBUG + + #define RTW_HALMAC /* Use HALMAC architecture */ + #define RTW_HALMAC_MU_BF 0 + #define RTW_HALMAC_SU_BF 0 + #define RTW_HALMAC_BT_COEX 0 + #define RTW_HALMAC_DUMP_INFO 0 + #define RTW_HALMAC_TXBF 0 + #define RTW_HALMAC_FW_OFFLOAD 0 + #define RTW_HALMAC_PHYSICAL_EFUSE 0 + #define RTW_HALMAC_SIZE_OPTIMIZATION 1 + #define RTW_HALMAC_SDIO_CIA_READ 0 + #define RTW_HALMAC_LTE_COEX 0 + + #define CONFIG_MAC_LOOPBACK_DRIVER_RTL8195B 0 #endif #elif defined(CONFIG_HARDWARE_8188F) #define CONFIG_RTL8188F +#elif defined(CONFIG_HARDWARE_8192E) +#define CONFIG_RTL8192E +#elif defined(CONFIG_HARDWARE_8821C) +#define CONFIG_RTL8821C +#elif defined(CONFIG_HARDWARE_8723D) +#define CONFIG_RTL8723D +#elif defined(CONFIG_HARDWARE_8188E) +#define CONFIG_RTL8188E #else #define CONFIG_RTL8188E #endif @@ -386,37 +518,57 @@ extern unsigned int g_ap_sta_num; #define RTL8188E_SUPPORT 0 #define RTL8188F_SUPPORT 0 #define RTL8711B_SUPPORT 0 +#define RTL8721D_SUPPORT 0 +#define RTL8821C_SUPPORT 0 +#define RTL8723D_SUPPORT 0 #if defined(CONFIG_PLATFORM_8195A) #undef RTL8195A_SUPPORT #define RTL8195A_SUPPORT 1 #elif defined(CONFIG_PLATFORM_8711B) #undef RTL8711B_SUPPORT #define RTL8711B_SUPPORT 1 +#elif defined(CONFIG_PLATFORM_8721D) +#undef RTL8721D_SUPPORT +#define RTL8721D_SUPPORT 1 +#elif defined(CONFIG_PLATFORM_8195BHP) +#undef RTL8195B_SUPPORT +#define RTL8195B_SUPPORT 1 #elif defined(CONFIG_HARDWARE_8188F) #undef RTL8188F_SUPPORT #define RTL8188F_SUPPORT 1 +#elif defined(CONFIG_HARDWARE_8192E) +#undef RTL8192E_SUPPORT +#define RTL8192E_SUPPORT 1 +#elif defined(CONFIG_HARDWARE_8821C) +#undef RTL8821C_SUPPORT +#define RTL8821C_SUPPORT 1 +#elif defined(CONFIG_HARDWARE_8723D) +#undef RTL8723D_SUPPORT +#define RTL8723D_SUPPORT 1 +#elif defined(CONFIG_HARDWARE_8188E) +#undef RTL8188E_SUPPORT +#define RTL8188E_SUPPORT 1 #else #undef RTL8188E_SUPPORT #define RTL8188E_SUPPORT 1 #endif -#define TEST_CHIP_SUPPORT 0 - -#define RTL8188E_FOR_TEST_CHIP 0 -#define RTL8188E_FPGA_TRUE_PHY_VERIFICATION 0 - // for Debug message #define DBG 0 -#if defined(CONFIG_PLATFORM_AMEBA_X) +#if (CONFIG_PLATFORM_AMEBA_X == 1) #if(DBG == 0) #define ROM_E_RTW_MSG 1 + #define ROM_F_RTW_MSG 1 +#if (CONFIG_INIC_EN == 0) && (PHYDM_LINUX_CODING_STYLE == 0) /* For DM debug*/ // BB #define DBG_RX_INFO 1 + #define DBG_DM_DIG 1 // DebugComponents: bit0 + #define DBG_DM_RA_MASK 1 // DebugComponents: bit1 + #define DBG_DM_ANT_DIV 1 // DebugComponents: bit6 #define DBG_TX_RATE 1 // DebugComponents: bit9 #define DBG_DM_RA 1 // DebugComponents: bit9 - #define DBG_DM_DIG 1 // DebugComponents: bit0 - #define DBG_DM_ADAPTIVITY 1 // DebugComponents: bit16 + #define DBG_DM_ADAPTIVITY 1 // DebugComponents: bit17 // RF #define DBG_PWR_TRACKING 1 // DebugComponents: bit24 #define DBG_RF_IQK 1 // DebugComponents: bit26 @@ -424,13 +576,23 @@ extern unsigned int g_ap_sta_num; #define DBG_PWR_INDEX 1 // DebugComponents: bit30 #endif #endif +#endif /* For DM support */ -#if defined(CONFIG_RTL8188F) +#if defined(CONFIG_RTL8188F) +#define RATE_ADAPTIVE_SUPPORT 0 +#elif defined(CONFIG_RTL8821C) +#define RATE_ADAPTIVE_SUPPORT 0 +#elif defined(CONFIG_RTL8192E) +#define RATE_ADAPTIVE_SUPPORT 0 +#elif defined(CONFIG_RTL8723D) #define RATE_ADAPTIVE_SUPPORT 0 #elif defined(CONFIG_PLATFORM_8711B) -#define RATE_ADAPTIVE_SUPPORT 1 +#define RATE_ADAPTIVE_SUPPORT 0 #define CONFIG_ODM_REFRESH_RAMASK +#elif defined(CONFIG_PLATFORM_8721D) +#define RATE_ADAPTIVE_SUPPORT 0 +//#define CONFIG_ODM_REFRESH_RAMASK #else #define RATE_ADAPTIVE_SUPPORT 1 #endif @@ -444,13 +606,13 @@ extern unsigned int g_ap_sta_num; #define CONFIG_RTW_ADAPTIVITY_DML 0 -#if defined(CONFIG_PLATFORM_AMEBA_X) +#if (CONFIG_PLATFORM_AMEBA_X == 1) #define CONFIG_POWER_TRAINING_WIL 0 // in RA #else #define POWER_BY_RATE_SUPPORT 0 #endif -#if defined(CONFIG_PLATFORM_AMEBA_X) +#if (CONFIG_PLATFORM_AMEBA_X == 1) #define RTL8195A_FOR_TEST_CHIP 0 //#define CONFIG_WIFI_TEST 1 @@ -466,7 +628,13 @@ extern unsigned int g_ap_sta_num; #endif #ifdef CONFIG_FPGA //Enable mac loopback for test mode (Ameba) - #define CONFIG_TWO_MAC_DRIVER // for test mode + #ifdef CONFIG_WIFI_NORMAL + #define CONFIG_TWO_MAC_DRIVER // for test mode + #else //CONFIG_WIFI_VERIFY + #define ENABLE_MAC_LB_FOR_TEST_MODE + #endif + + #define AP_PSK_SUPPORT_TKIP #endif #ifdef ENABLE_MAC_LB_FOR_TEST_MODE @@ -475,7 +643,7 @@ extern unsigned int g_ap_sta_num; #define CONFIG_LWIP_LAYER 0 #define CONFIG_WLAN_HAL_TEST #define CONFIG_WLAN_HAL_RX_TASK - #define CONFIG_MAC_LOOPBACK_DRIVER_RTL8711B 1 + #define CONFIG_MAC_LOOPBACK_DRIVER_AMEBA 1 #define HAL_MAC_ENABLE 1 #define CONFIG_TWO_MAC_TEST_MODE #define DISABLE_BB_RF 1 @@ -508,4 +676,27 @@ extern unsigned int g_ap_sta_num; #undef NOT_SUPPORT_40M #undef CONFIG_CONCURRENT_MODE #endif + +#if defined(CONFIG_HARDWARE_8821C) +#define FW_IQK +#define RTW_HALMAC +#define LOAD_FW_HEADER_FROM_DRIVER +#define RTW_HALMAC_SIZE_OPTIMIZATION 1 +//#define CONFIG_NO_FW +#ifdef NOT_SUPPORT_5G +#undef NOT_SUPPORT_5G +#define SUPPORT_5G_CHANNEL 1 +#endif +#endif + +#if defined(CONFIG_RTL8723D) +#define HAL_EFUSE_MEMORY +#endif + +#define CONFIG_DFS +//#define CONFIG_EMPTY_EFUSE_PG_ENABLE + +#define WLAN_WAPPER_VERSION 1 + #endif //WLANCONFIG_H + diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/drv_conf.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/drv_conf.h deleted file mode 100644 index db451a18f4..0000000000 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/drv_conf.h +++ /dev/null @@ -1,104 +0,0 @@ -/****************************************************************************** - * Copyright (c) 2013-2016 Realtek Semiconductor Corp. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ******************************************************************************/ - - -#ifndef __DRV_CONF_H__ -#define __DRV_CONF_H__ - -#include "autoconf.h" -#if ((RTL8195A_SUPPORT==1) || (RTL8711B_SUPPORT==1)) -#include "platform_autoconf.h" -#endif - -#if defined (PLATFORM_LINUX) && defined (PLATFORM_WINDOWS) - -#error "Shall be Linux or Windows, but not both!\n" - -#endif - -//Older Android kernel doesn't has CONFIG_ANDROID defined, -//add this to force CONFIG_ANDROID defined -#ifdef CONFIG_PLATFORM_ANDROID -#define CONFIG_ANDROID -#endif - -#ifdef CONFIG_ANDROID -//Some Android build will restart the UI while non-printable ascii is passed -//between java and c/c++ layer (JNI). We force CONFIG_VALIDATE_SSID -//for Android here. If you are sure there is no risk on your system about this, -//mask this macro define to support non-printable ascii ssid. -//#define CONFIG_VALIDATE_SSID -#ifdef CONFIG_PLATFORM_ARM_SUNxI - #ifdef CONFIG_VALIDATE_SSID - #undef CONFIG_VALIDATE_SSID - #endif -#endif - -//Android expect dbm as the rx signal strength unit -#define CONFIG_SIGNAL_DISPLAY_DBM -#endif - -#if defined(CONFIG_HAS_EARLYSUSPEND) && defined (CONFIG_RESUME_IN_WORKQUEUE) - #warning "You have CONFIG_HAS_EARLYSUSPEND enabled in your system, we disable CONFIG_RESUME_IN_WORKQUEUE automatically" - #undef CONFIG_RESUME_IN_WORKQUEUE -#endif - -#if defined(CONFIG_ANDROID_POWER) && defined (CONFIG_RESUME_IN_WORKQUEUE) - #warning "You have CONFIG_ANDROID_POWER enabled in your system, we disable CONFIG_RESUME_IN_WORKQUEUE automatically" - #undef CONFIG_RESUME_IN_WORKQUEUE -#endif - -#ifdef CONFIG_RESUME_IN_WORKQUEUE //this can be removed, because there is no case for this... - #if !defined( CONFIG_WAKELOCK) && !defined(CONFIG_ANDROID_POWER) - #error "enable CONFIG_RESUME_IN_WORKQUEUE without CONFIG_WAKELOCK or CONFIG_ANDROID_POWER will suffer from the danger of wifi's unfunctionality..." - #error "If you still want to enable CONFIG_RESUME_IN_WORKQUEUE in this case, mask this preprossor checking and GOOD LUCK..." - #endif -#endif - -//About USB VENDOR REQ -#if defined(CONFIG_USB_VENDOR_REQ_BUFFER_PREALLOC) && !defined(CONFIG_USB_VENDOR_REQ_MUTEX) - #warning "define CONFIG_USB_VENDOR_REQ_MUTEX for CONFIG_USB_VENDOR_REQ_BUFFER_PREALLOC automatically" - #define CONFIG_USB_VENDOR_REQ_MUTEX -#endif -#if defined(CONFIG_VENDOR_REQ_RETRY) && !defined(CONFIG_USB_VENDOR_REQ_MUTEX) - #warning "define CONFIG_USB_VENDOR_REQ_MUTEX for CONFIG_VENDOR_REQ_RETRY automatically" - #define CONFIG_USB_VENDOR_REQ_MUTEX -#endif - -#ifndef CONFIG_RTW_ADAPTIVITY_EN - #define CONFIG_RTW_ADAPTIVITY_EN 0 -#endif - -#ifndef CONFIG_RTW_ADAPTIVITY_MODE - #define CONFIG_RTW_ADAPTIVITY_MODE 0 -#endif - -#ifndef CONFIG_RTW_ADAPTIVITY_DML - #define CONFIG_RTW_ADAPTIVITY_DML 0 -#endif - -#ifndef CONFIG_RTW_ADAPTIVITY_DC_BACKOFF - #define CONFIG_RTW_ADAPTIVITY_DC_BACKOFF 4 -#endif - -#ifndef CONFIG_RTW_NHM_EN - #define CONFIG_RTW_NHM_EN 0 -#endif - -//#include - -#endif // __DRV_CONF_H__ - diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/rom_aes.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/rom_aes.h deleted file mode 100644 index 304da937be..0000000000 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/rom_aes.h +++ /dev/null @@ -1,52 +0,0 @@ -/****************************************************************************** - * - * mbed Microcontroller Library - * Copyright (c) 2013-2016 Realtek Semiconductor Corp. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ****************************************************************************** - * - * This is ROM code section. - * - ******************************************************************************/ -#ifndef ROM_AES_H -#define ROM_AES_H - -typedef struct -{ - u32 erk[64]; /* encryption round keys */ - u32 drk[64]; /* decryption round keys */ - int nr; /* number of rounds */ -}aes_context; - - -#define AES_BLOCKSIZE8 8 -#define AES_BLK_SIZE 16 // # octets in an AES block -typedef union _aes_block // AES cipher block -{ - unsigned long x[AES_BLK_SIZE/4]; // access as 8-bit octets or 32-bit words - unsigned char b[AES_BLK_SIZE]; -}aes_block; - - -void AES_WRAP(unsigned char * plain, int plain_len, - unsigned char * iv, int iv_len, - unsigned char * kek, int kek_len, - unsigned char *cipher, unsigned short *cipher_len); - -void AES_UnWRAP(unsigned char * cipher, int cipher_len, - unsigned char * kek, int kek_len, - unsigned char * plain); - -#endif diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/rtw_debug.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/rtw_debug.h deleted file mode 100644 index 92fa79d7a5..0000000000 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/rtw_debug.h +++ /dev/null @@ -1,453 +0,0 @@ -/****************************************************************************** - * Copyright (c) 2013-2016 Realtek Semiconductor Corp. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ******************************************************************************/ - -#ifndef __RTW_DEBUG_H__ -#define __RTW_DEBUG_H__ - - -#define _drv_always_ 1 -#define _drv_emerg_ 2 -#define _drv_alert_ 3 -#define _drv_crit_ 4 -#define _drv_err_ 5 -#define _drv_warning_ 6 -#define _drv_notice_ 7 -#define _drv_info_ 8 -#define _drv_dump_ 9 -#define _drv_debug_ 10 - - -#define _module_rtl871x_xmit_c_ BIT(0) -#define _module_xmit_osdep_c_ BIT(1) -#define _module_rtl871x_recv_c_ BIT(2) -#define _module_recv_osdep_c_ BIT(3) -#define _module_rtl871x_mlme_c_ BIT(4) -#define _module_mlme_osdep_c_ BIT(5) -#define _module_rtl871x_sta_mgt_c_ BIT(6) -#define _module_rtl871x_cmd_c_ BIT(7) -#define _module_cmd_osdep_c_ BIT(8) -#define _module_rtl871x_io_c_ BIT(9) -#define _module_io_osdep_c_ BIT(10) -#define _module_os_intfs_c_ BIT(11) -#define _module_rtl871x_security_c_ BIT(12) -#define _module_rtl871x_eeprom_c_ BIT(13) -#define _module_hal_init_c_ BIT(14) -#define _module_hci_hal_init_c_ BIT(15) -#define _module_rtl871x_ioctl_c_ BIT(16) -#define _module_rtl871x_ioctl_set_c_ BIT(17) -#define _module_rtl871x_ioctl_query_c_ BIT(18) -#define _module_rtl871x_pwrctrl_c_ BIT(19) -#define _module_hci_intfs_c_ BIT(20) -#define _module_hci_ops_c_ BIT(21) -#define _module_osdep_service_c_ BIT(22) -#define _module_mp_ BIT(23) -#define _module_hci_ops_os_c_ BIT(24) -#define _module_rtl871x_ioctl_os_c BIT(25) -#define _module_rtl8712_cmd_c_ BIT(26) -#define _module_fwcmd_c_ BIT(27) -#define _module_rtl8192c_xmit_c_ BIT(28) -#define _module_hal_xmit_c_ BIT(28) -#define _module_efuse_ BIT(29) -#define _module_rtl8712_recv_c_ BIT(30) -#define _module_rtl8712_led_c_ BIT(31) - -#undef _MODULE_DEFINE_ - -#if defined _RTW_XMIT_C_ - #define _MODULE_DEFINE_ _module_rtl871x_xmit_c_ -#elif defined _XMIT_OSDEP_C_ - #define _MODULE_DEFINE_ _module_xmit_osdep_c_ -#elif defined _RTW_RECV_C_ - #define _MODULE_DEFINE_ _module_rtl871x_recv_c_ -#elif defined _RECV_OSDEP_C_ - #define _MODULE_DEFINE_ _module_recv_osdep_c_ -#elif defined _RTW_MLME_C_ - #define _MODULE_DEFINE_ _module_rtl871x_mlme_c_ -#elif defined _MLME_OSDEP_C_ - #define _MODULE_DEFINE_ _module_mlme_osdep_c_ -#elif defined _RTW_MLME_EXT_C_ - #define _MODULE_DEFINE_ 1 -#elif defined _RTW_STA_MGT_C_ - #define _MODULE_DEFINE_ _module_rtl871x_sta_mgt_c_ -#elif defined _RTW_CMD_C_ - #define _MODULE_DEFINE_ _module_rtl871x_cmd_c_ -#elif defined _CMD_OSDEP_C_ - #define _MODULE_DEFINE_ _module_cmd_osdep_c_ -#elif defined _RTW_IO_C_ - #define _MODULE_DEFINE_ _module_rtl871x_io_c_ -#elif defined _IO_OSDEP_C_ - #define _MODULE_DEFINE_ _module_io_osdep_c_ -#elif defined _OS_INTFS_C_ - #define _MODULE_DEFINE_ _module_os_intfs_c_ -#elif defined _RTW_SECURITY_C_ - #define _MODULE_DEFINE_ _module_rtl871x_security_c_ -#elif defined _RTW_EEPROM_C_ - #define _MODULE_DEFINE_ _module_rtl871x_eeprom_c_ -#elif defined _HAL_INTF_C_ - #define _MODULE_DEFINE_ _module_hal_init_c_ -#elif (defined _HCI_HAL_INIT_C_) || (defined _SDIO_HALINIT_C_) - #define _MODULE_DEFINE_ _module_hci_hal_init_c_ -#elif defined _RTL871X_IOCTL_C_ - #define _MODULE_DEFINE_ _module_rtl871x_ioctl_c_ -#elif defined _RTL871X_IOCTL_SET_C_ - #define _MODULE_DEFINE_ _module_rtl871x_ioctl_set_c_ -#elif defined _RTL871X_IOCTL_QUERY_C_ - #define _MODULE_DEFINE_ _module_rtl871x_ioctl_query_c_ -#elif defined _RTL871X_PWRCTRL_C_ - #define _MODULE_DEFINE_ _module_rtl871x_pwrctrl_c_ -#elif defined _RTW_PWRCTRL_C_ - #define _MODULE_DEFINE_ 1 -#elif defined _HCI_INTF_C_ - #define _MODULE_DEFINE_ _module_hci_intfs_c_ -#elif defined _HCI_OPS_C_ - #define _MODULE_DEFINE_ _module_hci_ops_c_ -#elif defined _SDIO_OPS_C_ - #define _MODULE_DEFINE_ 1 -#elif defined _OSDEP_HCI_INTF_C_ - #define _MODULE_DEFINE_ _module_hci_intfs_c_ -#elif defined _OSDEP_SERVICE_C_ - #define _MODULE_DEFINE_ _module_osdep_service_c_ -#elif defined _HCI_OPS_OS_C_ - #define _MODULE_DEFINE_ _module_hci_ops_os_c_ -#elif defined _RTL871X_IOCTL_LINUX_C_ - #define _MODULE_DEFINE_ _module_rtl871x_ioctl_os_c -#elif defined _RTL8712_CMD_C_ - #define _MODULE_DEFINE_ _module_rtl8712_cmd_c_ -#elif defined _RTL8192C_XMIT_C_ - #define _MODULE_DEFINE_ 1 -#elif defined _RTL8723AS_XMIT_C_ - #define _MODULE_DEFINE_ 1 -#elif defined _RTL8712_RECV_C_ - #define _MODULE_DEFINE_ _module_rtl8712_recv_c_ -#elif defined _RTL8192CU_RECV_C_ - #define _MODULE_DEFINE_ _module_rtl8712_recv_c_ -#elif defined _RTL871X_MLME_EXT_C_ - #define _MODULE_DEFINE_ _module_mlme_osdep_c_ -#elif defined _RTW_MP_C_ - #define _MODULE_DEFINE_ _module_mp_ -#elif defined _RTW_MP_IOCTL_C_ - #define _MODULE_DEFINE_ _module_mp_ -#elif defined _RTW_EFUSE_C_ - #define _MODULE_DEFINE_ _module_efuse_ -#endif - -#ifdef PLATFORM_OS_CE -extern void rtl871x_cedbg(const char *fmt, ...); -#endif - -#define RT_TRACE(_Comp, _Level, Fmt) do{}while(0) -#define _func_enter_ do{}while(0) -#define _func_exit_ do{}while(0) -#define RT_PRINT_DATA(_Comp, _Level, _TitleString, _HexData, _HexDataLen) do{}while(0) - -#ifdef PLATFORM_WINDOWS - #define DBG_871X do {} while(0) - #define MSG_8192C do {} while(0) - #define DBG_8192C do {} while(0) - #define DBG_871X_LEVEL do {} while(0) -#else - #define DBG_871X(x, ...) do {} while(0) - #define MSG_8192C(x, ...) do {} while(0) - #define DBG_8192C(x,...) do {} while(0) - #define DBG_871X_LEVEL(x,...) do {} while(0) -#endif - -#undef _dbgdump -#ifdef PLATFORM_WINDOWS - - #ifdef PLATFORM_OS_XP - #define _dbgdump DbgPrint - #elif defined PLATFORM_OS_CE - #define _dbgdump rtl871x_cedbg - #endif - -#elif defined PLATFORM_LINUX - #define _dbgdump printk -#elif defined PLATFORM_ECOS - #define _dbgdump diag_printf -#elif defined(PLATFORM_FREERTOS) || defined (PLATFORM_CMSIS_RTOS) - #define _dbgdump printf("\n\r"); printf -#elif defined PLATFORM_FREEBSD - #define _dbgdump printf -#endif - -#if !defined(CONFIG_PLATFORM_8195A) && !defined(CONFIG_PLATFORM_8711B) -#define DRIVER_PREFIX "RTL871X: " -#endif - -#define DEBUG_LEVEL (_drv_err_) -#if defined (_dbgdump) - #undef DBG_871X_LEVEL -#if defined (__ICCARM__) || defined (__CC_ARM) ||defined(__GNUC__)|| defined(CONFIG_PLATFORM_8195A) || defined(CONFIG_PLATFORM_8711B) - #define DBG_871X_LEVEL(level, ...) \ - do {\ - _dbgdump(DRIVER_PREFIX __VA_ARGS__);\ - }while(0) -#else - #define DBG_871X_LEVEL(level, fmt, arg...) \ - do {\ - if (level <= DEBUG_LEVEL) {\ - if (level <= _drv_err_ && level > _drv_always_) {\ - _dbgdump(DRIVER_PREFIX"ERROR " fmt, ##arg);\ - } \ - else {\ - _dbgdump(DRIVER_PREFIX fmt, ##arg);\ - } \ - }\ - }while(0) -#endif //#ifdef __CC_ARM -#endif - -#ifdef CONFIG_DEBUG -#if defined (_dbgdump) - #undef DBG_871X - #define DBG_871X(...) do {\ - _dbgdump(DRIVER_PREFIX __VA_ARGS__);\ - }while(0) - - #undef MSG_8192C - #define MSG_8192C(...) do {\ - _dbgdump(DRIVER_PREFIX __VA_ARGS__);\ - }while(0) - - #undef DBG_8192C - #define DBG_8192C(...) do {\ - _dbgdump(DRIVER_PREFIX __VA_ARGS__);\ - }while(0) -#endif -#endif /* CONFIG_DEBUG */ - -#ifdef CONFIG_DEBUG_RTL871X -#ifndef _RTL871X_DEBUG_C_ - extern u32 GlobalDebugLevel; - extern u64 GlobalDebugComponents; -#endif - -#if defined (_dbgdump) && defined (_MODULE_DEFINE_) - - #undef RT_TRACE - #define RT_TRACE(_Comp, _Level, Fmt)\ - do {\ - if((_Comp & GlobalDebugComponents) && (_Level <= GlobalDebugLevel)) {\ - _dbgdump("%s [0x%08x,%d]", DRIVER_PREFIX, (unsigned int)_Comp, _Level);\ - _dbgdump Fmt;\ - }\ - }while(0) - -#endif - - -#if defined (_dbgdump) - - #undef _func_enter_ - #define _func_enter_ \ - do { \ - if (GlobalDebugLevel >= _drv_debug_) \ - { \ - _dbgdump("\n %s : %s enters at %d\n", DRIVER_PREFIX, __FUNCTION__, __LINE__);\ - } \ - } while(0) - - #undef _func_exit_ - #define _func_exit_ \ - do { \ - if (GlobalDebugLevel >= _drv_debug_) \ - { \ - _dbgdump("\n %s : %s exits at %d\n", DRIVER_PREFIX, __FUNCTION__, __LINE__); \ - } \ - } while(0) - - #undef RT_PRINT_DATA - #define RT_PRINT_DATA(_Comp, _Level, _TitleString, _HexData, _HexDataLen) \ - if(((_Comp) & GlobalDebugComponents) && (_Level <= GlobalDebugLevel)) \ - { \ - int __i; \ - u8 *ptr = (u8 *)_HexData; \ - printf("\r\n%s", DRIVER_PREFIX); \ - printf(_TitleString "--------Len=%d\n\r", _HexDataLen); \ - for( __i=0; __i<(int)_HexDataLen; __i++ ) \ - { \ - printf("%02X%s", ptr[__i], (((__i + 1) % 4) == 0)?" ":" "); \ - if (((__i + 1) % 16) == 0) printf("\n\r"); \ - } \ - printf("\n\r"); \ - } -#endif -#endif /* CONFIG_DEBUG_RTL871X */ - - -#ifdef CONFIG_PROC_DEBUG - - int proc_get_drv_version(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_write_reg(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_set_write_reg(struct file *file, const char *buffer, - unsigned long count, void *data); - - int proc_get_read_reg(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_set_read_reg(struct file *file, const char *buffer, - unsigned long count, void *data); - - - int proc_get_fwstate(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_sec_info(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_mlmext_state(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_qos_option(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_ht_option(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_rf_info(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_ap_info(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_adapter_state(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_trx_info(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_mac_reg_dump1(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_mac_reg_dump2(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_mac_reg_dump3(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_bb_reg_dump1(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_bb_reg_dump2(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_bb_reg_dump3(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_rf_reg_dump1(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_rf_reg_dump2(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_rf_reg_dump3(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_rf_reg_dump4(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - -#ifdef CONFIG_AP_MODE - - int proc_get_all_sta_info(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - -#endif - -#ifdef DBG_MEMORY_LEAK - int proc_get_malloc_cnt(char *page, char **start, - off_t offset, int count, - int *eof, void *data); -#endif - -#ifdef CONFIG_FIND_BEST_CHANNEL - int proc_get_best_channel(char *page, char **start, - off_t offset, int count, - int *eof, void *data); -#endif - - int proc_get_rx_signal(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_set_rx_signal(struct file *file, const char *buffer, - unsigned long count, void *data); -#ifdef CONFIG_80211N_HT - int proc_get_cbw40_enable(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_set_cbw40_enable(struct file *file, const char *buffer, - unsigned long count, void *data); - - int proc_get_ampdu_enable(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_set_ampdu_enable(struct file *file, const char *buffer, - unsigned long count, void *data); - - int proc_get_rx_stbc(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_set_rx_stbc(struct file *file, const char *buffer, - unsigned long count, void *data); -#endif //CONFIG_80211N_HT - - int proc_get_two_path_rssi(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_get_rssi_disp(char *page, char **start, - off_t offset, int count, - int *eof, void *data); - - int proc_set_rssi_disp(struct file *file, const char *buffer, - unsigned long count, void *data); - - -#endif //CONFIG_PROC_DEBUG - -#endif //__RTW_DEBUG_H__ - diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/wifi_constants.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/wifi_constants.h index 9952503417..a3416a1f3a 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/wifi_constants.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/wifi_constants.h @@ -23,6 +23,12 @@ #ifndef _WIFI_CONSTANTS_H #define _WIFI_CONSTANTS_H +/** @addtogroup nic NIC + * @ingroup wlan + * @brief NIC functions + * @{ + */ + #ifdef __cplusplus extern "C" { #endif @@ -46,7 +52,6 @@ extern "C" { #define RTW_MAX_PSK_LEN (64) #define RTW_MIN_PSK_LEN (8) - #define MCSSET_LEN 16 /** @@ -67,7 +72,6 @@ enum RTW_BUFFER_UNAVAILABLE_PERMANENT = 10, /**< Buffer unavailable permanently */ RTW_WPS_PBC_OVERLAP = 11, /**< WPS PBC overlap */ RTW_CONNECTION_LOST = 12, /**< Connection lost */ - RTW_ERROR = -1, /**< Generic Error */ RTW_BADARG = -2, /**< Bad Argument */ RTW_BADOPTION = -3, /**< Bad option */ @@ -129,12 +133,9 @@ enum { RTW_SECURITY_WPA2_TKIP_PSK = ( WPA2_SECURITY | TKIP_ENABLED ), /**< WPA2 Security with TKIP */ RTW_SECURITY_WPA2_MIXED_PSK = ( WPA2_SECURITY | AES_ENABLED | TKIP_ENABLED ), /**< WPA2 Security with AES & TKIP */ RTW_SECURITY_WPA_WPA2_MIXED = ( WPA_SECURITY | WPA2_SECURITY ), /**< WPA/WPA2 Security */ - RTW_SECURITY_WPS_OPEN = WPS_ENABLED, /**< WPS with open security */ RTW_SECURITY_WPS_SECURE = (WPS_ENABLED | AES_ENABLED), /**< WPS with AES security */ - RTW_SECURITY_UNKNOWN = -1, /**< May be returned by scan function if security is unknown. Do not pass this to the join function! */ - RTW_SECURITY_FORCE_32_BIT = 0x7fffffff /**< Exists only to force rtw_security_t type to 32 bits */ }; typedef unsigned long rtw_security_t; @@ -181,6 +182,7 @@ enum { RTW_COUNTRY_FCC2, // 0x2A RTW_COUNTRY_WORLD2, // 0x47 RTW_COUNTRY_MKK2, // 0x58 + RTW_COUNTRY_GLOBAL, // 0x41 /* SPECIAL */ RTW_COUNTRY_WORLD, // WORLD1 @@ -364,9 +366,7 @@ enum { RTW_COUNTRY_YT, RTW_COUNTRY_ZA, RTW_COUNTRY_ZW, - RTW_COUNTRY_MAX - }; typedef unsigned long rtw_country_code_t; @@ -401,6 +401,15 @@ enum { }; typedef unsigned long rtw_scan_mode_t; +/** + * @brief The enumeration lists the supported autoreconnect mode by WIFI driver. + */ +typedef enum{ + RTW_AUTORECONNECT_DISABLE, + RTW_AUTORECONNECT_FINITE, + RTW_AUTORECONNECT_INFINITE +} rtw_autoreconnect_mode_t; + /** * @brief The enumeration lists the status to describe the connection link. */ @@ -449,7 +458,8 @@ enum { RTW_WPS_TYPE_REKEY = 0x0003, RTW_WPS_TYPE_PUSHBUTTON = 0x0004, RTW_WPS_TYPE_REGISTRAR_SPECIFIED = 0x0005, - RTW_WPS_TYPE_NONE = 0x0006 + RTW_WPS_TYPE_NONE = 0x0006, + RTW_WPS_TYPE_WSC = 0x0007 }; typedef unsigned long rtw_wps_type_t; @@ -490,9 +500,20 @@ enum { RTW_PROMISC_ENABLE_1 = 2, /**< Fetch only B/M packets */ RTW_PROMISC_ENABLE_2 = 3, /**< Fetch all 802.11 packets*/ RTW_PROMISC_ENABLE_3 = 4, /**< Fetch only B/M 802.11 packets*/ + RTW_PROMISC_ENABLE_4 = 5, /**< Fetch all 802.11 packets & MIMO PLCP headers. Please note that the PLCP header would be struct rtw_rx_info_t defined in wifi_structures.h*/ }; typedef unsigned long rtw_rcr_level_t; +/** + * @brief The enumeration lists the promisc rx type. + */ +#if CONFIG_UNSUPPORT_PLCPHDR_RPT +enum { + RTW_RX_NORMAL = 0, /**< The supported 802.11 packet*/ + RTW_RX_UNSUPPORT = 1, /**< Unsupported 802.11 packet info */ +}; +typedef unsigned long rtw_rx_type_t; +#endif /** * @brief The enumeration lists the disconnect reasons. */ @@ -501,7 +522,8 @@ enum{ RTW_NONE_NETWORK = 1, RTW_CONNECT_FAIL = 2, RTW_WRONG_PASSWORD = 3 , - RTW_DHCP_FAIL = 4, + RTW_4WAY_HANDSHAKE_TIMEOUT = 4, + RTW_DHCP_FAIL = 5, RTW_UNKNOWN, }; typedef unsigned long rtw_connect_error_flag_t; @@ -535,10 +557,16 @@ enum _WIFI_EVENT_INDICATE{ WIFI_EVENT_EAPOL_RECVD = 13, WIFI_EVENT_NO_NETWORK = 14, WIFI_EVENT_BEACON_AFTER_DHCP = 15, + WIFI_EVENT_IP_CHANGED = 16, + WIFI_EVENT_ICV_ERROR = 17, + WIFI_EVENT_CHALLENGE_FAIL = 18, WIFI_EVENT_MAX, }; typedef unsigned long rtw_event_indicate_t; #ifdef __cplusplus } #endif + +/*\@}*/ + #endif /* _WIFI_CONSTANTS_H */ diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/wifi_structures.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/wifi_structures.h index 81331d1bf7..c170940239 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/wifi_structures.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/include/wifi_structures.h @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - ****************************************************************************** + ****************************************************************************** * @file wifi_structures.h * @author * @version @@ -23,6 +23,12 @@ #ifndef _WIFI_STRUCTURES_H #define _WIFI_STRUCTURES_H +/** @addtogroup nic NIC + * @ingroup wlan + * @brief NIC functions + * @{ + */ + //#include #include "wifi_constants.h" #include "dlist.h" @@ -30,7 +36,7 @@ extern "C" { #endif -#if defined(__IAR_SYSTEMS_ICC__) +#if defined(__IAR_SYSTEMS_ICC__) || defined (__GNUC__) || defined(__CC_ARM) || (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)) #pragma pack(1) #endif @@ -41,11 +47,11 @@ typedef struct rtw_ssid { unsigned char len; /**< SSID length */ unsigned char val[33]; /**< SSID name (AP name) */ } rtw_ssid_t; -#if defined(__IAR_SYSTEMS_ICC__) +#if defined(__IAR_SYSTEMS_ICC__) || defined (__GNUC__) || defined(__CC_ARM) || (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)) #pragma pack() #endif -#if defined(__IAR_SYSTEMS_ICC__) +#if defined(__IAR_SYSTEMS_ICC__) || defined (__GNUC__) || defined(__CC_ARM) || (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)) #pragma pack(1) #endif @@ -55,14 +61,15 @@ typedef struct rtw_ssid { typedef struct rtw_mac { unsigned char octet[6]; /**< Unique 6-byte MAC address */ } rtw_mac_t; -#if defined(__IAR_SYSTEMS_ICC__) +#if defined(__IAR_SYSTEMS_ICC__) || defined (__GNUC__) || defined(__CC_ARM) || (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)) #pragma pack() #endif /** * @brief The structure is used to describe the setting about SSID, * security type, password and default channel, used to start AP mode. - * @note The data length of string pointed by ssid and password should not exceed 32. + * @note The data length of string pointed by ssid should not exceed 32, + * and the data length of string pointed by password should not exceed 64. */ typedef struct rtw_ap_info { rtw_ssid_t ssid; @@ -75,7 +82,8 @@ typedef struct rtw_ap_info { /** * @brief The structure is used to describe the station mode setting about SSID, * security type and password, used when connecting to an AP. - * @note The data length of string pointed by ssid and password should not exceed 32. + * @note The data length of string pointed by ssid should not exceed 32, + * and the data length of string pointed by password should not exceed 64. */ typedef struct rtw_network_info { rtw_ssid_t ssid; @@ -86,7 +94,7 @@ typedef struct rtw_network_info { int key_id; }rtw_network_info_t; -#if defined(__IAR_SYSTEMS_ICC__) || defined(__GNUC__) +#if defined(__IAR_SYSTEMS_ICC__) || defined(__GNUC__) || defined(__CC_ARM) || (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)) #pragma pack(1) #endif @@ -103,7 +111,7 @@ typedef struct rtw_scan_result { unsigned int channel; /**< Radio channel that the AP beacon was received on */ rtw_802_11_band_t band; /**< Radio band */ } rtw_scan_result_t; -#if defined(__IAR_SYSTEMS_ICC__) || defined(__GNUC__) +#if defined(__IAR_SYSTEMS_ICC__) || defined(__GNUC__) || defined(__CC_ARM) || (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)) #pragma pack() #endif @@ -117,7 +125,7 @@ typedef struct rtw_scan_handler_result { } rtw_scan_handler_result_t; -#if defined(__IAR_SYSTEMS_ICC__) || defined(__GNUC__) +#if defined(__IAR_SYSTEMS_ICC__) || defined(__GNUC__) || defined(__CC_ARM) || (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)) #pragma pack(1) #endif @@ -132,7 +140,7 @@ typedef struct rtw_wifi_setting { unsigned char password[65]; unsigned char key_idx; }rtw_wifi_setting_t; -#if defined(__IAR_SYSTEMS_ICC__) || defined(__GNUC__) +#if defined(__IAR_SYSTEMS_ICC__) || defined(__GNUC__) || defined(__CC_ARM) || (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)) #pragma pack() #endif @@ -210,8 +218,33 @@ typedef struct ieee80211_frame_info{ unsigned char bssid[6]; unsigned char encrypt; signed char rssi; +#if CONFIG_UNSUPPORT_PLCPHDR_RPT + rtw_rx_type_t type; +#endif }ieee80211_frame_info_t; +#if CONFIG_UNSUPPORT_PLCPHDR_RPT +typedef struct rtw_rx_info { + uint16_t length; //length without FCS + uint8_t filter; // 2: 2T rate pkt; 3: LDPC pkt + signed char rssi; //-128~-1 +}rtw_rx_info_t; + +struct rtw_plcp_info { + struct rtw_plcp_info *prev; + struct rtw_plcp_info *next; + uint16_t length; //length without FCS + uint8_t filter; // 1: HT-20 pkt; 2: HT-40 and not LDPC pkt; 3: LDPC pkt + signed char rssi; //-128~-1 +}; + +struct rtw_rx_buffer { + struct rtw_plcp_info *head; + struct rtw_plcp_info *tail; +}; + +#endif + typedef struct { char filter_id; rtw_packet_filter_pattern_t patt; @@ -228,4 +261,6 @@ typedef struct rtw_mac_filter_list{ } #endif +/*\@}*/ + #endif /* _WIFI_STRUCTURES_H */ diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/freertos/wrapper.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/freertos/wrapper.h index 5488ce78fc..5cc291d17c 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/freertos/wrapper.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/freertos/wrapper.h @@ -18,7 +18,6 @@ #ifndef __WRAPPER_H__ #define __WRAPPER_H__ - //----- ------------------------------------------------------------------ // Include Files //----- ------------------------------------------------------------------ @@ -26,11 +25,8 @@ #include #include "wireless.h" #include -#ifdef PLATFORM_FREERTOS -#include "freertos_service.h" -#elif defined(PLATFORM_CMSIS_RTOS) -#include "rtx_service.h" -#endif +#include "osdep_service.h" + #ifndef __LIST_H #warning "DLIST_NOT_DEFINE!!!!!!" //----- ------------------------------------------------------------------ @@ -50,7 +46,6 @@ // }; #define LIST_HEAD_INIT(name) { &(name), &(name) } - #define INIT_LIST_HEAD(ptr) do { \ (ptr)->next = (ptr); (ptr)->prev = (ptr); \ } while (0) @@ -302,7 +297,6 @@ static __inline__ void skb_queue_head_init(struct sk_buff_head *list) static __inline__ void __skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk) { struct sk_buff *prev, *next; - newsk->list = list; list->qlen++; next = (struct sk_buff *)list; @@ -333,7 +327,7 @@ static __inline__ void skb_queue_tail(struct sk_buff_head *list, struct sk_buff } static __inline__ void skb_assign_buf(struct sk_buff *skb, unsigned char *buf, unsigned int len) -{ +{ skb->head = buf; skb->data = buf; skb->tail = buf; @@ -452,5 +446,3 @@ void rtw_del_timer(_timer *ptimer); #endif //__WRAPPER_H__ - - diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/lwip_intf.c b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/lwip_intf.c index aa036bca40..cae0c3ccce 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/lwip_intf.c +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/lwip_intf.c @@ -4,7 +4,7 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software @@ -19,31 +19,24 @@ #include #include #include - #if !defined(CONFIG_MBED_ENABLED) #include #include #endif - #include #include - //----- ------------------------------------------------------------------ // External Reference //----- ------------------------------------------------------------------ #if (CONFIG_LWIP_LAYER == 1) -#if defined(CONFIG_MBED_ENABLED) - extern struct netif *xnetif[]; -#else - extern struct netif xnetif[]; //LWIP netif -#endif +extern struct netif xnetif[]; //LWIP netif #endif /** * rltk_wlan_set_netif_info - set netif hw address and register dev pointer to netif device * @idx_wlan: netif index - * 0 for STA only or SoftAP only or STA in STA+SoftAP concurrent mode, - * 1 for SoftAP in STA+SoftAP concurrent mode + * 0 for STA only or SoftAP only or STA in STA+SoftAP concurrent mode, + * 1 for SoftAP in STA+SoftAP concurrent mode * @dev: register netdev pointer to LWIP. Reserved. * @dev_addr: set netif hw address * @@ -53,11 +46,11 @@ void rltk_wlan_set_netif_info(int idx_wlan, void * dev, unsigned char * dev_addr { #if (CONFIG_LWIP_LAYER == 1) #if defined(CONFIG_MBED_ENABLED) - //rtw_memcpy(xnetif[idx_wlan]->hwaddr, dev_addr, 6); - //set netif hwaddr later + //rtw_memcpy(xnetif[idx_wlan]->hwaddr, dev_addr, 6); + //set netif hwaddr later #else - rtw_memcpy(xnetif[idx_wlan].hwaddr, dev_addr, 6); - xnetif[idx_wlan].state = dev; + rtw_memcpy(xnetif[idx_wlan].hwaddr, dev_addr, 6); + xnetif[idx_wlan].state = dev; #endif #endif } @@ -74,45 +67,45 @@ void rltk_wlan_set_netif_info(int idx_wlan, void * dev, unsigned char * dev_addr int rltk_wlan_send(int idx, struct eth_drv_sg *sg_list, int sg_len, int total_len) { #if (CONFIG_LWIP_LAYER == 1) - struct eth_drv_sg *last_sg; - struct sk_buff *skb = NULL; - int ret = 0; + struct eth_drv_sg *last_sg; + struct sk_buff *skb = NULL; + int ret = 0; - if (idx == -1) { - DBG_ERR("netif is DOWN"); - return -1; - } - DBG_TRACE("%s is called", __FUNCTION__); + if(idx == -1){ + DBG_ERR("netif is DOWN"); + return -1; + } + DBG_TRACE("%s is called", __FUNCTION__); - save_and_cli(); - if (rltk_wlan_check_isup(idx)) { - rltk_wlan_tx_inc(idx); - } else { - DBG_ERR("netif is DOWN"); - restore_flags(); - return -1; - } - restore_flags(); + save_and_cli(); + if (rltk_wlan_check_isup(idx)) { + rltk_wlan_tx_inc(idx); + } else { + DBG_ERR("netif is DOWN"); + restore_flags(); + return -1; + } + restore_flags(); - skb = rltk_wlan_alloc_skb(total_len); - if (skb == NULL) { - //DBG_ERR("rltk_wlan_alloc_skb() for data len=%d failed!", total_len); - ret = -1; - goto exit; - } + skb = rltk_wlan_alloc_skb(total_len); + if (skb == NULL) { + //DBG_ERR("rltk_wlan_alloc_skb() for data len=%d failed!", total_len); + ret = -1; + goto exit; + } - for (last_sg = &sg_list[sg_len]; sg_list < last_sg; ++sg_list) { - rtw_memcpy(skb->tail, (void *)(sg_list->buf), sg_list->len); - skb_put(skb, sg_list->len); - } + for (last_sg = &sg_list[sg_len]; sg_list < last_sg; ++sg_list) { + rtw_memcpy(skb->tail, (void *)(sg_list->buf), sg_list->len); + skb_put(skb, sg_list->len); + } - rltk_wlan_send_skb(idx, skb); + rltk_wlan_send_skb(idx, skb); exit: - save_and_cli(); - rltk_wlan_tx_dec(idx); - restore_flags(); - return ret; + save_and_cli(); + rltk_wlan_tx_dec(idx); + restore_flags(); + return ret; #endif } @@ -127,128 +120,130 @@ exit: void rltk_wlan_recv(int idx, struct eth_drv_sg *sg_list, int sg_len) { #if (CONFIG_LWIP_LAYER == 1) - struct eth_drv_sg *last_sg; - struct sk_buff *skb; + struct eth_drv_sg *last_sg; + struct sk_buff *skb; + + DBG_TRACE("%s is called", __FUNCTION__); + if(idx == -1){ + DBG_ERR("skb is NULL"); + return; + } + skb = rltk_wlan_get_recv_skb(idx); + DBG_ASSERT(skb, "No pending rx skb"); - DBG_TRACE("%s is called", __FUNCTION__); - - if (!rltk_wlan_check_isup(idx)) { - return; - } - - if (idx == -1) { - DBG_ERR("skb is NULL"); - return; - } - - skb = rltk_wlan_get_recv_skb(idx); - DBG_ASSERT(skb, "No pending rx skb"); - - for (last_sg = &sg_list[sg_len]; sg_list < last_sg; ++sg_list) { - if (sg_list->buf != 0) { - rtw_memcpy((void *)(sg_list->buf), skb->data, sg_list->len); - skb_pull(skb, sg_list->len); - } - } + for (last_sg = &sg_list[sg_len]; sg_list < last_sg; ++sg_list) { + if (sg_list->buf != 0) { + rtw_memcpy((void *)(sg_list->buf), skb->data, sg_list->len); + skb_pull(skb, sg_list->len); + } + } #endif } int netif_is_valid_IP(int idx, unsigned char *ip_dest) { -#if CONFIG_LWIP_LAYER == 1 #if defined(CONFIG_MBED_ENABLED) - return 1; + return 1; #else - struct netif *pnetif = &xnetif[idx]; +#if CONFIG_LWIP_LAYER == 1 + struct netif * pnetif = &xnetif[idx]; - ip_addr_t addr = { 0 }; + ip_addr_t addr = { 0 }; #ifdef CONFIG_MEMORY_ACCESS_ALIGNED - unsigned int temp; - memcpy(&temp, ip_dest, sizeof(unsigned int)); - u32_t *ip_dest_addr = &temp; + unsigned int temp; + memcpy(&temp, ip_dest, sizeof(unsigned int)); + u32_t *ip_dest_addr = &temp; #else - u32_t *ip_dest_addr = (u32_t*)ip_dest; + u32_t *ip_dest_addr = (u32_t*)ip_dest; #endif - addr.addr = *ip_dest_addr; - - if (pnetif->ip_addr.addr == 0) { - return 1; - } - if (ip_addr_ismulticast(&addr) || ip_addr_isbroadcast(&addr,pnetif)) { - return 1; - } - - //if(ip_addr_netcmp(&(pnetif->ip_addr), &addr, &(pnetif->netmask))) //addr&netmask - // return 1; - - if (ip_addr_cmp(&(pnetif->ip_addr),&addr)) { - return 1; - } - - DBG_TRACE("invalid IP: %d.%d.%d.%d ",ip_dest[0],ip_dest[1],ip_dest[2],ip_dest[3]); +#if LWIP_VERSION_MAJOR >= 2 + ip_addr_set_ip4_u32(&addr, *ip_dest_addr); +#else + addr.addr = *ip_dest_addr; #endif + +#if (LWIP_VERSION_MAJOR >= 2) + if((ip_addr_get_ip4_u32(netif_ip_addr4(pnetif))) == 0) + return 1; +#else + + if(pnetif->ip_addr.addr == 0) + return 1; +#endif + + if(ip_addr_ismulticast(&addr) || ip_addr_isbroadcast(&addr,pnetif)){ + return 1; + } + + //if(ip_addr_netcmp(&(pnetif->ip_addr), &addr, &(pnetif->netmask))) //addr&netmask + // return 1; + + if(ip_addr_cmp(&(pnetif->ip_addr),&addr)) + return 1; + + DBG_TRACE("invalid IP: %d.%d.%d.%d ",ip_dest[0],ip_dest[1],ip_dest[2],ip_dest[3]); +#endif #ifdef CONFIG_DONT_CARE_TP - if (pnetif->flags & NETIF_FLAG_IPSWITCH) { - return 1; - } - else + if(pnetif->flags & NETIF_FLAG_IPSWITCH) + return 1; + else #endif - return 0; + return 0; #endif } -#if defined(CONFIG_MBED_ENABLED) - -#else -int netif_get_idx(struct netif *pnetif) +#if !defined(CONFIG_MBED_ENABLED) +int netif_get_idx(struct netif* pnetif) { #if (CONFIG_LWIP_LAYER == 1) - int idx = pnetif - xnetif; + int idx = pnetif - xnetif; - switch (idx) { - case 0: - return 0; - case 1: - return 1; - default: - return -1; - } -#else - return -1; + switch(idx) { + case 0: + return 0; + case 1: + return 1; + default: + return -1; + } +#else + return -1; #endif } unsigned char *netif_get_hwaddr(int idx_wlan) { #if (CONFIG_LWIP_LAYER == 1) - return xnetif[idx_wlan].hwaddr; + return xnetif[idx_wlan].hwaddr; #else - return NULL; + return NULL; #endif } #endif +#if defined(CONFIG_MBED_ENABLED) emac_callback emac_callback_func = NULL; void *emac_callback_data = NULL; -void set_callback_func(emac_callback p, void *data) { - emac_callback_func = p; - emac_callback_data = data; +void set_callback_func(emac_callback p, void *data) +{ + emac_callback_func = p; + emac_callback_data = data; } +#endif void netif_rx(int idx, unsigned int len) { #if (CONFIG_LWIP_LAYER == 1) #if defined(CONFIG_MBED_ENABLED) - emac_callback_func(emac_callback_data, NULL, len); + emac_callback_func(emac_callback_data, NULL, len); #else - ethernetif_recv(&xnetif[idx], len); + ethernetif_recv(&xnetif[idx], len); #endif #endif - #if (CONFIG_INIC_EN == 1) - inic_netif_rx(idx, len); + inic_netif_rx(idx, len); #endif } @@ -257,7 +252,7 @@ void netif_post_sleep_processing(void) #if (CONFIG_LWIP_LAYER == 1) #if defined(CONFIG_MBED_ENABLED) #else - lwip_POST_SLEEP_PROCESSING(); //For FreeRTOS tickless to enable Lwip ARP timer when leaving IPS - Alex Fang + lwip_POST_SLEEP_PROCESSING(); //For FreeRTOS tickless to enable Lwip ARP timer when leaving IPS - Alex Fang #endif #endif } @@ -267,7 +262,7 @@ void netif_pre_sleep_processing(void) #if (CONFIG_LWIP_LAYER == 1) #if defined(CONFIG_MBED_ENABLED) #else - lwip_PRE_SLEEP_PROCESSING(); + lwip_PRE_SLEEP_PROCESSING(); #endif #endif } @@ -275,9 +270,9 @@ void netif_pre_sleep_processing(void) #ifdef CONFIG_WOWLAN unsigned char *rltk_wlan_get_ip(int idx){ #if (CONFIG_LWIP_LAYER == 1) - return LwIP_GetIP(&xnetif[idx]); + return LwIP_GetIP(&xnetif[idx]); #else - return NULL; + return NULL; #endif } #endif diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/lwip_intf.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/lwip_intf.h index 5892aba322..5268dde776 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/lwip_intf.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/lwip_intf.h @@ -30,12 +30,12 @@ struct netif; //----- ------------------------------------------------------------------ #if defined(CONFIG_MBED_ENABLED) struct eth_drv_sg { - unsigned int buf; - unsigned int len; + unsigned int buf; + unsigned int len; }; -#define MAX_ETH_DRV_SG 32 -#define MAX_ETH_MSG 1540 +#define MAX_ETH_DRV_SG 32 +#define MAX_ETH_MSG 1540 #else #include "ethernetif.h" // moved to ethernetif.h by jimmy 12/2/2015 #endif @@ -52,8 +52,11 @@ void rltk_wlan_send_skb(int idx, struct sk_buff *skb); //struct sk_buff as defin int rltk_wlan_send(int idx, struct eth_drv_sg *sg_list, int sg_len, int total_len); void rltk_wlan_recv(int idx, struct eth_drv_sg *sg_list, int sg_len); unsigned char rltk_wlan_running(unsigned char idx); // interface is up. 0: interface is down + +#if defined(CONFIG_MBED_ENABLED) typedef void (*emac_callback)(void *param, struct netif *netif, unsigned int len); void set_callback_func(emac_callback p, void *data); +#endif //----- ------------------------------------------------------------------ // Network Interface provided @@ -73,7 +76,6 @@ extern void lwip_PRE_SLEEP_PROCESSING(void); extern void lwip_POST_SLEEP_PROCESSING(void); #endif //CONFIG_LWIP_LAYER == 1 - #ifdef CONFIG_WOWLAN extern unsigned char *rltk_wlan_get_ip(int idx); #endif diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/wireless.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/wireless.h index ac988590c4..4d664c8a6e 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/wireless.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/wireless.h @@ -1206,4 +1206,6 @@ struct iw_event #define IW_EVT_STR_STA_DISASSOC "STA Disassoc" #define IW_EVT_STR_SEND_ACTION_DONE "Send Action Done" #define IW_EVT_STR_NO_NETWORK "No Assoc Network After Scan Done" +#define IW_EVT_STR_ICV_ERROR "ICV Eror" +#define IW_EVT_STR_CHALLENGE_FAIL "Auth Challenge Fail" #endif /* _LINUX_WIRELESS_H */ diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/wlan_intf.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/wlan_intf.h index b586e0cc36..081447f699 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/wlan_intf.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/common/drivers/wlan/realtek/src/osdep/wlan_intf.h @@ -67,6 +67,7 @@ int rltk_wlan_rf_on(void); int rltk_wlan_rf_off(void); int rltk_wlan_check_bus(void); int rltk_wlan_wireless_mode(unsigned char mode); +int rltk_wlan_get_wireless_mode(unsigned char *pmode); int rltk_wlan_set_wps_phase(unsigned char is_trigger_wps); int rtw_ps_enable(int enable); int rltk_wlan_is_connected_to_ap(void); diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/cmsis_rtos/cmsis_rtos_service.c b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/cmsis_rtos/cmsis_rtos_service.c index f3d91ac100..ae92b9dc02 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/cmsis_rtos/cmsis_rtos_service.c +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/cmsis_rtos/cmsis_rtos_service.c @@ -1,48 +1,46 @@ /* RTX includes */ #include "osdep_service.h" #include "tcm_heap.h" -//#include -//#include //malloc(), free() -//#include //memcpy(), memcmp(), memset() #include "platform_stdlib.h" -//#include -//#include + /********************* os depended utilities ********************/ #ifndef USE_MUTEX_FOR_SPINLOCK #define USE_MUTEX_FOR_SPINLOCK 1 #endif -#define USE_HEAP_INFO 0 - -#define OS_TICK OS_TICK_FREQ -#define OS_TICK_RATE_MS (1000/OS_TICK) //----------------------------------------------------------------------- // Private Variables //----------------------------------------------------------------------- static unsigned long CriticalNesting = 0; +#if CONFIG_USE_TCM_HEAP +void *tcm_heap_malloc(int size); +#endif +#if defined(CONFIG_WIFI_NORMAL) && defined(CONFIG_NETWORK) +extern int rtw_if_wifi_thread(char *name); +#endif //----------------------------------------------------------------------- // Misc Function //----------------------------------------------------------------------- int osdep_print = 0; #define _func_enter_ do{\ - if(osdep_print)\ - printf("enter %s\r\n", __FUNCTION__);\ - }while(0) + if(osdep_print)\ + printf("enter %s\r\n", __FUNCTION__);\ + }while(0) #define _func_exit_ do{\ - if(osdep_print)\ - printf("exit %s\r\n", __FUNCTION__);\ - }while(0) + if(osdep_print)\ + printf("exit %s\r\n", __FUNCTION__);\ + }while(0) void save_and_cli() { _func_enter_; #if defined(__CC_ARM) - rtw_enter_critical(NULL, NULL); + rtw_enter_critical(NULL, NULL); #else - __disable_irq(); + __disable_irq(); #endif _func_exit_; } @@ -51,9 +49,9 @@ void restore_flags() { _func_enter_; #if defined(__CC_ARM) - rtw_exit_critical(NULL, NULL); + rtw_exit_critical(NULL, NULL); #else - __enable_irq(); + __enable_irq(); #endif _func_exit_; } @@ -61,76 +59,66 @@ _func_exit_; void cli() { _func_enter_; - __disable_irq(); + __disable_irq(); _func_exit_; } /* Not needed on 64bit architectures */ static unsigned int __div64_32(u64 *n, unsigned int base) { - u64 rem = *n; - u64 b = base; - u64 res, d = 1; - unsigned int high = rem >> 32; + u64 rem = *n; + u64 b = base; + u64 res, d = 1; + unsigned int high = rem >> 32; _func_enter_; - /* Reduce the thing a bit first */ - res = 0; - if (high >= base) { - high /= base; - res = (u64) high << 32; - rem -= (u64) (high * base) << 32; - } + /* Reduce the thing a bit first */ + res = 0; + if (high >= base) { + high /= base; + res = (u64) high << 32; + rem -= (u64) (high * base) << 32; + } - while ((u64)b > 0 && b < rem) { - b = b+b; - d = d+d; - } + while ((u64)b > 0 && b < rem) { + b = b+b; + d = d+d; + } - do { - if (rem >= b) { - rem -= b; - res += d; - } - b >>= 1; - d >>= 1; - } while (d); + do { + if (rem >= b) { + rem -= b; + res += d; + } + b >>= 1; + d >>= 1; + } while (d); _func_exit_; - *n = res; - return rem; + *n = res; + return rem; } /********************* os depended service ********************/ -#if USE_HEAP_INFO -static uint32_t osFreeBytesRemaining=0x400; -#endif + static void _rtx2_memset(void *pbuf, int c, u32 sz); u8* _rtx2_malloc(u32 sz) { _func_enter_; - void *p = NULL; - p = (void *)malloc(sz); - if(p != NULL){ -#if USE_HEAP_INFO - osFreeBytesRemaining-=sz; -#endif - } + void *p = NULL; + p = (void *)malloc(sz); _func_exit_; - return p; + return p; } u8* _rtx2_zmalloc(u32 sz) { _func_enter_; - u8 *pbuf = _rtx2_malloc(sz); + u8 *pbuf = _rtx2_malloc(sz); - if (pbuf != NULL){ -#if USE_HEAP_INFO - osFreeBytesRemaining-=sz; -#endif - _rtx2_memset(pbuf, 0, sz); - } + if (pbuf != NULL){ + _rtx2_memset(pbuf, 0, sz); + } _func_exit_; - return pbuf; + return pbuf; } static void (*ext_free)( void *p ) = NULL; @@ -138,265 +126,279 @@ static uint32_t ext_upper = 0; static uint32_t ext_lower = 0; void rtw_set_mfree_ext( void (*free)( void *p ), uint32_t upper, uint32_t lower ) { - ext_free = free; - ext_upper = upper; - ext_lower = lower; + ext_free = free; + ext_upper = upper; + ext_lower = lower; } void _rtx2_mfree(u8 *pbuf, u32 sz) { _func_enter_; - if( ((uint32_t)pbuf >= ext_lower) && ((uint32_t)pbuf < ext_upper) ){ - if(ext_free) - ext_free(pbuf); - }else{ - free(pbuf); - } -#if USE_HEAP_INFO - osFreeBytesRemaining+=sz; -#endif + if( ((uint32_t)pbuf >= ext_lower) && ((uint32_t)pbuf < ext_upper) ){ + if(ext_free) + ext_free(pbuf); + }else{ + free(pbuf); + } } static void _rtx2_memcpy(void* dst, void* src, u32 sz) { _func_enter_; - memcpy(dst, src, sz); + memcpy(dst, src, sz); _func_exit_; } static int _rtx2_memcmp(void *dst, void *src, u32 sz) { _func_enter_; -//under Linux/GNU/GLibc, the return value of memcmp for two same mem. chunk is 0 - if (!(memcmp(dst, src, sz))) - return _SUCCESS; + //under Linux/GNU/GLibc, the return value of memcmp for two same mem. chunk is 0 + if (!(memcmp(dst, src, sz))) + return _SUCCESS; _func_exit_; - return _FAIL; + return _FAIL; } static void _rtx2_memset(void *pbuf, int c, u32 sz) { _func_enter_; - memset(pbuf, c, sz); + memset(pbuf, c, sz); _func_exit_; } static void _rtx2_init_sema(_sema *sem, int init_val) { _func_enter_; - rtx_sema_t *p_sem = (rtx_sema_t *)_rtx2_zmalloc(sizeof(rtx_sema_t)); - if(p_sem == NULL){ - goto err_exit; - } - *sem = (_sema)p_sem; - _rtx2_memset(&p_sem->data, 0, sizeof(p_sem->data)); - p_sem->attr.cb_mem = &p_sem->data; - p_sem->attr.cb_size = sizeof(p_sem->data); - p_sem->id = osSemaphoreNew(osRtxSemaphoreTokenLimit, (uint32_t)init_val, &p_sem->attr); - if (p_sem->id == NULL){ - goto err_exit; - } + rtx_sema_t *p_sem = (rtx_sema_t *)_rtx2_zmalloc(sizeof(rtx_sema_t)); + if(p_sem == NULL){ + goto err_exit; + } + *sem = (_sema)p_sem; + _rtx2_memset(&p_sem->data, 0, sizeof(p_sem->data)); + p_sem->attr.cb_mem = &p_sem->data; + p_sem->attr.cb_size = sizeof(p_sem->data); + p_sem->id = osSemaphoreNew(osRtxSemaphoreTokenLimit, (uint32_t)init_val, &p_sem->attr); + if (p_sem->id == NULL){ + goto err_exit; + } _func_exit_; - return; + return; err_exit: - DBG_ERR("error"); - if(p_sem) - _rtx2_mfree((u8 *)p_sem, sizeof(rtx_sema_t)); - *sem = NULL; - return; + DBG_ERR("error"); + if(p_sem) + _rtx2_mfree((u8 *)p_sem, sizeof(rtx_sema_t)); + *sem = NULL; + return; } static void _rtx2_free_sema(_sema *sema) { _func_enter_; - if(*sema){ - rtx_sema_t *p_sem = (rtx_sema_t *)(*sema); - osSemaphoreDelete(p_sem->id); - if(p_sem) - _rtx2_mfree((u8 *)p_sem, sizeof(rtx_sema_t)); - *sema = NULL; - }else - DBG_ERR("NULL pointer get"); + if(*sema){ + rtx_sema_t *p_sem = (rtx_sema_t *)(*sema); + osSemaphoreDelete(p_sem->id); + if(p_sem) + _rtx2_mfree((u8 *)p_sem, sizeof(rtx_sema_t)); + *sema = NULL; + } else { + DBG_ERR("NULL pointer get"); + } _func_exit_; } static void _rtx2_up_sema(_sema *sema) { - if(*sema){ - rtx_sema_t *p_sem = (rtx_sema_t *)(*sema); - osStatus_t status = osSemaphoreRelease(p_sem->id); - if ( status != osOK){ - DBG_ERR("error %d", status); - } - }else - DBG_ERR("NULL pointer get"); +_func_enter_; + if(*sema){ + rtx_sema_t *p_sem = (rtx_sema_t *)(*sema); + osStatus_t status = osSemaphoreRelease(p_sem->id); + if (status != osOK){ + DBG_ERR("error %d", status); + } + } else { + DBG_ERR("NULL pointer get"); + } _func_exit_; } static void _rtx2_up_sema_from_isr(_sema *sema) { _func_enter_; - if(*sema){ - rtx_sema_t *p_sem = (rtx_sema_t *)*sema; - osStatus_t status = osSemaphoreRelease(p_sem->id); - if (status != osOK){ - DBG_ERR("error %d", status); - } - }else - DBG_ERR("NULL pointer get"); + if(*sema){ + rtx_sema_t *p_sem = (rtx_sema_t *)*sema; + osStatus_t status = osSemaphoreRelease(p_sem->id); + if (status != osOK){ + DBG_ERR("error %d", status); + } + } else { + DBG_ERR("NULL pointer get"); + } _func_exit_; } static u32 _rtx2_down_sema(_sema *sema, u32 timeout_ms) { - if(*sema){ - rtx_sema_t *p_sem = (rtx_sema_t *)*sema; - if(timeout_ms == RTW_MAX_DELAY) { - timeout_ms = osWaitForever; - } else { - timeout_ms = rtw_ms_to_systime(timeout_ms); - } - osStatus_t status = osSemaphoreAcquire(p_sem->id, timeout_ms); - if (status == osOK){ - return _TRUE; - }; - } - return _FALSE; + if(*sema){ + rtx_sema_t *p_sem = (rtx_sema_t *)*sema; + if(timeout_ms == RTW_MAX_DELAY) { + timeout_ms = osWaitForever; + } else { + timeout_ms = rtw_ms_to_systime(timeout_ms); + } + osStatus_t status = osSemaphoreAcquire(p_sem->id, timeout_ms); + if (status == osOK){ + return _TRUE; + } + } + return _FALSE; } static void _rtx2_mutex_init(_mutex *mutex) { _func_enter_; - rtx_mutex_t *p_mut = (rtx_mutex_t *)_rtx2_zmalloc(sizeof(rtx_mutex_t)); - if(p_mut == NULL) - goto err_exit; - memset(&p_mut->data, 0, sizeof(p_mut->data)); - p_mut->attr.cb_mem = &p_mut->data; - p_mut->attr.cb_size = sizeof(p_mut->data); - p_mut->id = osMutexNew(&p_mut->attr); - if (p_mut->id == NULL) - goto err_exit; - *mutex = (_mutex)p_mut; + rtx_mutex_t *p_mut = (rtx_mutex_t *)_rtx2_zmalloc(sizeof(rtx_mutex_t)); + if(p_mut == NULL) + goto err_exit; + memset(&p_mut->data, 0, sizeof(p_mut->data)); + p_mut->attr.cb_mem = &p_mut->data; + p_mut->attr.cb_size = sizeof(p_mut->data); + p_mut->id = osMutexNew(&p_mut->attr); + if (p_mut->id == NULL) + goto err_exit; + *mutex = (_mutex)p_mut; _func_exit_; - return; + return; err_exit: - DBG_ERR("error"); - if(p_mut) - _rtx2_mfree((u8 *)p_mut, sizeof(rtx_mutex_t)); - *mutex = NULL; - return; + DBG_ERR("error"); + if(p_mut) + _rtx2_mfree((u8 *)p_mut, sizeof(rtx_mutex_t)); + *mutex = NULL; + return; } static void _rtx2_mutex_free(_mutex *pmutex) { _func_enter_; - if(*pmutex){ - rtx_mutex_t *p_mut = (rtx_mutex_t *)(*pmutex); - osMutexDelete(p_mut->id); - if(p_mut) - _rtx2_mfree((u8 *)p_mut, sizeof(rtx_mutex_t)); - } + if(*pmutex){ + rtx_mutex_t *p_mut = (rtx_mutex_t *)(*pmutex); + osMutexDelete(p_mut->id); + if(p_mut) + _rtx2_mfree((u8 *)p_mut, sizeof(rtx_mutex_t)); + } _func_exit_; } static void _rtx2_mutex_get(_mutex *pmutex) { _func_enter_; - if(*pmutex){ - rtx_mutex_t *p_mut = (rtx_mutex_t *)(*pmutex); - if (osMutexAcquire(p_mut->id, 60 * 1000 / OS_TICK_RATE_MS) != osOK) - DBG_ERR("%s(%p) failed, retry\n", __FUNCTION__, p_mut); - } + if(*pmutex){ + rtx_mutex_t *p_mut = (rtx_mutex_t *)(*pmutex); + if (osMutexAcquire(p_mut->id, 60 * 1000 / OS_TICK_RATE_MS) != osOK) + DBG_ERR("%s(%p) failed, retry\n", __FUNCTION__, p_mut); + } _func_exit_; -} +} static int _rtx2_mutex_get_timeout(_mutex *pmutex, u32 timeout_ms) { _func_enter_; - if(*pmutex){ - rtx_mutex_t *p_mut = (rtx_mutex_t *)(*pmutex); - if(timeout_ms == RTW_MAX_DELAY) { - timeout_ms = osWaitForever; - } else { - timeout_ms = rtw_ms_to_systime(timeout_ms); - } - if(osMutexAcquire(p_mut->id, timeout_ms) == osOK){ - return _SUCCESS; - } - } + if(*pmutex){ + rtx_mutex_t *p_mut = (rtx_mutex_t *)(*pmutex); + if(timeout_ms == RTW_MAX_DELAY) { + timeout_ms = osWaitForever; + } else { + timeout_ms = rtw_ms_to_systime(timeout_ms); + } + if(osMutexAcquire(p_mut->id, timeout_ms) == osOK){ + return _SUCCESS; + } + } _func_exit_; - DBG_ERR("%s(%p) failed, retry\n", __FUNCTION__, pmutex); - return _FAIL; + DBG_ERR("%s(%p) failed, retry\n", __FUNCTION__, pmutex); + return _FAIL; } static void _rtx2_mutex_put(_mutex *pmutex) { _func_enter_; - if(*pmutex){ - rtx_mutex_t *p_mut = (rtx_mutex_t *)(*pmutex); - if (osMutexRelease(p_mut->id) != osOK) - DBG_ERR("\r\ninternal counter of mutex is 0 or calling task is not the owner of the mutex"); - } + if(*pmutex){ + rtx_mutex_t *p_mut = (rtx_mutex_t *)(*pmutex); + if (osMutexRelease(p_mut->id) != osOK) + DBG_ERR("\r\ninternal counter of mutex is 0 or calling task is not the owner of the mutex"); + } _func_exit_; } static void _rtx2_enter_critical(_lock *plock, _irqL *pirqL) { _func_enter_; - CriticalNesting++; - if(CriticalNesting == 1){ - osKernelLock();//tsk_lock & tsk_unlock should not be called nested - } + CriticalNesting++; + if(CriticalNesting == 1){ + osKernelLock();//tsk_lock & tsk_unlock should not be called nested + } _func_exit_; } void mbed_die(void){ - DBG_ERR(" %p die here", osThreadGetId()); - __disable_irq(); - while(1); + DBG_ERR(" %p die here", osThreadGetId()); + __disable_irq(); + while(1); } static void _rtx2_exit_critical(_lock *plock, _irqL *pirqL) { _func_enter_; - if(CriticalNesting == 0){ - DBG_ERR("die here"); - HALT(); - } - CriticalNesting--; - if(CriticalNesting == 0){ - osKernelUnlock(); - } + if(CriticalNesting == 0){ + DBG_ERR("die here"); + HALT(); + } + CriticalNesting--; + if(CriticalNesting == 0){ + osKernelUnlock(); + } _func_exit_; } static void _rtx2_enter_critical_from_isr(_lock *plock, _irqL *pirqL) { _func_enter_; - __disable_irq(); + __disable_irq(); _func_exit_; } static void _rtx2_exit_critical_from_isr(_lock *plock, _irqL *pirqL) { _func_enter_; - __enable_irq(); + __enable_irq(); _func_exit_; } static int _rtx2_enter_critical_mutex(_mutex *pmutex, _irqL *pirqL) { _func_enter_; - while(_rtx2_mutex_get_timeout(pmutex, 60 * 1000) != _SUCCESS) - DBG_ERR("\n\r[%p] %s(%p) failed, retry\n", osThreadGetId(), __FUNCTION__, pmutex); + while(_rtx2_mutex_get_timeout(pmutex, 60 * 1000) != _SUCCESS) + DBG_ERR("\n\r[%p] %s(%p) failed, retry\n", osThreadGetId(), __FUNCTION__, pmutex); _func_exit_; - return _SUCCESS; + return _SUCCESS; } static void _rtx2_exit_critical_mutex(_mutex *pmutex, _irqL *pirqL) { _func_enter_; - _rtx2_mutex_put(pmutex); + _rtx2_mutex_put(pmutex); +_func_exit_; +} + +static void _rtx2_cpu_lock(void) +{ +_func_enter_; + printf(" Not yet ready. Should not come over here!\r\n"); +_func_exit_; +} +static void _rtx2_cpu_unlock(void) +{ +_func_enter_; + printf(" Not yet ready. Should not come over here!\r\n"); _func_exit_; } @@ -404,7 +406,7 @@ static void _rtx2_spinlock_init(_lock *plock) { _func_enter_; #if USE_MUTEX_FOR_SPINLOCK - _rtx2_mutex_init(plock); + _rtx2_mutex_init(plock); #endif _func_exit_; } @@ -413,9 +415,9 @@ static void _rtx2_spinlock_free(_lock *plock) { _func_enter_; #if USE_MUTEX_FOR_SPINLOCK - if(plock != NULL){ - _rtx2_mutex_free(plock); - } + if(plock != NULL){ + _rtx2_mutex_free(plock); + } #endif _func_exit_; } @@ -424,7 +426,7 @@ static void _rtx2_spinlock(_lock *plock) { _func_enter_; #if USE_MUTEX_FOR_SPINLOCK - _rtx2_mutex_get(plock); + _rtx2_mutex_get(plock); #endif _func_exit_; } @@ -433,7 +435,7 @@ static void _rtx2_spinunlock(_lock *plock) { _func_enter_; #if USE_MUTEX_FOR_SPINLOCK - _rtx2_mutex_put(plock); + _rtx2_mutex_put(plock); #endif _func_exit_; } @@ -441,9 +443,9 @@ _func_exit_; static void _rtx2_spinlock_irqsave(_lock *plock, _irqL *irqL) { _func_enter_; - _rtx2_enter_critical(plock, irqL); + _rtx2_enter_critical(plock, irqL); #if USE_MUTEX_FOR_SPINLOCK - _rtx2_spinlock(plock); + _rtx2_spinlock(plock); #endif _func_exit_; } @@ -452,129 +454,130 @@ static void _rtx2_spinunlock_irqsave(_lock *plock, _irqL *irqL) { _func_enter_; #if USE_MUTEX_FOR_SPINLOCK - _rtx2_spinunlock(plock); + _rtx2_spinunlock(plock); #endif - _rtx2_exit_critical(plock, irqL); + _rtx2_exit_critical(plock, irqL); _func_exit_; } static int _rtx2_init_xqueue( _xqueue* queue, const char* name, u32 message_size, u32 number_of_messages ) { _func_enter_; - rtx_mbox_t *mbox = (rtx_mbox_t *)_rtx2_zmalloc(sizeof(rtx_mbox_t)); - if (mbox == NULL ){ - goto err_exit; - } - mbox->queue_mem = _rtx2_zmalloc(number_of_messages * (message_size + sizeof(os_message_t))); - if(mbox->queue_mem == NULL) - goto err_exit; - mbox->attr.mq_mem = mbox->queue_mem; - mbox->attr.mq_size = number_of_messages * (message_size + sizeof(os_message_t)); - mbox->attr.cb_mem = &mbox->data; - mbox->attr.cb_size = sizeof(mbox->data); - *queue = (_xqueue)mbox; - mbox->id = osMessageQueueNew(number_of_messages, message_size, &mbox->attr); - if(mbox->id == NULL) - goto err_exit; + rtx_mbox_t *mbox = (rtx_mbox_t *)_rtx2_zmalloc(sizeof(rtx_mbox_t)); + if (mbox == NULL ){ + goto err_exit; + } + mbox->queue_mem = _rtx2_zmalloc(number_of_messages * (message_size + sizeof(os_message_t))); + if(mbox->queue_mem == NULL) + goto err_exit; + mbox->attr.mq_mem = mbox->queue_mem; + mbox->attr.mq_size = number_of_messages * (message_size + sizeof(os_message_t)); + mbox->attr.cb_mem = &mbox->data; + mbox->attr.cb_size = sizeof(mbox->data); + *queue = (_xqueue)mbox; + mbox->id = osMessageQueueNew(number_of_messages, message_size, &mbox->attr); + if(mbox->id == NULL) + goto err_exit; _func_exit_; - return _SUCCESS; + return _SUCCESS; err_exit: - DBG_ERR("%s error\r\n", __FUNCTION__); - if(mbox){ - if(mbox->queue_mem) - _rtx2_mfree(mbox->queue_mem, number_of_messages * (message_size + sizeof(os_message_t))); - _rtx2_mfree((u8 *)mbox, sizeof(rtx_mbox_t)); - *queue = NULL; - } - return _FAIL; + DBG_ERR("%s error\r\n", __FUNCTION__); + if(mbox){ + if(mbox->queue_mem) + _rtx2_mfree(mbox->queue_mem, number_of_messages * (message_size + sizeof(os_message_t))); + _rtx2_mfree((u8 *)mbox, sizeof(rtx_mbox_t)); + *queue = NULL; + } + return _FAIL; } static int _rtx2_push_to_xqueue( _xqueue* queue, void* message, u32 timeout_ms ) { _func_enter_; - rtx_mbox_t *mbox; - if(timeout_ms == RTW_MAX_DELAY) { - timeout_ms = osWaitForever; - } else { - timeout_ms = rtw_ms_to_systime(timeout_ms); - } - - if (*queue != NULL){ - mbox = (rtx_mbox_t *)(*queue); - if(osMessageQueuePut(mbox->id, message, NULL, timeout_ms) != osOK ){ - DBG_ERR("%s error\n", __FUNCTION__); - return _FAIL; - } - } + rtx_mbox_t *mbox; + if(timeout_ms == RTW_MAX_DELAY) { + timeout_ms = osWaitForever; + } else { + timeout_ms = rtw_ms_to_systime(timeout_ms); + } + + if (*queue != NULL){ + mbox = (rtx_mbox_t *)(*queue); + if(osMessageQueuePut(mbox->id, message, 0, timeout_ms) != osOK ){ + DBG_ERR("%s error\n", __FUNCTION__); + return _FAIL; + } + } _func_exit_; - return _SUCCESS; + return _SUCCESS; } static int _rtx2_pop_from_xqueue( _xqueue* queue, void* message, u32 timeout_ms ) { _func_enter_; - if(timeout_ms == RTW_WAIT_FOREVER) { - timeout_ms = osWaitForever; - } else { - timeout_ms = rtw_ms_to_systime(timeout_ms); - } - if (*queue != NULL){ - rtx_mbox_t *mbox = (rtx_mbox_t *)(*queue); - osStatus_t res = osMessageQueueGet(mbox->id, message, NULL, timeout_ms); - if (res == osOK) { + if(timeout_ms == RTW_WAIT_FOREVER) { + timeout_ms = osWaitForever; + } else { + timeout_ms = rtw_ms_to_systime(timeout_ms); + } + if (*queue != NULL){ + rtx_mbox_t *mbox = (rtx_mbox_t *)(*queue); + osStatus_t res = osMessageQueueGet(mbox->id, message, NULL, timeout_ms); + if (res == osOK) { _func_exit_; - return _SUCCESS; - } - } + return _SUCCESS; + } + } - DBG_ERR("[%p] %s error", osThreadGetId(), __FUNCTION__); - return _FAIL; + DBG_ERR("[%p] %s error", osThreadGetId(), __FUNCTION__); +_func_exit_; + return _FAIL; } static int _rtx2_deinit_xqueue( _xqueue* queue ) { _func_enter_; - if(*queue != NULL){ - rtx_mbox_t *mbox = (rtx_mbox_t *)(*queue); - if(mbox->queue_mem) - _rtx2_mfree(mbox->queue_mem, mbox->attr.mq_size); - _rtx2_mfree((u8 *)mbox, sizeof(rtx_mbox_t)); - *queue = NULL; - } + if(*queue != NULL){ + rtx_mbox_t *mbox = (rtx_mbox_t *)(*queue); + if(mbox->queue_mem) + _rtx2_mfree(mbox->queue_mem, mbox->attr.mq_size); + _rtx2_mfree((u8 *)mbox, sizeof(rtx_mbox_t)); + *queue = NULL; + } _func_exit_; return 0; } static u32 _rtx2_get_current_time(void) { - return osKernelGetSysTimerCount(); + return osKernelGetSysTimerCount(); } static u32 _rtx2_systime_to_ms(u32 systime) { - return systime * OS_TICK_RATE_MS; + return systime * OS_TICK_RATE_MS; } static u32 _rtx2_systime_to_sec(u32 systime) { - return systime / OS_TICK; + return systime / OS_TICK; } static u32 _rtx2_ms_to_systime(u32 ms) { - return ms / OS_TICK_RATE_MS; + return ms / OS_TICK_RATE_MS; } static u32 _rtx2_sec_to_systime(u32 sec) { - return sec * OS_TICK; + return sec * OS_TICK; } static void _rtx2_msleep_os(int ms) { _func_enter_; - osDelay(_rtx2_ms_to_systime(ms)); + osDelay(_rtx2_ms_to_systime(ms)); _func_exit_; } @@ -582,13 +585,13 @@ static void _rtx2_usleep_os(int us) { _func_enter_; #if defined(STM32F2XX) || defined(STM32F4XX) || defined(STM32F10X_XL) - // FreeRTOS does not provide us level delay. Use busy wait - WLAN_BSP_UsLoop(us); + // FreeRTOS does not provide us level delay. Use busy wait + WLAN_BSP_UsLoop(us); #elif defined(CONFIG_PLATFORM_8195A) || defined(CONFIG_PLATFORM_8711B) - //DBG_ERR("%s: Please Implement micro-second delay\n", __FUNCTION__); - HalDelayUs(us); + //DBG_ERR("%s: Please Implement micro-second delay\n", __FUNCTION__); + HalDelayUs(us); #else -// #error "Please implement hardware dependent micro second level sleep here" + // #error "Please implement hardware dependent micro second level sleep here" #endif _func_exit_; } @@ -596,7 +599,7 @@ _func_exit_; static void _rtx2_mdelay_os(int ms) { _func_enter_; - osDelay(_rtx2_ms_to_systime(ms)); + osDelay(_rtx2_ms_to_systime(ms)); _func_exit_; } @@ -604,13 +607,13 @@ static void _rtx2_udelay_os(int us) { _func_enter_; #if defined(STM32F2XX) || defined(STM32F4XX) || defined(STM32F10X_XL) - // FreeRTOS does not provide us level delay. Use busy wait - WLAN_BSP_UsLoop(us); + // FreeRTOS does not provide us level delay. Use busy wait + WLAN_BSP_UsLoop(us); #elif defined(CONFIG_PLATFORM_8195A) || defined(CONFIG_PLATFORM_8711B) - //RtlUdelayOS(us); - HalDelayUs(us); + //RtlUdelayOS(us); + HalDelayUs(us); #else -// #error "Please implement hardware dependent micro second level sleep here" + // #error "Please implement hardware dependent micro second level sleep here" #endif _func_exit_; } @@ -618,256 +621,258 @@ _func_exit_; static void _rtx2_yield_os(void) { _func_enter_; - osThreadYield(); + osThreadYield(); _func_exit_; } static void _rtx2_ATOMIC_SET(ATOMIC_T *v, int i) { - atomic_set(v,i); + atomic_set(v,i); } static int _rtx2_ATOMIC_READ(ATOMIC_T *v) { - return atomic_read(v); + return atomic_read(v); } static void _rtx2_ATOMIC_ADD(ATOMIC_T *v, int i) { - save_and_cli(); - v->counter += i; - restore_flags(); + save_and_cli(); + v->counter += i; + restore_flags(); } static void _rtx2_ATOMIC_SUB(ATOMIC_T *v, int i) { - save_and_cli(); - v->counter -= i; - restore_flags(); + save_and_cli(); + v->counter -= i; + restore_flags(); } static void _rtx2_ATOMIC_INC(ATOMIC_T *v) { - save_and_cli(); - v->counter++; - restore_flags(); + save_and_cli(); + v->counter++; + restore_flags(); } static void _rtx2_ATOMIC_DEC(ATOMIC_T *v) { - save_and_cli(); - v->counter--; - restore_flags(); + save_and_cli(); + v->counter--; + restore_flags(); } static int _rtx2_ATOMIC_ADD_RETURN(ATOMIC_T *v, int i) { - int temp; + int temp; - save_and_cli(); - temp = v->counter; - temp += i; - v->counter = temp; - restore_flags(); + save_and_cli(); + temp = v->counter; + temp += i; + v->counter = temp; + restore_flags(); - return temp; + return temp; } static int _rtx2_ATOMIC_SUB_RETURN(ATOMIC_T *v, int i) { - int temp; + int temp; - save_and_cli(); - temp = v->counter; - temp -= i; - v->counter = temp; - restore_flags(); + save_and_cli(); + temp = v->counter; + temp -= i; + v->counter = temp; + restore_flags(); - return temp; + return temp; } static int _rtx2_ATOMIC_INC_RETURN(ATOMIC_T *v) { - return _rtx2_ATOMIC_ADD_RETURN(v, 1); + return _rtx2_ATOMIC_ADD_RETURN(v, 1); } static int _rtx2_ATOMIC_DEC_RETURN(ATOMIC_T *v) { - return _rtx2_ATOMIC_SUB_RETURN(v, 1); + return _rtx2_ATOMIC_SUB_RETURN(v, 1); } static u64 _rtx2_modular64(u64 n, u64 base) { - unsigned int __base = (base); - unsigned int __rem; + unsigned int __base = (base); + unsigned int __rem; _func_enter_; - if (((n) >> 32) == 0) { - __rem = (unsigned int)(n) % __base; - (n) = (unsigned int)(n) / __base; - } - else - __rem = __div64_32(&(n), __base); + if (((n) >> 32) == 0) { + __rem = (unsigned int)(n) % __base; + (n) = (unsigned int)(n) / __base; + } else { + __rem = __div64_32(&(n), __base); + } _func_exit_; - return __rem; + return __rem; } /* Refer to ecos bsd tcpip codes */ static int _rtx2_arc4random(void) { _func_enter_; - u32 res = _rtx2_get_current_time(); - static unsigned long seed = 0xDEADB00B; - seed = ((seed & 0x007F00FF) << 7) ^ - ((seed & 0x0F80FF00) >> 8) ^ // be sure to stir those low bits - (res << 13) ^ (res >> 9); // using the clock too! + u32 res = _rtx2_get_current_time(); + static unsigned long seed = 0xDEADB00B; + seed = ((seed & 0x007F00FF) << 7) ^ + ((seed & 0x0F80FF00) >> 8) ^ // be sure to stir those low bits + (res << 13) ^ (res >> 9); // using the clock too! _func_exit_; - return (int)seed; + return (int)seed; } static int _rtx2_get_random_bytes(void *buf, u32 len) { -#if 1 //becuase of 4-byte align, we use the follow code style. - unsigned int ranbuf; - unsigned int *lp; - int i, count; - count = len / sizeof(unsigned int); - lp = (unsigned int *) buf; + unsigned int ranbuf; + unsigned int *lp; + int i, count; + count = len / sizeof(unsigned int); + lp = (unsigned int *) buf; _func_enter_; - for(i = 0; i < count; i ++) { - lp[i] = _rtx2_arc4random(); - len -= sizeof(unsigned int); - } + for(i = 0; i < count; i ++) { + lp[i] = _rtx2_arc4random(); + len -= sizeof(unsigned int); + } - if(len > 0) { - ranbuf = _rtx2_arc4random(); - _rtx2_memcpy(&lp[i], &ranbuf, len); - } + if(len > 0) { + ranbuf = _rtx2_arc4random(); + _rtx2_memcpy(&lp[i], &ranbuf, len); + } _func_exit_; - return 0; -#else - unsigned long ranbuf, *lp; - lp = (unsigned long *)buf; - while (len > 0) { - ranbuf = _rtx2_arc4random(); - *lp++ = ranbuf; //this op need the pointer is 4Byte-align! - len -= sizeof(ranbuf); - } - return 0; -#endif + return 0; } static u32 _rtx2_GetFreeHeapSize(void) { -#if USE_HEAP_INFO - return osFreeBytesRemaining; -#else - return 0; -#endif + //TODO + return 0; } +/* Convert from wlan priority number to CMSIS type osPriority */ +static osPriority_t make_cmsis_priority (u32 fpriority) +{ + osPriority_t priority = (osPriority_t)fpriority; + priority += osPriorityHigh; + return priority; +} -#if CONFIG_USE_TCM_HEAP -void *tcm_heap_malloc(int size); -#endif static int _rtx2_create_task(struct task_struct *ptask, const char *name, u32 stack_size, u32 priority, thread_func_t func, void *thctx) { _func_enter_; - rtx_thread_data_t *thread_hdl = NULL; - u32 stacksize = stack_size * 4; //sizeof(DWORD) - if(!func) - goto err_exit; - thread_hdl = (rtx_thread_data_t *)_rtx2_zmalloc(sizeof(rtx_thread_data_t)); - if(thread_hdl == NULL) - goto err_exit; - if(priority > osPriorityRealtime){ - DBG_ERR("[%s]priority is higher than osPriorityRealtime", name); - priority = osPriorityRealtime; - } - thread_hdl->attr.name = name; - thread_hdl->attr.priority = (osPriority_t)priority; - thread_hdl->attr.cb_size = sizeof(thread_hdl->data); - thread_hdl->attr.cb_mem = &thread_hdl->data; - thread_hdl->attr.stack_size = stacksize; - thread_hdl->attr.stack_mem = (void *)_rtx2_malloc(stacksize); - if (thread_hdl->attr.stack_mem == NULL) - goto err_exit; + rtx_thread_data_t *thread_hdl = NULL; + u32 stacksize = stack_size * 4; //sizeof(DWORD) + u8 *(*_customized_malloc)( u32 size ) = _rtx2_malloc; + u8 *(*_customized_zmalloc)( u32 size ) = _rtx2_zmalloc; + if(!func) + goto err_exit; +#if defined(CONFIG_WIFI_NORMAL) && defined(CONFIG_NETWORK) + if(rtw_if_wifi_thread((char *)name) == 0){ + priority = make_cmsis_priority(priority); + _customized_malloc = _rtw_vmalloc; + _customized_zmalloc = _rtw_zvmalloc; + } +#endif + thread_hdl = (rtx_thread_data_t *)_customized_zmalloc(sizeof(rtx_thread_data_t)); + if(thread_hdl == NULL) + goto err_exit; + if(priority > osPriorityRealtime){ + DBG_ERR("[%s]priority is higher than osPriorityRealtime", name); + priority = osPriorityRealtime; + } + thread_hdl->attr.name = name; + thread_hdl->attr.priority = (osPriority_t)priority; + thread_hdl->attr.cb_size = sizeof(thread_hdl->data); + thread_hdl->attr.cb_mem = &thread_hdl->data; + thread_hdl->attr.stack_size = stacksize; + thread_hdl->attr.stack_mem = (void *)_customized_malloc(stacksize); + if (thread_hdl->attr.stack_mem == NULL) { + DBG_ERR("[%s] malloc failed", name); + goto err_exit; + } - ptask->task = (_thread_hdl_)thread_hdl; - ptask->task_name = name; - ptask->blocked = 0; - ptask->callback_running = 0; + ptask->task = (_thread_hdl_)thread_hdl; + ptask->task_name = name; + ptask->blocked = 0; + ptask->callback_running = 0; - _rtx2_init_sema(&ptask->wakeup_sema, 0); - _rtx2_init_sema(&ptask->terminate_sema, 0); - //rtw_init_queue(&wq->work_queue); + _rtx2_init_sema(&ptask->wakeup_sema, 0); + _rtx2_init_sema(&ptask->terminate_sema, 0); + //rtw_init_queue(&wq->work_queue); - thread_hdl->id = osThreadNew((osThreadFunc_t)func, thctx, &thread_hdl->attr); - if(thread_hdl->id == NULL) - goto err_exit; - return _SUCCESS; + thread_hdl->id = osThreadNew((osThreadFunc_t)func, thctx, &thread_hdl->attr); + if (thread_hdl->id == NULL) { + DBG_ERR("[%s] osThreadNew failed", name); + goto err_exit; + } + return _SUCCESS; err_exit: - if(thread_hdl){ - _rtx2_free_sema(&ptask->wakeup_sema); - _rtx2_free_sema(&ptask->terminate_sema); - _rtx2_memset((u8 *)ptask, 0, sizeof(*ptask)); - if(thread_hdl->attr.stack_mem) - _rtx2_mfree((void *)thread_hdl->attr.stack_mem, thread_hdl->attr.stack_size); - _rtx2_mfree((u8 *)thread_hdl, sizeof(rtx_thread_data_t)); - } - DBG_ERR("Create Task \"%s\" Failed! \n", ptask->task_name); - return _FAIL; + if(thread_hdl){ + _rtx2_free_sema(&ptask->wakeup_sema); + _rtx2_free_sema(&ptask->terminate_sema); + _rtx2_memset((u8 *)ptask, 0, sizeof(*ptask)); + if(thread_hdl->attr.stack_mem) + _rtx2_mfree((void *)thread_hdl->attr.stack_mem, thread_hdl->attr.stack_size); + _rtx2_mfree((u8 *)thread_hdl, sizeof(rtx_thread_data_t)); + } + DBG_ERR("Create Task \"%s\" Failed! \n", name); + return _FAIL; } static void _rtx2_delete_task(struct task_struct *ptask) { _func_enter_; - rtx_thread_data_t *thread_hdl = (rtx_thread_data_t *)ptask->task; - if (!thread_hdl){ - DBG_ERR("_rtx2_delete_task(): ptask is NULL!\n"); - return; - } + rtx_thread_data_t *thread_hdl = (rtx_thread_data_t *)ptask->task; + if (!thread_hdl){ + DBG_ERR("_rtx2_delete_task(): ptask is NULL!\n"); + return; + } - ptask->blocked = 1; + ptask->blocked = 1; - _rtx2_up_sema(&ptask->wakeup_sema); - _rtx2_down_sema(&ptask->terminate_sema, TIMER_MAX_DELAY); + _rtx2_up_sema(&ptask->wakeup_sema); + _rtx2_down_sema(&ptask->terminate_sema, TIMER_MAX_DELAY); - osThreadTerminate(thread_hdl->id); - if(thread_hdl->attr.stack_mem) - _rtx2_mfree((void *)thread_hdl->attr.stack_mem, thread_hdl->attr.stack_size); - _rtx2_mfree((u8 *)thread_hdl, sizeof(rtx_thread_data_t)); - - //rtw_deinit_queue(&wq->work_queue); - _rtx2_free_sema(&ptask->wakeup_sema); - _rtx2_free_sema(&ptask->terminate_sema); + osThreadTerminate(thread_hdl->id); + if(thread_hdl->attr.stack_mem) + _rtx2_mfree((void *)thread_hdl->attr.stack_mem, thread_hdl->attr.stack_size); + _rtx2_mfree((u8 *)thread_hdl, sizeof(rtx_thread_data_t)); - ptask->task = NULL; + //rtw_deinit_queue(&wq->work_queue); + _rtx2_free_sema(&ptask->wakeup_sema); + _rtx2_free_sema(&ptask->terminate_sema); - DBG_TRACE("Delete Task \"%s\"\n", ptask->task_name); + ptask->task = NULL; + + DBG_TRACE("Delete Task \"%s\"\n", ptask->task_name); _func_exit_; } void _rtx2_wakeup_task(struct task_struct *ptask) { _func_enter_; - if(ptask) - _rtx2_up_sema(&ptask->wakeup_sema); + if(ptask) + _rtx2_up_sema(&ptask->wakeup_sema); _func_exit_; } static void _rtx2_thread_enter(char *name) { _func_enter_; - DBG_INFO("\n\rRTKTHREAD %s\n", name); + DBG_INFO("\n\rRTKTHREAD %s\n", name); _func_exit_; } static void _rtx2_thread_exit(void) { _func_enter_; - osThreadExit(); -_func_exit_; + osThreadExit(); } /***************************************************** @@ -892,204 +897,335 @@ typedef struct os_timer_cb_ { // Timer Control Block } os_timer_cb; *****************************************************/ _timerHandle _rtx2_timerCreate( const signed char *pcTimerName, - osdepTickType xTimerPeriodInTicks, - u32 uxAutoReload, - void * pvTimerID, - TIMER_FUN pxCallbackFunction ) + osdepTickType xTimerPeriodInTicks, + u32 uxAutoReload, + void * pvTimerID, + TIMER_FUN pxCallbackFunction ) { _func_enter_; - rtx_tmr_t *tmr = (rtx_tmr_t *)_rtx2_zmalloc(sizeof(rtx_tmr_t)); - osTimerType_t type = (uxAutoReload == _TRUE)?osTimerPeriodic:osTimerOnce; - if(tmr == NULL) - goto err_exit; + rtx_tmr_t *tmr = (rtx_tmr_t *)_rtx2_zmalloc(sizeof(rtx_tmr_t)); + osTimerType_t type = (uxAutoReload == _TRUE)?osTimerPeriodic:osTimerOnce; + if(tmr == NULL) + goto err_exit; - tmr->attr.name = pcTimerName; - tmr->attr.cb_mem = (void *)&tmr->data; - tmr->attr.cb_size = sizeof(tmr->data); - if(pvTimerID == NULL) - pvTimerID = (void *)tmr; - tmr->id = osTimerNew(pxCallbackFunction, type, pvTimerID, &tmr->attr); - if(tmr->id == NULL) - goto err_exit; + tmr->attr.name = (const char *)pcTimerName; + tmr->attr.cb_mem = (void *)&tmr->data; + tmr->attr.cb_size = sizeof(tmr->data); + if(pvTimerID == NULL) + pvTimerID = (void *)tmr; + tmr->id = osTimerNew(pxCallbackFunction, type, pvTimerID, &tmr->attr); + if(tmr->id == NULL) + goto err_exit; _func_exit_; - return (_timerHandle)tmr; + return (_timerHandle)tmr; err_exit: - DBG_ERR("error"); - if(tmr) - _rtx2_mfree((u8 *)tmr, sizeof(rtx_tmr_t)); - return NULL; + DBG_ERR("error"); + if(tmr) + _rtx2_mfree((u8 *)tmr, sizeof(rtx_tmr_t)); + return NULL; } -u32 _rtx2_timerDelete( _timerHandle xTimer, - osdepTickType xBlockTime ) +u32 _rtx2_timerDelete(_timerHandle xTimer, + osdepTickType xBlockTime) { _func_enter_; - rtx_tmr_t *tmr = (rtx_tmr_t *) xTimer; - osStatus_t status = osTimerDelete(tmr->id); - _rtx2_mfree((u8 *)tmr, sizeof(rtx_tmr_t)); - if(status != osOK){ - DBG_ERR("error %d", status); - return _FAIL; - } + rtx_tmr_t *tmr = (rtx_tmr_t *) xTimer; + osStatus_t status = osTimerDelete(tmr->id); + _rtx2_mfree((u8 *)tmr, sizeof(rtx_tmr_t)); + if(status != osOK){ + DBG_ERR("error %d", status); + return _FAIL; + } _func_exit_; - return _SUCCESS; + return _SUCCESS; } -u32 _rtx2_timerIsTimerActive( _timerHandle xTimer ) +u32 _rtx2_timerIsTimerActive(_timerHandle xTimer) { _func_enter_; - rtx_tmr_t *tmr = (rtx_tmr_t *) xTimer; - if(osTimerIsRunning(tmr->id)) - return _TRUE; - return _FALSE; + rtx_tmr_t *tmr = (rtx_tmr_t *) xTimer; + if (osTimerIsRunning(tmr->id)) { + return _TRUE; + } + return _FALSE; } -u32 _rtx2_timerStop( _timerHandle xTimer, - osdepTickType xBlockTime ) +u32 _rtx2_timerStop(_timerHandle xTimer, + osdepTickType xBlockTime) { _func_enter_; - rtx_tmr_t *tmr = (rtx_tmr_t *) xTimer; - if(_rtx2_timerIsTimerActive(xTimer) == _TRUE){ - osStatus_t status = osTimerStop(tmr->id); + rtx_tmr_t *tmr = (rtx_tmr_t *) xTimer; + if(_rtx2_timerIsTimerActive(xTimer) == _TRUE){ + osStatus_t status = osTimerStop(tmr->id); + if(status != osOK){ + DBG_ERR("error %d\n", status); _func_exit_; - if(status != osOK){ - DBG_ERR("error %d\n", status); - return _FAIL; - } - } - return _SUCCESS; + return _FAIL; + } + } +_func_exit_; + return _SUCCESS; } -u32 _rtx2_timerChangePeriod( _timerHandle xTimer, - osdepTickType xNewPeriod, - osdepTickType xBlockTime ) +u32 _rtx2_timerChangePeriod(_timerHandle xTimer, + osdepTickType xNewPeriod, + osdepTickType xBlockTime) { _func_enter_; - rtx_tmr_t *tmr = (rtx_tmr_t *) xTimer; - osStatus_t ret; + rtx_tmr_t *tmr = (rtx_tmr_t *) xTimer; + osStatus_t ret; - if(xNewPeriod == 0) - xNewPeriod += 1; - //xNewPeriod = _rtx2_systime_to_ms(xNewPeriod); - ret = osTimerStart(tmr->id, xNewPeriod); + if(xNewPeriod == 0) + xNewPeriod += 1; + //xNewPeriod = _rtx2_systime_to_ms(xNewPeriod); + ret = osTimerStart(tmr->id, xNewPeriod); _func_exit_; - if(ret == osOK) - return _SUCCESS; - - DBG_ERR("%s error\n", __FUNCTION__); - return _FAIL; + if(ret == osOK) + return _SUCCESS; + + DBG_ERR("%s error\n", __FUNCTION__); + return _FAIL; } -//void _rtx2_acquire_wakelock() -//{ -//#if defined(configUSE_WAKELOCK_PMU) && (configUSE_WAKELOCK_PMU == 1) -// acquire_wakelock(WAKELOCK_WLAN); -//#endif -//} +void *_rtx2_timerGetID(_timerHandle xTimer) +{ + DBG_ERR("%s: Not implemented yet\n", __FUNCTION__); + return NULL; +} -//void _rtx2_release_wakelock() -//{ -//#if defined(configUSE_WAKELOCK_PMU) && (configUSE_WAKELOCK_PMU == 1) -// release_wakelock(WAKELOCK_WLAN); -//#endif -//} +u32 _rtx2_timerStart(_timerHandle xTimer, + osdepTickType xBlockTime) +{ + DBG_ERR("%s: Not implemented yet\n", __FUNCTION__); + return _FAIL; +} + +u32 _rtx2_timerStartFromISR(_timerHandle xTimer, + osdepBASE_TYPE *pxHigherPriorityTaskWoken) +{ + DBG_ERR("%s: Not implemented yet\n", __FUNCTION__); + return _FAIL; +} + +u32 _rtx2_timerStopFromISR(_timerHandle xTimer, + osdepBASE_TYPE *pxHigherPriorityTaskWoken) +{ + DBG_ERR("%s: Not implemented yet\n", __FUNCTION__); + return _FAIL; +} + +u32 _rtx2_timerResetFromISR(_timerHandle xTimer, + osdepBASE_TYPE *pxHigherPriorityTaskWoken) +{ + DBG_ERR("%s: Not implemented yet\n", __FUNCTION__); + return _FAIL; +} + +u32 _rtx2_timerChangePeriodFromISR(_timerHandle xTimer, + osdepTickType xNewPeriod, + osdepBASE_TYPE *pxHigherPriorityTaskWoken) +{ + if(xNewPeriod == 0) + xNewPeriod += 1; + DBG_ERR("%s: Not implemented yet\n", __FUNCTION__); + return _FAIL; +} + +u32 _rtx2_timerReset(_timerHandle xTimer, + osdepTickType xBlockTime) +{ + DBG_ERR("%s: Not implemented yet\n", __FUNCTION__); + return _FAIL; +} + +void _rtx2_acquire_wakelock() +{ + //TODO + return; +} + +void _rtx2_release_wakelock() +{ + //TODO + return; +} + +void _rtx2_wakelock_timeout(uint32_t timeout) +{ + //TODO + return; +} u8 _rtx2_get_scheduler_state(void) { _func_enter_; - osKernelState_t state = osKernelGetState(); - u8 state_out = OS_SCHEDULER_NOT_STARTED; - switch(state){ - case osKernelRunning: state = OS_SCHEDULER_RUNNING; break; - case osKernelSuspended: state = OS_SCHEDULER_SUSPENDED; break; - default: break; - } + osKernelState_t state = osKernelGetState(); + u8 state_out = OS_SCHEDULER_NOT_STARTED; + switch(state){ + case osKernelRunning: + state_out = OS_SCHEDULER_RUNNING; + break; + case osKernelSuspended: + state_out = OS_SCHEDULER_SUSPENDED; + break; + default: + break; + } _func_exit_; - return state_out; + return state_out; } const struct osdep_service_ops osdep_service = { - _rtx2_malloc, //rtw_vmalloc - _rtx2_zmalloc, //rtw_zvmalloc - _rtx2_mfree, //rtw_vmfree - _rtx2_malloc, //rtw_malloc - _rtx2_zmalloc, //rtw_zmalloc - _rtx2_mfree, //rtw_mfree - _rtx2_memcpy, //rtw_memcpy - _rtx2_memcmp, //rtw_memcmp - _rtx2_memset, //rtw_memset - _rtx2_init_sema, //rtw_init_sema - _rtx2_free_sema, //rtw_free_sema - _rtx2_up_sema, //rtw_up_sema - _rtx2_up_sema_from_isr,//rtw_up_sema_from_isr - _rtx2_down_sema, //rtw_down_sema - _rtx2_mutex_init, //rtw_mutex_init - _rtx2_mutex_free, //rtw_mutex_free - _rtx2_mutex_get, //rtw_mutex_get - _rtx2_mutex_get_timeout, //rtw_mutex_get_timeout - _rtx2_mutex_put, //rtw_mutex_put - _rtx2_enter_critical, //rtw_enter_critical - _rtx2_exit_critical, //rtw_exit_critical - _rtx2_enter_critical_from_isr, //rtw_enter_critical_from_isr - _rtx2_exit_critical_from_isr, //rtw_exit_critical_from_isr - NULL, //rtw_enter_critical_bh - NULL, //rtw_exit_critical_bh - _rtx2_enter_critical_mutex, //rtw_enter_critical_mutex - _rtx2_exit_critical_mutex, //rtw_exit_critical_mutex - _rtx2_spinlock_init, //rtw_spinlock_init - _rtx2_spinlock_free, //rtw_spinlock_free - _rtx2_spinlock, //rtw_spin_lock - _rtx2_spinunlock, //rtw_spin_unlock - _rtx2_spinlock_irqsave, //rtw_spinlock_irqsave - _rtx2_spinunlock_irqsave, //rtw_spinunlock_irqsave - _rtx2_init_xqueue,//rtw_init_xqueue - _rtx2_push_to_xqueue,//rtw_push_to_xqueue - _rtx2_pop_from_xqueue,//rtw_pop_from_xqueue - _rtx2_deinit_xqueue,//rtw_deinit_xqueue - _rtx2_get_current_time, //rtw_get_current_time - _rtx2_systime_to_ms, //rtw_systime_to_ms - _rtx2_systime_to_sec, //rtw_systime_to_sec - _rtx2_ms_to_systime, //rtw_ms_to_systime - _rtx2_sec_to_systime, //rtw_sec_to_systime - _rtx2_msleep_os, //rtw_msleep_os - _rtx2_usleep_os, //rtw_usleep_os - _rtx2_mdelay_os, //rtw_mdelay_os - _rtx2_udelay_os, //rtw_udelay_os - _rtx2_yield_os, //rtw_yield_os - - _rtx2_ATOMIC_SET, //ATOMIC_SET - _rtx2_ATOMIC_READ, //ATOMIC_READ - _rtx2_ATOMIC_ADD, //ATOMIC_ADD - _rtx2_ATOMIC_SUB, //ATOMIC_SUB - _rtx2_ATOMIC_INC, //ATOMIC_INC - _rtx2_ATOMIC_DEC, //ATOMIC_DEC - _rtx2_ATOMIC_ADD_RETURN, //ATOMIC_ADD_RETURN - _rtx2_ATOMIC_SUB_RETURN, //ATOMIC_SUB_RETURN - _rtx2_ATOMIC_INC_RETURN, //ATOMIC_INC_RETURN - _rtx2_ATOMIC_DEC_RETURN, //ATOMIC_DEC_RETURN + _rtx2_malloc, //rtw_vmalloc + _rtx2_zmalloc, //rtw_zvmalloc + _rtx2_mfree, //rtw_vmfree + _rtx2_malloc, //rtw_malloc + _rtx2_zmalloc, //rtw_zmalloc + _rtx2_mfree, //rtw_mfree + _rtx2_memcpy, //rtw_memcpy + _rtx2_memcmp, //rtw_memcmp + _rtx2_memset, //rtw_memset + _rtx2_init_sema, //rtw_init_sema + _rtx2_free_sema, //rtw_free_sema + _rtx2_up_sema, //rtw_up_sema + _rtx2_up_sema_from_isr, //rtw_up_sema_from_isr + _rtx2_down_sema, //rtw_down_timeout_sema + _rtx2_mutex_init, //rtw_mutex_init + _rtx2_mutex_free, //rtw_mutex_free + _rtx2_mutex_get, //rtw_mutex_get + _rtx2_mutex_get_timeout, //rtw_mutex_get_timeout + _rtx2_mutex_put, //rtw_mutex_put + _rtx2_enter_critical, //rtw_enter_critical + _rtx2_exit_critical, //rtw_exit_critical + _rtx2_enter_critical_from_isr, //rtw_enter_critical_from_isr + _rtx2_exit_critical_from_isr, //rtw_exit_critical_from_isr + NULL, //rtw_enter_critical_bh + NULL, //rtw_exit_critical_bh + _rtx2_enter_critical_mutex, //rtw_enter_critical_mutex + _rtx2_exit_critical_mutex, //rtw_exit_critical_mutex + _rtx2_cpu_lock, //rtw_cpu_lock + _rtx2_cpu_unlock, //rtw_cpu_unlock + _rtx2_spinlock_init, //rtw_spinlock_init + _rtx2_spinlock_free, //rtw_spinlock_free + _rtx2_spinlock, //rtw_spin_lock + _rtx2_spinunlock, //rtw_spin_unlock + _rtx2_spinlock_irqsave, //rtw_spinlock_irqsave + _rtx2_spinunlock_irqsave, //rtw_spinunlock_irqsave + _rtx2_init_xqueue, //rtw_init_xqueue + _rtx2_push_to_xqueue, //rtw_push_to_xqueue + _rtx2_pop_from_xqueue, //rtw_pop_from_xqueue + _rtx2_deinit_xqueue, //rtw_deinit_xqueue + _rtx2_get_current_time, //rtw_get_current_time + _rtx2_systime_to_ms, //rtw_systime_to_ms + _rtx2_systime_to_sec, //rtw_systime_to_sec + _rtx2_ms_to_systime, //rtw_ms_to_systime + _rtx2_sec_to_systime, //rtw_sec_to_systime + _rtx2_msleep_os, //rtw_msleep_os + _rtx2_usleep_os, //rtw_usleep_os + _rtx2_mdelay_os, //rtw_mdelay_os + _rtx2_udelay_os, //rtw_udelay_os + _rtx2_yield_os, //rtw_yield_os - _rtx2_modular64, //rtw_modular64 - _rtx2_get_random_bytes, //rtw_get_random_bytes - _rtx2_GetFreeHeapSize, //rtw_getFreeHeapSize + _rtx2_ATOMIC_SET, //ATOMIC_SET + _rtx2_ATOMIC_READ, //ATOMIC_READ + _rtx2_ATOMIC_ADD, //ATOMIC_ADD + _rtx2_ATOMIC_SUB, //ATOMIC_SUB + _rtx2_ATOMIC_INC, //ATOMIC_INC + _rtx2_ATOMIC_DEC, //ATOMIC_DEC + _rtx2_ATOMIC_ADD_RETURN, //ATOMIC_ADD_RETURN + _rtx2_ATOMIC_SUB_RETURN, //ATOMIC_SUB_RETURN + _rtx2_ATOMIC_INC_RETURN, //ATOMIC_INC_RETURN + _rtx2_ATOMIC_DEC_RETURN, //ATOMIC_DEC_RETURN - _rtx2_create_task, //rtw_create_task - _rtx2_delete_task, //rtw_delete_task - _rtx2_wakeup_task, //rtw_wakeup_task + _rtx2_modular64, //rtw_modular64 + _rtx2_get_random_bytes, //rtw_get_random_bytes + _rtx2_GetFreeHeapSize, //rtw_getFreeHeapSize - _rtx2_thread_enter, //rtw_thread_enter - _rtx2_thread_exit, //rtw_thread_exit + _rtx2_create_task, //rtw_create_task + _rtx2_delete_task, //rtw_delete_task + _rtx2_wakeup_task, //rtw_wakeup_task - _rtx2_timerCreate, //rtw_timerCreate, - _rtx2_timerDelete, //rtw_timerDelete, - _rtx2_timerIsTimerActive, //rtw_timerIsTimerActive, - _rtx2_timerStop, //rtw_timerStop, - _rtx2_timerChangePeriod, //rtw_timerChangePeriod + _rtx2_thread_enter, //rtw_thread_enter + _rtx2_thread_exit, //rtw_thread_exit - NULL, // rtw_acquire_wakelock - NULL, // rtw_release_wakelock - NULL, //rtw_wakelock_timeout + _rtx2_timerCreate, //rtw_timerCreate + _rtx2_timerDelete, //rtw_timerDelete + _rtx2_timerIsTimerActive, //rtw_timerIsTimerActive + _rtx2_timerStop, //rtw_timerStop + _rtx2_timerChangePeriod, //rtw_timerChangePeriod + _rtx2_timerGetID, //rtw_timerGetID + _rtx2_timerStart, //rtw_timerStart + _rtx2_timerStartFromISR, //rtw_timerStartFromISR + _rtx2_timerStopFromISR, //rtw_timerStopFromISR + _rtx2_timerResetFromISR, //rtw_timerResetFromISR + _rtx2_timerChangePeriodFromISR, //rtw_timerChangePeriodFromISR + _rtx2_timerReset, //rtw_timerReset - _rtx2_get_scheduler_state // rtw_get_scheduler_state + _rtx2_acquire_wakelock, //rtw_acquire_wakelock + _rtx2_release_wakelock, //rtw_release_wakelock + _rtx2_wakelock_timeout, //rtw_wakelock_timeout + _rtx2_get_scheduler_state //rtw_get_scheduler_state }; +/* +* Below block is to remove the compilation error of ARMCC +**/ +HAL_CUT_B_RAM_DATA_SECTION +_WEAK unsigned int rand_x = 123456789; + +_WEAK u8* RtlZmalloc(u32 sz) +{ + u8 *pbuf; + + pbuf= rtw_malloc(sz); + + if (pbuf != NULL) { + _memset(pbuf, 0, sz); + } + + return pbuf; +} + +_WEAK void RtlMfree(u8 *pbuf, u32 sz) +{ + rtw_mfree(pbuf, sz); +} + +_WEAK void UartLogIrqHandleRam(void * Data) +{ + printf("%s: Should not come over here!\r\n", __func__); +} + +_WEAK void vPortSVCHandler(void) +{ + printf("%s: Should not come over here!\r\n", __func__); +} + +_WEAK void xPortPendSVHandler(void) +{ + printf("%s: Should not come over here!\r\n", __func__); +} + +_WEAK void xPortSysTickHandler(void) +{ + printf("%s: Should not come over here!\r\n", __func__); +} + +_WEAK u8 __ram_start_table_start__[]; + +_WEAK void rtw_odm_acquirespinlock(void * adapter, int type) +{ + printf("%s: Should not come over here!\r\n", __func__); +} + +_WEAK void rtw_odm_releasespinlock(void * adapter, int type) +{ + printf("%s: Should not come over here!\r\n", __func__); +} + +_WEAK void ROM_WIFI_BSSID_SET(u8 iface_type, u8 variable, u8 *val) +{ + printf("%s: Should not come over here!\r\n", __func__); +} + diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/cmsis_rtos/cmsis_rtos_service.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/cmsis_rtos/cmsis_rtos_service.h index f35587f019..ff7a4ef7ad 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/cmsis_rtos/cmsis_rtos_service.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/cmsis_rtos/cmsis_rtos_service.h @@ -1,25 +1,33 @@ -#ifndef _RTX2_SERVICE_H_ -#define _RTX2_SERVICE_H_ +#ifndef _CMSIS_RTOS_SERVICE_H_ +#define _CMSIS_RTOS_SERVICE_H_ //----------------------------------------------------------------------- // Include Files //----------------------------------------------------------------------- -#include "wireless.h" +//#include "wireless.h" #include "dlist.h" #include -//#include #include "RTX_Config.h" -//#include -//#include -//#include #include "rtx_lib.h" // -------------------------------------------- // Platform dependent include file // -------------------------------------------- -#if defined(CONFIG_PLATFORM_8195A) || defined(CONFIG_PLATFORM_8711B) -//#include "platform_stdlib.h" -//#include "basic_types.h" -#include +#if defined(CONFIG_PLATFORM_8195A) || defined(CONFIG_PLATFORM_8195BHP) +#include "platform/platform_stdlib.h" +extern VOID RtlUdelayOS(u32 us); +#elif defined(CONFIG_PLATFORM_8711B) +#include "platform/platform_stdlib.h" +#elif defined(CONFIG_PLATFORM_8721D) +#include "platform/platform_stdlib.h" +#elif defined(CONFIG_HARDWARE_8821C) +#include "basic_types.h" +#include "wlan_basic_types.h" +#elif defined(CONFIG_HARDWARE_8188F) +#include "platform/platform_stdlib.h" +#elif defined(CONFIG_HARDWARE_8192E) +#include "platform/platform_stdlib.h" +#elif defined(CONFIG_HARDWARE_8723D) +#include "platform/platform_stdlib.h" #else // other MCU may use standard library #include @@ -28,7 +36,7 @@ #if (defined CONFIG_GSPI_HCI || defined CONFIG_SDIO_HCI) || defined(CONFIG_LX_HCI) /* For SPI interface transfer and us delay implementation */ -#if !defined(CONFIG_PLATFORM_8195A) && !defined(CONFIG_PLATFORM_8711B) +#if !defined(CONFIG_PLATFORM_8195A) && !defined(CONFIG_PLATFORM_8711B) && !defined(CONFIG_PLATFORM_8721D) && !defined(CONFIG_PLATFORM_8195BHP) #include #endif #endif @@ -37,129 +45,101 @@ // -------------------------------------------- // Platform dependent type define // -------------------------------------------- -#if !defined(CONFIG_PLATFORM_8195A) && !defined(CONFIG_PLATFORM_8711B) -typedef unsigned char u8; -typedef unsigned short u16; -typedef unsigned int u32; -typedef signed char s8; -typedef signed short s16; -typedef signed int s32; -typedef signed long long s64; -typedef unsigned long long u64; -typedef unsigned int uint; -typedef signed int sint; - -#ifndef bool -typedef int bool; -#define true 1 -#define false 0 -#endif - -#define IN -#define OUT -#define VOID void -#define NDIS_OID uint -#define NDIS_STATUS uint -#ifndef PVOID -typedef void * PVOID; -#endif - -typedef unsigned int __kernel_size_t; -typedef int __kernel_ssize_t; -typedef __kernel_size_t SIZE_T; -typedef __kernel_ssize_t SSIZE_T; - -#endif //CONFIG_PLATFORM_8195A +#define OS_TICK OS_TICK_FREQ +#define OS_TICK_RATE_MS (1000/OS_TICK) // === SEMAPHORE === typedef struct { - osSemaphoreId_t id; - osSemaphoreAttr_t attr; - os_semaphore_t data; + osSemaphoreId_t id; + osSemaphoreAttr_t attr; + os_semaphore_t data; } rtx_sema_t; // === THREAD === typedef struct { - osThreadId_t id; - osThreadAttr_t attr; - os_thread_t data; + osThreadId_t id; + osThreadAttr_t attr; + os_thread_t data; } rtx_thread_data_t; // === MUTEX === typedef struct { - osMutexId_t id; - osMutexAttr_t attr; - os_mutex_t data; + osMutexId_t id; + osMutexAttr_t attr; + os_mutex_t data; } rtx_mutex_t; // === MAIL BOX === -#define RTX_MB_SIZE 8 +#define RTX_MB_SIZE 8 typedef struct { - osEventFlagsId_t id; - osEventFlagsAttr_t attr; - os_event_flags_t data; + osEventFlagsId_t id; + osEventFlagsAttr_t attr; + os_event_flags_t data; - uint8_t post_idx; - uint8_t fetch_idx; - void* queue[RTX_MB_SIZE]; + uint8_t post_idx; + uint8_t fetch_idx; + void* queue[RTX_MB_SIZE]; } rtx_mqueue_t; typedef struct { - osMessageQueueId_t id; - osMessageQueueAttr_t attr; - void *queue_mem; - os_message_queue_t data; + osMessageQueueId_t id; + osMessageQueueAttr_t attr; + void *queue_mem; + os_message_queue_t data; } rtx_mbox_t; typedef struct{ - osTimerId_t id; - osTimerAttr_t attr; - os_timer_t data; -}rtx_tmr_t; + osTimerId_t id; + osTimerAttr_t attr; + os_timer_t data; +} rtx_tmr_t; -#define FIELD_OFFSET(s,field) ((SSIZE_T)&((s*)(0))->field) +#define FIELD_OFFSET(s,field) ((SSIZE_T)&((s*)(0))->field) // os types -typedef char osdepCHAR; -typedef float osdepFLOAT; -typedef double osdepDOUBLE; -typedef long osdepLONG; -typedef short osdepSHORT; -typedef unsigned long osdepSTACK_TYPE; -typedef long osdepBASE_TYPE; -typedef unsigned long osdepTickType; +typedef char osdepCHAR; +typedef float osdepFLOAT; +typedef double osdepDOUBLE; +typedef long osdepLONG; +typedef short osdepSHORT; +typedef unsigned long osdepSTACK_TYPE; +typedef long osdepBASE_TYPE; +typedef unsigned long osdepTickType; -typedef void * _timerHandle; -typedef void * _sema; -typedef void * _mutex; -typedef void * _lock; -typedef void * _queueHandle; -typedef void * _xqueue; -typedef struct timer_list _timer; +typedef void * _timerHandle; +typedef void * _sema; +typedef void * _mutex; +typedef void * _lock; +typedef void * _queueHandle; +typedef void * _xqueue; +typedef struct timer_list _timer; -typedef struct sk_buff _pkt; -typedef unsigned char _buffer; +typedef struct sk_buff _pkt; +typedef unsigned char _buffer; +typedef unsigned int systime; #ifndef __LIST_H #warning "DLIST_NOT_DEFINE!!!!!!" struct list_head { - struct list_head *next, *prev; + struct list_head *next, *prev; }; #endif -struct __queue { - struct list_head queue; - _lock lock; +struct __queue { + struct list_head queue; + _lock lock; }; -typedef struct __queue _queue; -typedef struct list_head _list; -typedef unsigned long _irqL; +typedef struct __queue _queue; +typedef struct list_head _list; +typedef unsigned long _irqL; -typedef void* _thread_hdl_; -typedef void thread_return; -typedef void* thread_context; +typedef void* _thread_hdl_; +typedef void thread_return; +typedef void* thread_context; + +typedef struct { volatile int counter; } atomic_t; #define ATOMIC_T atomic_t #define HZ configTICK_RATE_HZ @@ -168,33 +148,40 @@ typedef void* thread_context; /* emulate a modern version */ #define LINUX_VERSION_CODE KERNEL_VERSION(2, 6, 17) -static __inline _list *get_next(_list *list) +static __inline _list *get_next(_list *list) { - return list->next; -} + return list->next; +} -static __inline _list *get_list_head(_queue *queue) +static __inline _list *get_list_head(_queue *queue) { - return (&(queue->queue)); + return (&(queue->queue)); } #define LIST_CONTAINOR(ptr, type, member) \ - ((type *)((char *)(ptr)-(SIZE_T)((char *)&((type *)ptr)->member - (char *)ptr))) + ((type *)((char *)(ptr)-(SIZE_T)((char *)&((type *)ptr)->member - (char *)ptr))) //#define container_of(p,t,n) (t*)((p)-&(((t*)0)->n)) #define container_of(ptr, type, member) \ - ((type *)((char *)(ptr)-(SIZE_T)(&((type *)0)->member))) -#define TASK_PRORITY_LOW osPriorityAboveNormal//osPriorityNormal -#define TASK_PRORITY_MIDDLE osPriorityHigh//osPriorityAboveNormal -#define TASK_PRORITY_HIGH osPriorityRealtime//osPriorityHigh -#define TASK_PRORITY_SUPER osPriorityRealtime -#define TASK_PRORITY_IDEL osPriorityIdle + ((type *)((char *)(ptr)-(SIZE_T)(&((type *)0)->member))) +#define TASK_PRORITY_LOW 1 +#define TASK_PRORITY_MIDDLE 2 +#define TASK_PRORITY_HIGH 3 +#define TASK_PRORITY_SUPER 4 +#define PRIORITIE_OFFSET 4 +#define TIMER_MAX_DELAY 0xFFFFFFFF -#define TIMER_MAX_DELAY 0xFFFFFFFF void save_and_cli(void); void restore_flags(void); void cli(void); +#ifndef mdelay +#define mdelay(t) ((t/OS_TICK_RATE_MS)>0)?(osDelay(t/OS_TICK_RATE_MS)):(osDelay(1)) +#endif + +#ifndef udelay +#define udelay(t) ((t/(OS_TICK_RATE_MS*1000))>0)?osDelay(t/(OS_TICK_RATE_MS*1000)):(osDelay(1)) +#endif //----- ------------------------------------------------------------------ // Common Definition //----- ------------------------------------------------------------------ @@ -208,45 +195,43 @@ void cli(void); #define KERN_INFO #define KERN_NOTICE -#define GFP_KERNEL 1 -#define GFP_ATOMIC 1 +#undef GFP_KERNEL +#define GFP_KERNEL 1 +#define GFP_ATOMIC 1 -#define SET_MODULE_OWNER(some_struct) do { } while (0) -#define SET_NETDEV_DEV(dev, obj) do { } while (0) -#define register_netdev(dev) (0) -#define unregister_netdev(dev) do { } while (0) -#define netif_queue_stopped(dev) (0) -#define netif_wake_queue(dev) do { } while (0) -#define printk printf +#define SET_MODULE_OWNER(some_struct) do { } while (0) +#define SET_NETDEV_DEV(dev, obj) do { } while (0) +#define register_netdev(dev) (0) +#define unregister_netdev(dev) do { } while (0) +#define netif_queue_stopped(dev) (0) +#define netif_wake_queue(dev) do { } while (0) +#define printk printf -#define DBG_ERR(fmt, args...) printf("\n\r[%s] " fmt, __FUNCTION__, ## args) +#define DBG_ERR(fmt, args...) printf("\n\r[%s] " fmt, __FUNCTION__, ## args) #if WLAN_INTF_DBG -#define DBG_TRACE(fmt, args...) printf("\n\r[%s] " fmt, __FUNCTION__, ## args) -#define DBG_INFO(fmt, args...) printf("\n\r[%s] " fmt, __FUNCTION__, ## args) +#define DBG_TRACE(fmt, args...) printf("\n\r[%s] " fmt, __FUNCTION__, ## args) +#define DBG_INFO(fmt, args...) printf("\n\r[%s] " fmt, __FUNCTION__, ## args) #else #define DBG_TRACE(fmt, args...) #define DBG_INFO(fmt, args...) #endif -#define HALT() do { cli(); for(;;);} while(0) -#define ASSERT(x) do { \ - if((x) == 0) \ - printf("\n\rAssert(" #x ") failed on line %d in file %s", __LINE__, __FILE__); \ - HALT(); \ - } while(0) +#define HALT() do { cli(); for(;;);} while(0) +#undef ASSERT +#define ASSERT(x) do { \ + if((x) == 0){\ + printf("\n\rAssert(" #x ") failed on line %d in file %s", __LINE__, __FILE__); \ + HALT();}\ + } while(0) #undef DBG_ASSERT -#define DBG_ASSERT(x, msg) do { \ - if((x) == 0) \ - printf("\n\r%s, Assert(" #x ") failed on line %d in file %s", msg, __LINE__, __FILE__); \ - } while(0) +#define DBG_ASSERT(x, msg) do { \ + if((x) == 0) \ + printf("\n\r%s, Assert(" #x ") failed on line %d in file %s", msg, __LINE__, __FILE__); \ + } while(0) //----- ------------------------------------------------------------------ // Atomic Operation //----- ------------------------------------------------------------------ -#if !defined(CONFIG_PLATFORM_8195A) && !defined(CONFIG_PLATFORM_8711B) // for 8195A, it is defined in ..system../basic_types.h -typedef struct { volatile int counter; } atomic_t; -#endif - /* * atomic_read - read atomic variable @@ -255,6 +240,7 @@ typedef struct { volatile int counter; } atomic_t; * Atomically reads the value of @v. Note that the guaranteed * useful range of an atomic_t is only 24 bits. */ +#undef atomic_read #define atomic_read(v) ((v)->counter) /* @@ -265,6 +251,7 @@ typedef struct { volatile int counter; } atomic_t; * Atomically sets the value of @v to @i. Note that the guaranteed * useful range of an atomic_t is only 24 bits. */ +#undef atomic_set #define atomic_set(v,i) ((v)->counter = (i)) /* @@ -292,6 +279,10 @@ extern u32 rtw_is_list_empty(_list *phead); extern void rtw_list_insert_head(_list *plist, _list *phead); extern void rtw_list_insert_tail(_list *plist, _list *phead); extern void rtw_list_delete(_list *plist); -#define vPortExitCritical save_and_cli -#endif /* _RTX_SERVICE_H_ */ + +#if (defined CONFIG_PLATFORM_8711B) || (defined CONFIG_PLATFORM_8721D) +extern u32 random_seed; +#endif + +#endif /* _CMSIS_RTOS_SERVICE_H_ */ diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/device_lock.c b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/device_lock.c index b76516d71b..6cbef3cc3d 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/device_lock.c +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/device_lock.c @@ -53,7 +53,7 @@ void device_mutex_lock(RT_DEV_LOCK_E device) { device_mutex_init(device); while(rtw_mutex_get_timeout(&device_mutex[device], 10000)<0) - printf("device lock timeout: %d\n", device); + printf("device lock timeout: %d\n", (int)device); } //====================================================== diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/include/device_lock.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/include/device_lock.h index b82568fdd7..d6a8c71b97 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/include/device_lock.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/include/device_lock.h @@ -15,7 +15,9 @@ enum _RT_DEV_LOCK_E RT_DEV_LOCK_EFUSE = 0, RT_DEV_LOCK_FLASH = 1, RT_DEV_LOCK_CRYPTO = 2, - RT_DEV_LOCK_MAX = 3 + RT_DEV_LOCK_PTA = 3, + RT_DEV_LOCK_WLAN = 4, + RT_DEV_LOCK_MAX = 5 }; typedef uint32_t RT_DEV_LOCK_E; diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/include/osdep_service.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/include/osdep_service.h index 1eaf214e85..0299c40031 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/include/osdep_service.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/include/osdep_service.h @@ -1,4 +1,4 @@ -/* mbed Microcontroller Library +/****************************************************************************** * Copyright (c) 2013-2016 Realtek Semiconductor Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,42 +12,44 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ - + ******************************************************************************/ + #ifndef __OSDEP_SERVICE_H_ #define __OSDEP_SERVICE_H_ -/* OS dep feature enable */ -#include +/** @addtogroup RTOS + * @{ + */ #ifdef __cplusplus extern "C" { #endif +/*************************** OS dep feature enable *******************************/ + +/****************************************************** + * Macros + ******************************************************/ #define CONFIG_LITTLE_ENDIAN -#if defined(CONFIG_PLATFORM_8195A) || defined(CONFIG_PLATFORM_8711B) -#define CONFIG_PLATFORM_AMEBA_X +#if defined(CONFIG_PLATFORM_8195A) || defined(CONFIG_PLATFORM_8711B) || defined(CONFIG_PLATFORM_8721D) || defined(CONFIG_PLATFORM_8195BHP) || defined(CONFIG_PLATFORM_8710C) +#define CONFIG_PLATFORM_AMEBA_X 1 #endif #if defined(CONFIG_PLATFORM_8195A) - #ifndef CONFIG_USE_TCM_HEAP #define CONFIG_USE_TCM_HEAP 1 /* USE TCM HEAP */ - #endif #define USE_MUTEX_FOR_SPINLOCK 1 #endif -#if defined(CONFIG_PLATFORM_AMEBA_X) +#if (CONFIG_PLATFORM_AMEBA_X == 1) #define CONFIG_MEM_MONITOR MEM_MONITOR_SIMPLE #else #define CONFIG_MEM_MONITOR MEM_MONITOR_LEAK #endif /* Define compilor specific symbol */ -// -// inline function -// +/*************************** inline functions *******************************/ #if defined ( __ICCARM__ ) #define __inline__ inline #define __inline inline @@ -71,9 +73,20 @@ extern "C" { #endif #include -#if defined(CONFIG_PLATFORM_8195A) || defined(CONFIG_PLATFORM_8711B) + +#if defined(CONFIG_PLATFORM_8710C) || defined(CONFIG_PLATFORM_8195BHP) +#include +#include +#if (CONFIG_CMSIS_FREERTOS_EN==1) +#define PLATFORM_FREERTOS 1 +#endif +#else +#if (CONFIG_PLATFORM_AMEBA_X == 1) #include "platform_autoconf.h" -#else //for 8189FM/8189FTV add by frankie_li 20160408 +#endif +#endif + +#if (CONFIG_PLATFORM_AMEBA_X == 0) #ifndef SUCCESS #define SUCCESS 0 #endif @@ -90,38 +103,64 @@ extern "C" { #define FALSE 0 #endif +#ifndef false + #define false 0 +#endif + #ifndef TRUE #define TRUE (!FALSE) #endif + +#ifndef true + #define true (!false) +#endif + + +#ifndef DBG_8195A +#define DBG_8195A +#endif #define _TRUE TRUE #define _FALSE FALSE #endif -#if defined( PLATFORM_FREERTOS) +#if defined(PLATFORM_FREERTOS) #include "freertos_service.h" -#elif defined( PLATFORM_ECOS) +#elif defined(PLATFORM_ECOS) #include "ecos/ecos_service.h" #elif defined(PLATFORM_CMSIS_RTOS) #include "cmsis_rtos_service.h" +#elif defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) +#include "customer_rtos_service.h" #endif #define RTW_MAX_DELAY 0xFFFFFFFF #define RTW_WAIT_FOREVER 0xFFFFFFFF -/* Definitions returned by xTaskGetSchedulerState(). */ +/****************************************************** + * Constants + ******************************************************/ +/** + * @brief Definitions returned by xTaskGetSchedulerState(). + */ + #define OS_SCHEDULER_NOT_STARTED 0 #define OS_SCHEDULER_RUNNING 1 #define OS_SCHEDULER_SUSPENDED 2 - +/****************************************************** + * Structures + ******************************************************/ struct timer_list { _timerHandle timer_hdl; unsigned long data; void (*function)(void *); }; +/****************************************************** + * Type Definitions + ******************************************************/ typedef thread_return (*thread_func_t)(thread_context context); typedef void (*TIMER_FUN)(void *context); typedef int (*event_handler_t)(char *buf, int buf_len, int flags, void *user_data); @@ -129,19 +168,18 @@ typedef int (*event_handler_t)(char *buf, int buf_len, int flags, void *user_dat #define CONFIG_THREAD_COMM_SEMA struct task_struct { const char *task_name; - _thread_hdl_ task; /* I: workqueue thread */ + _thread_hdl_ task; /* I: workqueue thread */ #ifdef CONFIG_THREAD_COMM_SIGNAL - const char *name; /* I: workqueue thread name */ - u32 queue_num; /* total signal num */ - u32 cur_queue_num; /* cur signal num should < queue_num */ + const char *name; /* I: workqueue thread name */ + u32 queue_num; /* total signal num */ + u32 cur_queue_num; /* cur signal num should < queue_num */ #elif defined(CONFIG_THREAD_COMM_SEMA) - _sema wakeup_sema; - _sema terminate_sema; -// _queue work_queue; //TODO + _sema wakeup_sema; /* for internal use only */ + _sema terminate_sema; /* for internal use only */ #endif - u32 blocked; - u32 callback_running; + u32 blocked; /* for internal use only */ + u32 callback_running; /* for internal use only */ }; typedef struct { @@ -165,6 +203,7 @@ struct worker_timer_entry { rtw_worker_thread_t *worker_thread; u32 timeout; }; + #ifdef CONFIG_THREAD_COMM_SIGNAL struct work_struct; typedef void (*work_func_t)(void *context); @@ -182,10 +221,10 @@ struct delayed_work { }; #endif + #ifdef CONFIG_MEM_MONITOR -//----- ------------------------------------------------------------------ -// Memory Monitor -//----- ------------------------------------------------------------------ + +/*************************** Memory Monitor *******************************/ #define MEM_MONITOR_SIMPLE 0x1 #define MEM_MONITOR_LEAK 0x2 @@ -194,19 +233,59 @@ struct delayed_work { #if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK struct mem_entry { struct list_head list; - int size; - void *ptr; + int size; + void *ptr; }; #endif +/** + * @brief This function initializes a memory table. + * @param[in] pmem_table: The pointer to the memory table. + * @param[in] used_num: The number of mem_entry kept in monitor which will be set to 0. + * @return None + */ void init_mem_monitor(_list *pmem_table, int *used_num); + +/** + * @brief This function deinitializes a memory table. + * @param[in] pmem_table: The pointer to the memory table. + * @param[in] used_num: The number of mem_entry kept in monitor. + * @return None + */ void deinit_mem_monitor(_list *pmem_table, int *used_num); + +/** + * @brief This function alloc mem_entry to the memory table. + * @param[in] pmem_table: The pointer to the memory table to be added. + * @param[in] ptr: The pointer to the position to be added. + * @param[in] size: The size of added memory. + * @param[in] used_num: The number of mem_entry kept in monitor which will add 1 after. + * @param[in] flag: MEM_MONITOR_FLAG_WPAS/MEM_MONITOR_FLAG_WIFI_DRV + * @return None + */ void add_mem_usage(_list *pmem_table, void *ptr, int size, int *used_num, int flag); + +/** + * @brief This function frees memory from the memory table. + * @param[in] pmem_table: The pointer to the memory table + * @param[in] ptr: The pointer to the position to be free. + * @param[in] used_num: The number of mem_entry kept in monitor. + * @param[in] flag: MEM_MONITOR_FLAG_WPAS/MEM_MONITOR_FLAG_WIFI_DRV + * @return None + */ void del_mem_usage(_list *pmem_table, void *ptr, int *used_num, int flag); + +/** + * @brief This function get the memory usage of a memory table. + * @param[in] pmem_table: The pointer to the memory table. + * @return The size of the memory used + */ int get_mem_usage(_list *pmem_table); +/*************************** End Memory Monitor *******************************/ #endif -/*********************************** OSDEP API *****************************************/ + +/*************************** Memory Management *******************************/ u8* _rtw_vmalloc(u32 sz); u8* _rtw_zvmalloc(u32 sz); void _rtw_vmfree(u8 *pbuf, u32 sz); @@ -214,11 +293,51 @@ u8* _rtw_zmalloc(u32 sz); u8* _rtw_malloc(u32 sz); void _rtw_mfree(u8 *pbuf, u32 sz); #ifdef CONFIG_MEM_MONITOR + +/** + * @brief This function allocates the virtually contiguous memory. + * @param[in] sz: The size of memory to be allocated. + * @return The pointer to the beginning of the memory + */ u8* rtw_vmalloc(u32 sz); + +/** + * @brief This function allocates the virtually contiguous memory + * and the values of the memory are setted to 0. + * @param[in] sz: The size of memory to be allocated. + * @return The pointer to the beginning of the memory + */ u8* rtw_zvmalloc(u32 sz); + +/** + * @brief This function frees the virtually contiguous memory. + * @param[in] pbuf: The pointer to the beginning of the memory to be free + * @param[in] sz: The size of memory allocated. + * @return None + */ void rtw_vmfree(u8 *pbuf, u32 sz); + +/** + * @brief This function allocates the memory + * and the values of the memory are setted to 0. + * @param[in] sz: The size of memory to be allocated. + * @return The pointer to the beginning of the memory + */ u8* rtw_zmalloc(u32 sz); + +/** + * @brief This function allocates the memory. + * @param[in] sz: The size of memory to be allocated. + * @return The pointer to the beginning of the memory + */ u8* rtw_malloc(u32 sz); + +/** + * @brief This function frees the virtually contiguous memory. + * @param[in] pbuf: The pointer to the beginning of the memory to be free + * @param[in] sz: The size of memory allocated. + * @return None + */ void rtw_mfree(u8 *pbuf, u32 sz); #else #define rtw_vmalloc _rtw_vmalloc @@ -229,100 +348,666 @@ void rtw_mfree(u8 *pbuf, u32 sz); #define rtw_mfree _rtw_mfree #endif #define rtw_free(buf) rtw_mfree((u8 *)buf, 0) + +/** + * @brief This function allocates a 2 dimensional array memory. + * @param[in] h: The height of the 2D array. + * @param[in] w: The width of the 2D array. + * @param[in] size: The size of the each charactor in array. + * @return the pointer to the beginning of the block + */ void* rtw_malloc2d(int h, int w, int size); + +/** + * @brief This function deallocates the block of memory previously allocated to make it available again. + * @param[in] pbuf: Pointer to a memory block previously allocated. + * @param[in] h: The height of the 2D array. + * @param[in] w: The width of the 2D array. + * @param[in] size: The size of the each charactor in array. + * @return None + */ void rtw_mfree2d(void *pbuf, int h, int w, int size); + +/** + * @brief This function copies the values of "sz" bytes from the location pointed to by "src" + * directly to the memory block pointed to by "des". + * @param[in] dst: Pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*. + * @param[in] src: Pointer to the source of data to be copied, type-casted to a pointer of type void*. + * @param[in] sz: Size of memory to copy. + * @return None + */ void rtw_memcpy(void* dst, void* src, u32 sz); + +/** + * @brief This function compares the first "sz" bytes of the block of memory pointed by "dst" + * to the first "sz" bytes pointed by "src". + * @param[in] dst: Pointer to block of memory to be compared. + * @param[in] src: pointer to block of memory to compare. + * @param[in] sz: Size of memory to compare. + * @return <0: The first byte that does not match in both memory blocks has a lower value in dst than in src. + * @return 0: The contents of both memory blocks are equal. + * @return <0: The first byte that does not match in both memory blocks has a greater value in dst than in src. + */ int rtw_memcmp(void *dst, void *src, u32 sz); + +/** + * @brief This function sets the first "sz" bytes of the block of memory pointed by "pbuf" to the specified "c". + * @param[in] pbuf: Pointer to the block of memory to fill. + * @param[in] c: Value to be set. + * @param[in] sz: Size of memory to be set to the value "c". + * @return None + */ void rtw_memset(void *pbuf, int c, u32 sz); +/*************************** End Memory Management *******************************/ +/*************************** List *******************************/ + +/** + * @brief This function initializes the head of the list. + * @param[in] list: Pointer to the list to be initialized. + * @return None + */ void rtw_init_listhead(_list *list); + +/** + * @brief This function tests whether a list is empty. + * @param[in] phead: Pointer to the list to test. + * @return _TRUE/_FALSE + */ u32 rtw_is_list_empty(_list *phead); + +/** + * @brief This function adds a new entry after "phead" for the list. + * @param[in] plist: Pointer to the list to be added. + * @param[in] phead: List head to add it after. + * @return None + */ void rtw_list_insert_head(_list *plist, _list *phead); + +/** + * @brief This function adds a new entry before "phead" for the list. + * @param[in] plist: Pointer to the list to be added. + * @param[in] phead: List head to add it before. + * @return None + */ void rtw_list_insert_tail(_list *plist, _list *phead); + +/** + * @brief This function deletes entry from list and reinitialize it. + * @param[in] plist: The element to delete from the list. + * @return None + * @note Caller must check if the list is empty before calling rtw_list_delete + */ void rtw_list_delete(_list *plist); +/*************************** End List *******************************/ + +/*************************** Semaphores *******************************/ +/** + * @brief This function initializes the unnamed semaphore referred to by "sema" to the value "init_val". + * @param[in] sema: Pointer to the semaphore handle to be initialized. + * @param[in] init_val: Initial value for semaphore. + * @return None + */ void rtw_init_sema(_sema *sema, int init_val); -void rtw_free_sema(_sema *sema); -void rtw_up_sema(_sema *sema); -void rtw_up_sema_from_isr(_sema *sema); -u32 rtw_down_sema(_sema *sema); -u32 rtw_down_timeout_sema(_sema *sema, u32 timeout); -void rtw_mutex_init(_mutex *pmutex); -void rtw_mutex_free(_mutex *pmutex); -void rtw_mutex_put(_mutex *pmutex); -void rtw_mutex_get(_mutex *pmutex); -int rtw_mutex_get_timeout(_mutex *pmutex, u32 timeout_ms); -void rtw_enter_critical(_lock *plock, _irqL *pirqL); -void rtw_exit_critical(_lock *plock, _irqL *pirqL); -void rtw_enter_critical_from_isr(_lock *plock, _irqL *pirqL); -void rtw_exit_critical_from_isr(_lock *plock, _irqL *pirqL); -void rtw_enter_critical_bh(_lock *plock, _irqL *pirqL); -void rtw_exit_critical_bh(_lock *plock, _irqL *pirqL); -int rtw_enter_critical_mutex(_mutex *pmutex, _irqL *pirqL); -void rtw_exit_critical_mutex(_mutex *pmutex, _irqL *pirqL); -void rtw_spinlock_init(_lock *plock); -void rtw_spinlock_free(_lock *plock); -void rtw_spinlock_init(_lock *plock); -void rtw_spinlock_free(_lock *plock); -void rtw_spin_lock(_lock *plock); -void rtw_spin_unlock(_lock *plock); -void rtw_spinlock_irqsave(_lock *plock, _irqL *irqL); -void rtw_spinunlock_irqsave(_lock *plock, _irqL *irqL); +/** + * @brief This function deletes the semaphore. + * @param[in] sema: The semaphore to be deleted. + * @return None + */ +void rtw_free_sema(_sema *sema); + +/** + * @brief This function releases the semaphore. + * This macro must not be used from an ISR. + * @param[in] sema: The semaphore to be released. + * @return None + */ +void rtw_up_sema(_sema *sema); + +/** + * @brief This function releases the semaphore. + * This macro can be used from an ISR. + * @param[in] sema: The semaphore to be released. + * @return None + */ +void rtw_up_sema_from_isr(_sema *sema); + +/** + * @brief This function acquires the semaphore. If no more tasks are allowed to acquire the semaphore, + * calling this function will put the task to sleep until the semaphore is up. + * @param[in] sema: The semaphore to be acquired. + * @return pdTRUE: The semaphore was obtained. + * @return pdFALSE: Obtain the semaphore failed. + */ +u32 rtw_down_sema(_sema *sema); + +/** + * @brief This function acquires the semaphore. If no more tasks are allowed to acquire the semaphore, + * calling this function will put the task to sleep until the semaphore is up. + * @param[in] sema: The semaphore to be acquired. + * @param[in] timeout: The time in ms to wait for the semaphore to become available. + * @return pdTRUE: The semaphore was obtained. + * @return pdFALSE: Timeout without the semaphore becoming available. + */ +u32 rtw_down_timeout_sema(_sema *sema, u32 timeout); +/*************************** End Semaphores *******************************/ + +/*************************** Mutexes *******************************/ +/** + * @brief This function implements a mutex semaphore by using the existing queue mechanism. + * @param[in] pmutex: Pointer to the created mutex semaphore. + * @return None + */ +void rtw_mutex_init(_mutex *pmutex); + +/** + * @brief This function deletes the mutex semaphore. + * @param[in] pmutex: Pointer to the mutex semaphore to be deleted. + * @return None + */ +void rtw_mutex_free(_mutex *pmutex); + +/** + * @brief This function releases a mutex semaphore. + * @param[in] pmutex: Pointer to the mutex semaphore to be released. + * @return None + */ +void rtw_mutex_put(_mutex *pmutex); + +/** + * @brief This function obtains a mutex semaphore. + * @param[in] pmutex: Pointer to the mutex semaphore being taken - obtained when + * the mutex semaphore was created. + * @return None + */ +void rtw_mutex_get(_mutex *pmutex); + +/** + * @brief This function obtains a mutex semaphore with a timeout setting. + * @param[in] pmutex: Pointer to the mutex semaphore being taken - obtained when + * the mutex semaphore was created. + * @param[in] timeout: The time in ms to wait for the semaphore to become available. + * @return 0: The semaphore was obtained. + * @return -1: Timeout without the semaphore becoming available. + */ +int rtw_mutex_get_timeout(_mutex *pmutex, u32 timeout_ms); +/*************************** End Mutexes *******************************/ + +/*************************** SchedulerControl *******************************/ +/** + * @brief This function marks the start of a critical code region. + * Preemptive context switches cannot occur when in a critical region. + * @param[in] plock: Pointer to the spin lock semaphore. + * @param[in] pirqL: Pointer to the IRQ. + * @return None + * @note: This may alter the stack (depending on the portable implementation) + * so must be used with care! + */ +void rtw_enter_critical(_lock *plock, _irqL *pirqL); + +/** + * @brief This function marks end of a critical code region. Preemptive context + * switches cannot occur when in a critical region. + * @param[in] plock: Pointer to the spin lock semaphore. + * @param[in] pirqL: Pointer to the IRQ. + * @return None + * @note: This may alter the stack (depending on the portable implementation) + * so must be used with care! + */ +void rtw_exit_critical(_lock *plock, _irqL *pirqL); + +/** + * @brief This function marks the start of a critical code region from isr. + * @param[in] plock: Pointer to the spin lock semaphore. + * @param[in] pirqL: Pointer to the IRQ. + * @return None + */ +void rtw_enter_critical_from_isr(_lock *plock, _irqL *pirqL); + +/** + * @brief This function marks the end of a critical code region from isr. + * @param[in] plock: Pointer to the spin lock semaphore. + * @param[in] pirqL: Pointer to the IRQ. + * @return None + */ +void rtw_exit_critical_from_isr(_lock *plock, _irqL *pirqL); + +/** + * @brief This function obtains a spin lock semaphore. + * @param[in] plock: Pointer to the spin lock semaphore being taken - obtained when + * the mutex semaphore was created. + * @param[in] pirqL: Pointer to the IRQ. + * @return None + */ +void rtw_enter_critical_bh(_lock *plock, _irqL *pirqL); + +/** + * @brief This function releases a spin lock semaphore. + * @param[in] plock: Pointer to the spin lock semaphore to be released. + * @param[in] pirqL: Pointer to the IRQ. + * @return None + */ +void rtw_exit_critical_bh(_lock *plock, _irqL *pirqL); + +/** + * @brief This function obtains a semaphore. + * @param[in] pmutex: The handle to the mutex semaphore to be obtained. + * @param[in] pirqL: Pointer to the IRQ. + * @return None + */ +int rtw_enter_critical_mutex(_mutex *pmutex, _irqL *pirqL); + +/** + * @brief This function releases a semaphore. + * @param[in] pmutex: The handle to the mutex semaphore to be released. + * @param[in] pirqL: Pointer to the IRQ. + * @return None + */ +void rtw_exit_critical_mutex(_mutex *pmutex, _irqL *pirqL); + +/** + * @brief This function will lock cpu. Can be used when xip active and want to do some flash operation. + * @return None + */ +void rtw_cpu_lock(void); + + /** + * @brief This function unlock cpu. + * @return None + */ +void rtw_cpu_unlock(void); + +/*************************** End SchedulerControl *******************************/ + +/*************************** Semaphores *******************************/ + +/** + * @brief This function implements a spin lock semaphore by using the existing queue mechanism. + * @param[in] plock: Pointer to the created spin lock semaphore. + * @return None + */ +void rtw_spinlock_init(_lock *plock); + +/** + * @brief This function deletes the spin lock semaphore. + * @param[in] pmutex: Pointer to the spin lock semaphore to be deleted. + * @return None + */ +void rtw_spinlock_free(_lock *plock); + +/** + * @brief This function obtains a spin lock semaphore. + * @param[in] plock: Pointer to the spin lock semaphore being taken - obtained when + * the mutex semaphore was created. + * @return None + */ +void rtw_spin_lock(_lock *plock); + +/** + * @brief This function releases a spin lock semaphore. + * @param[in] plock: Pointer to the spin lock semaphore to be released. + * @return None + */ +void rtw_spin_unlock(_lock *plock); + +/** + * @brief This function marks the start of a critical code region and + * obtains a spin lock semaphore. + * @param[in] plock: Pointer to the spin lock semaphore being taken - obtained when + * the mutex semaphore was created. + * @param[in] irqL: Pointer to the IRQ. + * @return None + */ +void rtw_spinlock_irqsave(_lock *plock, _irqL *irqL); + +/** + * @brief This function releases a spin lock semaphore and + marks the end of a critical code region. + * @param[in] plock: Pointer to the spin lock semaphore to be released. + * @param[in] irqL: Pointer to the IRQ. + * @return None + */ +void rtw_spinunlock_irqsave(_lock *plock, _irqL *irqL); +/*************************** End Semaphores *******************************/ + +/*************************** Queues *******************************/ + +/** + * @brief This function creates a new queue instance. + * @param[in] queue: The handle to the newly created queue. + * @param[in] name: The name of the queue + * @param[in] message_size: The number of bytes each message in the queue will require. + * @param[in] number_of_messages: The maximum number of messages that kthe queue can contain. + * @return 0: Creating queue success + * @return -1: Creating queue fail + */ int rtw_init_xqueue( _xqueue* queue, const char* name, u32 message_size, u32 number_of_messages ); + +/** + * @brief This function posts a message to the back of a queue. + * The message is queued by copy, not by reference. + * @param[in] queue: The handle to the queue on which the message is to be posted. + * @param[in] message: The pointer to the message that is to be placed on the queue. + * @param[in] timeout_ms: The maximum amout of time the task should block waiting for + the space to become available on the queue, should it already be full. + The time is defined in ms. + * @return 0: The message was successfully posted. + * @return -1: The message was not posted. + */ int rtw_push_to_xqueue( _xqueue* queue, void* message, u32 timeout_ms ); + +/** + * @brief This function receives a message from a queue. + * The message is recieved by copy so a buffer adequate size must be provided. + * @param[in] queue: The handle to the queue from which the message is to be received. + * @param[in] message: The pointer to the buffer into which the received message will be copied. + * @param[in] timeout_ms: The maximum amout of time the task should block waiting for a message to + * receive should the queue be empty at the time of the call. + The time is defined in ms. + * @return 0: A message was successfully received from the queue. + * @return -1: No message was received from the queue. + */ int rtw_pop_from_xqueue( _xqueue* queue, void* message, u32 timeout_ms ); + +/** + * @brief Delete a queue - freeing all the memory allocated for storing of messages placed on the queue. + * @param[in] queue: The handle to the queue to be deleted. + * @return 0: The queue was successfully deleted. + * @return -1: The queue was not empty so cannot be deleted. + */ int rtw_deinit_xqueue( _xqueue* queue ); +/** + * @brief This function creates a new queue instance. + * @param[in] pqueue: The handle to the newly created queue. + * @return None + */ void rtw_init_queue(_queue *pqueue); void rtw_deinit_queue(_queue *pqueue); u32 rtw_is_queue_empty(_queue *pqueue); + +/** + * @brief This function tests whether the queue is empty. + * @param[in] pqueue: The handle to the queue to be tested. + * @return None + */ u32 rtw_queue_empty(_queue *pqueue); + +/** + * @brief This function tests whether the "pelement" is at the "queue". + * @param[in] queue: The pointer to the queue that to be tested. + * @param[in] pelement: The element that to be tested. + * @return _TRUE/_FALSE + */ u32 rtw_end_of_queue_search(_list *queue, _list *pelement); _list* rtw_get_queue_head(_queue *queue); +/*************************** End Queues *******************************/ +/*************************** Time Management *******************************/ + +/** + * @brief Get the count of ticks since the vTaskStartScheduler was called. + * @return The count of ticks since the vTaskStartScheduler was called. + */ u32 rtw_get_current_time(void); -u32 rtw_systime_to_ms(u32 systime); -u32 rtw_systime_to_sec(u32 systime); -u32 rtw_ms_to_systime(u32 ms); -u32 rtw_sec_to_systime(u32 sec); -s32 rtw_get_passing_time_ms(u32 start); -s32 rtw_get_time_interval_ms(u32 start, u32 end); +/** + * @brief Convert system time to milliseconds. + * @param[in] systime: The system time to be converted. + * @return : The milliseconds that converted by the system time. + */ +u32 rtw_systime_to_ms(u32 systime); + +/** + * @brief Convert system time to seconds. + * @param[in] systime: The system time to be converted. + * @return : The seconds that converted by the system time. + */ +u32 rtw_systime_to_sec(u32 systime); + +/** + * @brief Convert milliseconds to system time. + * @param[in] systime: The milliseconds to be converted. + * @return : The system time that converted by the milliseconds. + */ +u32 rtw_ms_to_systime(u32 ms); + +/** + * @brief Convert seconds to system time. + * @param[in] systime: The seconds to be converted. + * @return : The system time that converted by the seconds. + */ +u32 rtw_sec_to_systime(u32 sec); + +/** + * @brief Get the passing time from the "start" in milliseconds. + * @param[in] start: The start time which is in system time format. + * @return : The passing time from "start" in milliseconds. + */ +s32 rtw_get_passing_time_ms(u32 start); + +/** + * @brief Get the interval time from the "start" to "end" in milliseconds. + * @param[in] start: The start time which is in system time format. + * @param[in] end: The end time which is in system time format. + * @return : The interval time from "start" to "end" in milliseconds. + */ +s32 rtw_get_time_interval_ms(u32 start, u32 end); +/*************************** End Time Management *******************************/ + +/** + * @brief This function suspends execution of the calling thread for "ms" milliseconds. + * @param[in] ms: The time that the function sleep in milliseconds + * @return None +*/ void rtw_msleep_os(int ms); + +/** + * @brief This function suspends execution of the calling thread for "us" microseconds. + * @param[in] ms: The time that the function sleep in microseconds + * @return None +*/ void rtw_usleep_os(int us); + +/** + * @brief This function converts the initial portion of the string to integer. + * @param[in] s: The pointer to the string to be converted. + * @return The converted value. +*/ u32 rtw_atoi(u8* s); + +/** + * @brief This function delays a task for the giving time in milliseconds. + * @param[in] ms: The amount of time, in milliseconds, that the calling task should block. + * @return None +*/ void rtw_mdelay_os(int ms); + +/** + * @brief This function delays a task for the giving time in microseconds. + * @param[in] ms: The amount of time, in microseconds, that the calling task should block. + * @return None +*/ void rtw_udelay_os(int us); + +/** + * @brief This function for forcing a context switch. + * @return None +*/ void rtw_yield_os(void); -//Atomic integer operations +/*************************** ATOMIC Integer *******************************/ + +/** + * @brief This function atomically sets the value of the variable. + * @param[in] v: Pointer of type atomic_t that to be set value. + * @param[in] i: Required value. + * @return None + * @note The guaranteed useful range of an atomic_t is only 24 bits. +*/ void ATOMIC_SET(ATOMIC_T *v, int i); + +/** + * @brief This function atomically reads the value of the variable. + * @param[in] v: Pointer of type atomic_t that to be read. + * @return The value of the variable. + * @note The guaranteed useful range of an atomic_t is only 24 bits. +*/ int ATOMIC_READ(ATOMIC_T *v); + +/** + * @brief This function adds "i" to the contained "v". + * @param[in] v: Pointer of type atomic_t. + * @param[in] i: value to add. + * @return None +*/ void ATOMIC_ADD(ATOMIC_T *v, int i); + +/** + * @brief This function subtracts "i" from th econtained "v". + * @param[in] v: Pointer of type atomic_t. + * @param[in] i: value to subtract. + * @return None +*/ void ATOMIC_SUB(ATOMIC_T *v, int i); + +/** + * @brief This function adds 1 to the contained "v". + * @param[in] v: Pointer of type atomic_t. + * @return None +*/ void ATOMIC_INC(ATOMIC_T *v); + +/** + * @brief This function subtracts 1 from th econtained "v". + * @param[in] v: Pointer of type atomic_t. + * @return None +*/ void ATOMIC_DEC(ATOMIC_T *v); + +/** + * @brief This function adds "i" to the contained "v" and returns the result. + * @param[in] v: Pointer of type atomic_t. + * @param[in] i: value to add. + * @return None +*/ int ATOMIC_ADD_RETURN(ATOMIC_T *v, int i); + +/** + * @brief This function subtracts "i" from th econtained "v" and returns the result. + * @param[in] v: Pointer of type atomic_t. + * @param[in] i: value to subtract. + * @return None +*/ int ATOMIC_SUB_RETURN(ATOMIC_T *v, int i); + +/** + * @brief This function adds 1 to the contained "v" and returns the result. + * @param[in] v: Pointer of type atomic_t. + * @return None +*/ int ATOMIC_INC_RETURN(ATOMIC_T *v); + +/** + * @brief This function subtracts 1 from th econtained "v" and returns the result. + * @param[in] v: Pointer of type atomic_t. + * @return None +*/ int ATOMIC_DEC_RETURN(ATOMIC_T *v); + +/** + * @brief This function subtracts 1 from th econtained "v" and test if the result equals 0. + * @param[in] v: Pointer of type atomic_t. + * @return 0: The result after subtracting 1 is 0 + * @return -1: The result after subtracting 1 is not 0 +*/ int ATOMIC_DEC_AND_TEST(ATOMIC_T *v); +/*************************** End ATOMIC *******************************/ u64 rtw_modular64(u64 x, u64 y); + +/** + * @brief This function generates random bytes. + * @param[in] dst: The pointer to the buffer to store the random bytes. + * @param[in] size: The size of the random bytes. + * @return 0 +*/ int rtw_get_random_bytes(void* dst, u32 size); + +/** + * @brief This function gets the available heap size. + * @return The value of the available heap size. +*/ u32 rtw_getFreeHeapSize(void); + void flush_signals_thread(void); +/** + * @brief This function indicates that the WLAN needs to stay on which means cannot go into power saving mode. + * @return None + * @note Defining configUSE_WAKELOCK_PMU 1 in "FreeRTOSConfig.h" needs to be done before compiling, + * or this API won't be effective. + */ void rtw_acquire_wakelock(void); + +/** + * @brief This function indicates that the WLAN does not need to stay on which means can go into power saving mode. + * @return None + * @note Defining configUSE_WAKELOCK_PMU 1 in "FreeRTOSConfig.h" needs to be done before compiling, + * or this API won't be effective. + */ void rtw_release_wakelock(void); void rtw_wakelock_timeout(u32 timeout); /*********************************** Thread related *****************************************/ + +/** + * @brief This function creates a new task and adds it to the list of tasks that are ready to run. + * @param[in] task: The task stucture which will store the task related infomation. + * @param[in] name: A descriptive name for the task. + * @param[in] stack_size: The size of the task stack specified as the variables the stack can hold. + * @param[in] priority: The priority at which the task should run. + * @param[in] func: The task entry function. + * @param[in] thctx: The pointer that will be used as the parameter for the task being created. + * @return pdPASS: The task was successfully created and added to a ready list. + * @return other error code defined in the file errors.h. + * @note For the task name, please do not use "rtw_little_wifi_mcu_thread", "rtw_check_in_req_state_thread", + "rtw_TDMA_change_state_thread", "xmit_thread", "recv_thread", "rtw_recv_tasklet", "rtw_xmit_tasklet", + "rtw_interrupt_thread", "cmd_thread", "usb_init", "MSC_BULK_CMD" and "MSC_BULK_DATA". + */ int rtw_create_task(struct task_struct *task, const char *name, u32 stack_size, u32 priority, thread_func_t func, void *thctx); + +/** + * @brief This function deletes a task. + * @param[in] task: The task stucture which will be deleted. + * @return None + */ void rtw_delete_task(struct task_struct * task); + +/** + * @brief This function wake up a task. + * @param[in] task: The task stucture which will be waked up. + * @return None + */ void rtw_wakeup_task(struct task_struct *task); + +/** + * @brief This function creates a new worker thread. + * @param[in] worker_thread: The pointer to the worker thread stucture. + * @param[in] priority: The priority of the thread. + * @param[in] stack_size: The size of the thread stack specified as the variables the stack can hold. + * @param[in] event_queue_size: The queue size of events. + * @return SUCCESS/FAIL. + */ int rtw_create_worker_thread( rtw_worker_thread_t* worker_thread, u8 priority, u32 stack_size, u32 event_queue_size ); + +/** + * @brief This function deletes a worker thread. + * @param[in] worker_thread: The pointer to the worker thread stucture to be deleted. + * @return SUCCESS/FAIL. + */ int rtw_delete_worker_thread( rtw_worker_thread_t* worker_thread ); #if 0 //TODO @@ -332,32 +1017,136 @@ int rtw_queue_delayed_work(struct workqueue_struct *wq, struct delayed_work *dw BOOLEAN rtw_cancel_delayed_work(struct delayed_work *dwork); #endif +/** + * @brief This function prints the name of the thread in DBG_INFO. + * @param[in] name: The name of the thread. + * @return None + */ void rtw_thread_enter(char *name); + +/** + * @brief This function exits the calling thread. + * @return None + */ void rtw_thread_exit(void); + +/** + * @brief This function gets the scheduler state of the calling thread. + * @return OS_SCHEDULER_NOT_STARTED + * @return OS_SCHEDULER_RUNNING + * @return OS_SCHEDULER_SUSPENDED + */ u8 rtw_get_scheduler_state(void); +/*************************** End Threads *******************************/ #ifdef PLATFORM_LINUX #define rtw_warn_on(condition) WARN_ON(condition) #else #define rtw_warn_on(condition) do {} while (0) #endif -/*********************************** Timer related *****************************************/ +/*************************** Timers *******************************/ + +/** + * @brief This function creates a new software timer instance. + * @param[in] pcTimerName: A text name that is assigned to the timer. + * @param[in] xTimerPeriodInTicks: The timer period which is defined in tick periods. + * @param[in] uxAutoReload: If uxAutoReload is set to pdTRUE then the timer will + * expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. If + * uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and + * enter the dormant state after it expires. + * @param[in] pvTimerID: An identifier that is assigned to the timer being created. + * @param[in] pxCallbackFunction: The function to call when the timer expires. + * @return If the timer is successfully create then a handle to the newly + * created timer is returned. If the timer cannot be created, then 0 is returned. + */ _timerHandle rtw_timerCreate( const signed char *pcTimerName, osdepTickType xTimerPeriodInTicks, u32 uxAutoReload, void * pvTimerID, TIMER_FUN pxCallbackFunction ); -u32 rtw_timerDelete( _timerHandle xTimer, - osdepTickType xBlockTime ); + +/** + * @brief This function deletes a timer that was previously created using rtw_timerCreate. + * @param[in] xTimer: The handle of the timer being deleted. + * @param[in] xBlockTime: Specifies th etime, in ticks, that the calling task should be held in the Blocked + * State to wait for the delete command to be successfully sent to the timer command queue, + * should the queue already be full when rtw_timerDelete was called. + * @return pdFAIL will be returned if the delete command could not be sent to + * the timer command queue even after xTicksToWait ticks had passed. pdPASS will + * be returned if the command was successfully sent to the timer command queue. + * When the command is actually processed will depend on the priority of the + * timer service/daemon task relative to other tasks in the system. + */ +u32 rtw_timerDelete( _timerHandle xTimer, osdepTickType xBlockTime ); + +/** + * @brief This function queries a timer to see if it is active or dormant. + * @param[in] xTimer: The timer being queried. + * @return pdFALSE will be returned if the timer is dormant. A value other than + * pdFALSE will be returned if the timer is active. + * @note A timer will be dormant if: + * 1) It has been created but not started, or + * 2) It is an expired one-shot timer that has not been restarted. + */ u32 rtw_timerIsTimerActive( _timerHandle xTimer ); -u32 rtw_timerStop( _timerHandle xTimer, - osdepTickType xBlockTime ); + +/** + * @brief This function stops a timer that was previously started. + * @param[in] xTimer: The handle of the timer being stopped. + * @param[in] xBlockTime: Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the stop command to be successfully + * sent to the timer command queue, should the queue already be full when + * rtw_timerStop() was called. + * @return pdFAIL will be returned if the stop command could not be sent to + * the timer command queue even after xTicksToWait ticks had passed. pdPASS will + * be returned if the command was successfully sent to the timer command queue. + * When the command is actually processed will depend on the priority of the + * timer service/daemon task relative to other tasks in the system. + */ +u32 rtw_timerStop( _timerHandle xTimer, osdepTickType xBlockTime ); + +/** + * @brief This function changes the period of a timer that was previously created. + * @param[in] xTimer: The handle of the timer that is having its period changed. + * @param[in] xNewPeriod: The new period for xTimer. + * @param[in] xBlockTime: Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the change period command to be + * successfully sent to the timer command queue, should the queue already be + * full when rtw_timerChangePeriod() was called. + * @return pdFAIL will be returned if the change period command could not be + * sent to the timer command queue even after xTicksToWait ticks had passed. + * pdPASS will be returned if the command was successfully sent to the timer + * command queue. When the command is actually processed will depend on the + * priority of the timer service/daemon task relative to other tasks in the + * system. + */ u32 rtw_timerChangePeriod( _timerHandle xTimer, osdepTickType xNewPeriod, osdepTickType xBlockTime ); -/*********************************** OSDEP API end *****************************************/ +void *rtw_timerGetID( _timerHandle xTimer ); + +u32 rtw_timerStart( _timerHandle xTimer, osdepTickType xBlockTime ); + +u32 rtw_timerStartFromISR( _timerHandle xTimer, + osdepBASE_TYPE *pxHigherPriorityTaskWoken ); + +u32 rtw_timerStopFromISR( _timerHandle xTimer, + osdepBASE_TYPE *pxHigherPriorityTaskWoken ); + +u32 rtw_timerResetFromISR( _timerHandle xTimer, + osdepBASE_TYPE *pxHigherPriorityTaskWoken ); + +u32 rtw_timerChangePeriodFromISR( _timerHandle xTimer, + osdepTickType xNewPeriod, + osdepBASE_TYPE *pxHigherPriorityTaskWoken ); + +u32 rtw_timerReset( _timerHandle xTimer, + osdepTickType xBlockTime ); + + +/*************************** End Timers *******************************/ #define LIST_CONTAINOR(ptr, type, member) \ ((type *)((char *)(ptr)-(SIZE_T)((char *)&((type *)ptr)->member - (char *)ptr))) @@ -424,6 +1213,8 @@ __inline static u32 bitshift(u32 bitmask) return i; } +#define rtw_min(a, b) ((a > b) ? b : a) + /* Macros for handling unaligned memory accesses */ #define RTW_GET_BE16(a) ((u16) (((a)[0] << 8) | (a)[1])) @@ -518,6 +1309,8 @@ struct osdep_service_ops { void (*rtw_exit_critical_bh)(_lock *plock, _irqL *pirqL); int (*rtw_enter_critical_mutex)(_mutex *pmutex, _irqL *pirqL); void (*rtw_exit_critical_mutex)(_mutex *pmutex, _irqL *pirqL); + void (*rtw_cpu_lock)(void); + void (*rtw_cpu_unlock)(void); void (*rtw_spinlock_init)(_lock *plock); void (*rtw_spinlock_free)(_lock *plock); void (*rtw_spin_lock)(_lock *plock); @@ -576,16 +1369,36 @@ struct osdep_service_ops { u32 (*rtw_timerChangePeriod)( _timerHandle xTimer, osdepTickType xNewPeriod, osdepTickType xBlockTime ); + void* (*rtw_timerGetID)( _timerHandle xTimer ); + u32 (*rtw_timerStart)( _timerHandle xTimer, + osdepTickType xBlockTime ); + u32 (*rtw_timerStartFromISR)( _timerHandle xTimer, + osdepBASE_TYPE *pxHigherPriorityTaskWoken ); + + u32 (*rtw_timerStopFromISR)( _timerHandle xTimer, + osdepBASE_TYPE *pxHigherPriorityTaskWoken ); + + u32 (*rtw_timerResetFromISR)( _timerHandle xTimer, + osdepBASE_TYPE *pxHigherPriorityTaskWoken ); + + u32 (*rtw_timerChangePeriodFromISR)( _timerHandle xTimer, + osdepTickType xNewPeriod, + osdepBASE_TYPE *pxHigherPriorityTaskWoken ); + + u32 (*rtw_timerReset)( _timerHandle xTimer, + osdepTickType xBlockTime ); void (*rtw_acquire_wakelock)(void); void (*rtw_release_wakelock)(void); void (*rtw_wakelock_timeout)(u32 timeoutMs); u8 (*rtw_get_scheduler_state)(void); }; -/*********************************** OSDEP API end *****************************************/ #ifdef __cplusplus } #endif +/*\@}*/ + #endif //#ifndef __OSDEP_SERVICE_H_ + diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/osdep_service.c b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/osdep_service.c index 4b738e54d3..37bfc9821a 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/osdep_service.c +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/osdep_service.c @@ -5,6 +5,10 @@ ******************************************************************************/ #include +#if CONFIG_USE_TCM_HEAP +#include "tcm_heap.h" +#endif + #define OSDEP_DBG(x, ...) do {} while(0) extern struct osdep_service_ops osdep_service; @@ -53,7 +57,7 @@ int RTW_STATUS_CODE(int error_code) u32 rtw_atoi(u8* s) { int num=0,flag=0; - size_t i; + int i; for(i=0;i<=strlen((char *)s);i++) { @@ -70,8 +74,10 @@ u32 rtw_atoi(u8* s) return(num); } +#if CONFIG_USE_TCM_HEAP void *tcm_heap_malloc(int size); void *tcm_heap_calloc(int size); +#endif u8* _rtw_vmalloc(u32 sz) { u8 *pbuf = NULL; @@ -202,11 +208,10 @@ void add_mem_usage(_list *pmem_table, void *ptr, int size, int *used_num, int fl return; } else{ - if(flag == MEM_MONITOR_FLAG_WPAS) { + if(flag == MEM_MONITOR_FLAG_WPAS) DBG_INFO("Alloc memory at %p with size of %d", ptr, size); - } else { + else DBG_INFO("Alloc memory at %p with size of %d", ptr, size); - } } #if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK mem_entry = (struct mem_entry *) _rtw_malloc(sizeof(struct mem_entry)); @@ -608,6 +613,22 @@ void rtw_exit_critical_mutex(_mutex *pmutex, _irqL *pirqL) OSDEP_DBG("Not implement osdep service: rtw_exit_critical_mutex"); } +void rtw_cpu_lock(void) +{ + if(osdep_service.rtw_cpu_lock) + osdep_service.rtw_cpu_lock(); + else + OSDEP_DBG("Not implement osdep service: rtw_cpu_lock"); +} + +void rtw_cpu_unlock(void) +{ + if(osdep_service.rtw_cpu_unlock) + osdep_service.rtw_cpu_unlock(); + else + OSDEP_DBG("Not implement osdep service: rtw_cpu_unlock"); +} + void rtw_init_queue(_queue *pqueue) { rtw_init_listhead(&(pqueue->queue)); @@ -1159,6 +1180,83 @@ u32 rtw_timerChangePeriod( _timerHandle xTimer, return 0; } +void *rtw_timerGetID( _timerHandle xTimer ) +{ + if(osdep_service.rtw_timerGetID) + return osdep_service.rtw_timerGetID(xTimer); + else + OSDEP_DBG("Not implement osdep service: rtw_timerGetID"); + + return NULL; +} + +u32 rtw_timerStart( _timerHandle xTimer, osdepTickType xBlockTime ) +{ + if(osdep_service.rtw_timerStart) + return osdep_service.rtw_timerStart(xTimer, xBlockTime); + else + OSDEP_DBG("Not implement osdep service: rtw_timerStart"); + + return 0; +} + +u32 rtw_timerStartFromISR( _timerHandle xTimer, + osdepBASE_TYPE *pxHigherPriorityTaskWoken ) +{ + if(osdep_service.rtw_timerStartFromISR) + return osdep_service.rtw_timerStartFromISR(xTimer, pxHigherPriorityTaskWoken); + else + OSDEP_DBG("Not implement osdep service: rtw_timerStartFromISR"); + + return 0; +} + +u32 rtw_timerStopFromISR( _timerHandle xTimer, + osdepBASE_TYPE *pxHigherPriorityTaskWoken ) +{ + if(osdep_service.rtw_timerStopFromISR) + return osdep_service.rtw_timerStopFromISR(xTimer, pxHigherPriorityTaskWoken); + else + OSDEP_DBG("Not implement osdep service: rtw_timerStopFromISR"); + + return 0; +} + +u32 rtw_timerResetFromISR( _timerHandle xTimer, + osdepBASE_TYPE *pxHigherPriorityTaskWoken ) +{ + if(osdep_service.rtw_timerResetFromISR) + return osdep_service.rtw_timerResetFromISR(xTimer, pxHigherPriorityTaskWoken); + else + OSDEP_DBG("Not implement osdep service: rtw_timerResetFromISR"); + + return 0; +} + +u32 rtw_timerChangePeriodFromISR( _timerHandle xTimer, + osdepTickType xNewPeriod, + osdepBASE_TYPE *pxHigherPriorityTaskWoken ) +{ + if(osdep_service.rtw_timerChangePeriodFromISR) + return osdep_service.rtw_timerChangePeriodFromISR(xTimer, xNewPeriod, pxHigherPriorityTaskWoken); + else + OSDEP_DBG("Not implement osdep service: rtw_timerChangePeriodFromISR"); + + return 0; +} + +u32 rtw_timerReset( _timerHandle xTimer, + osdepTickType xBlockTime ) +{ + if(osdep_service.rtw_timerReset) + return osdep_service.rtw_timerReset(xTimer, xBlockTime); + else + OSDEP_DBG("Not implement osdep service: rtw_timerReset"); + + return 0; +} + + #if 0 //TODO void rtw_init_delayed_work(struct delayed_work *dwork, work_func_t func, const char *name) { diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/tcm_heap.c b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/tcm_heap.c index 40c1df764e..203a83039b 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/tcm_heap.c +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/os/os_dep/tcm_heap.c @@ -13,7 +13,7 @@ #define ROUND_UP2(x, pad) (((x) + ((pad) - 1)) & ~((pad) - 1)) -#define TCM_HEAP_SIZE (40*1024) +#define TCM_HEAP_SIZE (40*1024) static struct Heap g_tcm_heap; @@ -27,9 +27,9 @@ HEAP_DEFINE_BUF(tcm_heap, TCM_HEAP_SIZE); static int g_heap_inited=0; static _lock tcm_lock; -#ifdef PLATFORM_FREERTOS +#if defined(PLATFORM_FREERTOS) extern void vPortSetExtFree( void (*free)( void *p ), uint32_t upper, uint32_t lower ); -#else +#elif defined(PLATFORM_CMSIS_RTOS) extern void rtw_set_mfree_ext( void (*free)( void *p ), uint32_t upper, uint32_t lower ); #endif void tcm_heap_init(void) @@ -52,7 +52,7 @@ void tcm_heap_init(void) #if defined(PLATFORM_FREERTOS) // let RTOS know how to free memory if using as task stack vPortSetExtFree(tcm_heap_free, 0x20000000, 0x1fff0000); -#elif defined (PLATFORM_CMSIS_RTOS) +#elif defined(PLATFORM_CMSIS_RTOS) rtw_set_mfree_ext(tcm_heap_free, 0x20000000, 0x1fff0000); #endif } @@ -67,7 +67,7 @@ void tcm_heap_dump(void) chunk; prev = chunk, chunk = chunk->next) { - printf(" prev %p, chunk %p, size %d \n\r", prev, chunk, chunk->size); + printf(" prev %x, chunk %x, size %d \n\r", prev, chunk, chunk->size); } printf("--------------\n\r"); } @@ -246,10 +246,20 @@ int tcm_heap_freeSpace(void) */ void *tcm_heap_malloc(int size) { +#if defined(PLATFORM_CMSIS_RTOS) + int64_t *mem; + // Make sure that block is 8-byte aligned + size = (size + 7U) & ~((uint32_t)7U); + size += sizeof(int64_t); + mem = (int64_t *)tcm_heap_allocmem(size); +#else int *mem; - size += sizeof(int); - if ((mem = (int*)tcm_heap_allocmem(size))){ + mem = (int*)tcm_heap_allocmem(size); +#endif + + + if (mem){ *mem++ = size; } @@ -262,8 +272,8 @@ void *tcm_heap_malloc(int size) void *tcm_heap_calloc(int size) { void *mem; - - if ((mem = tcm_heap_malloc(size))) + mem = tcm_heap_malloc(size); + if (mem) memset(mem, 0, size); return mem; @@ -284,7 +294,11 @@ void *tcm_heap_calloc(int size) */ void tcm_heap_free(void *mem) { +#if defined(PLATFORM_CMSIS_RTOS) + int64_t *_mem = (int64_t *)mem; +#else int *_mem = (int *)mem; +#endif if (_mem) { diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_adc.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_adc.h index 819454c28f..1a0127a896 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_adc.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_adc.h @@ -45,7 +45,8 @@ enum _ADC_DBG_LVL_ { typedef uint32_t ADC_DBG_LVL; typedef uint32_t * PADC_DBG_LVL; -#if defined (CONFIG_DEBUG_LOG) && defined (CONFIG_DEBUG_LOG_ADC_HAL) +#ifdef CONFIG_DEBUG_LOG +#ifdef CONFIG_DEBUG_LOG_ADC_HAL #define DBG_8195A_ADC(...) do{ \ _DbgDump("\r"ADC_PREFIX __VA_ARGS__);\ @@ -63,6 +64,7 @@ typedef uint32_t * PADC_DBG_LVL; #define DBG_8195A_ADC(...) #define DBG_8195A_ADC_LVL(...) #endif +#endif //================ ADC HAL Related Enumeration ================== @@ -213,14 +215,10 @@ typedef struct _SAL_ADC_USERCB_ADPT_ { // ADC user callback structure typedef struct _SAL_ADC_USER_CB_ { - PSAL_ADC_USERCB_ADPT pTXCB; //ADC Transmit Callback - PSAL_ADC_USERCB_ADPT pTXCCB; //ADC Transmit Complete Callback PSAL_ADC_USERCB_ADPT pRXCB; //ADC Receive Callback PSAL_ADC_USERCB_ADPT pRXCCB; //ADC Receive Complete Callback - PSAL_ADC_USERCB_ADPT pRDREQCB; //ADC Read Request Callback PSAL_ADC_USERCB_ADPT pERRCB; //ADC Error Callback - PSAL_ADC_USERCB_ADPT pDMATXCB; //ADC DMA Transmit Callback - PSAL_ADC_USERCB_ADPT pDMATXCCB; //ADC DMA Transmit Complete Callback + PSAL_ADC_USERCB_ADPT pIDMARXCCB; //ADC Error Callback PSAL_ADC_USERCB_ADPT pDMARXCB; //ADC DMA Receive Callback PSAL_ADC_USERCB_ADPT pDMARXCCB; //ADC DMA Receive Complete Callback }SAL_ADC_USER_CB, *PSAL_ADC_USER_CB; @@ -229,7 +227,7 @@ typedef struct _SAL_ADC_USER_CB_ { typedef struct _SAL_ADC_TRANSFER_BUF_ { u32 DataLen; //ADC Transmfer Length u32 *pDataBuf; //ADC Transfer Buffer Pointer - u32 RSVD; // + u16 *pUserDataBuf; // }SAL_ADC_TRANSFER_BUF,*PSAL_ADC_TRANSFER_BUF; typedef struct _SAL_ADC_DMA_USER_DEF_ { diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_common.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_common.h new file mode 100644 index 0000000000..113c1a185a --- /dev/null +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_common.h @@ -0,0 +1,17 @@ +/* + * Routines to access hardware + * + * Copyright (c) 2013 Realtek Semiconductor Corp. + * + * This module is a confidential and proprietary property of RealTek and + * possession or use of this module requires written permission of RealTek. + */ + +#ifndef _HAL_COMMON_H_ +#define _HAL_COMMON_H_ + +//================= Function Prototype START =================== +HAL_Status HalCommonInit(void); +//================= Function Prototype END =================== + +#endif diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_dac.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_dac.h index c06f1b7e65..97c6dd06af 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_dac.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_dac.h @@ -228,14 +228,9 @@ typedef struct _SAL_DAC_USERCB_ADPT_ { typedef struct _SAL_DAC_USER_CB_ { PSAL_DAC_USERCB_ADPT pTXCB; //DAC Transmit Callback PSAL_DAC_USERCB_ADPT pTXCCB; //DAC Transmit Complete Callback - PSAL_DAC_USERCB_ADPT pRXCB; //DAC Receive Callback - PSAL_DAC_USERCB_ADPT pRXCCB; //DAC Receive Complete Callback - PSAL_DAC_USERCB_ADPT pRDREQCB; //DAC Read Request Callback PSAL_DAC_USERCB_ADPT pERRCB; //DAC Error Callback PSAL_DAC_USERCB_ADPT pDMATXCB; //DAC DMA Transmit Callback PSAL_DAC_USERCB_ADPT pDMATXCCB; //DAC DMA Transmit Complete Callback - PSAL_DAC_USERCB_ADPT pDMARXCB; //DAC DMA Receive Callback - PSAL_DAC_USERCB_ADPT pDMARXCCB; //DAC DMA Receive Complete Callback }SAL_DAC_USER_CB, *PSAL_DAC_USER_CB; // DAC Transmit Buffer diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_efuse.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_efuse.h index 2f0a7d03e6..0911d966e3 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_efuse.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_efuse.h @@ -16,10 +16,12 @@ _LONG_CALL_ROM_ extern VOID HalEFUSEPowerSwitch8195AROM(IN u8 bWrite, IN u8 PwrState, IN u8 L25OutVoltage); extern u32 HALEFUSEOneByteReadRAM(IN u32 CtrlSetting, IN u16 Addr, OUT u8 *Data, IN u8 L25OutVoltage); extern u32 HALEFUSEOneByteWriteRAM(IN u32 CtrlSetting, IN u16 Addr, IN u8 Data, IN u8 L25OutVoltage); +u32 HALOneByteWriteRAM(IN u32 CtrlSetting,IN u16 Addr,IN u8 Data,IN u8 L25OutVoltage); #define EFUSERead8 HALEFUSEOneByteReadRAM #define EFUSEWrite8 HALEFUSEOneByteWriteRAM #define L25EOUTVOLTAGE 7 +#define DISABLE 0 #endif diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_i2c.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_i2c.h index 6b70087d89..290d93e006 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_i2c.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_i2c.h @@ -308,25 +308,26 @@ enum _I2C_ERR_TYPE_ { I2C_ERR_TX_ABRT = 0x08, //I2C TX terminated I2C_ERR_SLV_TX_NACK = 0x10, //I2C slave transmission terminated by master NACK, //but there are data in slave TX FIFO - I2C_ERR_MST_A_NACK = 0x12, - I2C_ERR_MST_D_NACK = 0x13, - I2C_ERR_USER_REG_TO = 0x20, + I2C_ERR_MST_A_NACK = 0x20, + I2C_ERR_MST_D_NACK = 0x40, + I2C_ERR_USER_REG_TO = 0x80, - I2C_ERR_RX_CMD_TO = 0x21, - I2C_ERR_RX_FF_TO = 0x22, - I2C_ERR_TX_CMD_TO = 0x23, - I2C_ERR_TX_FF_TO = 0x24, + I2C_ERR_RX_CMD_TO = 0x100, + I2C_ERR_RX_FF_TO = 0x200, + I2C_ERR_TX_CMD_TO = 0x400, + I2C_ERR_TX_FF_TO = 0x800, - I2C_ERR_TX_ADD_TO = 0x25, - I2C_ERR_RX_ADD_TO = 0x26, + I2C_ERR_TX_ADD_TO = 0x1000, + I2C_ERR_RX_ADD_TO = 0x2000, }; typedef uint32_t I2C_ERR_TYPE; typedef uint32_t *PI2C_ERR_TYPE; // I2C Time Out type -#define I2C_TIMEOOUT_DISABLE 0x00 -#define I2C_TIMEOOUT_ENDLESS 0xFFFFFFFF - +enum _I2C_TIMEOUT_TYPE_ { + I2C_TIMEOUT_DISABLE = 0x00, + I2C_TIMEOUT_ENDLESS = 0xFFFFFFFF, +}; typedef uint32_t I2C_TIMEOUT_TYPE; typedef uint32_t *PI2C_TIMEOUT_TYPE; diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_i2s.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_i2s.h new file mode 100644 index 0000000000..10b92d31d4 --- /dev/null +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_i2s.h @@ -0,0 +1,347 @@ +/* + * Routines to access hardware + * + * Copyright (c) 2013 Realtek Semiconductor Corp. + * + * This module is a confidential and proprietary property of RealTek and + * possession or use of this module requires written permission of RealTek. + */ + +#ifndef _HAL_I2S_H_ +#define _HAL_I2S_H_ + +#include "rtl8195a_i2s.h" + +/* User Define Flags */ + +#define I2S_MAX_ID 1 // valid I2S index 0 ~ I2S_MAX_ID + +/**********************************************************************/ +/* I2S HAL initial data structure */ +typedef struct _HAL_I2S_INIT_DAT_ { + u8 I2SIdx; /*I2S index used*/ + u8 I2SEn; /*I2S module enable tx/rx/tx+rx*/ + u8 I2SMaster; /*I2S Master or Slave mode*/ + u8 I2SWordLen; /*I2S Word length 16 or 24bits*/ + + u8 I2SChNum; /*I2S Channel number mono or stereo*/ + u8 I2SPageNum; /*I2S Page Number 2~4*/ + u16 I2SPageSize; /*I2S page Size 1~4096 word*/ + + u8 *I2STxData; /*I2S Tx data pointer*/ + + u8 *I2SRxData; /*I2S Rx data pointer*/ + + u32 I2STxIntrMSK; /*I2S Tx Interrupt Mask*/ + u32 I2STxIntrClr; /*I2S Tx Interrupt register to clear */ + + u32 I2SRxIntrMSK; /*I2S Rx Interrupt Mask*/ + u32 I2SRxIntrClr; /*I2S Rx Interrupt register to clear*/ + + u16 I2STxIdx; /*I2S TX page index */ + u16 I2SRxIdx; /*I2S RX page index */ + + u16 I2SHWTxIdx; /*I2S HW TX page index */ + u16 I2SHWRxIdx; /*I2S HW RX page index */ + + + u16 I2SRate; /*I2S sample rate*/ + u8 I2STRxAct; /*I2S tx rx act*/ +}HAL_I2S_INIT_DAT, *PHAL_I2S_INIT_DAT; + +/**********************************************************************/ +/* I2S Data Structures */ +/* I2S Module Selection */ +typedef enum _I2S_MODULE_SEL_ { + I2S0_SEL = 0x0, + I2S1_SEL = 0x1, +}I2S_MODULE_SEL,*PI2S_MODULE_SEL; +/* +typedef struct _HAL_I2S_ADAPTER_ { + u32 Enable:1; + I2S_CTL_REG I2sCtl; + I2S_SETTING_REG I2sSetting; + u32 abc; + u8 I2sIndex; +}HAL_I2S_ADAPTER, *PHAL_I2S_ADAPTER; +*/ +/* I2S HAL Operations */ +typedef struct _HAL_I2S_OP_ { + RTK_STATUS (*HalI2SInit) (VOID *Data); + RTK_STATUS (*HalI2SDeInit) (VOID *Data); + RTK_STATUS (*HalI2STx) (VOID *Data, u8 *pBuff); + RTK_STATUS (*HalI2SRx) (VOID *Data, u8 *pBuff); + RTK_STATUS (*HalI2SEnable) (VOID *Data); + RTK_STATUS (*HalI2SIntrCtrl) (VOID *Data); + u32 (*HalI2SReadReg) (VOID *Data, u8 I2SReg); + RTK_STATUS (*HalI2SSetRate) (VOID *Data); + RTK_STATUS (*HalI2SSetWordLen) (VOID *Data); + RTK_STATUS (*HalI2SSetChNum) (VOID *Data); + RTK_STATUS (*HalI2SSetPageNum) (VOID *Data); + RTK_STATUS (*HalI2SSetPageSize) (VOID *Data); + + RTK_STATUS (*HalI2SClrIntr) (VOID *Data); + RTK_STATUS (*HalI2SClrAllIntr) (VOID *Data); + RTK_STATUS (*HalI2SDMACtrl) (VOID *Data); +/* + VOID (*HalI2sOnOff)(VOID *Data); + BOOL (*HalI2sInit)(VOID *Data); + BOOL (*HalI2sSetting)(VOID *Data); + BOOL (*HalI2sEn)(VOID *Data); + BOOL (*HalI2sIsrEnAndDis) (VOID *Data); + BOOL (*HalI2sDumpReg)(VOID *Data); + BOOL (*HalI2s)(VOID *Data); +*/ +}HAL_I2S_OP, *PHAL_I2S_OP; + + +/**********************************************************************/ + +/* I2S Pinmux Selection */ +#if 0 +typedef enum _I2S0_PINMUX_ { + I2S0_TO_S0 = 0x0, + I2S0_TO_S1 = 0x1, + I2S0_TO_S2 = 0x2, +}I2S0_PINMUX, *PI2S0_PINMUX; + +typedef enum _I2S1_PINMUX_ { + I2S1_TO_S0 = 0x0, + I2S1_TO_S1 = 0x1, +}I2S1_PINMUX, *PI2S1_PINMUX; +#endif + +typedef enum _I2S_PINMUX_ { + I2S_S0 = 0, + I2S_S1 = 1, + I2S_S2 = 2, + I2S_S3 = 3 +}I2S_PINMUX, *PI2S_PINMUX; + + +/* I2S Module Status */ +typedef enum _I2S_MODULE_STATUS_ { + I2S_DISABLE = 0x0, + I2S_ENABLE = 0x1, +}I2S_MODULE_STATUS, *PI2S_MODULE_STATUS; + + +/* I2S Device Status */ +typedef enum _I2S_Device_STATUS_ { + I2S_STS_UNINITIAL = 0x00, + I2S_STS_INITIALIZED = 0x01, + I2S_STS_IDLE = 0x02, + + I2S_STS_TX_READY = 0x03, + I2S_STS_TX_ING = 0x04, + + I2S_STS_RX_READY = 0x05, + I2S_STS_RX_ING = 0x06, + + I2S_STS_TRX_READY = 0x07, + I2S_STS_TRX_ING = 0x08, + + I2S_STS_ERROR = 0x09, +}I2S_Device_STATUS, *PI2S_Device_STATUS; + + +/* I2S Feature Status */ +typedef enum _I2S_FEATURE_STATUS_{ + I2S_FEATURE_DISABLED = 0, + I2S_FEATURE_ENABLED = 1, +}I2S_FEATURE_STATUS,*PI2S_FEATURE_STATUS; + +/* I2S Device Mode */ +typedef enum _I2S_DEV_MODE_ { + I2S_MASTER_MODE = 0x0, + I2S_SLAVE_MODE = 0x1 +}I2S_DEV_MODE, *PI2S_DEV_MODE; + +/* I2S Word Length */ +typedef enum _I2S_WORD_LEN_ { + I2S_WL_16 = 0x0, + I2S_WL_24 = 0x1, +}I2S_WORD_LEN, *PI2S_WORD_LEN; + +/* I2S Bus Transmit/Receive */ +typedef enum _I2S_DIRECTION_ { + I2S_ONLY_RX = 0x0, + I2S_ONLY_TX = 0x1, + I2S_TXRX = 0x2 +}I2S_DIRECTION, *PI2S_DIRECTION; + +/* I2S Channel number */ +typedef enum _I2S_CH_NUM_ { + I2S_CH_STEREO = 0x0, + I2S_CH_RSVD = 0x1, + I2S_CH_MONO = 0x2 +}I2S_CH_NUM, *PI2S_CH_NUM; + +/* I2S Page number */ +typedef enum _I2S_PAGE_NUM_ { + I2S_1PAGE = 0x0, + I2S_2PAGE = 0x1, + I2S_3PAGE = 0x2, + I2S_4PAGE = 0x3 +}I2S_PAGE_NUM, *PI2S_PAGE_NUM; + +/* I2S Sample rate*/ +typedef enum _I2S_SAMPLE_RATE_ { + I2S_SR_8KHZ = 0x00, // /12 + I2S_SR_16KHZ = 0x01, // /6 + I2S_SR_24KHZ = 0x02, // /4 + I2S_SR_32KHZ = 0x03, // /3 + I2S_SR_48KHZ = 0x05, // /2 + I2S_SR_96KHZ = 0x06, // x1, base 96kHz + I2S_SR_7p35KHZ = 0x10, + I2S_SR_14p7KHZ = 0x11, + I2S_SR_22p05KHZ = 0x12, + I2S_SR_29p4KHZ = 0x13, + I2S_SR_44p1KHZ = 0x15, + I2S_SR_88p2KHZ = 0x16 // x1, base 88200Hz +}I2S_SAMPLE_RATE, *PI2S_SAMPLE_RATE; + +/* I2S TX interrupt mask/status */ +typedef enum _I2S_TX_IMR_ { + I2S_TX_INT_PAGE0_OK = (1<<0), + I2S_TX_INT_PAGE1_OK = (1<<1), + I2S_TX_INT_PAGE2_OK = (1<<2), + I2S_TX_INT_PAGE3_OK = (1<<3), + I2S_TX_INT_FULL = (1<<4), + I2S_TX_INT_EMPTY = (1<<5) +} I2S_TX_IMR, *PI2S_TX_IMR; + +/* I2S RX interrupt mask/status */ +typedef enum _I2S_RX_IMR_ { + I2S_RX_INT_PAGE0_OK = (1<<0), + I2S_RX_INT_PAGE1_OK = (1<<1), + I2S_RX_INT_PAGE2_OK = (1<<2), + I2S_RX_INT_PAGE3_OK = (1<<3), + I2S_RX_INT_EMPTY = (1<<4), + I2S_RX_INT_FULL = (1<<5) +} I2S_RX_IMR, *PI2S_RX_IMR; + +/* I2S User Callbacks */ +typedef struct _SAL_I2S_USER_CB_{ + VOID (*TXCB) (VOID *Data); + VOID (*TXCCB) (VOID *Data); + VOID (*RXCB) (VOID *Data); + VOID (*RXCCB) (VOID *Data); + VOID (*RDREQCB) (VOID *Data); + VOID (*ERRCB) (VOID *Data); + VOID (*GENCALLCB) (VOID *Data); +}SAL_I2S_USER_CB,*PSAL_I2S_USER_CB; + +typedef struct _I2S_USER_CB_{ + VOID (*TxCCB)(uint32_t id, char *pbuf); + u32 TxCBId; + VOID (*RxCCB)(uint32_t id, char *pbuf); + u32 RxCBId; +}I2S_USER_CB,*PI2S_USER_CB; + +/* Software API Level I2S Handler */ +typedef struct _HAL_I2S_ADAPTER_{ + u8 DevNum; //I2S device number + u8 PinMux; //I2S pin mux seletion + u8 RSVD0; //Reserved + volatile u8 DevSts; //I2S device status + + u32 RSVD2; //Reserved + u32 I2SExd; //I2S extended options: + //bit 0: I2C RESTART supported, + // 0 for NOT supported, + // 1 for supported + //bit 1: I2C General Call supported + // 0 for NOT supported, + // 1 for supported + //bit 2: I2C START Byte supported + // 0 for NOT supported, + // 1 for supported + //bit 3: I2C Slave-No-Ack + // supported + // 0 for NOT supported, + // 1 for supported + //bit 4: I2C bus loading, + // 0 for 100pf, + // 1 for 400pf + //bit 5: I2C slave ack to General + // Call + //bit 6: I2C User register address + //bit 7: I2C 2-Byte User register + // address + //bit 31~bit 8: Reserved + u32 ErrType; // + u32 TimeOut; //I2S IO Timeout count + + PHAL_I2S_INIT_DAT pInitDat; //Pointer to I2S initial data struct + I2S_USER_CB UserCB; //Pointer to I2S User Callback + IRQ_HANDLE IrqHandle; // Irq Handler + + u32* TxPageList[4]; // The Tx DAM buffer: pointer of each page + u32* RxPageList[4]; // The Tx DAM buffer: pointer of each page +}HAL_I2S_ADAPTER, *PHAL_I2S_ADAPTER; + +typedef struct _HAL_I2S_DEF_SETTING_{ + u8 I2SMaster; // Master or Slave mode + u8 DevSts; //I2S device status + u8 I2SChNum; //I2S Channel number mono or stereo + u8 I2SPageNum; //I2S Page number 2~4 + u8 I2STRxAct; //I2S tx rx act, tx only or rx only or tx+rx + u8 I2SWordLen; //I2S Word length 16bit or 24bit + u16 I2SPageSize; //I2S Page size 1~4096 word + + u16 I2SRate; //I2S sample rate 8k ~ 96khz + + u32 I2STxIntrMSK; /*I2S Tx Interrupt Mask*/ + u32 I2SRxIntrMSK; /*I2S Rx Interrupt Mask*/ +}HAL_I2S_DEF_SETTING, *PHAL_I2S_DEF_SETTING; + + + +/**********************************************************************/ +HAL_Status +RtkI2SLoadDefault(IN VOID *Adapter, IN VOID *Setting); + +HAL_Status +RtkI2SInit(IN VOID *Data); + +HAL_Status +RtkI2SDeInit(IN VOID *Data); + +HAL_Status +RtkI2SEnable(IN VOID *Data); + +HAL_Status +RtkI2SDisable(IN VOID *Data); + +extern HAL_Status +HalI2SInit( IN VOID *Data); + +extern VOID +HalI2SDeInit( IN VOID *Data); + +extern HAL_Status +HalI2SDisable( IN VOID *Data); + +extern HAL_Status +HalI2SEnable( IN VOID *Data); + + + + +/**********************************************************************/ + + +VOID I2S0ISRHandle(VOID *Data); +VOID I2S1ISRHandle(VOID *Data); + + +/**********************************************************************/ + +VOID HalI2SOpInit( + IN VOID *Data +); + + +#endif + diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_misc.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_misc.h index 1888368821..f927a82c8d 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_misc.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_misc.h @@ -24,6 +24,19 @@ #define CHIP_ID_8710AM 0xFA #define CHIP_ID_SIP 0xF9 #define CHIP_ID_COMBO_SIP 0xF8 +#define CHIP_ID_SIP2 0xF7 +#define CHIP_ID_MICO100 0xF1 + +enum _HAL_RESET_REASON{ + REASON_DEFAULT_RST = 0, /**< normal startup by power on */ + REASON_WDT_RST, /**< hardware watch dog reset */ + REASON_EXCEPTION_RST, /**< exception reset, GPIO status won't change */ + REASON_SOFT_WDT_RST, /**< software watch dog reset, GPIO status won't change */ + REASON_SOFT_RESTART, /**< software restart ,system_restart , GPIO status won't change */ + REASON_DEEP_SLEEP_AWAKE, /**< wake up from deep-sleep */ + REASON_EXT_SYS_RST /**< external system reset */ +}; +typedef u32 HAL_RESET_REASON; #ifdef CONFIG_TIMER_MODULE extern _LONG_CALL_ u32 HalDelayUs(u32 us); @@ -43,5 +56,7 @@ extern _LONG_CALL_ROM_ int _memcmp( const void *av, const void *bv, SIZE_T len ) extern _LONG_CALL_ROM_ SIZE_T _strlen(const char *s); extern _LONG_CALL_ROM_ int _strcmp(const char *cs, const char *ct); +VOID HalSetResetCause(IN HAL_RESET_REASON reason); +HAL_RESET_REASON HalGetResetCause(VOID); #endif //_MISC_H_ diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_pwm.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_pwm.h index 7101120fe3..9197e5abef 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_pwm.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_pwm.h @@ -15,6 +15,9 @@ #define _HAL_PWM_H_ #define MAX_PWM_CTRL_PIN 4 +#define MAX_GTIMER_NUM 4 +#define MAX_DEVID_TICK 1020 + // the minimum tick time for G-timer is 61 us (clock source = 32768Hz, reload value=1 and reload takes extra 1T) //#define GTIMER_TICK_US 31 // micro-second, 1000000/32768 ~= 30.5 #define MIN_GTIMER_TIMEOUT 61 // in micro-sec, use this value to set the g-timer to generate tick for PWM. 61=(1000000/32768)*2 @@ -32,6 +35,10 @@ typedef struct _HAL_PWM_ADAPTER_ { // float duty_ratio; // the dyty ratio = pulswidth/period }HAL_PWM_ADAPTER, *PHAL_PWM_ADAPTER; +typedef struct _HAL_PWM_GTIMER_ { + u32 tick_time; // the tick time for the G-timer + u8 reference; // map of referenced by PWM +}HAL_PWM_TIMER, *PHAL_PWM_TIMER; extern HAL_Status HAL_Pwm_Init( diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_spi_flash.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_spi_flash.h index f4b8b5ee11..6380ed97bb 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_spi_flash.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_spi_flash.h @@ -69,6 +69,8 @@ enum _SPIC_BIT_MODE_ { #define FLASH_WINBOND 3 #define FLASH_MICRON 4 #define FLASH_EON 5 +#define FLASH_GD 6 +#define FLASH_CYPRESS 7 //#define FLASH_MXIC_MX25L4006E 0 //#define FLASH_MXIC_MX25L8073E 0 @@ -82,40 +84,41 @@ enum _SPIC_BIT_MODE_ { #define FLASH_CMD_WRDI 0x04 //write disable #define FLASH_CMD_WRSR 0x01 //write status register #define FLASH_CMD_RDID 0x9F //read idenfication +#define FLASH_CMD_RDUID 0x4B //Read Unique ID #define FLASH_CMD_RDSR 0x05 //read status register #define FLASH_CMD_RDSFDP 0x5A //Read SFDP #define FLASH_CMD_READ 0x03 //read data #define FLASH_CMD_FREAD 0x0B //fast read data #define FLASH_CMD_PP 0x02 //Page Program -#define FLASH_CMD_DREAD 0x3B //Double Output Mode command 1-1-2 -#define FLASH_CMD_2READ 0xBB // 2 x I/O read command 1-2-2 -#define FLASH_CMD_QREAD 0x6B // 1I / 4O read command 1-1-4 -#define FLASH_CMD_4READ 0xEB // 4 x I/O read command 1-4-4 -#define FLASH_CMD_DPP 0xA2 // 1-1-2 -#define FLASH_CMD_2PP 0xD2 // 1-2-2 -#define FLASH_CMD_QPP 0x32 // 1-1-4 -#define FLASH_CMD_4PP 0x38 //quad page program 1-4-4 +#define FLASH_CMD_DREAD 0x3B //Double Output Mode command 1-1-2 +#define FLASH_CMD_2READ 0xBB // 2 x I/O read command 1-2-2 +#define FLASH_CMD_QREAD 0x6B // 1I / 4O read command 1-1-4 +#define FLASH_CMD_4READ 0xEB // 4 x I/O read command 1-4-4 +#define FLASH_CMD_DPP 0xA2 // 1-1-2 +#define FLASH_CMD_2PP 0xD2 // 1-2-2 +#define FLASH_CMD_QPP 0x32 // 1-1-4 +#define FLASH_CMD_4PP 0x38 //quad page program 1-4-4 #define FLASH_CMD_SE 0x20 //Sector Erase -#define FLASH_CMD_BE 0xD8 //Block Erase(or 0x52) -#define FLASH_CMD_CE 0xC7 //Chip Erase(or 0xC7) -#define FLASH_CMD_DP 0xB9 //Deep Power Down -#define FLASH_CMD_RDP 0xAB //Release from Deep Power-Down +#define FLASH_CMD_BE 0xD8 //Block Erase(or 0x52) +#define FLASH_CMD_CE 0xC7 //Chip Erase(or 0xC7) +#define FLASH_CMD_DP 0xB9 //Deep Power Down +#define FLASH_CMD_RDP 0xAB //Release from Deep Power-Down /*Micron Special command*/ -#define FLASH_CMD_DE 0xC4 -#define FLASH_CMD_4PP2 0x12 -#define FLASH_CMD_RFSR 0x70 -#define FLASH_CMD_CFSR 0x50 -#define FLASH_CMD_RNCR 0xB5 -#define FLASH_CMD_WNCR 0xB1 -#define FLASH_CMD_RVCR 0x85 -#define FLASH_CMD_WVCR 0x81 -#define FLASH_CMD_REVCR 0x65 -#define FLASH_CMD_WEVCR 0x61 -#define FLASH_CMD_REAR 0xC8 -#define FLASH_CMD_WEAR 0xC5 -#define FLASH_CMD_ENQUAD 0x35 -#define FLASH_CMD_EXQUAD 0xF5 +#define FLASH_CMD_DE 0xC4 +#define FLASH_CMD_4PP2 0x12 +#define FLASH_CMD_RFSR 0x70 +#define FLASH_CMD_CFSR 0x50 +#define FLASH_CMD_RNCR 0xB5 +#define FLASH_CMD_WNCR 0xB1 +#define FLASH_CMD_RVCR 0x85 +#define FLASH_CMD_WVCR 0x81 +#define FLASH_CMD_REVCR 0x65 +#define FLASH_CMD_WEVCR 0x61 +#define FLASH_CMD_REAR 0xC8 +#define FLASH_CMD_WEAR 0xC5 +#define FLASH_CMD_ENQUAD 0x35 +#define FLASH_CMD_EXQUAD 0xF5 /*MXIC Special command*/ #define FLASH_CMD_RDCR 0x15 //read configurate register @@ -126,6 +129,19 @@ enum _SPIC_BIT_MODE_ { #define FLASH_CMD_RDSCUR 0x2B // read security register #define FLASH_CMD_WRSCUR 0x2F // write security register +/*WINBOND Special command*/ +#define FLASH_CMD_GLOCK 0x7E +#define FLASH_CMD_GUNLOCK 0x98 +#define FLASH_CMD_RLOCK 0x3D +#define FLASH_CMD_SLOCK 0x36 +#define FLASH_CMD_SUNLOCK 0x39 +#define FLASH_CMD_WRSR3 0x11 +#define FLASH_CMD_RDSR3 0x15 + +/*Cypress Special command*/ +#define FLASH_CMD_RDSR4 0x07 //read status register 2 +#define FLASH_CMD_CLSR 0x30 //Clear status register 2 error bit + //#endif #if 0 #if FLASH_MXIC_MX25L4006E @@ -331,11 +347,16 @@ VOID SpicBlockEraseFlashRtl8195A(IN u32 Address); VOID SpicSectorEraseFlashRtl8195A(IN u32 Address); VOID SpicDieEraseFlashRtl8195A(IN u32 Address); VOID SpicWriteProtectFlashRtl8195A(IN u32 Protect); -VOID SpicWaitWipDoneRefinedRtl8195A(IN SPIC_INIT_PARA SpicInitPara); +VOID SpicWaitWipDoneRefinedRtl8195A(IN SPIC_INIT_PARA SpicInitPara); VOID SpicWaitOperationDoneRtl8195A(IN SPIC_INIT_PARA SpicInitPara); -VOID SpicRxCmdRefinedRtl8195A(IN u8 cmd,IN SPIC_INIT_PARA SpicInitPara); +VOID SpicTxCmdWithDataRtl8195A(IN u8 cmd,IN u8 DataPhaseLen,IN u8* pData,IN SPIC_INIT_PARA SpicInitPara); +VOID SpicTxCmdWithDataNoCheckRtl8195A(IN u8 cmd, IN u8 DataPhaseLen,IN u8* pData); +VOID SpicRxCmdRefinedRtl8195A(IN u8 cmd,IN SPIC_INIT_PARA SpicInitPara); +VOID SpicRxCmdWithDataRtl8195A(IN u8 cmd,IN u8 DataPhaseLen, IN u8* pData,IN SPIC_INIT_PARA SpicInitPara); u8 SpicGetFlashStatusRefinedRtl8195A(IN SPIC_INIT_PARA SpicInitPara); -VOID SpicInitRefinedRtl8195A(IN u8 InitBaudRate,IN u8 SpicBitMode); +u8 SpicGetFlashStatus3Rtl8195A(IN SPIC_INIT_PARA SpicInitPara); +u8 SpicGetFlashStatus4Rtl8195A(IN SPIC_INIT_PARA SpicInitPara); +VOID SpicInitRefinedRtl8195A(IN u8 InitBaudRate,IN u8 SpicBitMode); u32 SpicWaitWipRtl8195A(VOID); u32 SpicOneBitCalibrationRtl8195A(IN u8 SysCpuClk); VOID SpicDisableRtl8195A(VOID); @@ -343,10 +364,18 @@ VOID SpicDeepPowerDownFlashRtl8195A(VOID); VOID SpicUserProgramRtl8195A(IN u8 * data, IN SPIC_INIT_PARA SpicInitPara, IN u32 addr, IN u32 * LengthInfo); VOID SpicUserReadRtl8195A(IN u32 Length, IN u32 addr, IN u8 * data, IN u8 BitMode); VOID SpicUserReadFourByteRtl8195A(IN u32 Length, IN u32 addr, IN u32 * data, IN u8 BitMode); +VOID SpicReadUniqueIDRtl8195A(IN u8 *buff,IN u8 len); VOID SpicReadIDRtl8195A(VOID); VOID SpicSetFlashStatusRefinedRtl8195A(IN u32 data, IN SPIC_INIT_PARA SpicInitPara); VOID SpicSetExtendAddrRtl8195A(IN u32 data, IN SPIC_INIT_PARA SpicInitPara); u8 SpicGetExtendAddrRtl8195A(IN SPIC_INIT_PARA SpicInitPara); +VOID SpicSetLockModeRtl8195A(IN u8 Mode); +VOID SpicLockFlashRtl8195A(VOID); +VOID SpicUnlockFlashRtl8195A(VOID); +VOID SpicSingleLockRtl8195A(IN u32 Address); +VOID SpicSingleUnlockRtl8195A(IN u32 Address); +u8 SpicReadLockStateRtl8195A(IN u32 Address); + #if SPIC_CALIBRATION_IN_NVM VOID SpicNVMCalLoad(u8 BitMode, u8 CpuClk); VOID SpicNVMCalLoadAll(void); diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_ssi.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_ssi.h index 04cb1e61c1..43881a18d2 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_ssi.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_ssi.h @@ -21,6 +21,7 @@ */ extern u32 SSI_DBG_CONFIG; +extern uint8_t SPI0_IS_AS_SLAVE; #define SSI_DBG_ENTRANCE(...) do {\ diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_timer.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_timer.h index b716cbaae3..d152487eab 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_timer.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/hal_timer.h @@ -44,19 +44,16 @@ typedef struct _HAL_TIMER_OP_ { u32 (*HalGetTimerId)(u32 *TimerId); BOOL (*HalTimerInit)(VOID *Data); u32 (*HalTimerReadCount)(u32 TimerId); - //VOID (*HalTimerIrqEn)(u32 TimerId); VOID (*HalTimerIrqClear)(u32 TimerId); VOID (*HalTimerDis)(u32 TimerId); VOID (*HalTimerEn)(u32 TimerId); VOID (*HalTimerDumpReg)(u32 TimerId); - //VOID (*HalTimerReLoad)(u32 TimerId, u32 LoadUs); }HAL_TIMER_OP, *PHAL_TIMER_OP; typedef struct _HAL_TIMER_OP_EXT_ { - PHAL_TIMER_OP phal_timer_op_rom; - VOID (*HalTimerIrqEn)(u32 TimerId); - VOID (*HalTimerReLoad)(u32 TimerId, u32 LoadUs); - VOID (*HalTimerSync)(u32 TimerId); + PHAL_TIMER_OP phal_timer_op_rom; + VOID (*HalTimerIrqEn)(u32 TimerId); + VOID (*HalTimerReLoad)(u32 TimerId, u32 LoadUs); }HAL_TIMER_OP_EXT, *PHAL_TIMER_OP_EXT; #ifdef CONFIG_TIMER_MODULE diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a.h index 499700ecec..24eda206aa 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a.h @@ -28,6 +28,7 @@ #include "hal_diag.h" #include "hal_spi_flash.h" #include "rtl8195a_spi_flash.h" +#include "hal_timer.h" #include "hal_util.h" #include "hal_efuse.h" #include "hal_soc_ps_monitor.h" @@ -148,11 +149,9 @@ __##name##_Disable(void) \ #include "rtl8195a_trap.h" #include "rtl8195a_clk.h" #include "rtl8195a_misc.h" -#include "rtl8195a_sdio.h" #endif - /* ---------------------------------------------------------------------------- -- Cortex M3 Core Configuration ---------------------------------------------------------------------------- */ @@ -198,6 +197,10 @@ __##name##_Disable(void) \ #include "rtl8195a_i2c.h" #endif +#ifdef CONFIG_PCM_EN +#include "hal_pcm.h" +#include "rtl8195a_pcm.h" +#endif #ifdef CONFIG_PWM_EN #include "hal_pwm.h" @@ -226,7 +229,7 @@ __##name##_Disable(void) \ #endif #ifdef CONFIG_SDIO_DEVICE_EN -//#include "hal_sdio.h" +#include "hal_sdio.h" #endif #ifdef CONFIG_NFC_EN diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a_i2s.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a_i2s.h new file mode 100644 index 0000000000..13d7f59ea6 --- /dev/null +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a_i2s.h @@ -0,0 +1,714 @@ +/* + * Routines to access hardware + * + * Copyright (c) 2013 Realtek Semiconductor Corp. + * + * This module is a confidential and proprietary property of RealTek and + * possession or use of this module requires written permission of RealTek. + */ + + +#ifndef _RTL8195A_I2S_H_ +#define _RTL8195A_I2S_H_ + + +//=============== Register Bit Field Definition ==================== +// REG_I2S_CONTROL +#define BIT_CTLX_I2S_EN BIT(0) +#define BIT_SHIFT_CTLX_I2S_EN 0 +#define BIT_MASK_CTLX_I2S_EN 0x1 +#define BIT_CTRL_CTLX_I2S_EN(x) (((x) & BIT_MASK_CTLX_I2S_EN) << BIT_SHIFT_CTLX_I2S_EN) + +#define BIT_SHIFT_CTLX_I2S_TRX_ACT 1 +#define BIT_MASK_CTLX_I2S_TRX_ACT 0x3 +#define BIT_CTRL_CTLX_I2S_TRX_ACT(x) (((x) & BIT_MASK_CTLX_I2S_TRX_ACT) << BIT_SHIFT_CTLX_I2S_TRX_ACT) +#define BIT_GET_CTLX_I2S_TRX_ACT(x) (((x) >> BIT_SHIFT_CTLX_I2S_TRX_ACT) & BIT_MASK_CTLX_I2S_TRX_ACT) + +#define BIT_SHIFT_CTLX_I2S_CH_NUM 3 +#define BIT_MASK_CTLX_I2S_CH_NUM 0x3 +#define BIT_CTRL_CTLX_I2S_CH_NUM(x) (((x) & BIT_MASK_CTLX_I2S_CH_NUM) << BIT_SHIFT_CTLX_I2S_CH_NUM) +#define BIT_GET_CTLX_I2S_CH_NUM(x) (((x) >> BIT_SHIFT_CTLX_I2S_CH_NUM) & BIT_MASK_CTLX_I2S_CH_NUM) + +#define BIT_CTLX_I2S_WL BIT(6) +#define BIT_SHIFT_CTLX_I2S_WL 6 +#define BIT_MASK_CTLX_I2S_WL 0x1 +#define BIT_CTRL_CTLX_I2S_WL(x) (((x) & BIT_MASK_CTLX_I2S_WL) << BIT_SHIFT_CTLX_I2S_WL) + +#define BIT_CTLX_I2S_LRSWAP BIT(10) +#define BIT_SHIFT_CTLX_I2S_LRSWAP 10 +#define BIT_MASK_CTLX_I2S_LRSWAP 0x1 +#define BIT_CTRL_CTLX_I2S_LRSWAP(x) (((x) & BIT_MASK_CTLX_I2S_LRSWAP) << BIT_SHIFT_CTLX_I2S_LRSWAP) + +#define BIT_CTLX_I2S_SCK_INV BIT(11) +#define BIT_SHIFT_CTLX_I2S_SCK_INV 11 +#define BIT_MASK_CTLX_I2S_SCK_INV 0x1 +#define BIT_CTRL_CTLX_I2S_SCK_INV(x) (((x) & BIT_MASK_CTLX_I2S_SCK_INV) << BIT_SHIFT_CTLX_I2S_SCK_INV) + +#define BIT_CTLX_I2S_ENDIAN_SWAP BIT(12) +#define BIT_SHIFT_CTLX_I2S_ENDIAN_SWAP 12 +#define BIT_MASK_CTLX_I2S_ENDIAN_SWAP 0x1 +#define BIT_CTRL_CTLX_I2S_ENDIAN_SWAP(x) (((x) & BIT_MASK_CTLX_I2S_ENDIAN_SWAP) << BIT_SHIFT_CTLX_I2S_ENDIAN_SWAP) + +#define BIT_CTLX_I2S_SLAVE_MODE BIT(29) +#define BIT_SHIFT_CTLX_I2S_SLAVE_MODE 29 +#define BIT_MASK_CTLX_I2S_SLAVE_MODE 0x1 +#define BIT_CTRL_CTLX_I2S_SLAVE_MODE(x) (((x) & BIT_MASK_CTLX_I2S_SLAVE_MODE) << BIT_SHIFT_CTLX_I2S_SLAVE_MODE) + +#define BIT_CTLX_I2S_CLK_SRC BIT(30) +#define BIT_SHIFT_CTLX_I2S_CLK_SRC 30 +#define BIT_MASK_CTLX_I2S_CLK_SRC 0x1 +#define BIT_CTRL_CTLX_I2S_CLK_SRC(x) (((x) & BIT_MASK_CTLX_I2S_CLK_SRC) << BIT_SHIFT_CTLX_I2S_CLK_SRC) + +#define BIT_CTLX_I2S_SW_RSTN BIT(31) +#define BIT_SHIFT_CTLX_I2S_SW_RSTN 31 +#define BIT_MASK_CTLX_I2S_SW_RSTN 0x1 +#define BIT_CTRL_CTLX_I2S_SW_RSTN(x) (((x) & BIT_MASK_CTLX_I2S_SW_RSTN) << BIT_SHIFT_CTLX_I2S_SW_RSTN) + +// REG_I2S_SETTING +#define BIT_SHIFT_SETTING_I2S_PAGE_SZ 0 +#define BIT_MASK_SETTING_I2S_PAGE_SZ 0xFFF +#define BIT_CTRL_SETTING_I2S_PAGE_SZ(x) (((x) & BIT_MASK_SETTING_I2S_PAGE_SZ) << BIT_SHIFT_SETTING_I2S_PAGE_SZ) +#define BIT_GET_SETTING_I2S_PAGE_SZ(x) (((x) >> BIT_SHIFT_SETTING_I2S_PAGE_SZ) & BIT_MASK_SETTING_I2S_PAGE_SZ) + +#define BIT_SHIFT_SETTING_I2S_PAGE_NUM 12 +#define BIT_MASK_SETTING_I2S_PAGE_NUM 0x3 +#define BIT_CTRL_SETTING_I2S_PAGE_NUM(x) (((x) & BIT_MASK_SETTING_I2S_PAGE_NUM) << BIT_SHIFT_SETTING_I2S_PAGE_NUM) +#define BIT_GET_SETTING_I2S_PAGE_NUM(x) (((x) >> BIT_SHIFT_SETTING_I2S_PAGE_NUM) & BIT_MASK_SETTING_I2S_PAGE_NUM) + +#define BIT_SHIFT_SETTING_I2S_SAMPLE_RATE 14 +#define BIT_MASK_SETTING_I2S_SAMPLE_RATE 0x7 +#define BIT_CTRL_SETTING_I2S_SAMPLE_RATE(x) (((x) & BIT_MASK_SETTING_I2S_SAMPLE_RATE) << BIT_SHIFT_SETTING_I2S_SAMPLE_RATE) +#define BIT_GET_SETTING_I2S_SAMPLE_RATE(x) (((x) >> BIT_SHIFT_SETTING_I2S_SAMPLE_RATE) & BIT_MASK_SETTING_I2S_SAMPLE_RATE) + +// i2s trx page own bit +#define BIT_PAGE_I2S_OWN_BIT BIT(31) +#define BIT_SHIFT_PAGE_I2S_OWN_BIT 31 +#define BIT_MASK_PAGE_I2S_OWN_BIT 0x1 +#define BIT_CTRL_PAGE_I2S_OWN_BIT(x) (((x) & BIT_MASK_PAGE_I2S_OWN_BIT) << BIT_SHIFT_PAGE_I2S_OWN_BIT) + +//=============== Register Address Definition ==================== +#define REG_I2S_PAGE_OWN_OFF 0x004 + +#define REG_I2S_CTL 0x000 +#define REG_I2S_TX_PAGE_PTR 0x004 +#define REG_I2S_RX_PAGE_PTR 0x008 +#define REG_I2S_SETTING 0x00C + +#define REG_I2S_TX_MASK_INT 0x010 +#define REG_I2S_TX_STATUS_INT 0x014 +#define REG_I2S_RX_MASK_INT 0x018 +#define REG_I2S_RX_STATUS_INT 0x01c + + +#define REG_I2S_TX_PAGE0_OWN 0x020 +#define REG_I2S_TX_PAGE1_OWN 0x024 +#define REG_I2S_TX_PAGE2_OWN 0x028 +#define REG_I2S_TX_PAGE3_OWN 0x02C +#define REG_I2S_RX_PAGE0_OWN 0x030 +#define REG_I2S_RX_PAGE1_OWN 0x034 +#define REG_I2S_RX_PAGE2_OWN 0x038 +#define REG_I2S_RX_PAGE3_OWN 0x03C + +/*I2S Essential Functions and Macros*/ +VOID +HalI2SWrite32( + IN u8 I2SIdx, + IN u8 I2SReg, + IN u32 I2SVal +); + +u32 +HalI2SRead32( + IN u8 I2SIdx, + IN u8 I2SReg +); + +/* +#define HAL_I2SX_READ32(I2sIndex, addr) \ + HAL_READ32(I2S0_REG_BASE+ (I2sIndex*I2S1_REG_OFF), addr) +#define HAL_I2SX_WRITE32(I2sIndex, addr, value) \ + HAL_WRITE32((I2S0_REG_BASE+ (I2sIndex*I2S1_REG_OFF)), addr, value) +*/ + +#define HAL_I2S_WRITE32(I2SIdx, addr, value) HalI2SWrite32(I2SIdx,addr,value) +#define HAL_I2S_READ32(I2SIdx, addr) HalI2SRead32(I2SIdx,addr) + +/* I2S debug output*/ +#define I2S_PREFIX "RTL8195A[i2s]: " +#define I2S_PREFIX_LVL " [i2s_DBG]: " + +typedef enum _I2S_DBG_LVL_ { + HAL_I2S_LVL = 0x01, + SAL_I2S_LVL = 0x02, + VERI_I2S_LVL = 0x03, +}I2S_DBG_LVL,*PI2S_DBG_LVL; + +#ifdef CONFIG_DEBUG_LOG +#ifdef CONFIG_DEBUG_LOG_I2S_HAL + + #define DBG_8195A_I2S(...) do{ \ + _DbgDump("\r"I2S_PREFIX __VA_ARGS__);\ + }while(0) + + + #define I2SDBGLVL 0xFF + #define DBG_8195A_I2S_LVL(LVL,...) do{\ + if (LVL&I2SDBGLVL){\ + _DbgDump("\r"I2S_PREFIX_LVL __VA_ARGS__);\ + }\ + }while(0) +#else + #define DBG_I2S_LOG_PERD 100 + #define DBG_8195A_I2S(...) + #define DBG_8195A_I2S_LVL(...) +#endif +#else + #define DBG_I2S_LOG_PERD 100 + #define DBG_8195A_I2S(...) + #define DBG_8195A_I2S_LVL(...) +#endif + +/* +#define REG_I2S_PAGE_OWN_OFF 0x004 +#define REG_I2S_CTL 0x000 +#define REG_I2S_TX_PAGE_PTR 0x004 +#define REG_I2S_RX_PAGE_PTR 0x008 +#define REG_I2S_SETTING 0x00C + +#define REG_I2S_TX_MASK_INT 0x010 +#define REG_I2S_TX_STATUS_INT 0x014 +#define REG_I2S_RX_MASK_INT 0x018 +#define REG_I2S_RX_STATUS_INT 0x01c + + + +#define REG_I2S_TX_PAGE0_OWN 0x020 +#define REG_I2S_TX_PAGE1_OWN 0x024 +#define REG_I2S_TX_PAGE2_OWN 0x028 +#define REG_I2S_TX_PAGE3_OWN 0x02C +#define REG_I2S_RX_PAGE0_OWN 0x030 +#define REG_I2S_RX_PAGE1_OWN 0x034 +#define REG_I2S_RX_PAGE2_OWN 0x038 +#define REG_I2S_RX_PAGE3_OWN 0x03C +*/ +/* template +#define BIT_SHIFT_CTLX_ 7 +#define BIT_MASK_CTLX_ 0x1 +#define BIT_CTLX_(x) (((x) & BIT_MASK_CTLX_) << BIT_SHIFT_CTLX_) +#define BIT_INV_CTLX_ (~(BIT_MASK_CTLX_ << BIT_SHIFT_CTLX_)) +*//* +#define BIT_SHIFT_CTLX_IIS_EN 0 +#define BIT_MASK_CTLX_IIS_EN 0x1 +#define BIT_CTLX_IIS_EN(x) (((x) & BIT_MASK_CTLX_IIS_EN) << BIT_SHIFT_CTLX_IIS_EN) +#define BIT_INV_CTLX_IIS_EN (~(BIT_MASK_CTLX_IIS_EN << BIT_SHIFT_CTLX_IIS_EN)) + +#define BIT_SHIFT_CTLX_TRX 1 +#define BIT_MASK_CTLX_TRX 0x3 +#define BIT_CTLX_TRX(x) (((x) & BIT_MASK_CTLX_TRX) << BIT_SHIFT_CTLX_TRX) +#define BIT_INV_CTLX_TRX (~(BIT_MASK_CTLX_TRX << BIT_SHIFT_CTLX_TRX)) + +#define BIT_SHIFT_CTLX_CH_NUM 3 +#define BIT_MASK_CTLX_CH_NUM 0x3 +#define BIT_CTLX_CH_NUM(x) (((x) & BIT_MASK_CTLX_CH_NUM) << BIT_SHIFT_CTLX_CH_NUM) +#define BIT_INV_CTLX_CH_NUM (~(BIT_MASK_CTLX_CH_NUM << BIT_SHIFT_CTLX_CH_NUM)) + +#define BIT_SHIFT_CTLX_EDGE_SW 5 +#define BIT_MASK_CTLX_EDGE_SW 0x1 +#define BIT_CTLX_EDGE_SW(x) (((x) & BIT_MASK_CTLX_EDGE_SW) << BIT_SHIFT_CTLX_EDGE_SW) +#define BIT_INV_CTLX_EDGE_SW (~(BIT_MASK_CTLX_EDGE_SW << BIT_SHIFT_CTLX_EDGE_SW)) + +#define BIT_SHIFT_CTLX_WL 6 +#define BIT_MASK_CTLX_WL 0x1 +#define BIT_CTLX_WL(x) (((x) & BIT_MASK_CTLX_WL) << BIT_SHIFT_CTLX_WL) +#define BIT_INV_CTLX_WL (~(BIT_MASK_CTLX_WL << BIT_SHIFT_CTLX_WL)) + +#define BIT_SHIFT_CTLX_LOOP_BACK 7 +#define BIT_MASK_CTLX_LOOP_BACK 0x1 +#define BIT_CTLX_LOOP_BACK(x) (((x) & BIT_MASK_CTLX_LOOP_BACK) << BIT_SHIFT_CTLX_LOOP_BACK) +#define BIT_INV_CTLX_LOOP_BACK (~(BIT_MASK_CTLX_LOOP_BACK << BIT_SHIFT_CTLX_LOOP_BACK)) + + +#define BIT_SHIFT_CTLX_FORMAT 8 +#define BIT_MASK_CTLX_FORMAT 0x3 +#define BIT_CTLX_FORMAT(x) (((x) & BIT_MASK_CTLX_FORMAT) << BIT_SHIFT_CTLX_FORMAT) +#define BIT_INV_CTLX_FORMAT (~(BIT_MASK_CTLX_FORMAT << BIT_SHIFT_CTLX_FORMAT)) + +#define BIT_SHIFT_CTLX_LRSWAP 10 +#define BIT_MASK_CTLX_LRSWAP 0x1 +#define BIT_CTLX_LRSWAP(x) (((x) & BIT_MASK_CTLX_LRSWAP) << BIT_SHIFT_CTLX_LRSWAP) +#define BIT_INV_CTLX_LRSWAP (~(BIT_MASK_CTLX_LRSWAP << BIT_SHIFT_CTLX_LRSWAP)) + +#define BIT_SHIFT_CTLX_SCK_INV 11 +#define BIT_MASK_CTLX_SCK_INV 0x1 +#define BIT_CTLX_SCK_INV(x) (((x) & BIT_MASK_CTLX_SCK_INV) << BIT_SHIFT_CTLX_SCK_INV) +#define BIT_INV_CTLX_SCK_INV (~(BIT_MASK_CTLX_SCK_INV << BIT_SHIFT_CTLX_SCK_INV)) + +#define BIT_SHIFT_CTLX_ENDIAN_SWAP 12 +#define BIT_MASK_CTLX_ENDIAN_SWAP 0x1 +#define BIT_CTLX_ENDIAN_SWAP(x) (((x) & BIT_MASK_CTLX_ENDIAN_SWAP) << BIT_SHIFT_CTLX_ENDIAN_SWAP) +#define BIT_INV_CTLX_ENDIAN_SWAP (~(BIT_MASK_CTLX_ENDIAN_SWAP << BIT_SHIFT_CTLX_ENDIAN_SWAP)) + + +#define BIT_SHIFT_CTLX_DEBUG_SWITCH 15 +#define BIT_MASK_CTLX_DEBUG_SWITCH 0x3 +#define BIT_CTLX_DEBUG_SWITCH(x) (((x) & BIT_MASK_CTLX_DEBUG_SWITCH) << BIT_SHIFT_CTLX_DEBUG_SWITCH) +#define BIT_INV_CTLX_DEBUG_SWITCH (~(BIT_MASK_CTLX_DEBUG_SWITCH << BIT_SHIFT_CTLX_DEBUG_SWITCH)) + +#define BIT_SHIFT_CTLX_SLAVE_SEL 29 +#define BIT_MASK_CTLX_SLAVE_SEL 0x1 +#define BIT_CTLX_SLAVE_SEL(x) (((x) & BIT_MASK_CTLX_SLAVE_SEL) << BIT_SHIFT_CTLX_SLAVE_SEL) +#define BIT_INV_CTLX_SLAVE_SEL (~(BIT_MASK_CTLX_SLAVE_SEL << BIT_SHIFT_CTLX_SLAVE_SEL)) + + +#define BIT_SHIFT_CTLX_CLK_SRC 30 +#define BIT_MASK_CTLX_CLK_SRC 0x1 +#define BIT_CTLX_CLK_SRC(x) (((x) & BIT_MASK_CTLX_CLK_SRC) << BIT_SHIFT_CTLX_CLK_SRC) +#define BIT_INV_CTLX_CLK_SRC (~(BIT_MASK_CTLX_CLK_SRC << BIT_SHIFT_CTLX_CLK_SRC)) + + + +#define BIT_SHIFT_CTLX_SW_RSTN 31 +#define BIT_MASK_CTLX_SW_RSTN 0x1 +#define BIT_CTLX_SW_RSTN(x) (((x) & BIT_MASK_CTLX_SW_RSTN) << BIT_SHIFT_CTLX_SW_RSTN) +#define BIT_INV_CTLX_SW_RSTN (~(BIT_MASK_CTLX_SW_RSTN << BIT_SHIFT_CTLX_SW_RSTN)) + + +#define BIT_SHIFT_SETTING_PAGE_SZ 0 +#define BIT_MASK_SETTING_PAGE_SZ 0xFFF +#define BIT_SETTING_PAGE_SZ(x) (((x) & BIT_MASK_SETTING_PAGE_SZ) << BIT_SHIFT_SETTING_PAGE_SZ) +#define BIT_INV_SETTING_PAGE_SZ (~(BIT_MASK_SETTING_PAGE_SZ << BIT_SHIFT_SETTING_PAGE_SZ)) + +#define BIT_SHIFT_SETTING_PAGE_NUM 12 +#define BIT_MASK_SETTING_PAGE_NUM 0x3 +#define BIT_SETTING_PAGE_NUM(x) (((x) & BIT_MASK_SETTING_PAGE_NUM) << BIT_SHIFT_SETTING_PAGE_NUM) +#define BIT_INV_SETTING_PAGE_NUM (~(BIT_MASK_SETTING_PAGE_NUM << BIT_SHIFT_SETTING_PAGE_NUM)) + +#define BIT_SHIFT_SETTING_SAMPLE_RATE 14 +#define BIT_MASK_SETTING_SAMPLE_RATE 0x7 +#define BIT_SETTING_SAMPLE_RATE(x) (((x) & BIT_MASK_SETTING_SAMPLE_RATE) << BIT_SHIFT_SETTING_SAMPLE_RATE) +#define BIT_INV_SETTING_SAMPLE_RATE (~(BIT_MASK_SETTING_SAMPLE_RATE << BIT_SHIFT_SETTING_SAMPLE_RATE)) +*/ + +typedef enum _I2S_CTL_FORMAT { + FormatI2s = 0x00, + FormatLeftJustified = 0x01, + FormatRightJustified = 0x02 +}I2S_CTL_FORMAT, *PI2S_CTL_FORMAT; + +typedef enum _I2S_CTL_CHNUM { + ChannelStereo = 0x00, + Channel5p1 = 0x01, + ChannelMono = 0x02 +}I2S_CTL_CHNUM, *PI2S_CTL_CHNUM; + +typedef enum _I2S_CTL_TRX_ACT { + RxOnly = 0x00, + TxOnly = 0x01, + TXRX = 0x02 +}I2S_CTL_TRX_ACT, *PI2S_CTL_TRX_ACT; +/* +typedef struct _I2S_CTL_REG_ { + I2S_CTL_FORMAT Format; + I2S_CTL_CHNUM ChNum; + I2S_CTL_TRX_ACT TrxAct; + + u32 I2s_En :1; // Bit 0 + u32 Rsvd1to4 :4; // Bit 1-4 is TrxAct, ChNum + u32 EdgeSw :1; // Bit 5 Edge switch + u32 WordLength :1; // Bit 6 + u32 LoopBack :1; // Bit 7 + u32 Rsvd8to9 :2; // Bit 8-9 is Format + u32 DacLrSwap :1; // Bit 10 + u32 SckInv :1; // Bit 11 + u32 EndianSwap :1; // Bit 12 + u32 Rsvd13to14 :2; // Bit 11-14 + u32 DebugSwitch :2; // Bit 15-16 + u32 Rsvd17to28 :12; // Bit 17-28 + u32 SlaveMode :1; // Bit 29 + u32 SR44p1KHz :1; // Bit 30 + u32 SwRstn :1; // Bit 31 +} I2S_CTL_REG, *PI2S_CTL_REG; +*/ +typedef enum _I2S_SETTING_PAGE_NUM { + I2s1Page = 0x00, + I2s2Page = 0x01, + I2s3Page = 0x02, + I2s4Page = 0x03 +}I2S_SETTING_PAGE_NUM, *PI2S_SETTING_PAGE_NUM; + +//sampling rate +typedef enum _I2S_SETTING_SR { + I2sSR8K = 0x00, + I2sSR16K = 0x01, + I2sSR24K = 0x02, + I2sSR32K = 0x03, + I2sSR48K = 0x05, + I2sSR44p1K = 0x15, + I2sSR96K = 0x06, + I2sSR88p2K = 0x16 +}I2S_SETTING_SR, *PI2S_SETTING_SR; +/* +typedef struct _I2S_SETTING_REG_ { + I2S_SETTING_PAGE_NUM PageNum; + I2S_SETTING_SR SampleRate; + + u32 PageSize:12; // Bit 0-11 +}I2S_SETTING_REG, *PI2S_SETTING_REG; + +typedef enum _I2S_TX_ISR { + I2sTxP0OK = 0x01, + I2sTxP1OK = 0x02, + I2sTxP2OK = 0x04, + I2sTxP3OK = 0x08, + I2sTxPageUn = 0x10, + I2sTxFifoEmpty = 0x20 +}I2S_TX_ISR, *PI2S_TX_ISR; + +typedef enum _I2S_RX_ISR { + I2sRxP0OK = 0x01, + I2sRxP1OK = 0x02, + I2sRxP2OK = 0x04, + I2sRxP3OK = 0x08, + I2sRxPageUn = 0x10, + I2sRxFifoFull = 0x20 +}I2S_RX_ISR, *PI2S_RX_ISR; +*/ + +/* Hal I2S function prototype*/ +RTK_STATUS +HalI2SInitRtl8195a( + IN VOID *Data +); + +RTK_STATUS +HalI2SInitRtl8195a_Patch( + IN VOID *Data +); + +RTK_STATUS +HalI2SDeInitRtl8195a( + IN VOID *Data +); + +RTK_STATUS +HalI2STxRtl8195a( + IN VOID *Data, + IN u8 *pBuff +); + +RTK_STATUS +HalI2SRxRtl8195a( + IN VOID *Data, + OUT u8 *pBuff +); + +RTK_STATUS +HalI2SEnableRtl8195a( + IN VOID *Data +); + +RTK_STATUS +HalI2SIntrCtrlRtl8195a( + IN VOID *Data +); + +u32 +HalI2SReadRegRtl8195a( + IN VOID *Data, + IN u8 I2SReg +); + +RTK_STATUS +HalI2SSetRateRtl8195a( + IN VOID *Data +); + +RTK_STATUS +HalI2SSetWordLenRtl8195a( + IN VOID *Data +); + +RTK_STATUS +HalI2SSetChNumRtl8195a( + IN VOID *Data +); + +RTK_STATUS +HalI2SSetPageNumRtl8195a( + IN VOID *Data +); + +RTK_STATUS +HalI2SSetPageSizeRtl8195a( + IN VOID *Data +); + +RTK_STATUS +HalI2SSetDirectionRtl8195a( + IN VOID *Data +); + +RTK_STATUS +HalI2SSetDMABufRtl8195a( + IN VOID *Data +); + +RTK_STATUS +HalI2SClrIntrRtl8195a( + IN VOID *Data +); + +RTK_STATUS +HalI2SClrAllIntrRtl8195a( + IN VOID *Data +); + +RTK_STATUS +HalI2SDMACtrlRtl8195a( + IN VOID *Data +); + +u8 +HalI2SGetTxPageRtl8195a( + IN VOID *Data +); + +u8 +HalI2SGetRxPageRtl8195a( + IN VOID *Data +); + +RTK_STATUS +HalI2SPageSendRtl8195a( + IN VOID *Data, + IN u8 PageIdx +); + +RTK_STATUS +HalI2SPageRecvRtl8195a( + IN VOID *Data +); + +RTK_STATUS +HalI2SClearAllOwnBitRtl8195a( + IN VOID *Data +); + +#ifdef CONFIG_CHIP_E_CUT +_LONG_CALL_ RTK_STATUS +HalI2SInitRtl8195a_V04( + IN VOID *Data +); + +_LONG_CALL_ RTK_STATUS +HalI2SSetRateRtl8195a_V04( + IN VOID *Data +); + +_LONG_CALL_ RTK_STATUS +HalI2SSetWordLenRtl8195a_V04( + IN VOID *Data +); + +_LONG_CALL_ RTK_STATUS +HalI2SSetChNumRtl8195a_V04( + IN VOID *Data +); + +_LONG_CALL_ RTK_STATUS +HalI2SSetPageNumRtl8195a_V04( + IN VOID *Data +); + +_LONG_CALL_ RTK_STATUS +HalI2SSetPageSizeRtl8195a_V04( + IN VOID *Data +); + +_LONG_CALL_ RTK_STATUS +HalI2SSetDirectionRtl8195a_V04( + IN VOID *Data +); + +_LONG_CALL_ RTK_STATUS +HalI2SSetDMABufRtl8195a_V04( + IN VOID *Data +); + +_LONG_CALL_ u8 +HalI2SGetTxPageRtl8195a_V04( + IN VOID *Data +); + +_LONG_CALL_ u8 +HalI2SGetRxPageRtl8195a_V04( + IN VOID *Data +); + +_LONG_CALL_ RTK_STATUS +HalI2SPageSendRtl8195a_V04( + IN VOID *Data, + IN u8 PageIdx +); + +_LONG_CALL_ RTK_STATUS +HalI2SPageRecvRtl8195a_V04( + IN VOID *Data +); + +_LONG_CALL_ RTK_STATUS +HalI2SClearAllOwnBitRtl8195a_V04( + IN VOID *Data +); + +#endif // #ifdef CONFIG_CHIP_E_CUT + +// HAL functions Wrapper +static __inline VOID +HalI2SSetRate( + IN VOID *Data +) +{ +#ifndef CONFIG_CHIP_E_CUT + HalI2SSetRateRtl8195a(Data); +#else + HalI2SSetRateRtl8195a_V04(Data); +#endif +} + +static __inline VOID +HalI2SSetWordLen( + IN VOID *Data +) +{ +#ifndef CONFIG_CHIP_E_CUT + HalI2SSetWordLenRtl8195a(Data); +#else + HalI2SSetWordLenRtl8195a_V04(Data); +#endif +} + +static __inline VOID +HalI2SSetChNum( + IN VOID *Data +) +{ +#ifndef CONFIG_CHIP_E_CUT + HalI2SSetChNumRtl8195a(Data); +#else + HalI2SSetChNumRtl8195a_V04(Data); +#endif +} + +static __inline VOID +HalI2SSetPageNum( + IN VOID *Data +) +{ +#ifndef CONFIG_CHIP_E_CUT + HalI2SSetPageNumRtl8195a(Data); +#else + HalI2SSetPageNumRtl8195a_V04(Data); +#endif +} + +static __inline VOID +HalI2SSetPageSize( + IN VOID *Data +) +{ +#ifndef CONFIG_CHIP_E_CUT + HalI2SSetPageSizeRtl8195a(Data); +#else + HalI2SSetPageSizeRtl8195a_V04(Data); +#endif +} + +static __inline VOID +HalI2SSetDirection( + IN VOID *Data +) +{ +#ifndef CONFIG_CHIP_E_CUT + HalI2SSetDirectionRtl8195a(Data); +#else + HalI2SSetDirectionRtl8195a_V04(Data); +#endif +} + +static __inline VOID +HalI2SSetDMABuf( + IN VOID *Data +) +{ +#ifndef CONFIG_CHIP_E_CUT + HalI2SSetDMABufRtl8195a(Data); +#else + HalI2SSetDMABufRtl8195a_V04(Data); +#endif +} + +static __inline u8 +HalI2SGetTxPage( + IN VOID *Data +) +{ +#ifndef CONFIG_CHIP_E_CUT + return HalI2SGetTxPageRtl8195a(Data); +#else + return HalI2SGetTxPageRtl8195a_V04(Data); +#endif +} + +static __inline u8 +HalI2SGetRxPage( + IN VOID *Data +) +{ +#ifndef CONFIG_CHIP_E_CUT + return HalI2SGetRxPageRtl8195a(Data); +#else + return HalI2SGetRxPageRtl8195a_V04(Data); +#endif +} + +static __inline VOID +HalI2SPageSend( + IN VOID *Data, + IN u8 PageIdx +) +{ +#ifndef CONFIG_CHIP_E_CUT + HalI2SPageSendRtl8195a(Data, PageIdx); +#else + HalI2SPageSendRtl8195a_V04(Data, PageIdx); +#endif +} + +static __inline VOID +HalI2SPageRecv( + IN VOID *Data +) +{ +#ifndef CONFIG_CHIP_E_CUT + HalI2SPageRecvRtl8195a(Data); +#else + HalI2SPageRecvRtl8195a_V04(Data); +#endif +} + +static __inline VOID +HalI2SClearAllOwnBit( + IN VOID *Data +) +{ +#ifndef CONFIG_CHIP_E_CUT + HalI2SClearAllOwnBitRtl8195a(Data); +#else + HalI2SClearAllOwnBitRtl8195a_V04(Data); +#endif +} + +#endif /* _RTL8195A_I2S_H_ */ + + diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a_pwm.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a_pwm.h index 9d7266096e..19e7fef38a 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a_pwm.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a_pwm.h @@ -37,6 +37,10 @@ HAL_Pwm_Disable_8195a( HAL_PWM_ADAPTER *pPwmAdapt ); +extern void +HAL_Pwm_Dinit_8195a( + HAL_PWM_ADAPTER *pPwmAdapt +); #ifdef CONFIG_CHIP_E_CUT extern _LONG_CALL_ void diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a_sdio.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a_sdio.h index 788413fea1..561ad06645 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a_sdio.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a_sdio.h @@ -13,46 +13,1028 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef MBED_RTL8195A_SDIO_H -#define MBED_RTL8195A_SDIO_H -__BUILD_CCTRL_MACRO(SDIOD, REG_PESOC_HCI_CLK_CTRL0) -__BUILD_CCTRL_MACRO(SDIOH, REG_PESOC_HCI_CLK_CTRL0) -#define __SDIOD_Enable() \ - do { \ - __RTK_PERI_SETBIT(REG_SOC_HCI_COM_FUNC_EN, BIT_SOC_HCI_SDIOD_ON_EN); \ - __RTK_PERI_SETBIT(REG_SOC_HCI_COM_FUNC_EN, BIT_SOC_HCI_SDIOD_OFF_EN); \ - } while (0) - -#define __SDIOH_Enable() \ - do { \ - __RTK_PERI_SETBIT(REG_SOC_HCI_COM_FUNC_EN, BIT_SOC_HCI_SDIOH_EN); \ - } while (0) - -#define __SDIOD_Disable() \ - do { \ - __RTK_READ32(SDIO_DEVICE_REG_BASE, 0); \ - __RTK_PERI_CLRBIT(REG_SOC_HCI_COM_FUNC_EN, BIT_SOC_HCI_SDIOD_ON_EN); \ - __RTK_PERI_CLRBIT(REG_SOC_HCI_COM_FUNC_EN, BIT_SOC_HCI_SDIOD_OFF_EN); \ - } while (0) - -#define __SDIOH_Disable() \ - do { \ - __RTK_READ32(SDIO_HOST_REG_BASE, 0); \ - __RTK_PERI_CLRBIT(REG_SOC_HCI_COM_FUNC_EN, BIT_SOC_HCI_SDIOH_EN); \ - } while (0) - -// PERI_MCTRL_HCI -#define __SDIOD_PINMUX_Enable() __RTK_PERI_SETBIT(REG_HCI_PINMUX_CTRL, BIT_HCI_SDIOD_PIN_EN) -#define __SDIOH_PINMUX_Enable() __RTK_PERI_SETBIT(REG_HCI_PINMUX_CTRL, BIT_HCI_SDIOH_PIN_EN) -#define __SDIOD_PINMUX_Disable() __RTK_PERI_CLRBIT(REG_HCI_PINMUX_CTRL, BIT_HCI_SDIOD_PIN_EN) -#define __SDIOH_PINMUX_Disable() __RTK_PERI_CLRBIT(REG_HCI_PINMUX_CTRL, BIT_HCI_SDIOH_PIN_EN) -#define __MII_PINMUX_Enable() __RTK_PERI_SETBIT(REG_HCI_PINMUX_CTRL, BIT_HCI_MII_PIN_EN) -#define __MII_PINMUX_Disable() __RTK_PERI_CLRBIT(REG_HCI_PINMUX_CTRL, BIT_HCI_MII_PIN_EN) - -// Interface for HAL functions -extern void SDIO_HST_Disable(void); -extern void SDIO_DEV_Disable(void); +#ifndef _RTL8195A_SDIO_H_ +#define _RTL8195A_SDIO_H_ +#include "hal_api.h" +#include "hal_util.h" +#if defined(CONFIG_SDIO_BOOT_SIM) || defined(CONFIG_SDIO_BOOT_ROM) +#define SDIO_BOOT_DRIVER 1 // is this SDIO driver works for booting +#else +#include "osdep_api.h" +#define SDIO_BOOT_DRIVER 0 // is this SDIO driver works for booting #endif + +#if defined(__IAR_SYSTEMS_ICC__) //for IAR SDK +#include "platform_opts.h" +#endif + +#ifndef CONFIG_INIC_EN +#define CONFIG_INIC_EN 0 +#endif +#if CONFIG_INIC_EN +#define CONFIG_INIC_SKB_TX 1 //use SKB for trx to improve the throughput +#define CONFIG_INIC_SKB_RX 1 +#endif + +#if defined(__IAR_SYSTEMS_ICC__) && (CONFIG_INIC_EN == 0)//for IAR SDK + #define SDIO_API_DEFINED 1 +#else + #define SDIO_API_DEFINED 0 +#endif + +#ifndef PRIORITIE_OFFSET //PRIORITIE_OFFSET in FreeRTOSConfig.h +#define PRIORITIE_OFFSET 0 +#endif + +#define SDIO_DEBUG 0 +#define SDIO_MP_MODE 0 // if includes MP mode function +#define SDIO_MAX_WAIT_RX_DMA 100 // Wait RX DMA done +#define SDIO_RX_PKT_SIZE_OVER_16K 0 /* is support SDIO RX packet size > 16K. if true, + a big packet will be transmited via multiple RX_BD */ +#define SDIO_MAILBOX_SIZE 10 // the maximum number of message block can be stored in this mailbox +#define SDIO_PERIODICAL_TIMER_INTERVAL 2000 // in ms, the interval of SDIO periodical timer +#define SDIO_AVG_TP_WIN_SIZE 20 // the number of entry to log the byte count for every periodical timer statistic, to calculate throughput + +#define HAL_SDIO_READ32(addr) HAL_READ32(SDIO_DEVICE_REG_BASE, addr) +#define HAL_SDIO_WRITE32(addr, value) HAL_WRITE32(SDIO_DEVICE_REG_BASE, addr, value) +#define HAL_SDIO_READ16(addr) HAL_READ16(SDIO_DEVICE_REG_BASE, addr) +#define HAL_SDIO_WRITE16(addr, value) HAL_WRITE16(SDIO_DEVICE_REG_BASE, addr, value) +#define HAL_SDIO_READ8(addr) HAL_READ8(SDIO_DEVICE_REG_BASE, addr) +#define HAL_SDIO_WRITE8(addr, value) HAL_WRITE8(SDIO_DEVICE_REG_BASE, addr, value) + +/***** Register Address *****/ +#define REG_SPDIO_TXBD_ADDR 0xA0 // 4 Bytes +#define REG_SPDIO_TXBD_SIZE 0xA4 // 4 Bytes +#define REG_SPDIO_TXBD_WPTR 0xA8 // 2 Bytes +#define REG_SPDIO_TXBD_RPTR 0xAC // 2 Bytes +#define REG_SPDIO_RXBD_ADDR 0xB0 // 4 Bytes +#define REG_SPDIO_RXBD_SIZE 0xB4 // 2 Bytes +#define REG_SPDIO_RXBD_C2H_WPTR 0xB6 // 2 Bytes +#define REG_SPDIO_RXBD_C2H_RPTR 0xB8 // 2 Bytes +#define REG_SPDIO_HCI_RX_REQ 0xBA // 1 Byte +#define REG_SPDIO_CPU_RST_DMA 0xBB // 1 Byte +#define REG_SPDIO_RX_REQ_ADDR 0xBC // 2 Bytes +#define REG_SPDIO_CPU_INT_MASK 0xC0 // 2 Bytes +#define REG_SPDIO_CPU_INT_STAS 0xC2 // 2 Bytes +#define REG_SPDIO_CCPWM 0xC4 // 1 Byts +#define REG_SPDIO_CPU_IND 0xC5 // 1 Byte +#define REG_SPDIO_CCPWM2 0xC6 // 2 Bytes +#define REG_SPDIO_CPU_H2C_MSG 0xC8 // 4 Bytes +#define REG_SPDIO_CPU_C2H_MSG 0xCC // 4 Bytes +#define REG_SPDIO_CRPWM 0xD0 // 1 Bytes +#define REG_SPDIO_CRPWM2 0xD2 // 2 Bytes +#define REG_SPDIO_AHB_DMA_CTRL 0xD4 // 4 Bytes +#define REG_SPDIO_RXBD_CNT 0xD8 // 4 Bytes +#define REG_SPDIO_TX_BUF_UNIT_SZ 0xD9 // 1 Bytes +#define REG_SPDIO_RX_BD_FREE_CNT 0xDA // 2 Bytes +#define REG_SPDIO_CPU_H2C_MSG_EXT 0xDC // 4 Bytes +#define REG_SPDIO_CPU_C2H_MSG_EXT 0xE0 // 4 Bytes + +// Register REG_SPDIO_CPU_RST_DMA +#define BIT_CPU_RST_SDIO_DMA BIT(7) + +// Register REG_SPDIO_CPU_INT_MASK, REG_SPDIO_CPU_INT_STAS +#define BIT_TXFIFO_H2C_OVF BIT(0) +#define BIT_H2C_BUS_RES_FAIL BIT(1) +#define BIT_H2C_DMA_OK BIT(2) +#define BIT_C2H_DMA_OK BIT(3) +#define BIT_H2C_MSG_INT BIT(4) +#define BIT_RPWM1_INT BIT(5) +#define BIT_RPWM2_INT BIT(6) +#define BIT_SDIO_RST_CMD_INT BIT(7) +#define BIT_RXBD_FLAG_ERR_INT BIT(8) +#define BIT_RX_BD_AVAI_INT BIT(9) +#define BIT_HOST_WAKE_CPU_INT BIT(10) + +// Register REG_SPDIO_CPU_IND +#define BIT_SYSTEM_TRX_RDY_IND BIT(0) + +// Register REG_SPDIO_HCI_RX_REQ +#define BIT_HCI_RX_REQ BIT(0) + +/* Register for SOC_HCI_COM_FUN_EN */ +#define BIT_SOC_HCI_SDIOD_OFF_EN BIT(1) // SDIO Function Block on Power_Off domain +#define BIT_SOC_HCI_SDIOD_ON_EN BIT(0) // SDIO Function Block on Power_On domain + +/* Register REG_PESOC_HCI_CLK_CTRL0 */ +#define BIT_SOC_SLPCK_SDIO_HST_EN BIT(3) // SDIO_HST clock enable when CPU sleep command +#define BIT_SOC_ACTCK_SDIO_HST_EN BIT(2) // SDIO_HST clock enable in CPU run mode +#define BIT_SOC_SLPCK_SDIO_DEV_EN BIT(1) // SDIO_DEV clock enable when CPU sleep command +#define BIT_SOC_ACTCK_SDIO_DEV_EN BIT(0) // SDIO_DEV clock enable in CPU run mode + +/***** Structer for each Register *****/ +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) +// Little Endian +// Register REG_SPDIO_HCI_RX_REQ @ 0xBA +typedef struct _SPDIO_HCI_RX_REQ { + u8 HCI_RX_REQ:1; /* bit[0], CPU trigger this bit to enable SDIO IP RX transfer by fetch BD info */ + u8 Reserved:7; /* bit[7:1], Reserved */ +} SPDIO_HCI_RX_REQ, *PSPDIO_HCI_RX_REQ; + +// Register REG_SPDIO_CPU_RST_DMA @ 0xBB +typedef struct _SPDIO_CPU_RST_DMA { + u8 Reserved:7; /* bit[6:0], Reserved */ + u8 CPU_RST_SDIO:1; /* bit[7], CPU set this bit to reset SDIO DMA */ +} SPDIO_CPU_RST_DMA, *PSPDIO_CPU_RST_DMA; + +// Register REG_SPDIO_CPU_INT_MASK @ 0xC0 +typedef struct _SPDIO_CPU_INT_MASK { + u16 TXFIFO_H2C_OVF:1; /* bit[0], set 0 to mask TXFIFO_H2C_OVF_INT */ + u16 H2C_BUS_RES_FAIL:1; /* bit[1], set 0 to mask H2C_BUS_RES_FAIL_INT */ + u16 H2C_DMA_OK:1; /* bit[2], set 0 to mask H2C_DMA_OK_INT */ + u16 C2H_DMA_OK:1; /* bit[3], set 0 to mask C2H_DMA_OK_INT */ + u16 H2C_MSG_INT:1; /* bit[4], set 0 to mask H2C_MSG_INT_INT */ + u16 RPWM_INT:1; /* bit[5], set 0 to mask RPWM_INT */ + u16 RPWM2_INT:1; /* bit[6], set 0 to mask RPWM2_INT */ + u16 SDIO_RST_CMD_INT:1; /* bit[7], set 0 to mask SDIO_RST_CMD_INT */ + u16 BD_FLAG_ERR_INT:1; /* bit[8], set 0 to mask BD_FLAG_ERR_INT */ + u16 Reserved:7; /* bit[15:9], Reserved */ +} SPDIO_CPU_INT_MASK, *PSPDIO_CPU_INT_MASK; + +// Register REG_SPDIO_CPU_INT_STATUS @ 0xC2 +typedef struct _SPDIO_CPU_INT_STAS { + u16 TXFIFO_H2C_OVF:1; /* bit[0], set 0 to mask TXFIFO_H2C_OVF_INT */ + u16 H2C_BUS_RES_FAIL:1; /* bit[1], set 0 to mask H2C_BUS_RES_FAIL_INT */ + u16 H2C_DMA_OK:1; /* bit[2], set 0 to mask H2C_DMA_OK_INT */ + u16 C2H_DMA_OK:1; /* bit[3], set 0 to mask C2H_DMA_OK_INT */ + u16 H2C_MSG_INT:1; /* bit[4], set 0 to mask H2C_MSG_INT_INT */ + u16 RPWM_INT:1; /* bit[5], set 0 to mask RPWM_INT */ + u16 RPWM2_INT:1; /* bit[6], set 0 to mask RPWM2_INT */ + u16 SDIO_RST_CMD_INT:1; /* bit[7], set 0 to mask SDIO_RST_CMD_INT */ + u16 BD_FLAG_ERR_INT:1; /* bit[8], set 0 to mask BD_FLAG_ERR_INT */ + u16 Reserved:7; /* bit[15:9], Reserved */ +} SPDIO_CPU_INT_STAS, *PSPDIO_CPU_INT_STAS; + +// Register REG_SPDIO_CCPWM @ 0xC4 +typedef struct _SPDIO_CCPWM { + u8 :1; /* bit[0] */ + u8 WLAN_TRX:1; /* bit[1], 0: WLAN Off; 1: WLAN On */ + u8 RPS_ST:1; /* bit[2], 0/1: AP Register Sleep/Active state */ + u8 WWLAN:1; /* bit[3], 0/1: "Wake on WLAN"/"Normal" state */ + u8 Reserved:3; /* bit[6:4], Reserved */ + u8 TOGGLING:1; /* bit[7], issue interrupt when 0->1 or 1->0 */ +} SPDIO_CCPWM, *PSPDIO_CCPWM; + +// Register REG_SPDIO_CPU_IND @ 0xC5 +typedef struct _SPDIO_CPU_IND { + u8 SYS_TRX_RDY:1; /* bit[0], To indicate the Host system that CPU is ready for TRX + , to be sync to 0x87[0] */ + u8 Reserved:7; /* bit[7:1], Reserved */ +} SPDIO_CPU_IND, *PSPDIO_CPU_IND; + +// Register REG_SPDIO_CPU_H2C_MSG @ 0xC8 +typedef struct _SPDIO_CPU_H2C_MSG { + u32 CPU_H2C_MSG:30; /* bit[30:0], Host CPU to FW message, sync from REG_SDIO_H2C_MSG */ + u32 Reserved:1; /* bit[31], Reserved */ +} SPDIO_CPU_H2C_MSG, *PSPDIO_CPU_H2C_MSG; + +// Register REG_SPDIO_CPU_C2H_MSG @ 0xCC +typedef struct _SPDIO_CPU_C2H_MSG { + u32 CPU_C2H_MSG:30; /* bit[30:0], FW to Host CPU message, sync to REG_SDIO_C2H_MSG */ + u32 Reserved:1; /* bit[31], Reserved */ +} SPDIO_CPU_C2H_MSG, *PSPDIO_CPU_C2H_MSG; + +// Register REG_SPDIO_CRPWM @ 0xD0 +typedef struct _SPDIO_CRPWM { + u8 :1; /* bit[0] */ + u8 WLAN_TRX:1; /* bit[1], 0: WLAN Off; 1: WLAN On */ + u8 RPS_ST:1; /* bit[2], 0/1: AP Register Sleep/Active state */ + u8 WWLAN:1; /* bit[3], 0/1: "Wake on WLAN"/"Normal" state */ + u8 Reserved:3; /* bit[6:4], Reserved */ + u8 TOGGLING:1; /* bit[7], issue interrupt when 0->1 or 1->0 */ +} SPDIO_CRPWM, *PSPDIO_CRPWM; + +// Register REG_SPDIO_AHB_DMA_CTRL @ 0xD4 +typedef struct _SPDIO_AHB_DMA_CTRL { + u32 TXFF_WLEVEL:7; /* bit[6:0], SPDIO TX FIFO water level */ + u32 :1; /* bit[7] */ + u32 RXFF_WLEVEL:7; /* bit[14:8], SPDIO RX FIFO water level */ + u32 :1; /* bit[15] */ + u32 AHB_DMA_CS:4; /* bit[19:16], AHB DMA state */ + u32 :1; /* bit[20] */ + u32 AHB_MASTER_RDY:1; /* bit[21], AHB Master Hready signal */ + u32 AHB_DMA_TRANS:2; /* bit[23:22], AHB DMA Trans value, for debugging */ + u32 AHB_BUSY_WAIT_CNT:4; /* bit[27:24], timeout for AHB controller to wait busy */ + u32 AHB_BURST_TYPE:3; /* bit[30:28], AHB burst type */ + u32 DISPATCH_TXAGG:1; /* bit[31], Enable to dispatch aggregated TX packet */ +} SPDIO_AHB_DMA_CTRL, *PSPDIO_AHB_DMA_CTRL; + +#else /* else of '#if LITTLE_ENDIAN' */ +// Big Endian +typedef struct _SPDIO_HCI_RX_REQ { + u8 Reserved:7; /* bit[7:1], Reserved */ + u8 HCI_RX_REQ:1; /* bit[0], CPU trigger this bit to enable SDIO IP RX transfer by fetch BD info */ +} SPDIO_HCI_RX_REQ, *PSPDIO_HCI_RX_REQ; + +// Register REG_SPDIO_CPU_RST_DMA @ 0xBB +typedef struct _SPDIO_CPU_RST_DMA { + u8 CPU_RST_SDIO:1; /* bit[7], CPU set this bit to reset SDIO DMA */ + u8 Reserved:7; /* bit[6:0], Reserved */ +} SPDIO_CPU_RST_DMA, *PSPDIO_CPU_RST_DMA; + +// Register REG_SPDIO_CPU_INT_MASK @ 0xC0 +typedef struct _SPDIO_CPU_INT_MASK { + u16 Reserved:7; /* bit[15:9], Reserved */ + u16 BD_FLAG_ERR_INT:1; /* bit[8], set 0 to mask BD_FLAG_ERR_INT */ + u16 SDIO_RST_CMD_INT:1; /* bit[7], set 0 to mask SDIO_RST_CMD_INT */ + u16 RPWM2_INT:1; /* bit[6], set 0 to mask RPWM2_INT */ + u16 RPWM_INT:1; /* bit[5], set 0 to mask RPWM_INT */ + u16 H2C_MSG_INT:1; /* bit[4], set 0 to mask H2C_MSG_INT_INT */ + u16 C2H_DMA_OK:1; /* bit[3], set 0 to mask C2H_DMA_OK_INT */ + u16 H2C_DMA_OK:1; /* bit[2], set 0 to mask H2C_DMA_OK_INT */ + u16 H2C_BUS_RES_FAIL:1; /* bit[1], set 0 to mask H2C_BUS_RES_FAIL_INT */ + u16 TXFIFO_H2C_OVF:1; /* bit[0], set 0 to mask TXFIFO_H2C_OVF_INT */ +} SPDIO_CPU_INT_MASK, *PSPDIO_CPU_INT_MASK; + +// Register REG_SPDIO_CPU_INT_STAS @ 0xC2 +typedef struct _SPDIO_CPU_INT_STAS { + u16 Reserved:7; /* bit[15:9], Reserved */ + u16 BD_FLAG_ERR_INT:1; /* bit[8], set 0 to mask BD_FLAG_ERR_INT */ + u16 SDIO_RST_CMD_INT:1; /* bit[7], set 0 to mask SDIO_RST_CMD_INT */ + u16 RPWM2_INT:1; /* bit[6], set 0 to mask RPWM2_INT */ + u16 RPWM_INT:1; /* bit[5], set 0 to mask RPWM_INT */ + u16 H2C_MSG_INT:1; /* bit[4], set 0 to mask H2C_MSG_INT_INT */ + u16 C2H_DMA_OK:1; /* bit[3], set 0 to mask C2H_DMA_OK_INT */ + u16 H2C_DMA_OK:1; /* bit[2], set 0 to mask H2C_DMA_OK_INT */ + u16 H2C_BUS_RES_FAIL:1; /* bit[1], set 0 to mask H2C_BUS_RES_FAIL_INT */ + u16 TXFIFO_H2C_OVF:1; /* bit[0], set 0 to mask TXFIFO_H2C_OVF_INT */ +} SPDIO_CPU_INT_STAS, *PSPDIO_CPU_INT_STAS; + +// Register REG_SPDIO_CCPWM @ 0xC4 +typedef struct _SPDIO_CCPWM { + u8 TOGGLING:1; /* bit[7], issue interrupt when 0->1 or 1->0 */ + u8 Reserved:3; /* bit[6:4], Reserved */ + u8 WWLAN:1; /* bit[3], 0/1: "Wake on WLAN"/"Normal" state */ + u8 RPS_ST:1; /* bit[2], 0/1: AP Register Sleep/Active state */ + u8 WLAN_TRX:1; /* bit[1], 0: WLAN Off; 1: WLAN On */ + u8 :1; /* bit[0] */ +} SPDIO_CCPWM, *PSPDIO_CCPWM; + +// Register REG_SPDIO_CPU_IND @ 0xC5 +typedef struct _SPDIO_CPU_IND { + u8 Reserved:7; /* bit[7:1], Reserved */ + u8 SYS_TRX_RDY:1; /* bit[0], To indicate the Host system that CPU is ready for TRX + , to be sync to 0x87[0] */ +} SPDIO_CPU_IND, *PSPDIO_CPU_IND; + +// Register REG_SPDIO_CPU_H2C_MSG @ 0xC8 +typedef struct _SPDIO_CPU_H2C_MSG { + u32 Reserved:1; /* bit[31], Reserved */ + u32 CPU_H2C_MSG:30; /* bit[30:0], Host CPU to FW message */ +} SPDIO_CPU_H2C_MSG, *PSPDIO_CPU_H2C_MSG; + +// Register REG_SPDIO_CPU_C2H_MSG @ 0xCC +typedef struct _SPDIO_CPU_C2H_MSG { + u32 Reserved:1; /* bit[31], Reserved */ + u32 CPU_C2H_MSG:30; /* bit[30:0], FW to Host CPU message, sync to REG_SDIO_C2H_MSG */ +} SPDIO_CPU_C2H_MSG, *PSPDIO_CPU_C2H_MSG; + +// Register REG_SPDIO_CRPWM @ 0xD0 +typedef struct _SPDIO_CRPWM { + u8 TOGGLING:1; /* bit[7], issue interrupt when 0->1 or 1->0 */ + u8 Reserved:3; /* bit[6:4], Reserved */ + u8 WWLAN:1; /* bit[3], 0/1: "Wake on WLAN"/"Normal" state */ + u8 RPS_ST:1; /* bit[2], 0/1: AP Register Sleep/Active state */ + u8 WLAN_TRX:1; /* bit[1], 0: WLAN Off; 1: WLAN On */ + u8 :1; /* bit[0] */ +} SPDIO_CRPWM, *PSPDIO_CRPWM; + +// Register REG_SPDIO_AHB_DMA_CTRL @ 0xD4 +typedef struct _SPDIO_AHB_DMA_CTRL { + u32 DISPATCH_TXAGG:1; /* bit[31], Enable to dispatch aggregated TX packet */ + u32 AHB_BURST_TYPE:3; /* bit[30:28], AHB burst type */ + u32 AHB_BUSY_WAIT_CNT:4; /* bit[27:24], timeout for AHB controller to wait busy */ + u32 AHB_DMA_TRANS:2; /* bit[23:22], AHB DMA Trans value, for debugging */ + u32 AHB_MASTER_RDY:1; /* bit[21], AHB Master Hready signal */ + u32 :1; /* bit[20] */ + u32 AHB_DMA_CS:4; /* bit[19:16], AHB DMA state */ + u32 :1; /* bit[15] */ + u32 RXFF_WLEVEL:7; /* bit[14:8], SPDIO RX FIFO water level */ + u32 :1; /* bit[7] */ + u32 TXFF_WLEVEL:7; /* bit[6:0], SPDIO TX FIFO water level */ +} SPDIO_AHB_DMA_CTRL, *PSPDIO_AHB_DMA_CTRL; + +#endif /* end of '#if LITTLE_ENDIAN' */ + + +//#define TX_FIFO_ADDR 0x0000 +//#define TX_FIFO_SIZE 0x8000 + +//TX BD setting +#if SDIO_BOOT_DRIVER +// for build ROM library +#define SDIO_TX_BD_NUM 2 // Number of TX BD +#define SDIO_TX_BD_BUF_SIZE (2048+32) // the size of a TX BD pointed buffer, WLan header = 26 bytes +#define SDIO_TX_PKT_NUM 10 // Number of TX packet handler + +//RX BD setting +#define RX_BD_FREE_TH 4 // trigger the interrupt when free RX BD over this threshold + +#define MAX_RX_BD_BUF_SIZE 16380 // the Maximum size for a RX_BD point to, make it 4-bytes aligned + +#define SDIO_RX_PKT_NUM 3 // Number of RX packet handler +//#define SDIO_RX_BD_NUM 10 // Number of RX BD, to make 32K of bus aggregation, it needs 22 RX_BD at least +#define SDIO_RX_BD_NUM (SDIO_RX_PKT_NUM*2) // Number of RX BD, to make 32K of bus aggregation, it needs 22 RX_BD at least +#define SDIO_RX_BD_BUF_SIZE (2048+24) // the size of a RX BD pointed buffer, sizeof(RX Desc) = 26 bytes +#define MIN_RX_BD_SEND_PKT 2 /* the minum needed RX_BD to send a Packet to Host, we need 2: + one for RX_Desc, the other for payload */ + +// CCPWM2 bit map definition for Firmware download +#define SDIO_INIT_DONE (BIT0) +#define SDIO_MEM_WR_DONE (BIT1) +#define SDIO_MEM_RD_DONE (BIT2) +#define SDIO_MEM_ST_DONE (BIT3) + +#define SDIO_CPWM2_TOGGLE (BIT15) + +#else +#if CONFIG_INIC_EN +//TX BD setting +#define SDIO_TX_BD_NUM 20 // Number of TX BD +#define SDIO_TX_BD_BUF_SIZE 1540 //1514+24 +//#define SDIO_TX_PKT_NUM 1 // not used + +//RX BD setting +#define RX_BD_FREE_TH 5 // trigger the interrupt when free RX BD over this threshold +#define SDIO_RX_BD_BUF_SIZE 1540 //1514+24 +#define MAX_RX_BD_BUF_SIZE 16380 // the Maximum size for a RX_BD point to, make it 4-bytes aligned +#define SDIO_RX_BD_NUM 32 // Number of RX BD, to make 32K of bus aggregation, it needs 22 RX_BD at least +#define SDIO_RX_PKT_NUM 128 // Number of RX packet handler +#define MIN_RX_BD_SEND_PKT 2 /* the minum needed RX_BD to send a Packet to Host, we need 2: + one for RX_Desc, the other for payload */ + +#else +#define SDIO_TX_BD_NUM 24 // Number of TX BD +#define SDIO_TX_BD_BUF_SIZE (2048+32) // the size of a TX BD pointed buffer, WLan header = 26 bytes +#define SDIO_TX_PKT_NUM 128 // Number of TX packet handler + +//RX BD setting +#define RX_BD_FREE_TH 5 // trigger the interrupt when free RX BD over this threshold + +#define SDIO_RX_BD_BUF_SIZE 2048 +#define MAX_RX_BD_BUF_SIZE 16380 // the Maximum size for a RX_BD point to, make it 4-bytes aligned + +//#define SDIO_TX_FIFO_SIZE (1024*64) // 64K +#define SDIO_RX_BD_NUM 24 // Number of RX BD, to make 32K of bus aggregation, it needs 22 RX_BD at least +#define SDIO_RX_PKT_NUM 128 // Number of RX packet handler +#define MIN_RX_BD_SEND_PKT 2 /* the minum needed RX_BD to send a Packet to Host, we need 2: + one for RX_Desc, the other for payload */ +#endif +#endif + +#define SDIO_IRQ_PRIORITY 10 + +/* SDIO Events */ +#define SDIO_EVENT_IRQ BIT(0) // Interrupt triggered +#define SDIO_EVENT_RX_PKT_RDY BIT(1) // A new SDIO packet ready +#define SDIO_EVENT_C2H_DMA_DONE BIT(2) // Interrupt of C2H DMA done triggered +#define SDIO_EVENT_DUMP BIT(3) // SDIO status dump periodically Enable +#define SDIO_EVENT_TXBD_REFILL BIT(4) // To refill TX BD buffer +#define SDIO_EVENT_EXIT BIT(28) // Request to exit the SDIO task +#define SDIO_EVENT_MP_STOPPED BIT(29) // The SDIO task is stopped +#define SDIO_EVENT_TX_STOPPED BIT(30) // The SDIO task is stopped +#define SDIO_EVENT_RX_STOPPED BIT(31) // The SDIO task is stopped + +#define SDIO_TASK_PRIORITY 1 // it can be 0(lowest) ~ configMAX_PRIORITIES-1(highest) +#define SDIO_MP_TASK_PRIORITY 2 // it can be 0(lowest) ~ configMAX_PRIORITIES-1(highest) +//#if SDIO_TASK_PRIORITY > (configMAX_PRIORITIES - 1) +#if SDIO_TASK_PRIORITY > (4 - 1) +#error "SDIO Task Priority Should be 0~(configMAX_PRIORITIES-1)" +#endif + +//#define TX_RX_PACKET_SIZE 0x144 + +typedef struct _SDIO_TX_BD_ { + u32 Address; /* The TX buffer physical address, it must be 4-bytes aligned */ +}SDIO_TX_BD, *PSDIO_TX_BD; + +#define TX_BD_STRUCTURE_SIZE (sizeof(SDIO_TX_BD)) + + +/* The RX Buffer Descriptor format */ + +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) +typedef struct _SDIO_RX_BD_ { + u32 BuffSize:14; /* bit[13:0], RX Buffer Size, Maximum 16384-1 */ + u32 LS:1; /* bit[14], is the Last Segment ? */ + u32 FS:1; /* bit[15], is the First Segment ? */ + u32 Seq:16; /* bit[31:16], The sequence number, it's no use for now */ + u32 PhyAddr; /* The RX buffer physical address, it must be 4-bytes aligned */ +} SDIO_RX_BD, *PSDIO_RX_BD; +#else +typedef struct _SDIO_RX_BD_ { + u32 Seq:16; /* bit[31:16], The sequence number, be used for ?? */ + u32 FS:1; /* bit[15], is the First Segment ? */ + u32 LS:1; /* bit[14], is the Last Segment ? */ + u32 BuffSize:14; /* bit[13:0], RX Buffer Size, Maximum 16384 */ + u32 PhyAddr; /* The RX buffer physical address, it must be 4-bytes aligned */ +} SDIO_RX_BD, *PSDIO_RX_BD; +#endif +#define RX_BD_STRUCTURE_SIZE (sizeof(SDIO_RX_BD)) + +// TODO: This data structer just for test, we should modify it for the normal driver +typedef struct _SDIO_TX_DESC{ + // u4Byte 0 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 txpktsize:16; // bit[15:0] + u32 offset:8; // bit[23:16], store the sizeof(SDIO_TX_DESC) + u32 bus_agg_num:8; // bit[31:24], the bus aggregation number +#else + u32 bus_agg_num:8; // bit[31:24], the bus aggregation number + u32 offset:8; // bit[23:16], store the sizeof(SDIO_TX_DESC) + u32 txpktsize:16; // bit[15:0] +#endif + + // u4Byte 1 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 type:8; // bit[7:0], the packet type + u32 rsvd0:24; +#else + u32 rsvd0:24; + u32 type:8; // bit[7:0], the packet type +#endif + + // u4Byte 2 + u32 rsvd1; + + // u4Byte 3 + u32 rsvd2; + + // u4Byte 4 + u32 rsvd3; + + // u4Byte 5 + u32 rsvd4; +} SDIO_TX_DESC, *PSDIO_TX_DESC; + +// TX Desc for Memory Write command +typedef struct _SDIO_TX_DESC_MW{ + // u4Byte 0 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 txpktsize:16; // bit[15:0] + u32 offset:8; // bit[23:16], store the sizeof(SDIO_TX_DESC) + u32 bus_agg_num:8; // bit[31:24], the bus aggregation number +#else + u32 bus_agg_num:8; // bit[31:24], the bus aggregation number + u32 offset:8; // bit[23:16], store the sizeof(SDIO_TX_DESC) + u32 txpktsize:16; // bit[15:0] +#endif + + // u4Byte 1 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 type:8; // bit[7:0], the packet type + u32 reply:1; // bit[8], request to send a reply message + u32 rsvd0:23; +#else + u32 rsvd0:23; + u32 reply:1; // bit[8], request to send a reply message + u32 type:8; // bit[7:0], the packet type +#endif + + // u4Byte 2 + u32 start_addr; // memory write start address + + // u4Byte 3 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 write_len:16; // bit[15:0], the length to write + u32 rsvd2:16; // bit[31:16] +#else + u32 rsvd2:16; // bit[31:16] + u32 write_len:16; // bit[15:0], the length to write +#endif + + // u4Byte 4 + u32 rsvd3; + + // u4Byte 5 + u32 rsvd4; +} SDIO_TX_DESC_MW, *PSDIO_TX_DESC_MW; + +// TX Desc for Memory Read command +typedef struct _SDIO_TX_DESC_MR{ + // u4Byte 0 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 txpktsize:16; // bit[15:0] + u32 offset:8; // bit[23:16], store the sizeof(SDIO_TX_DESC) + u32 bus_agg_num:8; // bit[31:24], the bus aggregation number +#else + u32 bus_agg_num:8; // bit[31:24], the bus aggregation number + u32 offset:8; // bit[23:16], store the sizeof(SDIO_TX_DESC) + u32 txpktsize:16; // bit[15:0] +#endif + + // u4Byte 1 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 type:8; // bit[7:0], the packet type + u32 rsvd0:24; +#else + u32 rsvd0:24; + u32 type:8; // bit[7:0], the packet type +#endif + + // u4Byte 2 + u32 start_addr; // memory write start address + + // u4Byte 3 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 read_len:16; // bit[15:0], the length to read + u32 rsvd2:16; // bit[31:16] +#else + u32 rsvd2:16; // bit[31:16] + u32 read_len:16; // bit[15:0], the length to read +#endif + + // u4Byte 4 + u32 rsvd3; + + // u4Byte 5 + u32 rsvd4; +} SDIO_TX_DESC_MR, *PSDIO_TX_DESC_MR; + +// TX Desc for Memory Set command +typedef struct _SDIO_TX_DESC_MS{ + // u4Byte 0 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 txpktsize:16; // bit[15:0] + u32 offset:8; // bit[23:16], store the sizeof(SDIO_TX_DESC) + u32 bus_agg_num:8; // bit[31:24], the bus aggregation number +#else + u32 bus_agg_num:8; // bit[31:24], the bus aggregation number + u32 offset:8; // bit[23:16], store the sizeof(SDIO_TX_DESC) + u32 txpktsize:16; // bit[15:0] +#endif + + // u4Byte 1 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 type:8; // bit[7:0], the packet type + u32 data:8; // bit[8:15], the value to be written to the memory + u32 reply:1; // bit[16], request to send a reply message + u32 rsvd0:15; +#else + u32 rsvd0:15; + u32 reply:1; // bit[16], request to send a reply message + u32 data:8; // bit[8:15], the value to be written to the memory + u32 type:8; // bit[7:0], the packet type +#endif + + // u4Byte 2 + u32 start_addr; // memory write start address + + // u4Byte 3 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 write_len:16; // bit[15:0], the length to write + u32 rsvd2:16; // bit[31:16] +#else + u32 rsvd2:16; // bit[31:16] + u32 write_len:16; // bit[15:0], the length to write +#endif + + // u4Byte 4 + u32 rsvd3; + + // u4Byte 5 + u32 rsvd4; +} SDIO_TX_DESC_MS, *PSDIO_TX_DESC_MS; + +// TX Desc for Jump to Start command +typedef struct _SDIO_TX_DESC_JS{ + // u4Byte 0 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 txpktsize:16; // bit[15:0] + u32 offset:8; // bit[23:16], store the sizeof(SDIO_TX_DESC) + u32 bus_agg_num:8; // bit[31:24], the bus aggregation number +#else + u32 bus_agg_num:8; // bit[31:24], the bus aggregation number + u32 offset:8; // bit[23:16], store the sizeof(SDIO_TX_DESC) + u32 txpktsize:16; // bit[15:0] +#endif + + // u4Byte 1 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 type:8; // bit[7:0], the packet type + u32 rsvd0:24; +#else + u32 rsvd0:24; + u32 type:8; // bit[7:0], the packet type +#endif + + // u4Byte 2 + u32 start_fun; // the pointer of the startup function + + // u4Byte 3 + u32 rsvd2; + + // u4Byte 4 + u32 rsvd3; + + // u4Byte 5 + u32 rsvd4; +} SDIO_TX_DESC_JS, *PSDIO_TX_DESC_JS; + + +#define SIZE_TX_DESC (sizeof(SDIO_TX_DESC)) +// define the TX BD buffer size with unite of 64 byets +/* Be carefull!! the setting of hardware's TX BD buffer size may exceed the real size of + the TX BD buffer size, and then it may cause the hardware DMA write the buffer overflow */ +#define SDIO_TX_BUF_SZ_UNIT 64 +#define SDIO_TX_BD_BUF_USIZE ((((SDIO_TX_BD_BUF_SIZE+sizeof(SDIO_TX_DESC)-1)/SDIO_TX_BUF_SZ_UNIT)+1)&0xff) + +typedef struct _SDIO_TX_BD_BUFFER_ { + SDIO_TX_DESC TX_Desc; + u8 TX_Buffer[SDIO_TX_BD_BUF_SIZE]; +}SDIO_TX_BD_BUFFER, *PSDIO_TX_BD_BUFFER; + + +// TODO: This data structer just for test, we should modify it for the normal driver +typedef struct _SDIO_RX_DESC{ + // u4Byte 0 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 pkt_len:16; // bit[15:0], the packet size + u32 offset:8; // bit[23:16], the offset from the packet start to the buf start, also means the size of RX Desc + u32 rsvd0:6; // bit[29:24] + u32 icv:1; // bit[30], ICV error + u32 crc:1; // bit[31], CRC error +#else + u32 crc:1; // bit[31], CRC error + u32 icv:1; // bit[30], ICV error + u32 rsvd0:6; // bit[29:24] + u32 offset:8; // bit[23:16], the offset from the packet start to the buf start, also means the size of RX Desc + u32 pkt_len:16; // bit[15:0], the packet size +#endif + + // u4Byte 1 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 type:8; // bit[7:0], the type of this packet + u32 rsvd1:24; // bit[31:8] +#else + u32 rsvd1:24; // bit[31:8] + u32 type:8; // bit[7:0], the type of this packet +#endif + + // u4Byte 2 + u32 rsvd2; + + // u4Byte 3 + u32 rsvd3; + + // u4Byte 4 + u32 rsvd4; + + // u4Byte 5 + u32 rsvd5; +} SDIO_RX_DESC, *PSDIO_RX_DESC; + +// For memory read command +typedef struct _SDIO_RX_DESC_MR{ + // u4Byte 0 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 pkt_len:16; // bit[15:0], the packet size + u32 offset:8; // bit[23:16], the offset from the packet start to the buf start, also means the size of RX Desc + u32 rsvd0:8; // bit[31:24] +#else + u32 rsvd0:8; // bit[31:24] + u32 offset:8; // bit[23:16], the offset from the packet start to the buf start, also means the size of RX Desc + u32 pkt_len:16; // bit[15:0], the packet size +#endif + + // u4Byte 1 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 type:8; // bit[7:0], the type of this packet + u32 rsvd1:24; // bit[31:8] +#else + u32 rsvd1:24; // bit[31:8] + u32 type:8; // bit[7:0], the type of this packet +#endif + + // u4Byte 2 + u32 start_addr; + + // u4Byte 3 + u32 rsvd2; + + // u4Byte 4 + u32 rsvd3; + + // u4Byte 5 + u32 rsvd4; +} SDIO_RX_DESC_MR, *PSDIO_RX_DESC_MR; + +// For memory write reply command +typedef struct _SDIO_RX_DESC_MW{ + // u4Byte 0 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 pkt_len:16; // bit[15:0], the packet size + u32 offset:8; // bit[23:16], the offset from the packet start to the buf start, also means the size of RX Desc + u32 rsvd0:8; // bit[31:24] +#else + u32 rsvd0:8; // bit[31:24] + u32 offset:8; // bit[23:16], the offset from the packet start to the buf start, also means the size of RX Desc + u32 pkt_len:16; // bit[15:0], the packet size +#endif + + // u4Byte 1 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 type:8; // bit[7:0], the type of this packet + u32 rsvd1:24; // bit[31:8] +#else + u32 rsvd1:24; // bit[31:8] + u32 type:8; // bit[7:0], the type of this packet +#endif + + // u4Byte 2 + u32 start_addr; + + // u4Byte 3 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 write_len:16; // bit[15:0], the type of this packet + u32 result:8; // bit[23:16], the result of memory write command + u32 rsvd2:8; // bit[31:24] +#else + u32 rsvd2:8; // bit[31:24] + u32 result:8; // bit[23:16], the result of memory write command + u32 write_len:16; // bit[15:0], the type of this packet +#endif + + // u4Byte 4 + u32 rsvd3; + + // u4Byte 5 + u32 rsvd4; +} SDIO_RX_DESC_MW, *PSDIO_RX_DESC_MW; + +// For memory set reply command +typedef struct _SDIO_RX_DESC_MS{ + // u4Byte 0 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 pkt_len:16; // bit[15:0], the packet size + u32 offset:8; // bit[23:16], the offset from the packet start to the buf start, also means the size of RX Desc + u32 rsvd0:8; // bit[31:24] +#else + u32 rsvd0:8; // bit[31:24] + u32 offset:8; // bit[23:16], the offset from the packet start to the buf start, also means the size of RX Desc + u32 pkt_len:16; // bit[15:0], the packet size +#endif + + // u4Byte 1 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 type:8; // bit[7:0], the type of this packet + u32 rsvd1:24; // bit[31:8] +#else + u32 rsvd1:24; // bit[31:8] + u32 type:8; // bit[7:0], the type of this packet +#endif + + // u4Byte 2 + u32 start_addr; + + // u4Byte 3 +#if (SYSTEM_ENDIAN==PLATFORM_LITTLE_ENDIAN) + u32 write_len:16; // bit[15:0], the type of this packet + u32 result:8; // bit[23:16], the result of memory write command + u32 rsvd2:8; // bit[31:24] +#else + u32 rsvd2:8; // bit[31:24] + u32 result:8; // bit[23:16], the result of memory write command + u32 write_len:16; // bit[15:0], the type of this packet +#endif + + // u4Byte 4 + u32 rsvd3; + + // u4Byte 5 + u32 rsvd4; +} SDIO_RX_DESC_MS, *PSDIO_RX_DESC_MS; + +#define SIZE_RX_DESC (sizeof(SDIO_RX_DESC)) + +typedef struct _SDIO_RX_BD_BUFFER_ { + SDIO_RX_DESC RX_Desc; + u8 RX_Buffer[SDIO_RX_BD_BUF_SIZE]; +}SDIO_RX_BD_BUFFER, *PSDIO_RX_BD_BUFFER; + + +/* The data structer for a packet fordwarding to the WLan driver to transmit it */ +// TODO: This data structer just for test, we may need modify it for the normal driver +typedef struct _SDIO_TX_PACKET_ { + u8 *pHeader; // Point to the 1st byte of the packets + u16 PktSize; // the size (bytes) of this packet + _LIST list; // the link list to chain packets + u8 isDyna; // is Dynamic allocated +} SDIO_TX_PACKET, *PSDIO_TX_PACKET; + +/* the data structer to bind a TX_BD with a TX Packet */ +typedef struct _SDIO_TX_BD_HANDLE_ { + SDIO_TX_BD *pTXBD; // Point to the TX_BD buffer +#if SDIO_API_DEFINED + VOID *priv; +#else +#if CONFIG_INIC_EN +#if CONFIG_INIC_SKB_TX + struct sk_buff *skb; +#endif +#endif +#endif + SDIO_TX_PACKET *pPkt; // point to the Tx Packet + u8 isPktEnd; // For a packet over 1 BD , this flag to indicate is this BD contains a packet end + u8 isFree; // is this TX BD free +} SDIO_TX_BD_HANDLE, *PSDIO_TX_BD_HANDLE; + +/* The data structer for a packet which from the WLan driver to send to the Host */ +// TODO: This data structer just for test, we may need modify it for the normal driver + +#if SDIO_BOOT_DRIVER +typedef struct _SDIO_RX_PACKET_ { +// SDIO_RX_DESC RxDesc; // The RX Descriptor for this packet, to be send to Host ahead this packet + u8 *pData; // point to the head of payload of this packet + u16 Offset; // the offset from the pData to the payload buffer + _LIST list; // the link list to chain packets + u8 PktBuf[SDIO_RX_BD_BUF_SIZE]; // the Rx_Desc + payload data buffer, the first 24 bytes is reserved for RX_DESC +} SDIO_RX_PACKET, *PSDIO_RX_PACKET; +#else +typedef struct _SDIO_RX_PACKET_ { + SDIO_RX_DESC RxDesc; // The RX Descriptor for this packet, to be send to Host ahead this packet +#if SDIO_API_DEFINED + VOID *priv; +#else +#if CONFIG_INIC_EN +#if CONFIG_INIC_SKB_RX + struct sk_buff *skb; +#endif +#endif +#endif + u8 *pData; // point to the head of payload of this packet + u16 Offset; // the offset from the pData to the payload buffer + _LIST list; // the link list to chain packets + u8 isDyna; // is Dynamic allocated +} SDIO_RX_PACKET, *PSDIO_RX_PACKET; +#endif + +/* the data structer to bind a RX_BD with a RX Packet */ +typedef struct _SDIO_RX_BD_HANDLE_ { + SDIO_RX_BD *pRXBD; // Point to the RX_BD buffer + SDIO_RX_PACKET *pPkt; // point to the Rx Packet + u8 isPktEnd; // For a packet over 1 BD , this flag to indicate is this BD contains a packet end + u8 isFree; // is this RX BD free (DMA done and its RX packet has been freed) +} SDIO_RX_BD_HANDLE, *PSDIO_RX_BD_HANDLE; + +#if SDIO_MP_MODE +typedef struct _SDIO_MP_CMD_ { + u8 cmd_name[16]; + u32 cmd_type; +} SDIO_MP_CMD, *PSDIO_MP_CMD; + +typedef enum _SDIO_MP_CMD_TYPE_{ + SDIO_MP_START=1, + SDIO_MP_STOP=2, + SDIO_MP_LOOPBACK=3, + SDIO_MP_STATUS=4, + SDIO_MP_READ_REG8=5, + SDIO_MP_READ_REG16=6, + SDIO_MP_READ_REG32=7, + SDIO_MP_WRITE_REG8=8, + SDIO_MP_WRITE_REG16=9, + SDIO_MP_WRITE_REG32=10, + SDIO_MP_WAKEUP=11, // wakeup the SDIO task manually, for debugging + SDIO_MP_DUMP=12, // start/stop to dump the SDIO status periodically + SDIO_MP_CTX=13, // setup continue TX test + SDIO_MP_CRX=14, // setup continue RX test + SDIO_MP_CRX_DA=15, // setup continue RX with dynamic allocate RX Buf test + SDIO_MP_CRX_STOP=16, // setup continue RX test + SDIO_MP_DBG_MSG=17, // Debug message On/Off + +}SDIO_MP_CMD_TYPE; + +typedef enum _SDIO_CRX_MODE_{ + SDIO_CRX_STATIC_BUF = 1, + SDIO_CRX_DYNA_BUF = 2, +} SDIO_CRX_MODE; + +typedef struct _SDIO_MP_RX_PACKET_ { + _LIST list; // this member MUST be the 1st one, the link list to chain packets + u8 *pData; // point to the head of payload of this packet + u16 Offset; // the offset from the pData to the payload + u16 DataLen; // the data length of this packet +} SDIO_MP_RX_PACKET, *PSDIO_MP_RX_PACKET; + +#endif // end of '#if SDIO_MP_MODE' + +#define SDIO_CMD_TX_ETH 0x83 // request to TX a 802.3 packet +#define SDIO_CMD_TX_WLN 0x81 // request to TX a 802.11 packet +#define SDIO_CMD_H2C 0x11 // H2C(host to device) command packet +#define SDIO_CMD_MEMRD 0x51 // request to read a block of memory data +#define SDIO_CMD_MEMWR 0x53 // request to write a block of memory +#define SDIO_CMD_MEMST 0x55 // request to set a block of memory with a value +#define SDIO_CMD_STARTUP 0x61 // request to jump to the start up function + +#define SDIO_CMD_RX_ETH 0x82 // indicate a RX 802.3 packet +#define SDIO_CMD_RX_WLN 0x80 // indicate a RX 802.11 packet +#define SDIO_CMD_C2H 0x10 // C2H(device to host) command packet +#define SDIO_CMD_MEMRD_RSP 0x50 // response to memory block read command +#define SDIO_CMD_MEMWR_RSP 0x52 // response to memory write command +#define SDIO_CMD_MEMST_RSP 0x54 // response to memory set command +#define SDIO_CMD_STARTED 0x60 // indicate the program has jumped to the given function + +enum SDIO_RPWM2_BITS { + RPWM2_ACT_BIT = BIT0, // Active + RPWM2_SLEEP_BIT = 0, // Sleep + RPWM2_DSTANDBY_BIT = BIT1, // Deep Standby + RPWM2_PG_BIT = 0, // Power Gated + RPWM2_FBOOT_BIT = BIT2, // fast reboot + RPWM2_NBOOT_BIT = 0, // normal reboot + RPWM2_WKPIN_A5_BIT = BIT3, // enable GPIO A5 wakeup + RPWM2_WKPIN_C7_BIT = BIT4, // enable GPIO C7 wakeup + RPWM2_WKPIN_D5_BIT = BIT5, // enable GPIO D5 wakeup + RPWM2_WKPIN_E3_BIT = BIT6, // enable GPIO E3 wakeup + RPWM2_PIN_A5_LV_BIT = BIT7, // GPIO A5 wakeup level + RPWM2_PIN_C7_LV_BIT = BIT8, // GPIO C7 wakeup level + RPWM2_PIN_D5_LV_BIT = BIT9, // GPIO D5 wakeup level + RPWM2_PIN_E3_LV_BIT = BIT10, // GPIO E3 wakeup level + RPWM2_CG_BIT = BIT11, // Clock Gated + RPWM2_ACK_BIT = BIT14, // Acknowledge + RPWM2_TOGGLE_BIT = BIT15, // Toggle bit +}; + +enum SDIO_CPWM2_BITS { + CPWM2_ACT_BIT = BIT0, // Active + CPWM2_DSTANDBY_BIT = BIT1, // Deep Standby + CPWM2_FBOOT_BIT = BIT2, // fast reboot + CPWM2_INIC_FW_RDY_BIT = BIT3, // is the iNIC FW(1) or Boot FW(0) + + CPWM2_TOGGLE_BIT = BIT15, // Toggle bit +}; + +#ifdef CONFIG_SDIO_DEVICE_VERIFY + +#define TX_BD_STRUCTURE_NUM 10 +#define RX_BD_STRUCTURE_NUM 10 +#define TX_BD_BUFFER_SIZE 0x1000//0x2000//0x800 +#define RX_BD_BUFFER_SIZE 0x400//0x800 + +#define SDIO_RAM_ADDR_BASE 0x20080000 +#define SDIO_BUFFER_HEAD(addr) SDIO_RAM_ADDR_BASE + addr +#define HAL_SDIO_BUFFER_READ8(addr) HAL_READ8(SDIO_RAM_ADDR_BASE, addr) +#define HAL_SDIO_BUFFER_READ32(addr) HAL_READ32(SDIO_RAM_ADDR_BASE, addr) +#define HAL_SDIO_BUFFER_WRITE32(addr, value) HAL_WRITE32(SDIO_RAM_ADDR_BASE, addr, value) + +//#define RX_BD_ADDR 0x8000 +//#define RX_BUFFER_ADDR 0x8050 + +typedef enum _SDIO_TEST_FUNC_ { + SDIO_TEST_INIT, // 0 + SDIO_TEST_INT_ON, // 1 + SDIO_TEST_INT_OFF, // 2 + SDIO_HCI_RX_REQ, // 3 + SDIO_RESET_TXFIFIO, // 4 + SDIO_CPU_RST_DMA, // 5 + SDIO_CPU_CLR_INT_REG, // 6 + SDIO_TIMER_TEST, // 7 + SDIO_TEST_DEBUG, // 8 + SDIO_TEST, // 9 + SDIO_HELP = 0xff +}SDIO_TEST_FUNC, *PSDIO_TEST_FUNC; + +typedef struct _SDIO_TEST_ADAPTER_ { + u32 TXWritePtr; + u32 TXReadPtr; + u16 RXWritePtr; + u16 RXReadPtr; + u16 IntMask; + u16 IntStatus; +} SDIO_TEST_ADAPTER, *PSDIO_TEST_ADAPTER; + + +VOID +MovePKTToRX( + IN u32 Source, IN u32 Destination, IN u32 PKTSize +); + +BOOL +PacketProcess( + IN SDIO_TEST_ADAPTER *pDevStatus +); + +VOID +SdioDeviceIrqHandleFunc( + IN VOID *DATA +); + +VOID +SdioDeviceTestApp( + IN u32 Data +); + +VOID +InitRXBD(VOID); + +VOID +InitTXFIFO(VOID); + +VOID +IrqRegister(VOID); + +#endif // end of "#ifdef CONFIG_SDIO_DEVICE_VERIFY" + +#endif /* #ifndef _RTL8195A_SDIO_H_ */ diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a_timer.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a_timer.h index 42d5c62e0c..caf8223d11 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a_timer.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a_timer.h @@ -94,11 +94,6 @@ HalTimerReadCountRtl8195a_Patch( IN u32 TimerId ); -VOID -HalTimerSync( - IN u32 TimerId -); - VOID HalTimerIrqEnRtl8195a( IN u32 TimerId diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a_uart.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a_uart.h index 1da6d5eb0a..1ddbce84af 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a_uart.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/fwlib/rtl8195a/rtl8195a_uart.h @@ -74,8 +74,10 @@ #define RUART_TRAN_HOLD_REG_OFF 0x24 //Transmitter Holding Register #define RUART_MISC_CTL_REG_OFF 0x28 -#define RUART_TXDMA_BURSTSIZE_MASK 0xF8 //7:3 -#define RUART_RXDMA_BURSTSIZE_MASK 0x1F00 //12:8 +#define RUART_TXDMA_EN_MASK 0x02 // [1] +#define RUART_RXDMA_EN_MASK 0x04 // [2] +#define RUART_TXDMA_BURSTSIZE_MASK 0xF8 // [7:3] +#define RUART_RXDMA_BURSTSIZE_MASK 0x1F00 // [12:8] #define RUART_DEBUG_REG_OFF 0x3C @@ -551,6 +553,26 @@ HalRuartExitCriticalRtl8195a( IN VOID *Data ); +VOID +HalRuartTxGdmaEnable8195a( + IN VOID *pHalRuartAdapter +); + +VOID +HalRuartTxGdmaDisable8195a( + IN VOID *pHalRuartAdapter +); + +VOID +HalRuartRxGdmaEnable8195a( + IN VOID *pHalRuartAdapter +); + +VOID +HalRuartRxGdmaDisable8195a( + IN VOID *pHalRuartAdapter +); + #if CONFIG_CHIP_E_CUT _LONG_CALL_ HAL_Status HalRuartResetTxFifoRtl8195a_V04( @@ -649,33 +671,10 @@ _LONG_CALL_ VOID HalRuartExitCriticalRtl8195a_V04( IN VOID *Data ); - #endif // #if CONFIG_CHIP_E_CUT #ifdef CONFIG_MBED_ENABLED // Interface to ROM functions -//extern __longcall void HalRuartAdapterLoadDefRtl8195a(UART_Handle *uart, uint8_t idx); -//extern __longcall void HalRuartDeInitRtl8195a(UART_Handle *uart); -//extern __longcall HAL_Status HalRuartDisableRtl8195a(UART_Handle *data); -//extern __longcall HAL_Status HalRuartEnableRtl8195a(UART_Handle *data); -//extern __longcall void HalRuartDmaInitRtl8195a(UART_Handle *data); -//extern __longcall void HalRuartTxGdmaLoadDefRtl8195a(UART_Handle *uart, RUART_DMA_Config *cfg); -//extern __longcall void HalRuartRxGdmaLoadDefRtl8195a(UART_Handle *uart, RUART_DMA_Config *cfg); -//extern __longcall HAL_Status HalRuartGetCRtl8195a(UART_Handle *uart, uint8_t *byte); -//extern __longcall HAL_Status HalRuartPutCRtl8195a(UART_Handle *uart, uint8_t byte); -//extern __longcall HAL_Status RuartLock(UART_Handle * uart); -//extern __longcall void RuartUnlock(UART_Handle * uart); -//extern __longcall void HalRuartSetIMRRtl8195a(UART_Handle *uart); -//extern __longcall uint8_t HalRuartGetIMRRtl8195a(UART_Handle *uart); -//extern __longcall uint32_t HalRuartSendRtl8195a(UART_Handle *, uint8_t *, uint32_t, uint32_t); -//extern __longcall HAL_Status HalRuartIntSendRtl8195a(UART_Handle *, uint8_t *, uint32_t); -//extern __longcall HAL_Status HalRuartIntRecvRtl8195a(UART_Handle *, uint8_t *, uint32_t); -//extern __longcall uint32_t HalRuartRecvRtl8195a(UART_Handle *, uint8_t *, uint32_t, uint32_t); -//extern __longcall void HalRuartRegIrqRtl8195a(UART_Handle *Data); -//extern __longcall void HalRuartIntEnableRtl8195a(UART_Handle *Data); -//extern __longcall void HalRuartIntDisableRtl8195a(UART_Handle *Data); -//extern __longcall uint32_t HalRuartGetDebugValueRtl8195a(HAL_RUART_ADAPTER *Data, uint32_t sel); -//extern __longcall void HalRuartRTSCtrlRtl8195a(UART_Handle *Data, bool val); extern __longcall HAL_Status RuartIsTimeout(uint32_t StartCount, uint32_t TimeoutCnt); #endif diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/misc/driver/rtl_consol.c b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/misc/driver/rtl_consol.c deleted file mode 100644 index ebeae470bd..0000000000 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/misc/driver/rtl_consol.c +++ /dev/null @@ -1,384 +0,0 @@ -/******************************************************************************* - *Copyright (c) 2013-2016 Realtek Semiconductor Corp, All Rights Reserved - * SPDX-License-Identifier: LicenseRef-PBL - * - * Licensed under the Permissive Binary License, Version 1.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * You may obtain a copy of the License at https://www.mbed.com/licenses/PBL-1.0 - * - * See the License for the specific language governing permissions and limitations under the License. - ******************************************************************************* - */ - -#include "rtl8195a.h" -//#include -#include "rtl_consol.h"//#include "osdep_service.h" -////#include "FreeRTOS.h" -////#include "task.h" -////#include "semphr.h" - -#include "tcm_heap.h" - -struct task_struct RtlConsolTaskRam_task; - -MON_RAM_BSS_SECTION - volatile UART_LOG_CTL UartLogCtl; -MON_RAM_BSS_SECTION - volatile UART_LOG_CTL *pUartLogCtl; -MON_RAM_BSS_SECTION - u8 *ArgvArray[MAX_ARGV]; -MON_RAM_BSS_SECTION - UART_LOG_BUF UartLogBuf; - - -#ifdef CONFIG_UART_LOG_HISTORY -MON_RAM_BSS_SECTION - u8 UartLogHistoryBuf[UART_LOG_HISTORY_LEN][UART_LOG_CMD_BUFLEN]; -#endif - -_LONG_CALL_ -extern u8 -UartLogCmdChk( - IN u8 RevData, - IN UART_LOG_CTL *prvUartLogCtl, - IN u8 EchoFlag -); - -_LONG_CALL_ -extern VOID -ArrayInitialize( - IN u8 *pArrayToInit, - IN u8 ArrayLen, - IN u8 InitValue -); - -_LONG_CALL_ -extern VOID -UartLogHistoryCmd( - IN u8 RevData, - IN UART_LOG_CTL *prvUartLogCtl, - IN u8 EchoFlag -); - -_LONG_CALL_ -extern VOID -UartLogCmdExecute( - IN PUART_LOG_CTL pUartLogCtlExe -); - - - -//================================================= - - -/* Minimum and maximum values a `signed long int' can hold. - (Same as `int'). */ -#ifndef __LONG_MAX__ -#if defined (__alpha__) || (defined (__sparc__) && defined(__arch64__)) || defined (__sparcv9) || defined (__s390x__) -#define __LONG_MAX__ 9223372036854775807L -#else -#define __LONG_MAX__ 2147483647L -#endif /* __alpha__ || sparc64 */ -#endif -#undef LONG_MIN -#define LONG_MIN (-LONG_MAX-1) -#undef LONG_MAX -#define LONG_MAX __LONG_MAX__ - -/* Maximum value an `unsigned long int' can hold. (Minimum is 0). */ -#undef ULONG_MAX -#define ULONG_MAX (LONG_MAX * 2UL + 1) - -#ifndef __LONG_LONG_MAX__ -#define __LONG_LONG_MAX__ 9223372036854775807LL -#endif - - -#if 0 -//====================================================== -//: UartLogIrqHandleRam -//: To deal with Uart-Log RX IRQ -//: VOID -//: VOID -//: NA -//====================================================== -//MON_RAM_TEXT_SECTION -VOID -UartLogIrqHandleRam -( - VOID * Data -) -{ - u8 UartReceiveData = 0; - //For Test - BOOL PullMode = _FALSE; - - u32 IrqEn = DiagGetIsrEnReg(); - - DiagSetIsrEnReg(0); - - UartReceiveData = DiagGetChar(PullMode); - if (UartReceiveData == 0) { - goto exit; - } - - //KB_ESC chk is for cmd history, it's a special case here. - if (UartReceiveData == KB_ASCII_ESC) { - //4 Esc detection is only valid in the first stage of boot sequence (few seconds) - if (pUartLogCtl->ExecuteEsc != _TRUE) - { - pUartLogCtl->ExecuteEsc = _TRUE; - (*pUartLogCtl).EscSTS = 0; - } - else - { - //4 the input commands are valid only when the task is ready to execute commands - if ((pUartLogCtl->BootRdy == 1) -#ifdef CONFIG_KERNEL - ||(pUartLogCtl->TaskRdy == 1) -#endif - ) - { - if ((*pUartLogCtl).EscSTS==0) - { - (*pUartLogCtl).EscSTS = 1; - } - } - else - { - (*pUartLogCtl).EscSTS = 0; - } - } - } - else if ((*pUartLogCtl).EscSTS==1){ - if (UartReceiveData != KB_ASCII_LBRKT){ - (*pUartLogCtl).EscSTS = 0; - } - else{ - (*pUartLogCtl).EscSTS = 2; - } - } - - else{ - if ((*pUartLogCtl).EscSTS==2){ - (*pUartLogCtl).EscSTS = 0; -#ifdef CONFIG_UART_LOG_HISTORY - if ((UartReceiveData=='A')|| UartReceiveData=='B'){ - UartLogHistoryCmd(UartReceiveData,(UART_LOG_CTL *)pUartLogCtl,1); - } -#endif - } - else{ - if (UartLogCmdChk(UartReceiveData,(UART_LOG_CTL *)pUartLogCtl,1)==2) - { - //4 check UartLog buffer to prevent from incorrect access - if (pUartLogCtl->pTmpLogBuf != NULL) - { - pUartLogCtl->ExecuteCmd = _TRUE; -#if defined(CONFIG_KERNEL) && !TASK_SCHEDULER_DISABLED - if (pUartLogCtl->TaskRdy) - //RtlUpSemaFromISR((_Sema *)&pUartLogCtl->Sema); - rtw_up_sema_from_isr((_sema *)&pUartLogCtl->Sema); -#endif - } - else - { - ArrayInitialize((u8 *)pUartLogCtl->pTmpLogBuf->UARTLogBuf, UART_LOG_CMD_BUFLEN, '\0'); - } - } - } - } -exit: - DiagSetIsrEnReg(IrqEn); - -} - - - -//MON_RAM_TEXT_SECTION -VOID -RtlConsolInitRam( - IN u32 Boot, - IN u32 TBLSz, - IN VOID *pTBL -) -{ - UartLogBuf.BufCount = 0; - ArrayInitialize(&UartLogBuf.UARTLogBuf[0],UART_LOG_CMD_BUFLEN,'\0'); - pUartLogCtl = &UartLogCtl; - - pUartLogCtl->NewIdx = 0; - pUartLogCtl->SeeIdx = 0; - pUartLogCtl->RevdNo = 0; - pUartLogCtl->EscSTS = 0; - pUartLogCtl->BootRdy = 0; - pUartLogCtl->pTmpLogBuf = &UartLogBuf; -#ifdef CONFIG_UART_LOG_HISTORY - pUartLogCtl->CRSTS = 0; - pUartLogCtl->pHistoryBuf = &UartLogHistoryBuf[0]; -#endif - pUartLogCtl->pfINPUT = (VOID*)&DiagPrintf; - pUartLogCtl->pCmdTbl = (PCOMMAND_TABLE) pTBL; - pUartLogCtl->CmdTblSz = TBLSz; -#ifdef CONFIG_KERNEL - pUartLogCtl->TaskRdy = 0; -#endif - //executing boot sequence - if (Boot == ROM_STAGE) - { - pUartLogCtl->ExecuteCmd = _FALSE; - pUartLogCtl->ExecuteEsc = _FALSE; - } - else - { - pUartLogCtl->ExecuteCmd = _FALSE; - pUartLogCtl->ExecuteEsc= _TRUE;//don't check Esc anymore -#if defined(CONFIG_KERNEL) - /* Create a Semaphone */ - //RtlInitSema((_Sema*)&(pUartLogCtl->Sema), 0); - rtw_init_sema((_sema*)&(pUartLogCtl->Sema), 0); - pUartLogCtl->TaskRdy = 0; -#ifdef PLATFORM_FREERTOS -#define LOGUART_STACK_SIZE 128 //USE_MIN_STACK_SIZE modify from 512 to 128 -//if(rtw_create_task(&g_tcp_client_task, "tcp_client_handler", LOGUART_STACK_SIZE, TASK_PRORITY_MIDDLE, tcp_client_handler, 0) != _SUCCESS) -#if CONFIG_USE_TCM_HEAP - { - int ret = 0; - void *stack_addr = tcm_heap_malloc(LOGUART_STACK_SIZE*sizeof(int)); - //void *stack_addr = rtw_malloc(stack_size*sizeof(int)); - if(stack_addr == NULL){ - DiagPrintf("Out of TCM heap in \"LOGUART_TASK\" "); - } - ret = xTaskGenericCreate( - RtlConsolTaskRam, - (const char *)"LOGUART_TASK", - LOGUART_STACK_SIZE, - NULL, - tskIDLE_PRIORITY + 5 + PRIORITIE_OFFSET, - NULL, - stack_addr, - NULL); - if (pdTRUE != ret) - { - DiagPrintf("Create Log UART Task Err!!\n"); - } - } -#else - if (pdTRUE != xTaskCreate( RtlConsolTaskRam, (const signed char * const)"LOGUART_TASK", LOGUART_STACK_SIZE, NULL, tskIDLE_PRIORITY + 5 + PRIORITIE_OFFSET, NULL)) - { - DiagPrintf("Create Log UART Task Err!!\n"); - } -#endif - -#endif - -#endif - } - - CONSOLE_8195A(); -} - -extern u8** GetArgv(const u8 *string); -#if SUPPORT_LOG_SERVICE -extern char log_buf[LOG_SERVICE_BUFLEN]; -//extern osSemaphore(log_rx_interrupt_sema); -_sema log_rx_interrupt_sema; -#endif -//====================================================== -void console_cmd_exec(PUART_LOG_CTL pUartLogCtlExe) -{ - u8 CmdCnt = 0; - u8 argc = 0; - u8 **argv; - //u32 CmdNum; - PUART_LOG_BUF pUartLogBuf = pUartLogCtlExe->pTmpLogBuf; -#if SUPPORT_LOG_SERVICE - strncpy(log_buf, (const u8*)&(*pUartLogBuf).UARTLogBuf[0], LOG_SERVICE_BUFLEN-1); -#endif - argc = GetArgc((const u8*)&((*pUartLogBuf).UARTLogBuf[0])); - argv = GetArgv((const u8*)&((*pUartLogBuf).UARTLogBuf[0])); - - if(argc > 0){ -#if SUPPORT_LOG_SERVICE -// if(log_handler(argv[0]) == NULL) -// legency_interactive_handler(argc, argv); - //RtlUpSema((_Sema *)&log_rx_interrupt_sema); - rtw_up_sema((_sema *)&log_rx_interrupt_sema); -#endif - ArrayInitialize(argv[0], sizeof(argv[0]) ,0); - }else{ -#if defined(configUSE_WAKELOCK_PMU) && (configUSE_WAKELOCK_PMU == 1) - pmu_acquire_wakelock(BIT(PMU_LOGUART_DEVICE)); -#endif - CONSOLE_8195A(); // for null command - } - - (*pUartLogBuf).BufCount = 0; - ArrayInitialize(&(*pUartLogBuf).UARTLogBuf[0], UART_LOG_CMD_BUFLEN, '\0'); -} -//====================================================== -// overload original RtlConsolTaskRam -//MON_RAM_TEXT_SECTION -VOID -RtlConsolTaskRam( - VOID *Data -) -{ -#if SUPPORT_LOG_SERVICE - log_service_init(); -#endif - //4 Set this for UartLog check cmd history -#ifdef CONFIG_KERNEL - pUartLogCtl->TaskRdy = 1; -#endif -#ifndef CONFIG_KERNEL - pUartLogCtl->BootRdy = 1; -#endif - do{ -#if defined(CONFIG_KERNEL) && !TASK_SCHEDULER_DISABLED - //RtlDownSema((_Sema *)&pUartLogCtl->Sema); - rtw_down_sema((_sema *)&pUartLogCtl->Sema); -#endif - if (pUartLogCtl->ExecuteCmd) { - // Add command handler here - console_cmd_exec((PUART_LOG_CTL)pUartLogCtl); - //UartLogCmdExecute((PUART_LOG_CTL)pUartLogCtl); - pUartLogCtl->ExecuteCmd = _FALSE; - } - }while(1); -} - -//====================================================== -extern void console_init_hs_uart(void); -void console_init(void) -{ - #if CONFIG_LOG_USE_HS_UART - sys_log_uart_off(); - console_init_hs_uart(); - #elif(CONFIG_LOG_USE_I2C) - sys_log_uart_off(); - // TODO: - #else - IRQ_HANDLE UartIrqHandle; - - //4 Register Log Uart Callback function - UartIrqHandle.Data = NULL;//(u32)&UartAdapter; - UartIrqHandle.IrqNum = UART_LOG_IRQ; - UartIrqHandle.IrqFun = (IRQ_FUN) UartLogIrqHandleRam; - UartIrqHandle.Priority = 6; - - - //4 Register Isr handle - InterruptUnRegister(&UartIrqHandle); - InterruptRegister(&UartIrqHandle); - #endif - -#if !TASK_SCHEDULER_DISABLED - RtlConsolInitRam((u32)RAM_STAGE,(u32)0,(VOID*)NULL); -#else - RtlConsolInitRam((u32)ROM_STAGE,(u32)0,(VOID*)NULL); -#endif -} - -#endif diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/misc/driver/rtl_consol.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/misc/driver/rtl_consol.h deleted file mode 100644 index 538d2c5460..0000000000 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/misc/driver/rtl_consol.h +++ /dev/null @@ -1,139 +0,0 @@ -/******************************************************************************* - *Copyright (c) 2013-2016 Realtek Semiconductor Corp, All Rights Reserved - * SPDX-License-Identifier: LicenseRef-PBL - * - * Licensed under the Permissive Binary License, Version 1.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * You may obtain a copy of the License at https://www.mbed.com/licenses/PBL-1.0 - * - * See the License for the specific language governing permissions and limitations under the License. - ******************************************************************************* - */ - -#ifndef _RTK_CONSOL_H_ -#define _RTK_CONSOL_H_ -/* - * Include user defined options first. Anything not defined in these files - * will be set to standard values. Override anything you dont like! - */ - #if defined(CONFIG_PLATFORM_8195A) || defined(CONFIG_PLATFORM_8711B) -#include "platform_opts.h" -#endif - -//#include "osdep_api.h" -#include "osdep_service.h" -#include "hal_diag.h" - -#define CONSOLE_PREFIX "#" - - -//Log UART -//UART_LOG_CMD_BUFLEN: only 126 bytes could be used for keeping input -// cmd, the last byte is for string end ('\0'). -#define UART_LOG_CMD_BUFLEN 127 -#define MAX_ARGV 10 - - - -typedef u32 (*ECHOFUNC)(IN u8*,...); //UART LOG echo-function type. - -typedef struct _UART_LOG_BUF_ { - u8 BufCount; //record the input cmd char number. - u8 UARTLogBuf[UART_LOG_CMD_BUFLEN]; //record the input command. -} UART_LOG_BUF, *PUART_LOG_BUF; - - - -typedef struct _UART_LOG_CTL_ { - u8 NewIdx; - u8 SeeIdx; - u8 RevdNo; - u8 EscSTS; - u8 ExecuteCmd; - u8 ExecuteEsc; - u8 BootRdy; - u8 Resvd; - PUART_LOG_BUF pTmpLogBuf; - VOID *pfINPUT; - PCOMMAND_TABLE pCmdTbl; - u32 CmdTblSz; -#ifdef CONFIG_UART_LOG_HISTORY - u32 CRSTS; -#endif -#ifdef CONFIG_UART_LOG_HISTORY - u8 (*pHistoryBuf)[UART_LOG_CMD_BUFLEN]; -#endif -#ifdef CONFIG_KERNEL - u32 TaskRdy; - //_Sema Sema; - _sema Sema; -#else - // Since ROM code will reference this typedef, so keep the typedef same size - u32 TaskRdy; - void *Sema; -#endif -} UART_LOG_CTL, *PUART_LOG_CTL; - - -#define KB_ASCII_NUL 0x00 -#define KB_ASCII_BS 0x08 -#define KB_ASCII_TAB 0x09 -#define KB_ASCII_LF 0x0A -#define KB_ASCII_CR 0x0D -#define KB_ASCII_ESC 0x1B -#define KB_ASCII_SP 0x20 -#define KB_ASCII_BS_7F 0x7F -#define KB_ASCII_LBRKT 0x5B //[ - -#define KB_SPACENO_TAB 1 - -#ifdef CONFIG_UART_LOG_HISTORY -#define UART_LOG_HISTORY_LEN 5 -#endif - -#ifdef CONFIG_DEBUG_LOG -#define _ConsolePrint DiagPrintf -#else -#define _ConsolePrint -#endif - -#ifndef CONSOLE_PREFIX -#define CONSOLE_PREFIX "" -#endif - -#define CONSOLE_8195A(...) do {\ - _ConsolePrint("\r"CONSOLE_PREFIX __VA_ARGS__);\ -}while(0) - - -_LONG_CALL_ VOID -RtlConsolInit( - IN u32 Boot, - IN u32 TBLSz, - IN VOID *pTBL -); - -#if defined(CONFIG_KERNEL) -_LONG_CALL_ VOID -RtlConsolTaskRam( - VOID *Data -); -#endif - -_LONG_CALL_ VOID -RtlConsolTaskRom( - VOID *Data -); - - -_LONG_CALL_ u32 -Strtoul( - IN const u8 *nptr, - IN u8 **endptr, - IN u32 base -); - -void console_init(void); - -#endif //_RTK_CONSOL_H_ diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/misc/os/cmsis_pmu_8195a.c b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/misc/os/cmsis_pmu_8195a.c new file mode 100644 index 0000000000..f787ad8126 --- /dev/null +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/misc/os/cmsis_pmu_8195a.c @@ -0,0 +1,213 @@ +#if DEVICE_SLEEP + +//#include "FreeRTOS.h" +#include "cmsis_pmu_8195a.h" + +#include + +#include "platform_autoconf.h" +#include "platform_stdlib.h" +//#include "sys_api.h" + +#include "sleep_ex_api.h" + +#ifndef portNVIC_SYSTICK_CURRENT_VALUE_REG +#define portNVIC_SYSTICK_CURRENT_VALUE_REG ( * ( ( volatile uint32_t * ) 0xe000e018 ) ) +#endif + +uint32_t missing_tick = 0; + +static uint32_t wakelock = 0; +//static uint32_t wakelock = DEFAULT_WAKELOCK; + +static uint32_t wakeup_event = DEFAULT_WAKEUP_EVENT; + +typedef struct { + uint32_t nDeviceId; + PSM_HOOK_FUN sleep_hook_fun; + void* sleep_param_ptr; + PSM_HOOK_FUN wakeup_hook_fun; + void* wakeup_param_ptr; +} PSM_DD_HOOK_INFO; + +#define MAX_PSM_DD_HOOK_INFO_SIZE 8 +uint32_t psm_dd_hook_info_size = 0; +PSM_DD_HOOK_INFO psm_dd_hook_infos[MAX_PSM_DD_HOOK_INFO_SIZE]; + +static uint8_t last_wakelock_state[32] = { + DEFAULT_WAKELOCK & 0x01, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0 +}; +static uint32_t last_acquire_wakelock_time[32] = {0}; +static uint32_t hold_wakelock_time[32] = {0}; +static uint32_t base_sys_time = 0; + +static uint32_t sys_sleep_time = 0; + +unsigned char reserve_pll = 0; +unsigned char generate_wakelock_stats = 0; + + +/* -------- FreeRTOS macro implementation -------- */ + +int cmsis_ready_to_sleep() { + return wakelock == 0; +} + +void pmu_acquire_wakelock(uint32_t lock_id) { + + wakelock |= BIT(lock_id); + + if (generate_wakelock_stats) { + uint32_t i; + + //uint32_t current_timestamp = osKernelSysTick(); + uint32_t current_timestamp = osKernelGetSysTimerCount(); + + for (i=0; i<32; i++) { + if ( (1< 0) { + sprintf(pcWriteBuffer, "%x\t\t%d\r\n", i, hold_wakelock_time[i]); + } + } + pcWriteBuffer += strlen( pcWriteBuffer ); + } + sprintf(pcWriteBuffer, "time passed: %d ms, system sleep %d ms\r\n", current_timestamp - base_sys_time, sys_sleep_time); + } +} + +void pmu_clean_wakelock_stat() { + uint32_t i; + + //base_sys_time = osKernelSysTick(); + base_sys_time = osKernelGetSysTimerCount(); + + for (i=0; i<32; i++) { + hold_wakelock_time[i] = 0; + if (last_wakelock_state[i] == 1) { + last_acquire_wakelock_time[i] = base_sys_time; + } + } + sys_sleep_time = 0; +} + +void pmu_add_wakeup_event(uint32_t event) { + wakeup_event |= event; +} + +void pmu_del_wakeup_event(uint32_t event) { + wakeup_event &= ~event; + // To fulfill tickless design, system timer is required to be wakeup event + wakeup_event |= SLEEP_WAKEUP_BY_STIMER; +} + +void pmu_register_sleep_callback(uint32_t nDeviceId, PSM_HOOK_FUN sleep_hook_fun, void* sleep_param_ptr, PSM_HOOK_FUN wakeup_hook_fun, void* wakeup_param_ptr) { + uint32_t i; + for (i=0; i 1) { + // if we have more than 2 items, just swap the last item into current slot + psm_dd_hook_infos[i].nDeviceId = psm_dd_hook_infos[psm_dd_hook_info_size-1].nDeviceId; + psm_dd_hook_infos[i].sleep_hook_fun = psm_dd_hook_infos[psm_dd_hook_info_size-1].sleep_hook_fun; + psm_dd_hook_infos[i].sleep_param_ptr = psm_dd_hook_infos[psm_dd_hook_info_size-1].sleep_param_ptr; + psm_dd_hook_infos[i].wakeup_hook_fun = psm_dd_hook_infos[psm_dd_hook_info_size-1].wakeup_hook_fun; + psm_dd_hook_infos[i].wakeup_param_ptr = psm_dd_hook_infos[psm_dd_hook_info_size-1].wakeup_param_ptr; + + // Then erase the last item + psm_dd_hook_infos[psm_dd_hook_info_size-1].nDeviceId = 0; + psm_dd_hook_infos[psm_dd_hook_info_size-1].sleep_hook_fun = NULL; + psm_dd_hook_infos[psm_dd_hook_info_size-1].sleep_param_ptr = NULL; + psm_dd_hook_infos[psm_dd_hook_info_size-1].wakeup_hook_fun = NULL; + psm_dd_hook_infos[psm_dd_hook_info_size-1].wakeup_param_ptr = NULL; + } else { + // we only have one item, just erase it + psm_dd_hook_infos[i].nDeviceId = 0; + psm_dd_hook_infos[i].sleep_hook_fun = NULL; + psm_dd_hook_infos[i].sleep_param_ptr = NULL; + psm_dd_hook_infos[i].wakeup_hook_fun = NULL; + psm_dd_hook_infos[i].wakeup_param_ptr = NULL; + } + psm_dd_hook_info_size--; + break; + } + } +} + +void pmu_set_pll_reserved(unsigned char reserve) { + reserve_pll = reserve; +} + +#endif diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/misc/os/cmsis_pmu_8195a.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/misc/os/cmsis_pmu_8195a.h new file mode 100644 index 0000000000..adff9cc8ea --- /dev/null +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/8195a/misc/os/cmsis_pmu_8195a.h @@ -0,0 +1,110 @@ +#ifndef __FREERTOS_PMU_H_ +#define __FREERTOS_PMU_H_ + +#if DEVICE_SLEEP +#include "sleep_ex_api.h" + +#ifndef BIT +#define BIT(n) (1<= 8000000) +#define _USED __attribute__((used)) +#else +#define _USED _Pragma("__root") +#endif + #elif defined(__CC_ARM) // defined in rtl8195a_compiler.h #define SECTION(_name) __attribute__ ((section(_name))) #define _LONG_CALL_ __attribute__ ((long_call)) #define ALIGNMTO(_bound) __attribute__ ((aligned (_bound))) - #define _LONG_CALL_ROM_ _LONG_CALL_ +#define _WEAK __attribute__ ((weak)) +#define _USED __attribute__((used)) #elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) #define SECTION(_name) __attribute__ ((__section__(_name))) @@ -222,6 +236,7 @@ typedef __kernel_ssize_t SSIZE_T; #define _LONG_CALL_ROM_ _LONG_CALL_ #endif #define _WEAK __attribute__ ((weak)) +#define _USED __attribute__((used)) #else #define SECTION(_name) __attribute__ ((__section__(_name))) @@ -239,6 +254,7 @@ typedef __kernel_ssize_t SSIZE_T; #define _LONG_CALL_ROM_ _LONG_CALL_ #endif #define _WEAK __attribute__ ((weak)) +#define _USED __attribute__((used)) #endif @@ -526,11 +542,9 @@ typedef unsigned char BOOLEAN,*PBOOLEAN; #define __restrict /* Ignore */ #endif -/* in rtl8195a_trap.h typedef struct _RAM_START_FUNCTION_ { VOID (*RamStartFun) (VOID); }RAM_START_FUNCTION, *PRAM_START_FUNCTION; -*/ typedef struct _RAM_FUNCTION_START_TABLE_ { VOID (*RamStartFun) (VOID); diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/common/bsp/section_config.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/common/bsp/section_config.h index d6f87264df..06031d9ca7 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/common/bsp/section_config.h +++ b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/common/bsp/section_config.h @@ -1,21 +1,17 @@ -/******************************************************************************* - *Copyright (c) 2013-2016 Realtek Semiconductor Corp, All Rights Reserved - * SPDX-License-Identifier: LicenseRef-PBL - * - * Licensed under the Permissive Binary License, Version 1.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * You may obtain a copy of the License at https://www.mbed.com/licenses/PBL-1.0 - * - * See the License for the specific language governing permissions and limitations under the License. - ******************************************************************************* +/* + * Routines to access hardware + * + * Copyright (c) 2013 Realtek Semiconductor Corp. + * + * This module is a confidential and proprietary property of RealTek and + * possession or use of this module requires written permission of RealTek. */ #ifndef _SECTION_CONFIG_H_ #define _SECTION_CONFIG_H_ -#include "platform_autoconf.h" #include "basic_types.h" +#include "platform_autoconf.h" #define RAM_DEDECATED_VECTOR_TABLE_SECTION \ SECTION(".ram_dedecated_vector_table") @@ -131,16 +127,20 @@ #define E_CUT_ROM_DATA_SECTION \ SECTION(".cute.ram.data") -//#define FWUROM_DATA_SECTION SECTION(".fwurom.data") - -//#define FWUROM_RODATA_SECTION SECTION(".fwurom.rodata") - +/* +#define FWUROM_DATA_SECTION \ + SECTION(".fwurom.data") + +#define FWUROM_RODATA_SECTION \ + SECTION(".fwurom.rodata") +*/ + #define FWUROM_TEXT_SECTION \ SECTION(".fwurom.text") - + #define XMPORT_ROM_TEXT_SECTION \ SECTION(".xmportrom.text") - + #define XDMROM_TEXT_SECTION \ SECTION(".xmodemrom.text") @@ -149,7 +149,6 @@ #if defined (__CC_ARM) #define IMAGE1_VALID_PATTEN_SECTION \ SECTION(".image1.validate.rodata") __attribute__((used)) - #define IMAGE2_VALID_PATTEN_SECTION \ SECTION(".image2.validate.rodata") __attribute__((used)) #else @@ -230,7 +229,6 @@ #define SRAM_BF_DATA_SECTION \ SECTION(".bfsram.data") - #define START_RAM_FUN_SECTION \ SECTION(".start.ram.data") @@ -288,10 +286,10 @@ #if defined (__CC_ARM) #define IMAGE2_START_RAM_FUN_SECTION \ - SECTION(".image2.ram.data") __attribute__((used)) + SECTION(".image2.ram.data") __attribute__((used)) #else #define IMAGE2_START_RAM_FUN_SECTION \ - SECTION(".image2.ram.data") + SECTION(".image2.ram.data") #endif #define SDRAM_DATA_SECTION \ diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/common/rtl_std_lib/include/rtl_lib.h b/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/common/rtl_std_lib/include/rtl_lib.h deleted file mode 100644 index d936cf1355..0000000000 --- a/targets/TARGET_Realtek/TARGET_AMEBA/sdk/soc/realtek/common/rtl_std_lib/include/rtl_lib.h +++ /dev/null @@ -1,155 +0,0 @@ -/****************************************************************************** - * Copyright (c) 2013-2016 Realtek Semiconductor Corp. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -#ifndef _RTL_LIB_H_ -#define _RTL_LIB_H_ - - -#include -#include - - -extern int __rtl_errno; - - -void init_rom_libgloss_ram_map(void); - - -// -// RTL library functions for Libc::stdio -// - -extern int rtl_printf(IN const char* fmt, ...); -extern int rtl_vprintf(const char *fmt, void *param); -extern int rtl_sprintf(char* str, const char* fmt, ...); -extern int rtl_snprintf(char* str, size_t size, const char* fmt, ...); -extern int rtl_vsnprintf(char *str, size_t size, const char *fmt, void *param); - -// -// RTL library functions for string -// - -extern void * rtl_memchr(const void * src_void , int c , size_t length); -extern int rtl_memcmp(const void * m1 , const void * m2 , size_t n); -extern void * rtl_memcpy(void * dst0 , const void * src0 , size_t len0); -extern void * rtl_memmove( void * dst_void , const void * src_void , size_t length); -extern void * rtl_memset(void * m , int c , size_t n); -extern char * rtl_strcat(char * s1 , const char * s2); -extern char * rtl_strchr(const char *s1 , int i); -extern int rtl_strcmp(const char *s1 , const char *s2); -extern char* rtl_strcpy(char *dst0 , const char *src0); -extern size_t rtl_strlen(const char *str); -extern char * rtl_strncat(char * s1 , const char * s2 , size_t n); -extern int rtl_strncmp(const char *s1 , const char *s2 , size_t n); -extern char * rtl_strncpy(char * dst0 , const char * src0 , size_t count); -extern char * rtl_strstr(const char *searchee , const char *lookfor); -extern char * rtl_strsep(char **source_ptr , const char *delim); -extern char * rtl_strtok(char * s , const char * delim); - -// -// RTL library functions for math -// - - -extern double rtl_fabs(double); -extern float rtl_fabsf(float a); -extern float rtl_cos_f32(float a); -extern float rtl_sin_f32(float a); - -extern float rtl_fadd(float a, float b); -extern float rtl_fsub(float a, float b); -extern float rtl_fmul(float a, float b); -extern float rtl_fdiv(float a, float b); - -extern int rtl_fcmplt(float a, float b); -extern int rtl_fcmpgt(float a, float b); - - - - - -// -// RTL eabi functions - -extern double rtl_ftod(float f); - -extern double rtl_ddiv(double a, double b); - - -// -// Macro Library Functions -// - -typedef union -{ - float value; - u32 word; -} ieee_float_shape_type; - -/* Get a 32 bit int from a float. */ - -#define GET_FLOAT_WORD(i,d) \ -do { \ - ieee_float_shape_type gf_u; \ - gf_u.value = (d); \ - (i) = gf_u.word; \ -} while (0) - -/* Set a float from a 32 bit int. */ - -#define SET_FLOAT_WORD(d,i) \ -do { \ - ieee_float_shape_type sf_u; \ - sf_u.word = (i); \ - (d) = sf_u.value; \ -} while (0) - -static inline -float rtl_nanf(void) -{ - float x; - - SET_FLOAT_WORD(x,0x7fc00000); - return x; -} - - -// -// Library Test functions -// - -extern int rtl_lib_test(IN u16 argc, IN u8 *argv[]); -extern int rtl_math_test(IN u16 argc, IN u8 *argv[]); -extern int rtl_string_test(IN u16 argc, IN u8 *argv[]); - - -// -// Macro functions -// - -#undef dbg_printf -#define dbg_printf(fmt, args...) \ - rtl_printf("%s():%d : " fmt "\n", __FUNCTION__, __LINE__, ##args); - - -#undef err_printf -#define err_printf(fmt, args...) \ - rtl_printf("%s():%d : " fmt "\n", __FUNCTION__, __LINE__, ##args); - - -#endif /* _RTL_LIB_H_ */ - diff --git a/targets/TARGET_Realtek/mbed_rtx.h b/targets/TARGET_Realtek/mbed_rtx.h index 934726af56..96a8bc0756 100644 --- a/targets/TARGET_Realtek/mbed_rtx.h +++ b/targets/TARGET_Realtek/mbed_rtx.h @@ -41,4 +41,4 @@ #endif #endif -#endif \ No newline at end of file +#endif diff --git a/targets/TARGET_STM/TARGET_STM32F0/common_objects.h b/targets/TARGET_STM/TARGET_STM32F0/common_objects.h index fee640796f..89b076ef07 100644 --- a/targets/TARGET_STM/TARGET_STM32F0/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32F0/common_objects.h @@ -148,7 +148,6 @@ struct flash_s { #endif /* STM32F0 HAL doesn't provide this API called in rtc_api.c */ -#define __HAL_RCC_RTC_CLKPRESCALER(__RTCCLKSource__) #define RTC_WKUP_IRQn RTC_IRQn #endif diff --git a/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/PeripheralPins.c index 5deb5abe5c..28b470a744 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/PeripheralPins.c @@ -1,6 +1,6 @@ /* mbed Microcontroller Library ******************************************************************************* - * Copyright (c) 2014, STMicroelectronics + * Copyright (c) 2018, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -26,19 +26,35 @@ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************* + * + * Automatically generated from STM32F103C(8-B)Tx.xml */ #include "PeripheralPins.h" +#include "mbed_toolchain.h" + +//============================================================================== +// Notes +// +// - The pins mentioned Px_y_ALTz are alternative possibilities which use other +// HW peripheral instances. You can use them the same way as any other "normal" +// pin (i.e. PwmOut pwm(PA_7_ALT0);). These pins are not displayed on the board +// pinout image on mbed.org. +// +// - The pins which are connected to other components present on the board have +// the comment "Connected to xxx". The pin function may not work properly in this +// case. These pins may not be displayed on the board pinout image on mbed.org. +// Please read the board reference manual and schematic for more information. +// +// - Warning: pins connected to the default STDIO_UART_TX and STDIO_UART_RX pins are commented +// See https://os.mbed.com/teams/ST/wiki/STDIO for more information. +// +//============================================================================== -// ===== -// Note: Commented lines are alternative possibilities which are not used per default. -// If you change them, you will have also to modify the corresponding xxx_api.c file -// for pwmout, analogin, analogout, ... -// ===== //*** ADC *** -const PinMap PinMap_ADC[] = { +MBED_WEAK const PinMap PinMap_ADC[] = { {PA_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 0, 0)}, // ADC_IN0 {PA_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // ADC_IN1 {PA_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // ADC_IN2 @@ -55,7 +71,7 @@ const PinMap PinMap_ADC[] = { {PC_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 13, 0)}, // ADC_IN13 {PC_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 14, 0)}, // ADC_IN14 {PC_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 15, 0)}, // ADC_IN15 - {NC, NC, 0} + {NC, NC, 0} }; const PinMap PinMap_ADC_Internal[] = { @@ -66,118 +82,135 @@ const PinMap PinMap_ADC_Internal[] = { //*** I2C *** -const PinMap PinMap_I2C_SDA[] = { - {PB_7, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, 0)}, - {PB_9, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, 2)}, // GPIO_Remap_I2C1 - {PB_11, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, 0)}, - {NC, NC, 0} +MBED_WEAK const PinMap PinMap_I2C_SDA[] = { + {PB_7, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, 0)}, + {PB_9, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, 2)}, + {PB_11, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, 0)}, + {NC, NC, 0} }; -const PinMap PinMap_I2C_SCL[] = { - {PB_6, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, 0)}, - {PB_8, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, 2)}, // GPIO_Remap_I2C1 - {PB_10, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, 0)}, - {NC, NC, 0} +MBED_WEAK const PinMap PinMap_I2C_SCL[] = { + {PB_6, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, 0)}, + {PB_8, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, 2)}, + {PB_10, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, 0)}, + {NC, NC, 0} }; //*** PWM *** // TIM4 cannot be used because already used by the us_ticker -const PinMap PinMap_PWM[] = { - {PA_1, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 2, 0)}, // TIM2_CH2 - Default - {PA_2, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 3, 0)}, // TIM2_CH3 - Default (warning: not connected on D1 per default) - {PA_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 4, 0)}, // TIM2_CH4 - Default (warning: not connected on D0 per default) - {PA_6, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 1, 0)}, // TIM3_CH1 - Default - {PA_7, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 2, 0)}, // TIM3_CH2 - Default -// {PA_7, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 6, 1, 1)}, // TIM1_CH1N - GPIO_PartialRemap_TIM1 - {PA_8, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 1, 0)}, // TIM1_CH1 - Default - {PA_9, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 2, 0)}, // TIM1_CH2 - Default - {PA_10, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 3, 0)}, // TIM1_CH3 - Default - {PA_11, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 4, 0)}, // TIM1_CH4 - Default - {PA_15, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 8, 1, 0)}, // TIM2_CH1_ETR - GPIO_FullRemap_TIM2 - - {PB_0, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 3, 0)}, // TIM3_CH3 - Default -// {PB_0, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 6, 2, 1)}, // TIM1_CH2N - GPIO_PartialRemap_TIM1 - {PB_1, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 4, 0)}, // TIM3_CH4 - Default -// {PB_1, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 6, 3, 1)}, // TIM1_CH3N - GPIO_PartialRemap_TIM1 - {PB_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 8, 2, 0)}, // TIM2_CH2 - GPIO_FullRemap_TIM2 - {PB_4, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 7, 1, 0)}, // TIM3_CH1 - GPIO_PartialRemap_TIM3 - {PB_5, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 7, 2, 0)}, // TIM3_CH2 - GPIO_PartialRemap_TIM3 -// {PB_6, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 1, 0)}, // TIM4_CH1 - Default (used by ticker) -// {PB_7, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 2, 0)}, // TIM4_CH2 - Default (used by ticker) -// {PB_8, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 3, 0)}, // TIM4_CH3 - Default (used by ticker) -// {PB_9, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 4, 0)}, // TIM4_CH4 - Default (used by ticker) - {PB_10, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 8, 3, 0)}, // TIM2_CH3 - GPIO_FullRemap_TIM2 - {PB_11, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 8, 4, 0)}, // TIM2_CH4 - GPIO_FullRemap_TIM2 - {PB_13, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 1, 1)}, // TIM1_CH1N - Default - {PB_14, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 2, 1)}, // TIM1_CH2N - Default - {PB_15, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 3, 1)}, // TIM1_CH3N - Default - - {PC_6, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 9, 1, 0)}, // TIM3_CH1 - GPIO_FullRemap_TIM3 - {PC_7, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 9, 2, 0)}, // TIM3_CH2 - GPIO_FullRemap_TIM3 - {PC_8, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 9, 3, 0)}, // TIM3_CH3 - GPIO_FullRemap_TIM3 - {PC_9, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 9, 4, 0)}, // TIM3_CH4 - GPIO_FullRemap_TIM3 - {NC, NC, 0} +// You have to comment all PWM_4 +MBED_WEAK const PinMap PinMap_PWM[] = { + {PA_0, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 1, 0)}, // TIM2_CH1 + {PA_1, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 2, 0)}, // TIM2_CH2 + {PA_2, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 3, 0)}, // TIM2_CH3 + {PA_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 4, 0)}, // TIM2_CH4 + {PA_6, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 1, 0)}, // TIM3_CH1 + {PA_7, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 2, 0)}, // TIM3_CH2 + {PA_8, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 1, 0)}, // TIM1_CH1 + {PA_8, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 6, 1, 0)}, // TIM1_CH1 + {PA_9, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 2, 0)}, // TIM1_CH2 + {PA_9, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 6, 2, 0)}, // TIM1_CH2 + {PA_10, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 3, 0)}, // TIM1_CH3 + {PA_10, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 6, 3, 0)}, // TIM1_CH3 + {PA_11, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 4, 0)}, // TIM1_CH4 + {PA_11, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 6, 4, 0)}, // TIM1_CH4 + {PA_15, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 8, 1, 0)}, // TIM2_CH1 + {PB_0, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 6, 2, 1)}, // TIM1_CH2N + {PB_0_ALT0, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 3, 0)}, // TIM3_CH3 + {PB_0_ALT0, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 7, 3, 0)}, // TIM3_CH3 + {PB_1, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 6, 3, 1)}, // TIM1_CH3N + {PB_1_ALT0, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 4, 0)}, // TIM3_CH4 + {PB_1_ALT0, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 7, 4, 0)}, // TIM3_CH4 + {PB_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 8, 2, 0)}, // TIM2_CH2 + {PB_4, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 7, 1, 0)}, // TIM3_CH1 + {PB_5, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 7, 2, 0)}, // TIM3_CH2 +// {PB_6, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 1, 0)}, // TIM4_CH1 +// {PB_7, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 2, 0)}, // TIM4_CH2 +// {PB_8, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 3, 0)}, // TIM4_CH3 +// {PB_9, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 4, 0)}, // TIM4_CH4 + {PB_10, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 8, 3, 0)}, // TIM2_CH3 + {PB_11, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 8, 4, 0)}, // TIM2_CH4 + {PB_13, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 1, 1)}, // TIM1_CH1N + {PB_14, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 2, 1)}, // TIM1_CH2N + {PB_15, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, 0, 3, 1)}, // TIM1_CH3N + {NC, NC, 0} }; //*** SERIAL *** -const PinMap PinMap_UART_TX[] = { - {PA_2, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, 0)}, - {PA_9, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, 0)}, - {PB_6, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, 3)}, // GPIO_Remap_USART1 - {PB_10, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, 0)}, - {PC_10, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, 5)}, // GPIO_PartialRemap_USART3 - {NC, NC, 0} +MBED_WEAK const PinMap PinMap_UART_TX[] = { + {PA_2, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, 0)}, + {PA_9, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, 0)}, + {PB_6, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, 3)}, // GPIO_Remap_USART1 + {PB_10, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, 0)}, + {PC_10, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, 5)}, // GPIO_PartialRemap_USART3 + {NC, NC, 0} }; -const PinMap PinMap_UART_RX[] = { - {PA_3, UART_2, STM_PIN_DATA(STM_MODE_INPUT, GPIO_PULLUP, 0)}, - {PA_10, UART_1, STM_PIN_DATA(STM_MODE_INPUT, GPIO_PULLUP, 0)}, - {PB_7, UART_1, STM_PIN_DATA(STM_MODE_INPUT, GPIO_PULLUP, 3)}, // GPIO_Remap_USART1 - {PB_11, UART_3, STM_PIN_DATA(STM_MODE_INPUT, GPIO_PULLUP, 0)}, - {PC_11, UART_3, STM_PIN_DATA(STM_MODE_INPUT, GPIO_PULLUP, 5)}, // GPIO_PartialRemap_USART3 - {NC, NC, 0} +MBED_WEAK const PinMap PinMap_UART_RX[] = { + {PA_3, UART_2, STM_PIN_DATA(STM_MODE_INPUT, GPIO_PULLUP, 0)}, + {PA_10, UART_1, STM_PIN_DATA(STM_MODE_INPUT, GPIO_PULLUP, 0)}, + {PB_7, UART_1, STM_PIN_DATA(STM_MODE_INPUT, GPIO_PULLUP, 3)}, // GPIO_Remap_USART1 + {PB_11, UART_3, STM_PIN_DATA(STM_MODE_INPUT, GPIO_PULLUP, 0)}, + {PC_11, UART_3, STM_PIN_DATA(STM_MODE_INPUT, GPIO_PULLUP, 5)}, // GPIO_PartialRemap_USART3 + {NC, NC, 0} +}; + +MBED_WEAK const PinMap PinMap_UART_RTS[] = { + {PA_1, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, 0)}, + {PA_12, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, 0)}, + {PB_14, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, 0)}, + {NC, NC, 0} +}; + +MBED_WEAK const PinMap PinMap_UART_CTS[] = { + {PA_0, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, 0)}, + {PA_11, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, 0)}, + {PB_13, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, 0)}, + {NC, NC, 0} }; //*** SPI *** -const PinMap PinMap_SPI_MOSI[] = { - {PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 0)}, - {PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 1)}, // GPIO_Remap_SPI1 - {PB_15, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 0)}, - {NC, NC, 0} +MBED_WEAK const PinMap PinMap_SPI_MOSI[] = { + {PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 0)}, + {PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 1)}, + {PB_15, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 0)}, + {NC, NC, 0} }; -const PinMap PinMap_SPI_MISO[] = { - {PA_6, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 0)}, - {PB_4, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 1)}, // GPIO_Remap_SPI1 - {PB_14, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 0)}, - {NC, NC, 0} +MBED_WEAK const PinMap PinMap_SPI_MISO[] = { + {PA_6, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 0)}, + {PB_4, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 1)}, + {PB_14, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 0)}, + {NC, NC, 0} }; -const PinMap PinMap_SPI_SCLK[] = { - {PA_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 0)}, - {PB_3, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 1)}, // GPIO_Remap_SPI1 - {PB_13, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 0)}, - {NC, NC, 0} +MBED_WEAK const PinMap PinMap_SPI_SCLK[] = { + {PA_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 0)}, + {PB_3, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 1)}, + {PB_13, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 0)}, + {NC, NC, 0} }; -const PinMap PinMap_SPI_SSEL[] = { - {PA_4, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 0)}, - {PA_15, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 1)}, // GPIO_Remap_SPI1 - {PB_12, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 0)}, - {NC, NC, 0} +MBED_WEAK const PinMap PinMap_SPI_SSEL[] = { + {PA_4, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 0)}, + {PA_15, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 1)}, + {PB_12, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 0)}, + {NC, NC, 0} }; -const PinMap PinMap_CAN_RD[] = { - {PA_11, CAN_1, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)}, - {PB_8, CAN_1, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 1)}, - {NC, NC, 0} +//*** CAN *** + +MBED_WEAK const PinMap PinMap_CAN_RD[] = { + {PA_11, CAN_1, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)}, + {PB_8, CAN_1, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 10)}, + {NC, NC, 0} }; -const PinMap PinMap_CAN_TD[] = { - {PA_12, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 0)}, - {PB_9, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 1)}, - {NC, NC, 0} +MBED_WEAK const PinMap PinMap_CAN_TD[] = { + {PA_12, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 0)}, + {PB_9, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, 10)}, + {NC, NC, 0} }; diff --git a/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/PinNames.h b/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/PinNames.h index cd2e2e9416..6756cb7bb7 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/PinNames.h @@ -37,6 +37,13 @@ extern "C" { #endif +typedef enum { + ALT0 = 0x100, + ALT1 = 0x200, + ALT2 = 0x300, + ALT3 = 0x400 +} ALTx; + typedef enum { PA_0 = 0x00, PA_1 = 0x01, @@ -46,6 +53,7 @@ typedef enum { PA_5 = 0x05, PA_6 = 0x06, PA_7 = 0x07, + PA_7_ALT0 = 0x07 | ALT0, PA_8 = 0x08, PA_9 = 0x09, PA_10 = 0x0A, @@ -56,7 +64,9 @@ typedef enum { PA_15 = 0x0F, PB_0 = 0x10, + PB_0_ALT0 = 0x10 | ALT0, PB_1 = 0x11, + PB_1_ALT0 = 0x11 | ALT0, PB_2 = 0x12, PB_3 = 0x13, PB_4 = 0x14, diff --git a/targets/TARGET_STM/TARGET_STM32F1/common_objects.h b/targets/TARGET_STM/TARGET_STM32F1/common_objects.h index d57c6128f9..b22a153b0c 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32F1/common_objects.h @@ -137,8 +137,4 @@ struct flash_s { } #endif -/* STM32F1 HAL doesn't provide this API called in rtc_api.c */ -#define __HAL_RCC_RTC_CLKPRESCALER(__RTCCLKSource__) - #endif - diff --git a/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/device/TOOLCHAIN_IAR/stm32f207xx.icf b/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/device/TOOLCHAIN_IAR/stm32f207xx.icf index 7432e2bcf1..b82a5368cb 100644 --- a/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/device/TOOLCHAIN_IAR/stm32f207xx.icf +++ b/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/device/TOOLCHAIN_IAR/stm32f207xx.icf @@ -21,7 +21,7 @@ define region RAM_region = mem:[from __region_RAM_start__ to __region_RAM_end__] /* Stack: 1024B */ /* Heap: 64kB */ define symbol __size_cstack__ = 0x400; -define symbol __size_heap__ = 0x10000; +define symbol __size_heap__ = 0xF000; define block CSTACK with alignment = 8, size = __size_cstack__ { }; define block HEAP with alignment = 8, size = __size_heap__ { }; define block STACKHEAP with fixed order { block HEAP, block CSTACK }; diff --git a/targets/TARGET_STM/TARGET_STM32F3/analogin_device.c b/targets/TARGET_STM/TARGET_STM32F3/analogin_device.c index fe82886354..84f771b66d 100644 --- a/targets/TARGET_STM/TARGET_STM32F3/analogin_device.c +++ b/targets/TARGET_STM/TARGET_STM32F3/analogin_device.c @@ -34,6 +34,7 @@ #include "cmsis.h" #include "pinmap.h" #include "mbed_error.h" +#include "mbed_debug.h" #include "PeripheralPins.h" void analogin_init(analogin_t *obj, PinName pin) @@ -211,16 +212,27 @@ uint16_t adc_read(analogin_t *obj) return 0; } - HAL_ADC_ConfigChannel(&obj->handle, &sConfig); - - HAL_ADC_Start(&obj->handle); // Start conversion - - // Wait end of conversion and get value - if (HAL_ADC_PollForConversion(&obj->handle, 10) == HAL_OK) { - return (uint16_t)HAL_ADC_GetValue(&obj->handle); - } else { - return 0; + if (HAL_ADC_ConfigChannel(&obj->handle, &sConfig) != HAL_OK) { + debug("HAL_ADC_ConfigChannel issue\n");; } + + if (HAL_ADC_Start(&obj->handle) != HAL_OK) { + debug("HAL_ADC_Start issue\n");; + } + + uint16_t MeasuredValue = 0; + + if (HAL_ADC_PollForConversion(&obj->handle, 10) == HAL_OK) { + MeasuredValue = (uint16_t)HAL_ADC_GetValue(&obj->handle); + } else { + debug("HAL_ADC_PollForConversion issue\n"); + } + + if (HAL_ADC_Stop(&obj->handle) != HAL_OK) { + debug("HAL_ADC_Stop issue\n");; + } + + return MeasuredValue; } #endif diff --git a/targets/TARGET_STM/TARGET_STM32F3/common_objects.h b/targets/TARGET_STM/TARGET_STM32F3/common_objects.h index 590b60d94c..b1d82d34e7 100644 --- a/targets/TARGET_STM/TARGET_STM32F3/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32F3/common_objects.h @@ -145,8 +145,4 @@ struct flash_s { } #endif -/* STM32F3 HAL doesn't provide this API called in rtc_api.c */ -#define __HAL_RCC_RTC_CLKPRESCALER(__RTCCLKSource__) - #endif - diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/TARGET_UBLOX_C030/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/TARGET_UBLOX_C030/PeripheralPins.c index fdadcf533b..0e981e7764 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/TARGET_UBLOX_C030/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/TARGET_UBLOX_C030/PeripheralPins.c @@ -43,6 +43,7 @@ const PinMap PinMap_ADC[] = { {PA_6, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC1_IN6 {PB_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC1_IN8 {PC_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 10, 0)}, // ADC1_IN10 + {PC_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 12, 0)}, // ADC1_IN12 {PC_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 13, 0)}, // ADC1_IN13 {NC, NC, 0} }; diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_STM32L072xZ/TARGET_DISCO_L072CZ_LRWAN1/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32L0/TARGET_STM32L072xZ/TARGET_DISCO_L072CZ_LRWAN1/PeripheralPins.c index 1a9fee696f..91be89aa14 100644 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_STM32L072xZ/TARGET_DISCO_L072CZ_LRWAN1/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32L0/TARGET_STM32L072xZ/TARGET_DISCO_L072CZ_LRWAN1/PeripheralPins.c @@ -70,9 +70,8 @@ MBED_WEAK const PinMap PinMap_ADC[] = { }; MBED_WEAK const PinMap PinMap_ADC_Internal[] = { - {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, - {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 0, 0)}, - {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, + {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // ADC_IN17 // VREFINT + {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // ADC_IN18 // VSENSE {NC, NC, 0} }; diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_STM32L0x2xZ/TARGET_MTB_MURATA_ABZ/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32L0/TARGET_STM32L0x2xZ/TARGET_MTB_MURATA_ABZ/PeripheralPins.c index 9dc154d337..ca284f3b7e 100644 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_STM32L0x2xZ/TARGET_MTB_MURATA_ABZ/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32L0/TARGET_STM32L0x2xZ/TARGET_MTB_MURATA_ABZ/PeripheralPins.c @@ -48,9 +48,8 @@ const PinMap PinMap_ADC[] = { }; const PinMap PinMap_ADC_Internal[] = { - {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // Internal channel - {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 0, 0)}, // Internal channel - {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // Internal channel + {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // ADC_IN17 // VREFINT + {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // ADC_IN18 // VSENSE {NC, NC, 0} }; diff --git a/targets/TARGET_STM/TARGET_STM32L0/analogin_device.c b/targets/TARGET_STM/TARGET_STM32L0/analogin_device.c index 004db4b6e4..cdfd2a7dc5 100644 --- a/targets/TARGET_STM/TARGET_STM32L0/analogin_device.c +++ b/targets/TARGET_STM/TARGET_STM32L0/analogin_device.c @@ -172,6 +172,12 @@ uint16_t adc_read(analogin_t *obj) HAL_ADC_ConfigChannel(&obj->handle, &sConfig); + /* need to wait for some stabilization time after setting the TSEN bit in the ADC_CCR + register to wake up the temperature sensor from power down mode */ + if (sConfig.Channel == ADC_CHANNEL_TEMPSENSOR) { + wait_ms(20); + } + HAL_ADC_Start(&obj->handle); // Start conversion // Wait end of conversion and get value diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L432xC/TARGET_NUCLEO_L432KC/system_clock.c b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L432xC/TARGET_NUCLEO_L432KC/system_clock.c index 8f7409a57c..c47c24bb84 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L432xC/TARGET_NUCLEO_L432KC/system_clock.c +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L432xC/TARGET_NUCLEO_L432KC/system_clock.c @@ -322,15 +322,19 @@ uint8_t SetSysClock_PLL_MSI(void) RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; +#if MBED_CONF_TARGET_LSE_AVAILABLE // Enable LSE Oscillator to automatically calibrate the MSI clock RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // No PLL update RCC_OscInitStruct.LSEState = RCC_LSE_ON; // External 32.768 kHz clock on OSC_IN/OSC_OUT - if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK) { - RCC->CR |= RCC_CR_MSIPLLEN; // Enable MSI PLL-mode + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + return 0; // FAIL } + /* Enable the CSS interrupt in case LSE signal is corrupted or not present */ HAL_RCCEx_DisableLSECSS(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Enable MSI Oscillator and activate PLL with MSI as source */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.MSIState = RCC_MSI_ON; @@ -349,8 +353,12 @@ uint8_t SetSysClock_PLL_MSI(void) if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { return 0; // FAIL } + +#if MBED_CONF_TARGET_LSE_AVAILABLE /* Enable MSI Auto-calibration through LSE */ HAL_RCCEx_EnableMSIPLLMode(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Select MSI output as USB clock source */ PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USB; PeriphClkInitStruct.UsbClockSelection = RCC_USBCLKSOURCE_MSI; /* 48 MHz */ diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L433xC/TARGET_NUCLEO_L433RC_P/system_clock.c b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L433xC/TARGET_NUCLEO_L433RC_P/system_clock.c index 8f7409a57c..c47c24bb84 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L433xC/TARGET_NUCLEO_L433RC_P/system_clock.c +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L433xC/TARGET_NUCLEO_L433RC_P/system_clock.c @@ -322,15 +322,19 @@ uint8_t SetSysClock_PLL_MSI(void) RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; +#if MBED_CONF_TARGET_LSE_AVAILABLE // Enable LSE Oscillator to automatically calibrate the MSI clock RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // No PLL update RCC_OscInitStruct.LSEState = RCC_LSE_ON; // External 32.768 kHz clock on OSC_IN/OSC_OUT - if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK) { - RCC->CR |= RCC_CR_MSIPLLEN; // Enable MSI PLL-mode + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + return 0; // FAIL } + /* Enable the CSS interrupt in case LSE signal is corrupted or not present */ HAL_RCCEx_DisableLSECSS(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Enable MSI Oscillator and activate PLL with MSI as source */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.MSIState = RCC_MSI_ON; @@ -349,8 +353,12 @@ uint8_t SetSysClock_PLL_MSI(void) if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { return 0; // FAIL } + +#if MBED_CONF_TARGET_LSE_AVAILABLE /* Enable MSI Auto-calibration through LSE */ HAL_RCCEx_EnableMSIPLLMode(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Select MSI output as USB clock source */ PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USB; PeriphClkInitStruct.UsbClockSelection = RCC_USBCLKSOURCE_MSI; /* 48 MHz */ diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L443xC/TARGET_MTB_ADV_WISE_1510/system_clock.c b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L443xC/TARGET_MTB_ADV_WISE_1510/system_clock.c index 8f7409a57c..c47c24bb84 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L443xC/TARGET_MTB_ADV_WISE_1510/system_clock.c +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L443xC/TARGET_MTB_ADV_WISE_1510/system_clock.c @@ -322,15 +322,19 @@ uint8_t SetSysClock_PLL_MSI(void) RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; +#if MBED_CONF_TARGET_LSE_AVAILABLE // Enable LSE Oscillator to automatically calibrate the MSI clock RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // No PLL update RCC_OscInitStruct.LSEState = RCC_LSE_ON; // External 32.768 kHz clock on OSC_IN/OSC_OUT - if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK) { - RCC->CR |= RCC_CR_MSIPLLEN; // Enable MSI PLL-mode + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + return 0; // FAIL } + /* Enable the CSS interrupt in case LSE signal is corrupted or not present */ HAL_RCCEx_DisableLSECSS(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Enable MSI Oscillator and activate PLL with MSI as source */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.MSIState = RCC_MSI_ON; @@ -349,8 +353,12 @@ uint8_t SetSysClock_PLL_MSI(void) if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { return 0; // FAIL } + +#if MBED_CONF_TARGET_LSE_AVAILABLE /* Enable MSI Auto-calibration through LSE */ HAL_RCCEx_EnableMSIPLLMode(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Select MSI output as USB clock source */ PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USB; PeriphClkInitStruct.UsbClockSelection = RCC_USBCLKSOURCE_MSI; /* 48 MHz */ diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L475xG/TARGET_DISCO_L475VG_IOT01A/system_clock.c b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L475xG/TARGET_DISCO_L475VG_IOT01A/system_clock.c index 4c232a41c3..d71a36fb67 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L475xG/TARGET_DISCO_L475VG_IOT01A/system_clock.c +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L475xG/TARGET_DISCO_L475VG_IOT01A/system_clock.c @@ -309,15 +309,19 @@ uint8_t SetSysClock_PLL_MSI(void) RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; +#if MBED_CONF_TARGET_LSE_AVAILABLE // Enable LSE Oscillator to automatically calibrate the MSI clock RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // No PLL update RCC_OscInitStruct.LSEState = RCC_LSE_ON; // External 32.768 kHz clock on OSC_IN/OSC_OUT - if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK) { - RCC->CR |= RCC_CR_MSIPLLEN; // Enable MSI PLL-mode + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + return 0; // FAIL } + /* Enable the CSS interrupt in case LSE signal is corrupted or not present */ HAL_RCCEx_DisableLSECSS(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Enable MSI Oscillator and activate PLL with MSI as source */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.MSIState = RCC_MSI_ON; @@ -336,8 +340,12 @@ uint8_t SetSysClock_PLL_MSI(void) if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { return 0; // FAIL } + +#if MBED_CONF_TARGET_LSE_AVAILABLE /* Enable MSI Auto-calibration through LSE */ HAL_RCCEx_EnableMSIPLLMode(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Select MSI output as USB clock source */ PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USB; PeriphClkInitStruct.UsbClockSelection = RCC_USBCLKSOURCE_MSI; /* 48 MHz */ diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/system_clock.c b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/system_clock.c index 4c232a41c3..d71a36fb67 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/system_clock.c +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/system_clock.c @@ -309,15 +309,19 @@ uint8_t SetSysClock_PLL_MSI(void) RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; +#if MBED_CONF_TARGET_LSE_AVAILABLE // Enable LSE Oscillator to automatically calibrate the MSI clock RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // No PLL update RCC_OscInitStruct.LSEState = RCC_LSE_ON; // External 32.768 kHz clock on OSC_IN/OSC_OUT - if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK) { - RCC->CR |= RCC_CR_MSIPLLEN; // Enable MSI PLL-mode + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + return 0; // FAIL } + /* Enable the CSS interrupt in case LSE signal is corrupted or not present */ HAL_RCCEx_DisableLSECSS(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Enable MSI Oscillator and activate PLL with MSI as source */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.MSIState = RCC_MSI_ON; @@ -336,8 +340,12 @@ uint8_t SetSysClock_PLL_MSI(void) if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { return 0; // FAIL } + +#if MBED_CONF_TARGET_LSE_AVAILABLE /* Enable MSI Auto-calibration through LSE */ HAL_RCCEx_EnableMSIPLLMode(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Select MSI output as USB clock source */ PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USB; PeriphClkInitStruct.UsbClockSelection = RCC_USBCLKSOURCE_MSI; /* 48 MHz */ diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_NUCLEO_L476RG/system_clock.c b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_NUCLEO_L476RG/system_clock.c index 4c232a41c3..d71a36fb67 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_NUCLEO_L476RG/system_clock.c +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_NUCLEO_L476RG/system_clock.c @@ -309,15 +309,19 @@ uint8_t SetSysClock_PLL_MSI(void) RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; +#if MBED_CONF_TARGET_LSE_AVAILABLE // Enable LSE Oscillator to automatically calibrate the MSI clock RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // No PLL update RCC_OscInitStruct.LSEState = RCC_LSE_ON; // External 32.768 kHz clock on OSC_IN/OSC_OUT - if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK) { - RCC->CR |= RCC_CR_MSIPLLEN; // Enable MSI PLL-mode + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + return 0; // FAIL } + /* Enable the CSS interrupt in case LSE signal is corrupted or not present */ HAL_RCCEx_DisableLSECSS(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Enable MSI Oscillator and activate PLL with MSI as source */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.MSIState = RCC_MSI_ON; @@ -336,8 +340,12 @@ uint8_t SetSysClock_PLL_MSI(void) if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { return 0; // FAIL } + +#if MBED_CONF_TARGET_LSE_AVAILABLE /* Enable MSI Auto-calibration through LSE */ HAL_RCCEx_EnableMSIPLLMode(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Select MSI output as USB clock source */ PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USB; PeriphClkInitStruct.UsbClockSelection = RCC_USBCLKSOURCE_MSI; /* 48 MHz */ diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_SILICA_SENSOR_NODE/system_clock.c b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_SILICA_SENSOR_NODE/system_clock.c index 4c232a41c3..d71a36fb67 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_SILICA_SENSOR_NODE/system_clock.c +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_SILICA_SENSOR_NODE/system_clock.c @@ -309,15 +309,19 @@ uint8_t SetSysClock_PLL_MSI(void) RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; +#if MBED_CONF_TARGET_LSE_AVAILABLE // Enable LSE Oscillator to automatically calibrate the MSI clock RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // No PLL update RCC_OscInitStruct.LSEState = RCC_LSE_ON; // External 32.768 kHz clock on OSC_IN/OSC_OUT - if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK) { - RCC->CR |= RCC_CR_MSIPLLEN; // Enable MSI PLL-mode + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + return 0; // FAIL } + /* Enable the CSS interrupt in case LSE signal is corrupted or not present */ HAL_RCCEx_DisableLSECSS(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Enable MSI Oscillator and activate PLL with MSI as source */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.MSIState = RCC_MSI_ON; @@ -336,8 +340,12 @@ uint8_t SetSysClock_PLL_MSI(void) if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { return 0; // FAIL } + +#if MBED_CONF_TARGET_LSE_AVAILABLE /* Enable MSI Auto-calibration through LSE */ HAL_RCCEx_EnableMSIPLLMode(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Select MSI output as USB clock source */ PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USB; PeriphClkInitStruct.UsbClockSelection = RCC_USBCLKSOURCE_MSI; /* 48 MHz */ diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_MTB_ADV_WISE_1570/system_clock.c b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_MTB_ADV_WISE_1570/system_clock.c index 09fdb7c9e9..2f32d14892 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_MTB_ADV_WISE_1570/system_clock.c +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_MTB_ADV_WISE_1570/system_clock.c @@ -321,15 +321,19 @@ uint8_t SetSysClock_PLL_MSI(void) RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; +#if MBED_CONF_TARGET_LSE_AVAILABLE // Enable LSE Oscillator to automatically calibrate the MSI clock RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // No PLL update RCC_OscInitStruct.LSEState = RCC_LSE_ON; // External 32.768 kHz clock on OSC_IN/OSC_OUT - if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK) { - RCC->CR |= RCC_CR_MSIPLLEN; // Enable MSI PLL-mode + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + return 0; // FAIL } + /* Enable the CSS interrupt in case LSE signal is corrupted or not present */ HAL_RCCEx_DisableLSECSS(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Enable MSI Oscillator and activate PLL with MSI as source */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.MSIState = RCC_MSI_ON; @@ -348,8 +352,12 @@ uint8_t SetSysClock_PLL_MSI(void) if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { return 0; // FAIL } + +#if MBED_CONF_TARGET_LSE_AVAILABLE /* Enable MSI Auto-calibration through LSE */ HAL_RCCEx_EnableMSIPLLMode(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Select MSI output as USB clock source */ PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USB; PeriphClkInitStruct.UsbClockSelection = RCC_USBCLKSOURCE_MSI; /* 48 MHz */ diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_NUCLEO_L486RG/system_clock.c b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_NUCLEO_L486RG/system_clock.c index 8e2272547c..fbc19d8920 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_NUCLEO_L486RG/system_clock.c +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_NUCLEO_L486RG/system_clock.c @@ -309,15 +309,19 @@ uint8_t SetSysClock_PLL_MSI(void) RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; +#if MBED_CONF_TARGET_LSE_AVAILABLE // Enable LSE Oscillator to automatically calibrate the MSI clock RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // No PLL update RCC_OscInitStruct.LSEState = RCC_LSE_ON; // External 32.768 kHz clock on OSC_IN/OSC_OUT - if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK) { - RCC->CR |= RCC_CR_MSIPLLEN; // Enable MSI PLL-mode + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + return 0; // FAIL } + /* Enable the CSS interrupt in case LSE signal is corrupted or not present */ HAL_RCCEx_DisableLSECSS(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Enable MSI Oscillator and activate PLL with MSI as source */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.MSIState = RCC_MSI_ON; @@ -336,8 +340,12 @@ uint8_t SetSysClock_PLL_MSI(void) if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { return 0; // FAIL } + +#if MBED_CONF_TARGET_LSE_AVAILABLE /* Enable MSI Auto-calibration through LSE */ HAL_RCCEx_EnableMSIPLLMode(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Select MSI output as USB clock source */ PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USB; PeriphClkInitStruct.UsbClockSelection = RCC_USBCLKSOURCE_MSI; /* 48 MHz */ diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L496xG/TARGET_DISCO_L496AG/system_clock.c b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L496xG/TARGET_DISCO_L496AG/system_clock.c index cddb9c174a..97902d6886 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L496xG/TARGET_DISCO_L496AG/system_clock.c +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L496xG/TARGET_DISCO_L496AG/system_clock.c @@ -323,15 +323,19 @@ uint8_t SetSysClock_PLL_MSI(void) RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; +#if MBED_CONF_TARGET_LSE_AVAILABLE // Enable LSE Oscillator to automatically calibrate the MSI clock RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // No PLL update RCC_OscInitStruct.LSEState = RCC_LSE_ON; // External 32.768 kHz clock on OSC_IN/OSC_OUT - if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK) { - RCC->CR |= RCC_CR_MSIPLLEN; // Enable MSI PLL-mode + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + return 0; // FAIL } + /* Enable the CSS interrupt in case LSE signal is corrupted or not present */ HAL_RCCEx_DisableLSECSS(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Enable MSI Oscillator and activate PLL with MSI as source */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.MSIState = RCC_MSI_ON; @@ -349,8 +353,12 @@ uint8_t SetSysClock_PLL_MSI(void) if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { return 0; // FAIL } + +#if MBED_CONF_TARGET_LSE_AVAILABLE /* Enable MSI Auto-calibration through LSE */ HAL_RCCEx_EnableMSIPLLMode(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Select MSI output as USB clock source */ PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USB; PeriphClkInitStruct.UsbClockSelection = RCC_USBCLKSOURCE_MSI; /* 48 MHz */ diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L496xG/TARGET_NUCLEO_L496ZG/system_clock.c b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L496xG/TARGET_NUCLEO_L496ZG/system_clock.c index cddb9c174a..97902d6886 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L496xG/TARGET_NUCLEO_L496ZG/system_clock.c +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L496xG/TARGET_NUCLEO_L496ZG/system_clock.c @@ -323,15 +323,19 @@ uint8_t SetSysClock_PLL_MSI(void) RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; +#if MBED_CONF_TARGET_LSE_AVAILABLE // Enable LSE Oscillator to automatically calibrate the MSI clock RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // No PLL update RCC_OscInitStruct.LSEState = RCC_LSE_ON; // External 32.768 kHz clock on OSC_IN/OSC_OUT - if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK) { - RCC->CR |= RCC_CR_MSIPLLEN; // Enable MSI PLL-mode + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + return 0; // FAIL } + /* Enable the CSS interrupt in case LSE signal is corrupted or not present */ HAL_RCCEx_DisableLSECSS(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Enable MSI Oscillator and activate PLL with MSI as source */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.MSIState = RCC_MSI_ON; @@ -349,8 +353,12 @@ uint8_t SetSysClock_PLL_MSI(void) if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { return 0; // FAIL } + +#if MBED_CONF_TARGET_LSE_AVAILABLE /* Enable MSI Auto-calibration through LSE */ HAL_RCCEx_EnableMSIPLLMode(); +#endif /* MBED_CONF_TARGET_LSE_AVAILABLE */ + /* Select MSI output as USB clock source */ PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USB; PeriphClkInitStruct.UsbClockSelection = RCC_USBCLKSOURCE_MSI; /* 48 MHz */ diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/TARGET_NUCLEO_L4R5ZI/PeripheralNames.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/TARGET_NUCLEO_L4R5ZI/PeripheralNames.h new file mode 100644 index 0000000000..19c36949aa --- /dev/null +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/TARGET_NUCLEO_L4R5ZI/PeripheralNames.h @@ -0,0 +1,89 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2018, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#ifndef MBED_PERIPHERALNAMES_H +#define MBED_PERIPHERALNAMES_H + +#include "cmsis.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + ADC_1 = (int)ADC1_BASE +} ADCName; + +typedef enum { + DAC_1 = (int)DAC_BASE +} DACName; + +typedef enum { + UART_1 = (int)USART1_BASE, + UART_2 = (int)USART2_BASE, + UART_3 = (int)USART3_BASE, + UART_4 = (int)UART4_BASE, + UART_5 = (int)UART5_BASE, + LPUART_1 = (int)LPUART1_BASE +} UARTName; + +typedef enum { + SPI_1 = (int)SPI1_BASE, + SPI_2 = (int)SPI2_BASE, + SPI_3 = (int)SPI3_BASE +} SPIName; + +typedef enum { + I2C_1 = (int)I2C1_BASE, + I2C_2 = (int)I2C2_BASE, + I2C_3 = (int)I2C3_BASE, + I2C_4 = (int)I2C4_BASE +} I2CName; + +typedef enum { + PWM_1 = (int)TIM1_BASE, + PWM_2 = (int)TIM2_BASE, + PWM_3 = (int)TIM3_BASE, + PWM_4 = (int)TIM4_BASE, + PWM_5 = (int)TIM5_BASE, + PWM_8 = (int)TIM8_BASE, + PWM_15 = (int)TIM15_BASE, + PWM_16 = (int)TIM16_BASE, + PWM_17 = (int)TIM17_BASE +} PWMName; + +typedef enum { + CAN_1 = (int)CAN1_BASE +} CANName; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/TARGET_NUCLEO_L4R5ZI/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/TARGET_NUCLEO_L4R5ZI/PeripheralPins.c new file mode 100644 index 0000000000..7875002cd4 --- /dev/null +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/TARGET_NUCLEO_L4R5ZI/PeripheralPins.c @@ -0,0 +1,378 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2018, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ + +#include "PeripheralPins.h" +#include "mbed_toolchain.h" + +//============================================================================== +// Notes +// +// - The pins mentioned Px_y_ALTz are alternative possibilities which use other +// HW peripheral instances. You can use them the same way as any other "normal" +// pin (i.e. PwmOut pwm(PA_7_ALT0);). These pins are not displayed on the board +// pinout image on mbed.org. +// +// - The pins which are connected to other components present on the board have +// the comment "Connected to xxx". The pin function may not work properly in this +// case. These pins may not be displayed on the board pinout image on mbed.org. +// Please read the board reference manual and schematic for more information. +// +// - Warning: pins connected to the default STDIO_UART_TX and STDIO_UART_RX pins are commented +// See https://os.mbed.com/teams/ST/wiki/STDIO for more information. +// +//============================================================================== + + +//*** ADC *** + +MBED_WEAK const PinMap PinMap_ADC[] = { + {PA_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 5, 0)}, // ADC1_IN5 + {PA_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC1_IN6 + {PA_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC1_IN7 + {PA_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC1_IN8 + {PA_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 9, 0)}, // ADC1_IN9 + {PA_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 10, 0)}, // ADC1_IN10 + {PA_6, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 11, 0)}, // ADC1_IN11 + {PA_7, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 12, 0)}, // ADC1_IN12 + {PB_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 15, 0)}, // ADC1_IN15 + {PB_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // ADC1_IN16 + {PC_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // ADC1_IN1 + {PC_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // ADC1_IN2 + {PC_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 3, 0)}, // ADC1_IN3 + {PC_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 4, 0)}, // ADC1_IN4 + {PC_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 13, 0)}, // ADC1_IN13 + {PC_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 14, 0)}, // ADC1_IN14 + {NC, NC, 0} +}; + +MBED_WEAK const PinMap PinMap_ADC_Internal[] = { + {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, + {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 0, 0)}, + {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, + {NC, NC, 0} +}; + +//*** DAC *** + +MBED_WEAK const PinMap PinMap_DAC[] = { + {PA_4, DAC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // DAC1_OUT1 + {PA_5, DAC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // DAC1_OUT2 + {NC, NC, 0} +}; + +//*** I2C *** + +MBED_WEAK const PinMap PinMap_I2C_SDA[] = { + {PB_4, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, + {PB_7, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, // Connected to LD2 [Blue] + {PB_7_ALT0, I2C_4, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF5_I2C4)}, // Connected to LD2 [Blue] + {PB_9, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, + {PB_11, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, + {PB_11_ALT0, I2C_4, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF3_I2C4)}, + {PB_14, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, // Connected to LD3 [Red] + {PC_1, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, + {PC_9, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF6_I2C3)}, + {PD_13, I2C_4, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C4)}, + {PF_0, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, + {PF_15, I2C_4, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C4)}, +// {PG_8, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, // Connected to STDIO_UART_RX + {PG_13, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, + {NC, NC, 0} +}; + +MBED_WEAK const PinMap PinMap_I2C_SCL[] = { + {PA_7, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, + {PB_6, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, + {PB_6_ALT0, I2C_4, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF5_I2C4)}, + {PB_8, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, + {PB_10, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, + {PB_10_ALT0, I2C_4, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF3_I2C4)}, + {PB_13, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, + {PC_0, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, + {PD_12, I2C_4, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C4)}, + {PF_1, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, + {PF_14, I2C_4, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C4)}, +// {PG_7, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, // Connected to STDIO_UART_TX + {PG_14, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, + {NC, NC, 0} +}; + +//*** PWM *** + +// TIM5 (i.e. PWM_5) cannot be used because already used by the us_ticker +MBED_WEAK const PinMap PinMap_PWM[] = { + {PA_0, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1 +// {PA_0_ALT0, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 1, 0)}, // TIM5_CH1 + {PA_1, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2 +// {PA_1_ALT0, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 2, 0)}, // TIM5_CH2 + {PA_1_ALT0, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 1)}, // TIM15_CH1N + {PA_2, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3 +// {PA_2_ALT0, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 3, 0)}, // TIM5_CH3 + {PA_2_ALT0, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 0)}, // TIM15_CH1 + {PA_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4 +// {PA_3_ALT0, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 4, 0)}, // TIM5_CH4 + {PA_3_ALT0, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 2, 0)}, // TIM15_CH2 + {PA_5, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1 + {PA_5_ALT0, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N + {PA_6, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 + {PA_6_ALT0, PWM_16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM16, 1, 0)}, // TIM16_CH1 + {PA_7, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N + {PA_7_ALT0, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 + {PA_7_ALT1, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N + {PA_7_ALT2, PWM_17, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM17, 1, 0)}, // TIM17_CH1 + {PA_8, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 0)}, // TIM1_CH1 // Connected to USB_SOF [TP1] + {PA_9, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 0)}, // TIM1_CH2 // Connected to USB_VBUS + {PA_10, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 0)}, // TIM1_CH3 // Connected to USB_ID + {PA_11, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 4, 0)}, // TIM1_CH4 // Connected to USB_DM + {PA_15, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1 + {PB_0, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 1)}, // TIM1_CH2N + {PB_0_ALT0, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 3, 0)}, // TIM3_CH3 + {PB_0_ALT1, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 2, 1)}, // TIM8_CH2N + {PB_1, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 1)}, // TIM1_CH3N + {PB_1_ALT0, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 4, 0)}, // TIM3_CH4 + {PB_1_ALT1, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 3, 1)}, // TIM8_CH3N + {PB_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2 + {PB_4, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 + {PB_5, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 + {PB_6, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 1, 0)}, // TIM4_CH1 + {PB_6_ALT0, PWM_16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM16, 1, 1)}, // TIM16_CH1N + {PB_7, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 2, 0)}, // TIM4_CH2 // Connected to LD2 [Blue] + {PB_7_ALT0, PWM_17, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM17, 1, 1)}, // TIM17_CH1N // Connected to LD2 [Blue] + {PB_8, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 3, 0)}, // TIM4_CH3 + {PB_8_ALT0, PWM_16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM16, 1, 0)}, // TIM16_CH1 + {PB_9, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 4, 0)}, // TIM4_CH4 + {PB_9_ALT0, PWM_17, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM17, 1, 0)}, // TIM17_CH1 + {PB_10, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3 + {PB_11, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4 + {PB_13, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N + {PB_13_ALT0, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 1)}, // TIM15_CH1N + {PB_14, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 1)}, // TIM1_CH2N // Connected to LD3 [Red] + {PB_14_ALT0, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 2, 1)}, // TIM8_CH2N // Connected to LD3 [Red] + {PB_14_ALT1, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 0)}, // TIM15_CH1 // Connected to LD3 [Red] + {PB_15, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 1)}, // TIM1_CH3N + {PB_15_ALT0, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 3, 1)}, // TIM8_CH3N + {PB_15_ALT1, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 2, 0)}, // TIM15_CH2 + {PC_6, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 + {PC_6_ALT0, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 0)}, // TIM8_CH1 + {PC_7, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 + {PC_7_ALT0, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 2, 0)}, // TIM8_CH2 + {PC_8, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 3, 0)}, // TIM3_CH3 + {PC_8_ALT0, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 3, 0)}, // TIM8_CH3 + {PC_9, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 4, 0)}, // TIM3_CH4 + {PC_9_ALT0, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 4, 0)}, // TIM8_CH4 + {PD_12, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 1, 0)}, // TIM4_CH1 + {PD_13, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 2, 0)}, // TIM4_CH2 + {PD_14, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 3, 0)}, // TIM4_CH3 + {PD_15, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 4, 0)}, // TIM4_CH4 + {PE_0, PWM_16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM16, 1, 0)}, // TIM16_CH1 + {PE_1, PWM_17, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM17, 1, 0)}, // TIM17_CH1 + {PE_3, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 + {PE_4, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 + {PE_5, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 3, 0)}, // TIM3_CH3 + {PE_6, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 4, 0)}, // TIM3_CH4 + {PE_8, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N + {PE_9, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 0)}, // TIM1_CH1 + {PE_10, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 1)}, // TIM1_CH2N + {PE_11, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 0)}, // TIM1_CH2 + {PE_12, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 1)}, // TIM1_CH3N + {PE_13, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 0)}, // TIM1_CH3 + {PE_14, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 4, 0)}, // TIM1_CH4 +// {PF_6, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 1, 0)}, // TIM5_CH1 +// {PF_7, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 2, 0)}, // TIM5_CH2 +// {PF_8, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 3, 0)}, // TIM5_CH3 +// {PF_9, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 4, 0)}, // TIM5_CH4 + {PF_9, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 0)}, // TIM15_CH1 + {PF_10, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 2, 0)}, // TIM15_CH2 + {PG_9, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 1)}, // TIM15_CH1N + {PG_10, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 0)}, // TIM15_CH1 + {PG_11, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 2, 0)}, // TIM15_CH2 + {NC, NC, 0} +}; + +//*** SERIAL *** + +MBED_WEAK const PinMap PinMap_UART_TX[] = { + {PA_0, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, + {PA_2, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, + {PA_2_ALT0, LPUART_1,STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, + {PA_9, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, // Connected to USB_VBUS + {PB_6, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, + {PB_10, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, + {PB_11, LPUART_1,STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, + {PC_1, LPUART_1,STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, + {PC_4, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, + {PC_10, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, + {PC_10_ALT0, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, + {PC_12, UART_5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART5)}, + {PD_5, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, + {PD_8, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, // Connected to STDIO_UART_TX + {PG_7, LPUART_1,STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, // Connected to STDIO_UART_TX + {PG_9, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, + {NC, NC, 0} +}; + +MBED_WEAK const PinMap PinMap_UART_RX[] = { + {PA_1, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, + {PA_3, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, + {PA_3_ALT0, LPUART_1,STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, + {PA_10, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, // Connected to USB_ID + {PA_15, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_USART2)}, + {PB_7, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, // Connected to LD2 [Blue] + {PB_10, LPUART_1,STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, + {PB_11, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, + {PC_0, LPUART_1,STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, + {PC_5, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, + {PC_11, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, + {PC_11_ALT0, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, + {PD_2, UART_5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART5)}, + {PD_6, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, + {PD_9, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, // Connected to STDIO_UART_RX + {PG_8, LPUART_1,STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, // Connected to STDIO_UART_RX + {PG_10, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, + {NC, NC, 0} +}; + +MBED_WEAK const PinMap PinMap_UART_RTS[] = { + {PA_1, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, + {PA_12, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, // Connected to USB_DP + {PA_15, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, + {PA_15_ALT0, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, + {PB_1, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, + {PB_1_ALT0, LPUART_1,STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, + {PB_3, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, + {PB_4, UART_5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART5)}, + {PB_12, LPUART_1,STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, + {PB_14, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, // Connected to LD3 [Red] + {PD_2, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, + {PD_4, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, + {PD_12, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, + {PG_6, LPUART_1,STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, // Connected to USB_OverCurrent [STMPS2151STR_FAULT] + {PG_12, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, + {NC, NC, 0} +}; + +MBED_WEAK const PinMap PinMap_UART_CTS[] = { + {PA_0, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, + {PA_6, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, + {PA_6_ALT0, LPUART_1,STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, + {PA_11, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, // Connected to USB_DM + {PB_4, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, + {PB_5, UART_5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART5)}, + {PB_7, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, // Connected to LD2 [Blue] + {PB_13, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, + {PB_13_ALT0, LPUART_1,STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, + {PD_3, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, + {PD_11, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, + {PG_5, LPUART_1,STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, // Connected to USB_PowerSwitchOn [STMPS2151STR_EN] + {PG_11, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, + {NC, NC, 0} +}; + +//*** SPI *** + +MBED_WEAK const PinMap PinMap_SPI_MOSI[] = { + {PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, + {PA_12, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, // Connected to USB_DP + {PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, + {PB_5_ALT0, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, + {PB_15, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, + {PC_1, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF3_SPI2)}, + {PC_3, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, + {PC_12, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, + {PD_4, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, + {PD_6, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI3)}, + {PE_15, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, + {PG_4, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, + {PG_11, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, + {NC, NC, 0} +}; + +MBED_WEAK const PinMap PinMap_SPI_MISO[] = { + {PA_6, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, + {PA_11, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, // Connected to USB_DM + {PB_4, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, + {PB_4_ALT0, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, + {PB_14, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, // Connected to LD3 [Red] + {PC_2, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, + {PC_11, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, + {PD_3, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, + {PE_14, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, + {PG_3, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, + {PG_10, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, + {NC, NC, 0} +}; + +MBED_WEAK const PinMap PinMap_SPI_SCLK[] = { + {PA_1, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, + {PA_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, + {PA_9, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF3_SPI2)}, // Connected to USB_VBUS + {PB_3, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, + {PB_3_ALT0, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, + {PB_10, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, + {PB_13, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, + {PC_10, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, + {PD_1, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, + {PD_3, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF3_SPI2)}, + {PE_13, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, + {PG_2, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, + {PG_9, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, + {NC, NC, 0} +}; + +MBED_WEAK const PinMap PinMap_SPI_SSEL[] = { + {PA_4, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, + {PA_4_ALT0, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, + {PA_15, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, + {PA_15_ALT0, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, + {PB_0, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, + {PB_9, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, + {PB_12, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, + {PD_0, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, + {PE_12, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, + {PG_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, // Connected to USB_PowerSwitchOn [STMPS2151STR_EN] + {PG_12, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, + {NC, NC, 0} +}; + +//*** CAN *** + +MBED_WEAK const PinMap PinMap_CAN_RD[] = { + {PA_11, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, // Connected to USB_DM + {PB_8, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, + {PD_0, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, + {NC, NC, 0} +}; + +MBED_WEAK const PinMap PinMap_CAN_TD[] = { + {PA_12, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, // Connected to USB_DP + {PB_9, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, + {PD_1, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, + {NC, NC, 0} +}; diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/TARGET_NUCLEO_L4R5ZI/PinNames.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/TARGET_NUCLEO_L4R5ZI/PinNames.h new file mode 100644 index 0000000000..981e097d56 --- /dev/null +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/TARGET_NUCLEO_L4R5ZI/PinNames.h @@ -0,0 +1,331 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2018, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ + +#ifndef MBED_PINNAMES_H +#define MBED_PINNAMES_H + +#include "cmsis.h" +#include "PinNamesTypes.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + ALT0 = 0x100, + ALT1 = 0x200, + ALT2 = 0x300, + ALT3 = 0x400 +} ALTx; + +typedef enum { + + PA_0 = 0x00, + PA_0_ALT0 = PA_0 | ALT0, + PA_1 = 0x01, + PA_1_ALT0 = PA_1 | ALT0, + PA_1_ALT1 = PA_1 | ALT1, + PA_2 = 0x02, + PA_2_ALT0 = PA_2 | ALT0, + PA_2_ALT1 = PA_2 | ALT1, + PA_3 = 0x03, + PA_3_ALT0 = PA_3 | ALT0, + PA_3_ALT1 = PA_3 | ALT1, + PA_4 = 0x04, + PA_4_ALT0 = PA_4 | ALT0, + PA_5 = 0x05, + PA_5_ALT0 = PA_5 | ALT0, + PA_6 = 0x06, + PA_6_ALT0 = PA_6 | ALT0, + PA_7 = 0x07, + PA_7_ALT0 = PA_7 | ALT0, + PA_7_ALT1 = PA_7 | ALT1, + PA_7_ALT2 = PA_7 | ALT2, + PA_8 = 0x08, + PA_9 = 0x09, + PA_10 = 0x0A, + PA_11 = 0x0B, + PA_12 = 0x0C, + PA_13 = 0x0D, + PA_14 = 0x0E, + PA_15 = 0x0F, + PA_15_ALT0 = PA_15 | ALT0, + + PB_0 = 0x10, + PB_0_ALT0 = PB_0 | ALT0, + PB_0_ALT1 = PB_0 | ALT1, + PB_1 = 0x11, + PB_1_ALT0 = PB_1 | ALT0, + PB_1_ALT1 = PB_1 | ALT1, + PB_2 = 0x12, + PB_3 = 0x13, + PB_3_ALT0 = PB_3 | ALT0, + PB_4 = 0x14, + PB_4_ALT0 = PB_4 | ALT0, + PB_5 = 0x15, + PB_5_ALT0 = PB_5 | ALT0, + PB_6 = 0x16, + PB_6_ALT0 = PB_6 | ALT0, + PB_7 = 0x17, + PB_7_ALT0 = PB_7 | ALT0, + PB_8 = 0x18, + PB_8_ALT0 = PB_8 | ALT0, + PB_9 = 0x19, + PB_9_ALT0 = PB_9 | ALT0, + PB_10 = 0x1A, + PB_10_ALT0 = PB_10 | ALT0, + PB_11 = 0x1B, + PB_11_ALT0 = PB_11 | ALT0, + PB_12 = 0x1C, + PB_13 = 0x1D, + PB_13_ALT0 = PB_13 | ALT0, + PB_14 = 0x1E, + PB_14_ALT0 = PB_14 | ALT0, + PB_14_ALT1 = PB_14 | ALT1, + PB_15 = 0x1F, + PB_15_ALT0 = PB_15 | ALT0, + PB_15_ALT1 = PB_15 | ALT1, + + PC_0 = 0x20, + PC_0_ALT0 = PC_0 | ALT0, + PC_0_ALT1 = PC_0 | ALT1, + PC_1 = 0x21, + PC_1_ALT0 = PC_1 | ALT0, + PC_1_ALT1 = PC_1 | ALT1, + PC_2 = 0x22, + PC_2_ALT0 = PC_2 | ALT0, + PC_2_ALT1 = PC_2 | ALT1, + PC_3 = 0x23, + PC_3_ALT0 = PC_3 | ALT0, + PC_3_ALT1 = PC_3 | ALT1, + PC_4 = 0x24, + PC_4_ALT0 = PC_4 | ALT0, + PC_5 = 0x25, + PC_5_ALT0 = PC_5 | ALT0, + PC_6 = 0x26, + PC_6_ALT0 = PC_6 | ALT0, + PC_7 = 0x27, + PC_7_ALT0 = PC_7 | ALT0, + PC_8 = 0x28, + PC_8_ALT0 = PC_8 | ALT0, + PC_9 = 0x29, + PC_9_ALT0 = PC_9 | ALT0, + PC_10 = 0x2A, + PC_10_ALT0 = PC_10 | ALT0, + PC_11 = 0x2B, + PC_11_ALT0 = PC_11 | ALT0, + PC_12 = 0x2C, + PC_13 = 0x2D, + PC_14 = 0x2E, + PC_15 = 0x2F, + + PD_0 = 0x30, + PD_1 = 0x31, + PD_2 = 0x32, + PD_3 = 0x33, + PD_4 = 0x34, + PD_5 = 0x35, + PD_6 = 0x36, + PD_7 = 0x37, + PD_8 = 0x38, + PD_9 = 0x39, + PD_10 = 0x3A, + PD_11 = 0x3B, + PD_12 = 0x3C, + PD_13 = 0x3D, + PD_14 = 0x3E, + PD_15 = 0x3F, + + PE_0 = 0x40, + PE_1 = 0x41, + PE_2 = 0x42, + PE_3 = 0x43, + PE_4 = 0x44, + PE_5 = 0x45, + PE_6 = 0x46, + PE_7 = 0x47, + PE_8 = 0x48, + PE_9 = 0x49, + PE_10 = 0x4A, + PE_11 = 0x4B, + PE_12 = 0x4C, + PE_13 = 0x4D, + PE_14 = 0x4E, + PE_15 = 0x4F, + + PF_0 = 0x50, + PF_1 = 0x51, + PF_2 = 0x52, + PF_3 = 0x53, + PF_4 = 0x54, + PF_5 = 0x55, + PF_6 = 0x56, + PF_7 = 0x57, + PF_8 = 0x58, + PF_9 = 0x59, + PF_9_ALT0 = PF_9 | ALT0, + PF_10 = 0x5A, + PF_11 = 0x5B, + PF_12 = 0x5C, + PF_13 = 0x5D, + PF_14 = 0x5E, + PF_15 = 0x5F, + + PG_0 = 0x60, + PG_1 = 0x61, + PG_2 = 0x62, + PG_3 = 0x63, + PG_4 = 0x64, + PG_5 = 0x65, + PG_6 = 0x66, + PG_7 = 0x67, + PG_8 = 0x68, + PG_9 = 0x69, + PG_10 = 0x6A, + PG_11 = 0x6B, + PG_12 = 0x6C, + PG_13 = 0x6D, + PG_14 = 0x6E, + PG_15 = 0x6F, + + PH_0 = 0x70, + PH_1 = 0x71, + + // ADC internal channels + ADC_TEMP = 0xF0, + ADC_VREF = 0xF1, + ADC_VBAT = 0xF2, + + // Arduino J3 connector namings + A0 = PA_3, + A1 = PC_0, + A2 = PC_3, + A3 = PC_1, + A4 = PC_4, + A5 = PC_5, + D0 = PD_9, + D1 = PD_8, + D2 = PF_15, + D3 = PE_13, + D4 = PF_14, + D5 = PE_11, + D6 = PE_9, + D7 = PF_13, + D8 = PF_12, + D9 = PD_15, + D10 = PD_14, + D11 = PA_7, + D12 = PA_6, + D13 = PA_5, + D14 = PB_9, + D15 = PB_8, + + // STDIO for console print +#ifdef MBED_CONF_TARGET_STDIO_UART_TX + STDIO_UART_TX = MBED_CONF_TARGET_STDIO_UART_TX, +#else + STDIO_UART_TX = PG_7, +#endif +#ifdef MBED_CONF_TARGET_STDIO_UART_RX + STDIO_UART_RX = MBED_CONF_TARGET_STDIO_UART_RX, +#else + STDIO_UART_RX = PG_8, +#endif + + // Generic signals namings + LED1 = PC_7, // Green + LED2 = PB_7, // Blue + LED3 = PB_14, // Red + LED4 = LED1, + LED_RED = LED3, + USER_BUTTON = PC_13, + + // Standardized button names + BUTTON1 = USER_BUTTON, + SERIAL_TX = STDIO_UART_TX, // Virtual Com Port + SERIAL_RX = STDIO_UART_RX, // Virtual Com Port + USBTX = STDIO_UART_TX, // Virtual Com Port + USBRX = STDIO_UART_RX, // Virtual Com Port + I2C_SCL = D15, + I2C_SDA = D14, + SPI_MOSI = D11, + SPI_MISO = D12, + SPI_SCK = D13, + SPI_CS = D10, + PWM_OUT = D9, + +/**** USB pins ****/ + USB_OTG_FS_DM = PA_11, + USB_OTG_FS_DP = PA_12, + USB_OTG_FS_ID = PA_10, + USB_OTG_FS_NOE = PC_9, + USB_OTG_FS_NOE_ALT0 = PA_13, + USB_OTG_FS_SOF = PA_8, + USB_OTG_FS_SOF_ALT0 = PA_14, + USB_OTG_FS_VBUS = PA_9, + +/**** OSCILLATOR pins ****/ + RCC_OSC32_IN = PC_14, + RCC_OSC32_OUT = PC_15, + RCC_OSC_IN = PH_0, + RCC_OSC_OUT = PH_1, + +/**** DEBUG pins ****/ + SYS_JTCK_SWCLK = PA_14, + SYS_JTDI = PA_15, + SYS_JTDO_SWO = PB_3, + SYS_JTMS_SWDIO = PA_13, + SYS_JTRST = PB_4, + SYS_PVD_IN = PB_7, + SYS_TRACECLK = PE_2, + SYS_TRACED0 = PE_3, + SYS_TRACED0_ALT0 = PC_1, + SYS_TRACED0_ALT1 = PC_9, + SYS_TRACED1 = PE_4, + SYS_TRACED1_ALT0 = PC_10, + SYS_TRACED2 = PE_5, + SYS_TRACED2_ALT0 = PD_2, + SYS_TRACED3 = PE_6, + SYS_TRACED3_ALT0 = PC_12, + SYS_WKUP1 = PA_0, + SYS_WKUP2 = PC_13, + SYS_WKUP3 = PE_6, + SYS_WKUP4 = PA_2, + SYS_WKUP5 = PC_5, + + // Not connected + NC = (int)0xFFFFFFFF +} PinName; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/TARGET_NUCLEO_L4R5ZI/system_clock.c b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/TARGET_NUCLEO_L4R5ZI/system_clock.c new file mode 100644 index 0000000000..2943dc51cc --- /dev/null +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/TARGET_NUCLEO_L4R5ZI/system_clock.c @@ -0,0 +1,383 @@ +/* mbed Microcontroller Library +* Copyright (c) 2006-2017 ARM Limited +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * This file configures the system clock as follows: + *----------------------------------------------------------------------------- + * System clock source | 1- USE_PLL_HSE_EXTC (external 8 MHz clock) + * | 2- USE_PLL_HSE_XTAL (external 8 MHz xtal) + * | 3- USE_PLL_HSI (internal 16 MHz) + * | 4- USE_PLL_MSI (internal 100kHz to 48 MHz) + *----------------------------------------------------------------------------- + * SYSCLK(MHz) | 80 + * AHBCLK (MHz) | 80 + * APB1CLK (MHz) | 80 + * APB2CLK (MHz) | 80 + * USB capable | YES + *----------------------------------------------------------------------------- +**/ + +#include "stm32l4xx.h" +#include "nvic_addr.h" +#include "mbed_assert.h" + +/*!< Uncomment the following line if you need to relocate your vector Table in + Internal SRAM. */ +/* #define VECT_TAB_SRAM */ +#define VECT_TAB_OFFSET 0x00 /*!< Vector Table base offset field. + This value must be a multiple of 0x200. */ + + +// clock source is selected with CLOCK_SOURCE in json config +#define USE_PLL_HSE_EXTC 0x8 // Use external clock (ST Link MCO - not enabled by default) +#define USE_PLL_HSE_XTAL 0x4 // Use external xtal (X3 on board - not provided by default) +#define USE_PLL_HSI 0x2 // Use HSI internal clock +#define USE_PLL_MSI 0x1 // Use MSI internal clock + +#define DEBUG_MCO (0) // Output the MCO on PA8 for debugging (0=OFF, 1=SYSCLK, 2=HSE, 3=HSI, 4=MSI) + +#if ( ((CLOCK_SOURCE) & USE_PLL_HSE_XTAL) || ((CLOCK_SOURCE) & USE_PLL_HSE_EXTC) ) +uint8_t SetSysClock_PLL_HSE(uint8_t bypass); +#endif /* ((CLOCK_SOURCE) & USE_PLL_HSE_XTAL) || ((CLOCK_SOURCE) & USE_PLL_HSE_EXTC) */ + +#if ((CLOCK_SOURCE) & USE_PLL_HSI) +uint8_t SetSysClock_PLL_HSI(void); +#endif /* ((CLOCK_SOURCE) & USE_PLL_HSI) */ + +#if ((CLOCK_SOURCE) & USE_PLL_MSI) +uint8_t SetSysClock_PLL_MSI(void); +#endif /* ((CLOCK_SOURCE) & USE_PLL_MSI) */ + + +/** + * @brief Setup the microcontroller system. + * @param None + * @retval None + */ + +void SystemInit(void) +{ + /* FPU settings ------------------------------------------------------------*/ +#if (__FPU_PRESENT == 1) && (__FPU_USED == 1) + SCB->CPACR |= ((3UL << 10 * 2) | (3UL << 11 * 2)); /* set CP10 and CP11 Full Access */ +#endif + /* Reset the RCC clock configuration to the default reset state ------------*/ + /* Set MSION bit */ + RCC->CR |= RCC_CR_MSION; + + /* Reset CFGR register */ + RCC->CFGR = 0x00000000; + + /* Reset HSEON, CSSON , HSION, and PLLON bits */ + RCC->CR &= (uint32_t)0xEAF6FFFF; + + /* Reset PLLCFGR register */ + RCC->PLLCFGR = 0x00001000; + + /* Reset HSEBYP bit */ + RCC->CR &= (uint32_t)0xFFFBFFFF; + + /* Disable all interrupts */ + RCC->CIER = 0x00000000; + + /* Configure the Vector Table location add offset address ------------------*/ +#ifdef VECT_TAB_SRAM + SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */ +#else + SCB->VTOR = NVIC_FLASH_VECTOR_ADDRESS; /* Vector Table Relocation in Internal FLASH */ +#endif + +} + + +/** + * @brief Configures the System clock source, PLL Multiplier and Divider factors, + * AHB/APBx prescalers and Flash settings + * @note This function should be called only once the RCC clock configuration + * is reset to the default reset state (done in SystemInit() function). + * @param None + * @retval None + */ + +void SetSysClock(void) +{ +#if ((CLOCK_SOURCE) & USE_PLL_HSE_EXTC) + /* 1- Try to start with HSE and external clock */ + if (SetSysClock_PLL_HSE(1) == 0) +#endif + { +#if ((CLOCK_SOURCE) & USE_PLL_HSE_XTAL) + /* 2- If fail try to start with HSE and external xtal */ + if (SetSysClock_PLL_HSE(0) == 0) +#endif + { +#if ((CLOCK_SOURCE) & USE_PLL_HSI) + /* 3- If fail start with HSI clock */ + if (SetSysClock_PLL_HSI() == 0) +#endif + { +#if ((CLOCK_SOURCE) & USE_PLL_MSI) + /* 4- If fail start with MSI clock */ + if (SetSysClock_PLL_MSI() == 0) +#endif + { + while (1) { + MBED_ASSERT(1); + } + } + } + } + } + + // Output clock on MCO1 pin(PA8) for debugging purpose +#if DEBUG_MCO == 1 + HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_SYSCLK, RCC_MCODIV_1); +#endif +} + +#if ( ((CLOCK_SOURCE) & USE_PLL_HSE_XTAL) || ((CLOCK_SOURCE) & USE_PLL_HSE_EXTC) ) +/******************************************************************************/ +/* PLL (clocked by HSE) used as System clock source */ +/******************************************************************************/ +uint8_t SetSysClock_PLL_HSE(uint8_t bypass) +{ + RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; + RCC_OscInitTypeDef RCC_OscInitStruct = {0}; + RCC_PeriphCLKInitTypeDef RCC_PeriphClkInit = {0}; + + // Used to gain time after DeepSleep in case HSI is used + if (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) { + return 0; + } + + // Select MSI as system clock source to allow modification of the PLL configuration + RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK; + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_MSI; + HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0); + + // Enable HSE oscillator and activate PLL with HSE as source + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI; + if (bypass == 0) { + RCC_OscInitStruct.HSEState = RCC_HSE_ON; // External 8 MHz xtal on OSC_IN/OSC_OUT + } else { + RCC_OscInitStruct.HSEState = RCC_HSE_BYPASS; // External 8 MHz clock on OSC_IN + } + RCC_OscInitStruct.HSIState = RCC_HSI_OFF; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; // 8 MHz + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLM = 1; // VCO input clock = 8 MHz (8 MHz / 1) + RCC_OscInitStruct.PLL.PLLN = 20; // VCO output clock = 160 MHz (8 MHz * 20) + RCC_OscInitStruct.PLL.PLLP = 7; // PLLSAI3 clock = 22 MHz (160 MHz / 7) + RCC_OscInitStruct.PLL.PLLQ = 2; + RCC_OscInitStruct.PLL.PLLR = 2; // PLL clock = 80 MHz (160 MHz / 2) + + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + return 0; // FAIL + } + + // Select PLL clock as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers + RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; // 80 MHz + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; // 80 MHz + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; /* 80 MHz */ + RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; // 80 MHz + if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK) { + return 0; // FAIL + } + + RCC_PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USB; + RCC_PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_PLLSAI1; + RCC_PeriphClkInit.PLLSAI1.PLLSAI1Source = RCC_PLLSOURCE_HSE; + RCC_PeriphClkInit.PLLSAI1.PLLSAI1M = 1; + RCC_PeriphClkInit.PLLSAI1.PLLSAI1N = 12; + RCC_PeriphClkInit.PLLSAI1.PLLSAI1P = RCC_PLLP_DIV7; + RCC_PeriphClkInit.PLLSAI1.PLLSAI1Q = RCC_PLLQ_DIV2; + RCC_PeriphClkInit.PLLSAI1.PLLSAI1R = RCC_PLLR_DIV2; + RCC_PeriphClkInit.PLLSAI1.PLLSAI1ClockOut = RCC_PLLSAI1_48M2CLK; + if (HAL_RCCEx_PeriphCLKConfig(&RCC_PeriphClkInit) != HAL_OK) { + return 0; // FAIL + } + + // Disable MSI Oscillator + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI; + RCC_OscInitStruct.MSIState = RCC_MSI_OFF; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // No PLL update + HAL_RCC_OscConfig(&RCC_OscInitStruct); + + /* Select HSI as clock source for LPUART1 */ + RCC_PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_LPUART1; + RCC_PeriphClkInit.Lpuart1ClockSelection = RCC_LPUART1CLKSOURCE_HSI; + if (HAL_RCCEx_PeriphCLKConfig(&RCC_PeriphClkInit) != HAL_OK) { + return 0; // FAIL + } + + // Output clock on MCO1 pin(PA8) for debugging purpose +#if DEBUG_MCO == 2 + if (bypass == 0) { + HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_HSE, RCC_MCODIV_2); // 4 MHz + } else { + HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_HSE, RCC_MCODIV_1); // 8 MHz + } +#endif + + return 1; // OK +} +#endif /* ((CLOCK_SOURCE) & USE_PLL_HSE_XTAL) || ((CLOCK_SOURCE) & USE_PLL_HSE_EXTC) */ + +#if ((CLOCK_SOURCE) & USE_PLL_HSI) +/******************************************************************************/ +/* PLL (clocked by HSI) used as System clock source */ +/******************************************************************************/ +uint8_t SetSysClock_PLL_HSI(void) +{ + RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; + RCC_OscInitTypeDef RCC_OscInitStruct = {0}; + RCC_PeriphCLKInitTypeDef RCC_PeriphClkInit = {0}; + + // Select MSI as system clock source to allow modification of the PLL configuration + RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK; + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_MSI; + HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0); + + // Enable HSI oscillator and activate PLL with HSI as source + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSE; + RCC_OscInitStruct.HSEState = RCC_HSE_OFF; + RCC_OscInitStruct.HSIState = RCC_HSI_ON; + RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; // 16 MHz + RCC_OscInitStruct.PLL.PLLM = 2; // VCO input clock = 8 MHz (16 MHz / 2) + RCC_OscInitStruct.PLL.PLLN = 20; // VCO output clock = 160 MHz (8 MHz * 20) + RCC_OscInitStruct.PLL.PLLP = 7; // PLLSAI3 clock = 22 MHz (160 MHz / 7) + RCC_OscInitStruct.PLL.PLLQ = 2; + RCC_OscInitStruct.PLL.PLLR = 2; // PLL clock = 80 MHz (160 MHz / 2) + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + return 0; // FAIL + } + + // Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers + RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; // 80 MHz + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; // 80 MHz + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; // 80 MHz + RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; // 80 MHz + if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK) { + return 0; // FAIL + } + + RCC_PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USB; + RCC_PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_PLLSAI1; + RCC_PeriphClkInit.PLLSAI1.PLLSAI1Source = RCC_PLLSOURCE_HSI; + RCC_PeriphClkInit.PLLSAI1.PLLSAI1M = 2; + RCC_PeriphClkInit.PLLSAI1.PLLSAI1N = 12; + RCC_PeriphClkInit.PLLSAI1.PLLSAI1P = RCC_PLLP_DIV7; + RCC_PeriphClkInit.PLLSAI1.PLLSAI1Q = RCC_PLLQ_DIV2; + RCC_PeriphClkInit.PLLSAI1.PLLSAI1R = RCC_PLLR_DIV2; + RCC_PeriphClkInit.PLLSAI1.PLLSAI1ClockOut = RCC_PLLSAI1_48M2CLK; + if (HAL_RCCEx_PeriphCLKConfig(&RCC_PeriphClkInit) != HAL_OK) { + return 0; // FAIL + } + + // Disable MSI Oscillator + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI; + RCC_OscInitStruct.MSIState = RCC_MSI_OFF; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // No PLL update + HAL_RCC_OscConfig(&RCC_OscInitStruct); + + /* Select HSI as clock source for LPUART1 */ + RCC_PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_LPUART1; + RCC_PeriphClkInit.Lpuart1ClockSelection = RCC_LPUART1CLKSOURCE_HSI; + if (HAL_RCCEx_PeriphCLKConfig(&RCC_PeriphClkInit) != HAL_OK) { + return 0; // FAIL + } + + // Output clock on MCO1 pin(PA8) for debugging purpose +#if DEBUG_MCO == 3 + HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_HSI, RCC_MCODIV_1); // 16 MHz +#endif + + return 1; // OK +} +#endif /* ((CLOCK_SOURCE) & USE_PLL_HSI) */ + +#if ((CLOCK_SOURCE) & USE_PLL_MSI) +/******************************************************************************/ +/* PLL (clocked by MSI) used as System clock source */ +/******************************************************************************/ +uint8_t SetSysClock_PLL_MSI(void) +{ + RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; + RCC_OscInitTypeDef RCC_OscInitStruct = {0}; + RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; + + // Enable LSE Oscillator to automatically calibrate the MSI clock + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // No PLL update + RCC_OscInitStruct.LSEState = RCC_LSE_ON; // External 32.768 kHz clock on OSC_IN/OSC_OUT + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK) { + RCC->CR |= RCC_CR_MSIPLLEN; // Enable MSI PLL-mode + } + + HAL_RCCEx_DisableLSECSS(); + /* Enable MSI Oscillator and activate PLL with MSI as source */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSE; + RCC_OscInitStruct.MSIState = RCC_MSI_ON; + RCC_OscInitStruct.HSEState = RCC_HSE_OFF; + RCC_OscInitStruct.HSIState = RCC_HSI_OFF; + RCC_OscInitStruct.MSICalibrationValue = RCC_MSICALIBRATION_DEFAULT; + RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_11; /* 48 MHz */ + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI; + RCC_OscInitStruct.PLL.PLLM = 6; /* 8 MHz */ + RCC_OscInitStruct.PLL.PLLN = 40; /* 320 MHz */ + RCC_OscInitStruct.PLL.PLLP = 7; /* 45 MHz */ + RCC_OscInitStruct.PLL.PLLQ = 4; /* 80 MHz */ + RCC_OscInitStruct.PLL.PLLR = 4; /* 80 MHz */ + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + return 0; // FAIL + } + /* Enable MSI Auto-calibration through LSE */ + HAL_RCCEx_EnableMSIPLLMode(); + /* Select MSI output as USB clock source */ + PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USB; + PeriphClkInitStruct.UsbClockSelection = RCC_USBCLKSOURCE_MSI; /* 48 MHz */ + HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct); + + // Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers + RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; /* 80 MHz */ + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; /* 80 MHz */ + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; /* 80 MHz */ + RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; /* 80 MHz */ + if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK) { + return 0; // FAIL + } + + /* Select LSE as clock source for LPUART1 */ + PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_LPUART1; + PeriphClkInitStruct.Lpuart1ClockSelection = RCC_LPUART1CLKSOURCE_LSE; + if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) { + return 0; // FAIL + } + + // Output clock on MCO1 pin(PA8) for debugging purpose +#if DEBUG_MCO == 4 + HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_MSI, RCC_MCODIV_2); // 2 MHz +#endif + + return 1; // OK +} +#endif /* ((CLOCK_SOURCE) & USE_PLL_MSI) */ diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_ARM_MICRO/startup_stm32l4r5xx.S b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_ARM_MICRO/startup_stm32l4r5xx.S new file mode 100644 index 0000000000..17d2c86545 --- /dev/null +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_ARM_MICRO/startup_stm32l4r5xx.S @@ -0,0 +1,432 @@ +;********************** COPYRIGHT(c) 2017 STMicroelectronics ****************** +;* File Name : startup_stm32l4r5xx.s +;* Author : MCD Application Team +;* Description : STM32L4R5xx Ultra Low Power devices vector table for MDK-ARM toolchain. +;* This module performs: +;* - Set the initial SP +;* - Set the initial PC == Reset_Handler +;* - Set the vector table entries with the exceptions ISR address +;* - Branches to __main in the C library (which eventually +;* calls main()). +;* After Reset the Cortex-M4 processor is in Thread mode, +;* priority is Privileged, and the Stack is set to Main. +;* <<< Use Configuration Wizard in Context Menu >>> +;******************************************************************************* +;* +;* Redistribution and use in source and binary forms, with or without modification, +;* are permitted provided that the following conditions are met: +;* 1. Redistributions of source code must retain the above copyright notice, +;* this list of conditions and the following disclaimer. +;* 2. Redistributions in binary form must reproduce the above copyright notice, +;* this list of conditions and the following disclaimer in the documentation +;* and/or other materials provided with the distribution. +;* 3. Neither the name of STMicroelectronics nor the names of its contributors +;* may be used to endorse or promote products derived from this software +;* without specific prior written permission. +;* +;* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +;* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +;* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +;* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +;* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +;* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +;* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +;* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +;* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +;* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +;* +;******************************************************************************* + + AREA STACK, NOINIT, READWRITE, ALIGN=3 + EXPORT __initial_sp + +__initial_sp EQU 0x200A0000 ; Top of RAM (640KB) + +; Heap Configuration +; Heap Size (in Bytes) <0x0-0xFFFFFFFF:8> +; + +Heap_Size EQU 0x17800 ; 94KB (96KB, -2*1KB for main thread and scheduler) + + AREA HEAP, NOINIT, READWRITE, ALIGN=3 + EXPORT __heap_base + EXPORT __heap_limit + +__heap_base +Heap_Mem SPACE Heap_Size +__heap_limit + + PRESERVE8 + THUMB + + +; Vector Table Mapped to Address 0 at Reset + AREA RESET, DATA, READONLY + EXPORT __Vectors + EXPORT __Vectors_End + EXPORT __Vectors_Size + +__Vectors DCD __initial_sp ; Top of Stack + DCD Reset_Handler ; Reset Handler + DCD NMI_Handler ; NMI Handler + DCD HardFault_Handler ; Hard Fault Handler + DCD MemManage_Handler ; MPU Fault Handler + DCD BusFault_Handler ; Bus Fault Handler + DCD UsageFault_Handler ; Usage Fault Handler + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD SVC_Handler ; SVCall Handler + DCD DebugMon_Handler ; Debug Monitor Handler + DCD 0 ; Reserved + DCD PendSV_Handler ; PendSV Handler + DCD SysTick_Handler ; SysTick Handler + + ; External Interrupts + DCD WWDG_IRQHandler ; Window WatchDog + DCD PVD_PVM_IRQHandler ; PVD/PVM1/PVM2/PVM3/PVM4 through EXTI Line detection + DCD TAMP_STAMP_IRQHandler ; Tamper and TimeStamps through the EXTI line + DCD RTC_WKUP_IRQHandler ; RTC Wakeup through the EXTI line + DCD FLASH_IRQHandler ; FLASH + DCD RCC_IRQHandler ; RCC + DCD EXTI0_IRQHandler ; EXTI Line0 + DCD EXTI1_IRQHandler ; EXTI Line1 + DCD EXTI2_IRQHandler ; EXTI Line2 + DCD EXTI3_IRQHandler ; EXTI Line3 + DCD EXTI4_IRQHandler ; EXTI Line4 + DCD DMA1_Channel1_IRQHandler ; DMA1 Channel 1 + DCD DMA1_Channel2_IRQHandler ; DMA1 Channel 2 + DCD DMA1_Channel3_IRQHandler ; DMA1 Channel 3 + DCD DMA1_Channel4_IRQHandler ; DMA1 Channel 4 + DCD DMA1_Channel5_IRQHandler ; DMA1 Channel 5 + DCD DMA1_Channel6_IRQHandler ; DMA1 Channel 6 + DCD DMA1_Channel7_IRQHandler ; DMA1 Channel 7 + DCD ADC1_IRQHandler ; ADC1 + DCD CAN1_TX_IRQHandler ; CAN1 TX + DCD CAN1_RX0_IRQHandler ; CAN1 RX0 + DCD CAN1_RX1_IRQHandler ; CAN1 RX1 + DCD CAN1_SCE_IRQHandler ; CAN1 SCE + DCD EXTI9_5_IRQHandler ; External Line[9:5]s + DCD TIM1_BRK_TIM15_IRQHandler ; TIM1 Break and TIM15 + DCD TIM1_UP_TIM16_IRQHandler ; TIM1 Update and TIM16 + DCD TIM1_TRG_COM_TIM17_IRQHandler ; TIM1 Trigger and Commutation and TIM17 + DCD TIM1_CC_IRQHandler ; TIM1 Capture Compare + DCD TIM2_IRQHandler ; TIM2 + DCD TIM3_IRQHandler ; TIM3 + DCD TIM4_IRQHandler ; TIM4 + DCD I2C1_EV_IRQHandler ; I2C1 Event + DCD I2C1_ER_IRQHandler ; I2C1 Error + DCD I2C2_EV_IRQHandler ; I2C2 Event + DCD I2C2_ER_IRQHandler ; I2C2 Error + DCD SPI1_IRQHandler ; SPI1 + DCD SPI2_IRQHandler ; SPI2 + DCD USART1_IRQHandler ; USART1 + DCD USART2_IRQHandler ; USART2 + DCD USART3_IRQHandler ; USART3 + DCD EXTI15_10_IRQHandler ; External Line[15:10] + DCD RTC_Alarm_IRQHandler ; RTC Alarm (A and B) through EXTI Line + DCD DFSDM1_FLT3_IRQHandler ; DFSDM1 Filter 3 global Interrupt + DCD TIM8_BRK_IRQHandler ; TIM8 Break Interrupt + DCD TIM8_UP_IRQHandler ; TIM8 Update Interrupt + DCD TIM8_TRG_COM_IRQHandler ; TIM8 Trigger and Commutation Interrupt + DCD TIM8_CC_IRQHandler ; TIM8 Capture Compare Interrupt + DCD 0 ; Reserved + DCD FMC_IRQHandler ; FMC + DCD SDMMC1_IRQHandler ; SDMMC1 + DCD TIM5_IRQHandler ; TIM5 + DCD SPI3_IRQHandler ; SPI3 + DCD UART4_IRQHandler ; UART4 + DCD UART5_IRQHandler ; UART5 + DCD TIM6_DAC_IRQHandler ; TIM6 and DAC1&2 underrun errors + DCD TIM7_IRQHandler ; TIM7 + DCD DMA2_Channel1_IRQHandler ; DMA2 Channel 1 + DCD DMA2_Channel2_IRQHandler ; DMA2 Channel 2 + DCD DMA2_Channel3_IRQHandler ; DMA2 Channel 3 + DCD DMA2_Channel4_IRQHandler ; DMA2 Channel 4 + DCD DMA2_Channel5_IRQHandler ; DMA2 Channel 5 + DCD DFSDM1_FLT0_IRQHandler ; DFSDM1 Filter 0 global Interrupt + DCD DFSDM1_FLT1_IRQHandler ; DFSDM1 Filter 1 global Interrupt + DCD DFSDM1_FLT2_IRQHandler ; DFSDM1 Filter 2 global Interrupt + DCD COMP_IRQHandler ; COMP Interrupt + DCD LPTIM1_IRQHandler ; LP TIM1 interrupt + DCD LPTIM2_IRQHandler ; LP TIM2 interrupt + DCD OTG_FS_IRQHandler ; USB OTG FS + DCD DMA2_Channel6_IRQHandler ; DMA2 Channel 6 + DCD DMA2_Channel7_IRQHandler ; DMA2 Channel 7 + DCD LPUART1_IRQHandler ; LP UART1 interrupt + DCD OCTOSPI1_IRQHandler ; OctoSPI1 global interrupt + DCD I2C3_EV_IRQHandler ; I2C3 event + DCD I2C3_ER_IRQHandler ; I2C3 error + DCD SAI1_IRQHandler ; Serial Audio Interface 1 global interrupt + DCD SAI2_IRQHandler ; Serial Audio Interface 2 global interrupt + DCD OCTOSPI2_IRQHandler ; OctoSPI2 global interrupt + DCD TSC_IRQHandler ; Touch Sense Controller global interrupt + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD RNG_IRQHandler ; RNG global interrupt + DCD FPU_IRQHandler ; FPU + DCD CRS_IRQHandler ; CRS global interrupt + DCD I2C4_ER_IRQHandler ; I2C4 error + DCD I2C4_EV_IRQHandler ; I2C4 event + DCD DCMI_IRQHandler ; DCMI global interrupt + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD DMA2D_IRQHandler ; DMA2D global interrupt + DCD LTDC_IRQHandler ; LTDC global interrupt + DCD LTDC_ER_IRQHandler ; LTDC error global interrupt + DCD GFXMMU_IRQHandler ; GFXMMU global interrupt + DCD DMAMUX1_OVR_IRQHandler ; DMAMUX1 overrun global interrupt + +__Vectors_End + +__Vectors_Size EQU __Vectors_End - __Vectors + + AREA |.text|, CODE, READONLY + +; Reset handler +Reset_Handler PROC + EXPORT Reset_Handler [WEAK] + IMPORT SystemInit + IMPORT __main + + LDR R0, =SystemInit + BLX R0 + LDR R0, =__main + BX R0 + ENDP + +; Dummy Exception Handlers (infinite loops which can be modified) + +NMI_Handler PROC + EXPORT NMI_Handler [WEAK] + B . + ENDP +HardFault_Handler\ + PROC + EXPORT HardFault_Handler [WEAK] + B . + ENDP +MemManage_Handler\ + PROC + EXPORT MemManage_Handler [WEAK] + B . + ENDP +BusFault_Handler\ + PROC + EXPORT BusFault_Handler [WEAK] + B . + ENDP +UsageFault_Handler\ + PROC + EXPORT UsageFault_Handler [WEAK] + B . + ENDP +SVC_Handler PROC + EXPORT SVC_Handler [WEAK] + B . + ENDP +DebugMon_Handler\ + PROC + EXPORT DebugMon_Handler [WEAK] + B . + ENDP +PendSV_Handler PROC + EXPORT PendSV_Handler [WEAK] + B . + ENDP +SysTick_Handler PROC + EXPORT SysTick_Handler [WEAK] + B . + ENDP + +Default_Handler PROC + + EXPORT WWDG_IRQHandler [WEAK] + EXPORT PVD_PVM_IRQHandler [WEAK] + EXPORT TAMP_STAMP_IRQHandler [WEAK] + EXPORT RTC_WKUP_IRQHandler [WEAK] + EXPORT FLASH_IRQHandler [WEAK] + EXPORT RCC_IRQHandler [WEAK] + EXPORT EXTI0_IRQHandler [WEAK] + EXPORT EXTI1_IRQHandler [WEAK] + EXPORT EXTI2_IRQHandler [WEAK] + EXPORT EXTI3_IRQHandler [WEAK] + EXPORT EXTI4_IRQHandler [WEAK] + EXPORT DMA1_Channel1_IRQHandler [WEAK] + EXPORT DMA1_Channel2_IRQHandler [WEAK] + EXPORT DMA1_Channel3_IRQHandler [WEAK] + EXPORT DMA1_Channel4_IRQHandler [WEAK] + EXPORT DMA1_Channel5_IRQHandler [WEAK] + EXPORT DMA1_Channel6_IRQHandler [WEAK] + EXPORT DMA1_Channel7_IRQHandler [WEAK] + EXPORT ADC1_IRQHandler [WEAK] + EXPORT CAN1_TX_IRQHandler [WEAK] + EXPORT CAN1_RX0_IRQHandler [WEAK] + EXPORT CAN1_RX1_IRQHandler [WEAK] + EXPORT CAN1_SCE_IRQHandler [WEAK] + EXPORT EXTI9_5_IRQHandler [WEAK] + EXPORT TIM1_BRK_TIM15_IRQHandler [WEAK] + EXPORT TIM1_UP_TIM16_IRQHandler [WEAK] + EXPORT TIM1_TRG_COM_TIM17_IRQHandler [WEAK] + EXPORT TIM1_CC_IRQHandler [WEAK] + EXPORT TIM2_IRQHandler [WEAK] + EXPORT TIM3_IRQHandler [WEAK] + EXPORT TIM4_IRQHandler [WEAK] + EXPORT I2C1_EV_IRQHandler [WEAK] + EXPORT I2C1_ER_IRQHandler [WEAK] + EXPORT I2C2_EV_IRQHandler [WEAK] + EXPORT I2C2_ER_IRQHandler [WEAK] + EXPORT SPI1_IRQHandler [WEAK] + EXPORT SPI2_IRQHandler [WEAK] + EXPORT USART1_IRQHandler [WEAK] + EXPORT USART2_IRQHandler [WEAK] + EXPORT USART3_IRQHandler [WEAK] + EXPORT EXTI15_10_IRQHandler [WEAK] + EXPORT RTC_Alarm_IRQHandler [WEAK] + EXPORT DFSDM1_FLT3_IRQHandler [WEAK] + EXPORT TIM8_BRK_IRQHandler [WEAK] + EXPORT TIM8_UP_IRQHandler [WEAK] + EXPORT TIM8_TRG_COM_IRQHandler [WEAK] + EXPORT TIM8_CC_IRQHandler [WEAK] + EXPORT FMC_IRQHandler [WEAK] + EXPORT SDMMC1_IRQHandler [WEAK] + EXPORT TIM5_IRQHandler [WEAK] + EXPORT SPI3_IRQHandler [WEAK] + EXPORT UART4_IRQHandler [WEAK] + EXPORT UART5_IRQHandler [WEAK] + EXPORT TIM6_DAC_IRQHandler [WEAK] + EXPORT TIM7_IRQHandler [WEAK] + EXPORT DMA2_Channel1_IRQHandler [WEAK] + EXPORT DMA2_Channel2_IRQHandler [WEAK] + EXPORT DMA2_Channel3_IRQHandler [WEAK] + EXPORT DMA2_Channel4_IRQHandler [WEAK] + EXPORT DMA2_Channel5_IRQHandler [WEAK] + EXPORT DFSDM1_FLT0_IRQHandler [WEAK] + EXPORT DFSDM1_FLT1_IRQHandler [WEAK] + EXPORT DFSDM1_FLT2_IRQHandler [WEAK] + EXPORT COMP_IRQHandler [WEAK] + EXPORT LPTIM1_IRQHandler [WEAK] + EXPORT LPTIM2_IRQHandler [WEAK] + EXPORT OTG_FS_IRQHandler [WEAK] + EXPORT DMA2_Channel6_IRQHandler [WEAK] + EXPORT DMA2_Channel7_IRQHandler [WEAK] + EXPORT LPUART1_IRQHandler [WEAK] + EXPORT OCTOSPI1_IRQHandler [WEAK] + EXPORT I2C3_EV_IRQHandler [WEAK] + EXPORT I2C3_ER_IRQHandler [WEAK] + EXPORT SAI1_IRQHandler [WEAK] + EXPORT SAI2_IRQHandler [WEAK] + EXPORT OCTOSPI2_IRQHandler [WEAK] + EXPORT TSC_IRQHandler [WEAK] + EXPORT RNG_IRQHandler [WEAK] + EXPORT FPU_IRQHandler [WEAK] + EXPORT CRS_IRQHandler [WEAK] + EXPORT I2C4_ER_IRQHandler [WEAK] + EXPORT I2C4_EV_IRQHandler [WEAK] + EXPORT DCMI_IRQHandler [WEAK] + EXPORT DMA2D_IRQHandler [WEAK] + EXPORT LTDC_IRQHandler [WEAK] + EXPORT LTDC_ER_IRQHandler [WEAK] + EXPORT GFXMMU_IRQHandler [WEAK] + EXPORT DMAMUX1_OVR_IRQHandler [WEAK] + +WWDG_IRQHandler +PVD_PVM_IRQHandler +TAMP_STAMP_IRQHandler +RTC_WKUP_IRQHandler +FLASH_IRQHandler +RCC_IRQHandler +EXTI0_IRQHandler +EXTI1_IRQHandler +EXTI2_IRQHandler +EXTI3_IRQHandler +EXTI4_IRQHandler +DMA1_Channel1_IRQHandler +DMA1_Channel2_IRQHandler +DMA1_Channel3_IRQHandler +DMA1_Channel4_IRQHandler +DMA1_Channel5_IRQHandler +DMA1_Channel6_IRQHandler +DMA1_Channel7_IRQHandler +ADC1_IRQHandler +CAN1_TX_IRQHandler +CAN1_RX0_IRQHandler +CAN1_RX1_IRQHandler +CAN1_SCE_IRQHandler +EXTI9_5_IRQHandler +TIM1_BRK_TIM15_IRQHandler +TIM1_UP_TIM16_IRQHandler +TIM1_TRG_COM_TIM17_IRQHandler +TIM1_CC_IRQHandler +TIM2_IRQHandler +TIM3_IRQHandler +TIM4_IRQHandler +I2C1_EV_IRQHandler +I2C1_ER_IRQHandler +I2C2_EV_IRQHandler +I2C2_ER_IRQHandler +SPI1_IRQHandler +SPI2_IRQHandler +USART1_IRQHandler +USART2_IRQHandler +USART3_IRQHandler +EXTI15_10_IRQHandler +RTC_Alarm_IRQHandler +DFSDM1_FLT3_IRQHandler +TIM8_BRK_IRQHandler +TIM8_UP_IRQHandler +TIM8_TRG_COM_IRQHandler +TIM8_CC_IRQHandler +FMC_IRQHandler +SDMMC1_IRQHandler +TIM5_IRQHandler +SPI3_IRQHandler +UART4_IRQHandler +UART5_IRQHandler +TIM6_DAC_IRQHandler +TIM7_IRQHandler +DMA2_Channel1_IRQHandler +DMA2_Channel2_IRQHandler +DMA2_Channel3_IRQHandler +DMA2_Channel4_IRQHandler +DMA2_Channel5_IRQHandler +DFSDM1_FLT0_IRQHandler +DFSDM1_FLT1_IRQHandler +DFSDM1_FLT2_IRQHandler +COMP_IRQHandler +LPTIM1_IRQHandler +LPTIM2_IRQHandler +OTG_FS_IRQHandler +DMA2_Channel6_IRQHandler +DMA2_Channel7_IRQHandler +LPUART1_IRQHandler +OCTOSPI1_IRQHandler +I2C3_EV_IRQHandler +I2C3_ER_IRQHandler +SAI1_IRQHandler +SAI2_IRQHandler +OCTOSPI2_IRQHandler +TSC_IRQHandler +RNG_IRQHandler +FPU_IRQHandler +CRS_IRQHandler +I2C4_ER_IRQHandler +I2C4_EV_IRQHandler +DCMI_IRQHandler +DMA2D_IRQHandler +LTDC_IRQHandler +LTDC_ER_IRQHandler +GFXMMU_IRQHandler +DMAMUX1_OVR_IRQHandler + + B . + + ENDP + + ALIGN + END + +;************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE***** diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_ARM_MICRO/stm32l4r5xx.sct b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_ARM_MICRO/stm32l4r5xx.sct new file mode 100644 index 0000000000..78df546290 --- /dev/null +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_ARM_MICRO/stm32l4r5xx.sct @@ -0,0 +1,52 @@ +#! armcc -E +; Scatter-Loading Description File +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; Copyright (c) 2018, STMicroelectronics +; All rights reserved. +; +; Redistribution and use in source and binary forms, with or without +; modification, are permitted provided that the following conditions are met: +; +; 1. Redistributions of source code must retain the above copyright notice, +; this list of conditions and the following disclaimer. +; 2. Redistributions in binary form must reproduce the above copyright notice, +; this list of conditions and the following disclaimer in the documentation +; and/or other materials provided with the distribution. +; 3. Neither the name of STMicroelectronics nor the names of its contributors +; may be used to endorse or promote products derived from this software +; without specific prior written permission. +; +; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +#if !defined(MBED_APP_START) + #define MBED_APP_START 0x08000000 +#endif + +#if !defined(MBED_APP_SIZE) + #define MBED_APP_SIZE 0x200000 +#endif + +; 2MB FLASH (0x200000) + 640KB SRAM (0xA0000) +LR_IROM1 MBED_APP_START MBED_APP_SIZE { ; load region size_region + + ER_IROM1 MBED_APP_START MBED_APP_SIZE { ; load address = execution address + *.o (RESET, +First) + *(InRoot$$Sections) + .ANY (+RO) + } + + ; Total: 111 vectors = 444 bytes (0x1BC) to be reserved in RAM + RW_IRAM1 (0x20000000+0x1BC) (0xA0000-0x1BC) { ; RW data + .ANY (+RW +ZI) + } +} diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_ARM_STD/startup_stm32l4r5xx.S b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_ARM_STD/startup_stm32l4r5xx.S new file mode 100644 index 0000000000..4524787e37 --- /dev/null +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_ARM_STD/startup_stm32l4r5xx.S @@ -0,0 +1,415 @@ +;********************** COPYRIGHT(c) 2017 STMicroelectronics ****************** +;* File Name : startup_stm32l4r5xx.s +;* Author : MCD Application Team +;* Description : STM32L4R5xx Ultra Low Power devices vector table for MDK-ARM toolchain. +;* This module performs: +;* - Set the initial SP +;* - Set the initial PC == Reset_Handler +;* - Set the vector table entries with the exceptions ISR address +;* - Branches to __main in the C library (which eventually +;* calls main()). +;* After Reset the Cortex-M4 processor is in Thread mode, +;* priority is Privileged, and the Stack is set to Main. +;* <<< Use Configuration Wizard in Context Menu >>> +;******************************************************************************* +;* +;* Redistribution and use in source and binary forms, with or without modification, +;* are permitted provided that the following conditions are met: +;* 1. Redistributions of source code must retain the above copyright notice, +;* this list of conditions and the following disclaimer. +;* 2. Redistributions in binary form must reproduce the above copyright notice, +;* this list of conditions and the following disclaimer in the documentation +;* and/or other materials provided with the distribution. +;* 3. Neither the name of STMicroelectronics nor the names of its contributors +;* may be used to endorse or promote products derived from this software +;* without specific prior written permission. +;* +;* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +;* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +;* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +;* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +;* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +;* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +;* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +;* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +;* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +;* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +;* +;******************************************************************************* + +__initial_sp EQU 0x200A0000 ; Top of RAM (640KB) + + PRESERVE8 + THUMB + + +; Vector Table Mapped to Address 0 at Reset + AREA RESET, DATA, READONLY + EXPORT __Vectors + EXPORT __Vectors_End + EXPORT __Vectors_Size + +__Vectors DCD __initial_sp ; Top of Stack + DCD Reset_Handler ; Reset Handler + DCD NMI_Handler ; NMI Handler + DCD HardFault_Handler ; Hard Fault Handler + DCD MemManage_Handler ; MPU Fault Handler + DCD BusFault_Handler ; Bus Fault Handler + DCD UsageFault_Handler ; Usage Fault Handler + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD SVC_Handler ; SVCall Handler + DCD DebugMon_Handler ; Debug Monitor Handler + DCD 0 ; Reserved + DCD PendSV_Handler ; PendSV Handler + DCD SysTick_Handler ; SysTick Handler + + ; External Interrupts + DCD WWDG_IRQHandler ; Window WatchDog + DCD PVD_PVM_IRQHandler ; PVD/PVM1/PVM2/PVM3/PVM4 through EXTI Line detection + DCD TAMP_STAMP_IRQHandler ; Tamper and TimeStamps through the EXTI line + DCD RTC_WKUP_IRQHandler ; RTC Wakeup through the EXTI line + DCD FLASH_IRQHandler ; FLASH + DCD RCC_IRQHandler ; RCC + DCD EXTI0_IRQHandler ; EXTI Line0 + DCD EXTI1_IRQHandler ; EXTI Line1 + DCD EXTI2_IRQHandler ; EXTI Line2 + DCD EXTI3_IRQHandler ; EXTI Line3 + DCD EXTI4_IRQHandler ; EXTI Line4 + DCD DMA1_Channel1_IRQHandler ; DMA1 Channel 1 + DCD DMA1_Channel2_IRQHandler ; DMA1 Channel 2 + DCD DMA1_Channel3_IRQHandler ; DMA1 Channel 3 + DCD DMA1_Channel4_IRQHandler ; DMA1 Channel 4 + DCD DMA1_Channel5_IRQHandler ; DMA1 Channel 5 + DCD DMA1_Channel6_IRQHandler ; DMA1 Channel 6 + DCD DMA1_Channel7_IRQHandler ; DMA1 Channel 7 + DCD ADC1_IRQHandler ; ADC1 + DCD CAN1_TX_IRQHandler ; CAN1 TX + DCD CAN1_RX0_IRQHandler ; CAN1 RX0 + DCD CAN1_RX1_IRQHandler ; CAN1 RX1 + DCD CAN1_SCE_IRQHandler ; CAN1 SCE + DCD EXTI9_5_IRQHandler ; External Line[9:5]s + DCD TIM1_BRK_TIM15_IRQHandler ; TIM1 Break and TIM15 + DCD TIM1_UP_TIM16_IRQHandler ; TIM1 Update and TIM16 + DCD TIM1_TRG_COM_TIM17_IRQHandler ; TIM1 Trigger and Commutation and TIM17 + DCD TIM1_CC_IRQHandler ; TIM1 Capture Compare + DCD TIM2_IRQHandler ; TIM2 + DCD TIM3_IRQHandler ; TIM3 + DCD TIM4_IRQHandler ; TIM4 + DCD I2C1_EV_IRQHandler ; I2C1 Event + DCD I2C1_ER_IRQHandler ; I2C1 Error + DCD I2C2_EV_IRQHandler ; I2C2 Event + DCD I2C2_ER_IRQHandler ; I2C2 Error + DCD SPI1_IRQHandler ; SPI1 + DCD SPI2_IRQHandler ; SPI2 + DCD USART1_IRQHandler ; USART1 + DCD USART2_IRQHandler ; USART2 + DCD USART3_IRQHandler ; USART3 + DCD EXTI15_10_IRQHandler ; External Line[15:10] + DCD RTC_Alarm_IRQHandler ; RTC Alarm (A and B) through EXTI Line + DCD DFSDM1_FLT3_IRQHandler ; DFSDM1 Filter 3 global Interrupt + DCD TIM8_BRK_IRQHandler ; TIM8 Break Interrupt + DCD TIM8_UP_IRQHandler ; TIM8 Update Interrupt + DCD TIM8_TRG_COM_IRQHandler ; TIM8 Trigger and Commutation Interrupt + DCD TIM8_CC_IRQHandler ; TIM8 Capture Compare Interrupt + DCD 0 ; Reserved + DCD FMC_IRQHandler ; FMC + DCD SDMMC1_IRQHandler ; SDMMC1 + DCD TIM5_IRQHandler ; TIM5 + DCD SPI3_IRQHandler ; SPI3 + DCD UART4_IRQHandler ; UART4 + DCD UART5_IRQHandler ; UART5 + DCD TIM6_DAC_IRQHandler ; TIM6 and DAC1&2 underrun errors + DCD TIM7_IRQHandler ; TIM7 + DCD DMA2_Channel1_IRQHandler ; DMA2 Channel 1 + DCD DMA2_Channel2_IRQHandler ; DMA2 Channel 2 + DCD DMA2_Channel3_IRQHandler ; DMA2 Channel 3 + DCD DMA2_Channel4_IRQHandler ; DMA2 Channel 4 + DCD DMA2_Channel5_IRQHandler ; DMA2 Channel 5 + DCD DFSDM1_FLT0_IRQHandler ; DFSDM1 Filter 0 global Interrupt + DCD DFSDM1_FLT1_IRQHandler ; DFSDM1 Filter 1 global Interrupt + DCD DFSDM1_FLT2_IRQHandler ; DFSDM1 Filter 2 global Interrupt + DCD COMP_IRQHandler ; COMP Interrupt + DCD LPTIM1_IRQHandler ; LP TIM1 interrupt + DCD LPTIM2_IRQHandler ; LP TIM2 interrupt + DCD OTG_FS_IRQHandler ; USB OTG FS + DCD DMA2_Channel6_IRQHandler ; DMA2 Channel 6 + DCD DMA2_Channel7_IRQHandler ; DMA2 Channel 7 + DCD LPUART1_IRQHandler ; LP UART1 interrupt + DCD OCTOSPI1_IRQHandler ; OctoSPI1 global interrupt + DCD I2C3_EV_IRQHandler ; I2C3 event + DCD I2C3_ER_IRQHandler ; I2C3 error + DCD SAI1_IRQHandler ; Serial Audio Interface 1 global interrupt + DCD SAI2_IRQHandler ; Serial Audio Interface 2 global interrupt + DCD OCTOSPI2_IRQHandler ; OctoSPI2 global interrupt + DCD TSC_IRQHandler ; Touch Sense Controller global interrupt + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD RNG_IRQHandler ; RNG global interrupt + DCD FPU_IRQHandler ; FPU + DCD CRS_IRQHandler ; CRS global interrupt + DCD I2C4_ER_IRQHandler ; I2C4 error + DCD I2C4_EV_IRQHandler ; I2C4 event + DCD DCMI_IRQHandler ; DCMI global interrupt + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD DMA2D_IRQHandler ; DMA2D global interrupt + DCD LTDC_IRQHandler ; LTDC global interrupt + DCD LTDC_ER_IRQHandler ; LTDC error global interrupt + DCD GFXMMU_IRQHandler ; GFXMMU global interrupt + DCD DMAMUX1_OVR_IRQHandler ; DMAMUX1 overrun global interrupt + +__Vectors_End + +__Vectors_Size EQU __Vectors_End - __Vectors + + AREA |.text|, CODE, READONLY + +; Reset handler +Reset_Handler PROC + EXPORT Reset_Handler [WEAK] + IMPORT SystemInit + IMPORT __main + + LDR R0, =SystemInit + BLX R0 + LDR R0, =__main + BX R0 + ENDP + +; Dummy Exception Handlers (infinite loops which can be modified) + +NMI_Handler PROC + EXPORT NMI_Handler [WEAK] + B . + ENDP +HardFault_Handler\ + PROC + EXPORT HardFault_Handler [WEAK] + B . + ENDP +MemManage_Handler\ + PROC + EXPORT MemManage_Handler [WEAK] + B . + ENDP +BusFault_Handler\ + PROC + EXPORT BusFault_Handler [WEAK] + B . + ENDP +UsageFault_Handler\ + PROC + EXPORT UsageFault_Handler [WEAK] + B . + ENDP +SVC_Handler PROC + EXPORT SVC_Handler [WEAK] + B . + ENDP +DebugMon_Handler\ + PROC + EXPORT DebugMon_Handler [WEAK] + B . + ENDP +PendSV_Handler PROC + EXPORT PendSV_Handler [WEAK] + B . + ENDP +SysTick_Handler PROC + EXPORT SysTick_Handler [WEAK] + B . + ENDP + +Default_Handler PROC + + EXPORT WWDG_IRQHandler [WEAK] + EXPORT PVD_PVM_IRQHandler [WEAK] + EXPORT TAMP_STAMP_IRQHandler [WEAK] + EXPORT RTC_WKUP_IRQHandler [WEAK] + EXPORT FLASH_IRQHandler [WEAK] + EXPORT RCC_IRQHandler [WEAK] + EXPORT EXTI0_IRQHandler [WEAK] + EXPORT EXTI1_IRQHandler [WEAK] + EXPORT EXTI2_IRQHandler [WEAK] + EXPORT EXTI3_IRQHandler [WEAK] + EXPORT EXTI4_IRQHandler [WEAK] + EXPORT DMA1_Channel1_IRQHandler [WEAK] + EXPORT DMA1_Channel2_IRQHandler [WEAK] + EXPORT DMA1_Channel3_IRQHandler [WEAK] + EXPORT DMA1_Channel4_IRQHandler [WEAK] + EXPORT DMA1_Channel5_IRQHandler [WEAK] + EXPORT DMA1_Channel6_IRQHandler [WEAK] + EXPORT DMA1_Channel7_IRQHandler [WEAK] + EXPORT ADC1_IRQHandler [WEAK] + EXPORT CAN1_TX_IRQHandler [WEAK] + EXPORT CAN1_RX0_IRQHandler [WEAK] + EXPORT CAN1_RX1_IRQHandler [WEAK] + EXPORT CAN1_SCE_IRQHandler [WEAK] + EXPORT EXTI9_5_IRQHandler [WEAK] + EXPORT TIM1_BRK_TIM15_IRQHandler [WEAK] + EXPORT TIM1_UP_TIM16_IRQHandler [WEAK] + EXPORT TIM1_TRG_COM_TIM17_IRQHandler [WEAK] + EXPORT TIM1_CC_IRQHandler [WEAK] + EXPORT TIM2_IRQHandler [WEAK] + EXPORT TIM3_IRQHandler [WEAK] + EXPORT TIM4_IRQHandler [WEAK] + EXPORT I2C1_EV_IRQHandler [WEAK] + EXPORT I2C1_ER_IRQHandler [WEAK] + EXPORT I2C2_EV_IRQHandler [WEAK] + EXPORT I2C2_ER_IRQHandler [WEAK] + EXPORT SPI1_IRQHandler [WEAK] + EXPORT SPI2_IRQHandler [WEAK] + EXPORT USART1_IRQHandler [WEAK] + EXPORT USART2_IRQHandler [WEAK] + EXPORT USART3_IRQHandler [WEAK] + EXPORT EXTI15_10_IRQHandler [WEAK] + EXPORT RTC_Alarm_IRQHandler [WEAK] + EXPORT DFSDM1_FLT3_IRQHandler [WEAK] + EXPORT TIM8_BRK_IRQHandler [WEAK] + EXPORT TIM8_UP_IRQHandler [WEAK] + EXPORT TIM8_TRG_COM_IRQHandler [WEAK] + EXPORT TIM8_CC_IRQHandler [WEAK] + EXPORT FMC_IRQHandler [WEAK] + EXPORT SDMMC1_IRQHandler [WEAK] + EXPORT TIM5_IRQHandler [WEAK] + EXPORT SPI3_IRQHandler [WEAK] + EXPORT UART4_IRQHandler [WEAK] + EXPORT UART5_IRQHandler [WEAK] + EXPORT TIM6_DAC_IRQHandler [WEAK] + EXPORT TIM7_IRQHandler [WEAK] + EXPORT DMA2_Channel1_IRQHandler [WEAK] + EXPORT DMA2_Channel2_IRQHandler [WEAK] + EXPORT DMA2_Channel3_IRQHandler [WEAK] + EXPORT DMA2_Channel4_IRQHandler [WEAK] + EXPORT DMA2_Channel5_IRQHandler [WEAK] + EXPORT DFSDM1_FLT0_IRQHandler [WEAK] + EXPORT DFSDM1_FLT1_IRQHandler [WEAK] + EXPORT DFSDM1_FLT2_IRQHandler [WEAK] + EXPORT COMP_IRQHandler [WEAK] + EXPORT LPTIM1_IRQHandler [WEAK] + EXPORT LPTIM2_IRQHandler [WEAK] + EXPORT OTG_FS_IRQHandler [WEAK] + EXPORT DMA2_Channel6_IRQHandler [WEAK] + EXPORT DMA2_Channel7_IRQHandler [WEAK] + EXPORT LPUART1_IRQHandler [WEAK] + EXPORT OCTOSPI1_IRQHandler [WEAK] + EXPORT I2C3_EV_IRQHandler [WEAK] + EXPORT I2C3_ER_IRQHandler [WEAK] + EXPORT SAI1_IRQHandler [WEAK] + EXPORT SAI2_IRQHandler [WEAK] + EXPORT OCTOSPI2_IRQHandler [WEAK] + EXPORT TSC_IRQHandler [WEAK] + EXPORT RNG_IRQHandler [WEAK] + EXPORT FPU_IRQHandler [WEAK] + EXPORT CRS_IRQHandler [WEAK] + EXPORT I2C4_ER_IRQHandler [WEAK] + EXPORT I2C4_EV_IRQHandler [WEAK] + EXPORT DCMI_IRQHandler [WEAK] + EXPORT DMA2D_IRQHandler [WEAK] + EXPORT LTDC_IRQHandler [WEAK] + EXPORT LTDC_ER_IRQHandler [WEAK] + EXPORT GFXMMU_IRQHandler [WEAK] + EXPORT DMAMUX1_OVR_IRQHandler [WEAK] + +WWDG_IRQHandler +PVD_PVM_IRQHandler +TAMP_STAMP_IRQHandler +RTC_WKUP_IRQHandler +FLASH_IRQHandler +RCC_IRQHandler +EXTI0_IRQHandler +EXTI1_IRQHandler +EXTI2_IRQHandler +EXTI3_IRQHandler +EXTI4_IRQHandler +DMA1_Channel1_IRQHandler +DMA1_Channel2_IRQHandler +DMA1_Channel3_IRQHandler +DMA1_Channel4_IRQHandler +DMA1_Channel5_IRQHandler +DMA1_Channel6_IRQHandler +DMA1_Channel7_IRQHandler +ADC1_IRQHandler +CAN1_TX_IRQHandler +CAN1_RX0_IRQHandler +CAN1_RX1_IRQHandler +CAN1_SCE_IRQHandler +EXTI9_5_IRQHandler +TIM1_BRK_TIM15_IRQHandler +TIM1_UP_TIM16_IRQHandler +TIM1_TRG_COM_TIM17_IRQHandler +TIM1_CC_IRQHandler +TIM2_IRQHandler +TIM3_IRQHandler +TIM4_IRQHandler +I2C1_EV_IRQHandler +I2C1_ER_IRQHandler +I2C2_EV_IRQHandler +I2C2_ER_IRQHandler +SPI1_IRQHandler +SPI2_IRQHandler +USART1_IRQHandler +USART2_IRQHandler +USART3_IRQHandler +EXTI15_10_IRQHandler +RTC_Alarm_IRQHandler +DFSDM1_FLT3_IRQHandler +TIM8_BRK_IRQHandler +TIM8_UP_IRQHandler +TIM8_TRG_COM_IRQHandler +TIM8_CC_IRQHandler +FMC_IRQHandler +SDMMC1_IRQHandler +TIM5_IRQHandler +SPI3_IRQHandler +UART4_IRQHandler +UART5_IRQHandler +TIM6_DAC_IRQHandler +TIM7_IRQHandler +DMA2_Channel1_IRQHandler +DMA2_Channel2_IRQHandler +DMA2_Channel3_IRQHandler +DMA2_Channel4_IRQHandler +DMA2_Channel5_IRQHandler +DFSDM1_FLT0_IRQHandler +DFSDM1_FLT1_IRQHandler +DFSDM1_FLT2_IRQHandler +COMP_IRQHandler +LPTIM1_IRQHandler +LPTIM2_IRQHandler +OTG_FS_IRQHandler +DMA2_Channel6_IRQHandler +DMA2_Channel7_IRQHandler +LPUART1_IRQHandler +OCTOSPI1_IRQHandler +I2C3_EV_IRQHandler +I2C3_ER_IRQHandler +SAI1_IRQHandler +SAI2_IRQHandler +OCTOSPI2_IRQHandler +TSC_IRQHandler +RNG_IRQHandler +FPU_IRQHandler +CRS_IRQHandler +I2C4_ER_IRQHandler +I2C4_EV_IRQHandler +DCMI_IRQHandler +DMA2D_IRQHandler +LTDC_IRQHandler +LTDC_ER_IRQHandler +GFXMMU_IRQHandler +DMAMUX1_OVR_IRQHandler + + B . + + ENDP + + ALIGN + END + +;************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE***** diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_ARM_STD/stm32l4r5xx.sct b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_ARM_STD/stm32l4r5xx.sct new file mode 100644 index 0000000000..78df546290 --- /dev/null +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_ARM_STD/stm32l4r5xx.sct @@ -0,0 +1,52 @@ +#! armcc -E +; Scatter-Loading Description File +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; Copyright (c) 2018, STMicroelectronics +; All rights reserved. +; +; Redistribution and use in source and binary forms, with or without +; modification, are permitted provided that the following conditions are met: +; +; 1. Redistributions of source code must retain the above copyright notice, +; this list of conditions and the following disclaimer. +; 2. Redistributions in binary form must reproduce the above copyright notice, +; this list of conditions and the following disclaimer in the documentation +; and/or other materials provided with the distribution. +; 3. Neither the name of STMicroelectronics nor the names of its contributors +; may be used to endorse or promote products derived from this software +; without specific prior written permission. +; +; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +#if !defined(MBED_APP_START) + #define MBED_APP_START 0x08000000 +#endif + +#if !defined(MBED_APP_SIZE) + #define MBED_APP_SIZE 0x200000 +#endif + +; 2MB FLASH (0x200000) + 640KB SRAM (0xA0000) +LR_IROM1 MBED_APP_START MBED_APP_SIZE { ; load region size_region + + ER_IROM1 MBED_APP_START MBED_APP_SIZE { ; load address = execution address + *.o (RESET, +First) + *(InRoot$$Sections) + .ANY (+RO) + } + + ; Total: 111 vectors = 444 bytes (0x1BC) to be reserved in RAM + RW_IRAM1 (0x20000000+0x1BC) (0xA0000-0x1BC) { ; RW data + .ANY (+RW +ZI) + } +} diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_GCC_ARM/startup_stm32l4r5xx.S b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_GCC_ARM/startup_stm32l4r5xx.S new file mode 100644 index 0000000000..1df9ca41c3 --- /dev/null +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_GCC_ARM/startup_stm32l4r5xx.S @@ -0,0 +1,560 @@ +/** + ****************************************************************************** + * @file startup_stm32l4r5xx.s + * @author MCD Application Team + * @brief STM32L4R5xx devices vector table GCC toolchain. + * This module performs: + * - Set the initial SP + * - Set the initial PC == Reset_Handler, + * - Set the vector table entries with the exceptions ISR address, + * - Configure the clock system + * - Branches to main in the C library (which eventually + * calls main()). + * After Reset the Cortex-M4 processor is in Thread mode, + * priority is Privileged, and the Stack is set to Main. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2017 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + + .syntax unified + .cpu cortex-m4 + .fpu softvfp + .thumb + +.global g_pfnVectors +.global Default_Handler + +/* start address for the initialization values of the .data section. +defined in linker script */ +.word _sidata +/* start address for the .data section. defined in linker script */ +.word _sdata +/* end address for the .data section. defined in linker script */ +.word _edata +/* start address for the .bss section. defined in linker script */ +.word _sbss +/* end address for the .bss section. defined in linker script */ +.word _ebss + +.equ BootRAM, 0xF1E0F85F +/** + * @brief This is the code that gets called when the processor first + * starts execution following a reset event. Only the absolutely + * necessary set is performed, after which the application + * supplied main() routine is called. + * @param None + * @retval : None +*/ + + .section .text.Reset_Handler + .weak Reset_Handler + .type Reset_Handler, %function +Reset_Handler: + ldr sp, =_estack /* Atollic update: set stack pointer */ + +/* Copy the data segment initializers from flash to SRAM */ + movs r1, #0 + b LoopCopyDataInit + +CopyDataInit: + ldr r3, =_sidata + ldr r3, [r3, r1] + str r3, [r0, r1] + adds r1, r1, #4 + +LoopCopyDataInit: + ldr r0, =_sdata + ldr r3, =_edata + adds r2, r0, r1 + cmp r2, r3 + bcc CopyDataInit + ldr r2, =_sbss + b LoopFillZerobss +/* Zero fill the bss segment. */ +FillZerobss: + movs r3, #0 + str r3, [r2], #4 + +LoopFillZerobss: + ldr r3, = _ebss + cmp r2, r3 + bcc FillZerobss + +/* Call the clock system intitialization function.*/ + bl SystemInit +/* Call static constructors */ + //bl __libc_init_array +/* Call the application's entry point.*/ + //bl main + // Calling the crt0 'cold-start' entry point. There __libc_init_array is called + // and when existing hardware_init_hook() and software_init_hook() before + // starting main(). software_init_hook() is available and has to be called due + // to initializsation when using rtos. + bl _start + bx lr +.size Reset_Handler, .-Reset_Handler + +/** + * @brief This is the code that gets called when the processor receives an + * unexpected interrupt. This simply enters an infinite loop, preserving + * the system state for examination by a debugger. + * + * @param None + * @retval : None +*/ + .section .text.Default_Handler,"ax",%progbits +Default_Handler: +Infinite_Loop: + b Infinite_Loop + .size Default_Handler, .-Default_Handler +/****************************************************************************** +* +* The minimal vector table for a Cortex-M4. Note that the proper constructs +* must be placed on this to ensure that it ends up at physical address +* 0x0000.0000. +* +******************************************************************************/ + .section .isr_vector,"a",%progbits + .type g_pfnVectors, %object + .size g_pfnVectors, .-g_pfnVectors + + +g_pfnVectors: + .word _estack + .word Reset_Handler + .word NMI_Handler + .word HardFault_Handler + .word MemManage_Handler + .word BusFault_Handler + .word UsageFault_Handler + .word 0 + .word 0 + .word 0 + .word 0 + .word SVC_Handler + .word DebugMon_Handler + .word 0 + .word PendSV_Handler + .word SysTick_Handler + .word WWDG_IRQHandler + .word PVD_PVM_IRQHandler + .word TAMP_STAMP_IRQHandler + .word RTC_WKUP_IRQHandler + .word FLASH_IRQHandler + .word RCC_IRQHandler + .word EXTI0_IRQHandler + .word EXTI1_IRQHandler + .word EXTI2_IRQHandler + .word EXTI3_IRQHandler + .word EXTI4_IRQHandler + .word DMA1_Channel1_IRQHandler + .word DMA1_Channel2_IRQHandler + .word DMA1_Channel3_IRQHandler + .word DMA1_Channel4_IRQHandler + .word DMA1_Channel5_IRQHandler + .word DMA1_Channel6_IRQHandler + .word DMA1_Channel7_IRQHandler + .word ADC1_IRQHandler + .word CAN1_TX_IRQHandler + .word CAN1_RX0_IRQHandler + .word CAN1_RX1_IRQHandler + .word CAN1_SCE_IRQHandler + .word EXTI9_5_IRQHandler + .word TIM1_BRK_TIM15_IRQHandler + .word TIM1_UP_TIM16_IRQHandler + .word TIM1_TRG_COM_TIM17_IRQHandler + .word TIM1_CC_IRQHandler + .word TIM2_IRQHandler + .word TIM3_IRQHandler + .word TIM4_IRQHandler + .word I2C1_EV_IRQHandler + .word I2C1_ER_IRQHandler + .word I2C2_EV_IRQHandler + .word I2C2_ER_IRQHandler + .word SPI1_IRQHandler + .word SPI2_IRQHandler + .word USART1_IRQHandler + .word USART2_IRQHandler + .word USART3_IRQHandler + .word EXTI15_10_IRQHandler + .word RTC_Alarm_IRQHandler + .word DFSDM1_FLT3_IRQHandler + .word TIM8_BRK_IRQHandler + .word TIM8_UP_IRQHandler + .word TIM8_TRG_COM_IRQHandler + .word TIM8_CC_IRQHandler + .word 0 + .word FMC_IRQHandler + .word SDMMC1_IRQHandler + .word TIM5_IRQHandler + .word SPI3_IRQHandler + .word UART4_IRQHandler + .word UART5_IRQHandler + .word TIM6_DAC_IRQHandler + .word TIM7_IRQHandler + .word DMA2_Channel1_IRQHandler + .word DMA2_Channel2_IRQHandler + .word DMA2_Channel3_IRQHandler + .word DMA2_Channel4_IRQHandler + .word DMA2_Channel5_IRQHandler + .word DFSDM1_FLT0_IRQHandler + .word DFSDM1_FLT1_IRQHandler + .word DFSDM1_FLT2_IRQHandler + .word COMP_IRQHandler + .word LPTIM1_IRQHandler + .word LPTIM2_IRQHandler + .word OTG_FS_IRQHandler + .word DMA2_Channel6_IRQHandler + .word DMA2_Channel7_IRQHandler + .word LPUART1_IRQHandler + .word OCTOSPI1_IRQHandler + .word I2C3_EV_IRQHandler + .word I2C3_ER_IRQHandler + .word SAI1_IRQHandler + .word SAI2_IRQHandler + .word OCTOSPI2_IRQHandler + .word TSC_IRQHandler + .word 0 + .word 0 + .word RNG_IRQHandler + .word FPU_IRQHandler + .word CRS_IRQHandler + .word I2C4_ER_IRQHandler + .word I2C4_EV_IRQHandler + .word DCMI_IRQHandler + .word 0 + .word 0 + .word 0 + .word 0 + .word DMA2D_IRQHandler + .word LTDC_IRQHandler + .word LTDC_ER_IRQHandler + .word GFXMMU_IRQHandler + .word DMAMUX1_OVR_IRQHandler + + +/******************************************************************************* +* +* Provide weak aliases for each Exception handler to the Default_Handler. +* As they are weak aliases, any function with the same name will override +* this definition. +* +*******************************************************************************/ + + .weak NMI_Handler + .thumb_set NMI_Handler,Default_Handler + + .weak HardFault_Handler + .thumb_set HardFault_Handler,Default_Handler + + .weak MemManage_Handler + .thumb_set MemManage_Handler,Default_Handler + + .weak BusFault_Handler + .thumb_set BusFault_Handler,Default_Handler + + .weak UsageFault_Handler + .thumb_set UsageFault_Handler,Default_Handler + + .weak SVC_Handler + .thumb_set SVC_Handler,Default_Handler + + .weak DebugMon_Handler + .thumb_set DebugMon_Handler,Default_Handler + + .weak PendSV_Handler + .thumb_set PendSV_Handler,Default_Handler + + .weak SysTick_Handler + .thumb_set SysTick_Handler,Default_Handler + + .weak WWDG_IRQHandler + .thumb_set WWDG_IRQHandler,Default_Handler + + .weak PVD_PVM_IRQHandler + .thumb_set PVD_PVM_IRQHandler,Default_Handler + + .weak TAMP_STAMP_IRQHandler + .thumb_set TAMP_STAMP_IRQHandler,Default_Handler + + .weak RTC_WKUP_IRQHandler + .thumb_set RTC_WKUP_IRQHandler,Default_Handler + + .weak FLASH_IRQHandler + .thumb_set FLASH_IRQHandler,Default_Handler + + .weak RCC_IRQHandler + .thumb_set RCC_IRQHandler,Default_Handler + + .weak EXTI0_IRQHandler + .thumb_set EXTI0_IRQHandler,Default_Handler + + .weak EXTI1_IRQHandler + .thumb_set EXTI1_IRQHandler,Default_Handler + + .weak EXTI2_IRQHandler + .thumb_set EXTI2_IRQHandler,Default_Handler + + .weak EXTI3_IRQHandler + .thumb_set EXTI3_IRQHandler,Default_Handler + + .weak EXTI4_IRQHandler + .thumb_set EXTI4_IRQHandler,Default_Handler + + .weak DMA1_Channel1_IRQHandler + .thumb_set DMA1_Channel1_IRQHandler,Default_Handler + + .weak DMA1_Channel2_IRQHandler + .thumb_set DMA1_Channel2_IRQHandler,Default_Handler + + .weak DMA1_Channel3_IRQHandler + .thumb_set DMA1_Channel3_IRQHandler,Default_Handler + + .weak DMA1_Channel4_IRQHandler + .thumb_set DMA1_Channel4_IRQHandler,Default_Handler + + .weak DMA1_Channel5_IRQHandler + .thumb_set DMA1_Channel5_IRQHandler,Default_Handler + + .weak DMA1_Channel6_IRQHandler + .thumb_set DMA1_Channel6_IRQHandler,Default_Handler + + .weak DMA1_Channel7_IRQHandler + .thumb_set DMA1_Channel7_IRQHandler,Default_Handler + + .weak ADC1_IRQHandler + .thumb_set ADC1_IRQHandler,Default_Handler + + .weak CAN1_TX_IRQHandler + .thumb_set CAN1_TX_IRQHandler,Default_Handler + + .weak CAN1_RX0_IRQHandler + .thumb_set CAN1_RX0_IRQHandler,Default_Handler + + .weak CAN1_RX1_IRQHandler + .thumb_set CAN1_RX1_IRQHandler,Default_Handler + + .weak CAN1_SCE_IRQHandler + .thumb_set CAN1_SCE_IRQHandler,Default_Handler + + .weak EXTI9_5_IRQHandler + .thumb_set EXTI9_5_IRQHandler,Default_Handler + + .weak TIM1_BRK_TIM15_IRQHandler + .thumb_set TIM1_BRK_TIM15_IRQHandler,Default_Handler + + .weak TIM1_UP_TIM16_IRQHandler + .thumb_set TIM1_UP_TIM16_IRQHandler,Default_Handler + + .weak TIM1_TRG_COM_TIM17_IRQHandler + .thumb_set TIM1_TRG_COM_TIM17_IRQHandler,Default_Handler + + .weak TIM1_CC_IRQHandler + .thumb_set TIM1_CC_IRQHandler,Default_Handler + + .weak TIM2_IRQHandler + .thumb_set TIM2_IRQHandler,Default_Handler + + .weak TIM3_IRQHandler + .thumb_set TIM3_IRQHandler,Default_Handler + + .weak TIM4_IRQHandler + .thumb_set TIM4_IRQHandler,Default_Handler + + .weak I2C1_EV_IRQHandler + .thumb_set I2C1_EV_IRQHandler,Default_Handler + + .weak I2C1_ER_IRQHandler + .thumb_set I2C1_ER_IRQHandler,Default_Handler + + .weak I2C2_EV_IRQHandler + .thumb_set I2C2_EV_IRQHandler,Default_Handler + + .weak I2C2_ER_IRQHandler + .thumb_set I2C2_ER_IRQHandler,Default_Handler + + .weak SPI1_IRQHandler + .thumb_set SPI1_IRQHandler,Default_Handler + + .weak SPI2_IRQHandler + .thumb_set SPI2_IRQHandler,Default_Handler + + .weak USART1_IRQHandler + .thumb_set USART1_IRQHandler,Default_Handler + + .weak USART2_IRQHandler + .thumb_set USART2_IRQHandler,Default_Handler + + .weak USART3_IRQHandler + .thumb_set USART3_IRQHandler,Default_Handler + + .weak EXTI15_10_IRQHandler + .thumb_set EXTI15_10_IRQHandler,Default_Handler + + .weak RTC_Alarm_IRQHandler + .thumb_set RTC_Alarm_IRQHandler,Default_Handler + + .weak DFSDM1_FLT3_IRQHandler + .thumb_set DFSDM1_FLT3_IRQHandler,Default_Handler + + .weak TIM8_BRK_IRQHandler + .thumb_set TIM8_BRK_IRQHandler,Default_Handler + + .weak TIM8_UP_IRQHandler + .thumb_set TIM8_UP_IRQHandler,Default_Handler + + .weak TIM8_TRG_COM_IRQHandler + .thumb_set TIM8_TRG_COM_IRQHandler,Default_Handler + + .weak TIM8_CC_IRQHandler + .thumb_set TIM8_CC_IRQHandler,Default_Handler + + .weak FMC_IRQHandler + .thumb_set FMC_IRQHandler,Default_Handler + + .weak SDMMC1_IRQHandler + .thumb_set SDMMC1_IRQHandler,Default_Handler + + .weak TIM5_IRQHandler + .thumb_set TIM5_IRQHandler,Default_Handler + + .weak SPI3_IRQHandler + .thumb_set SPI3_IRQHandler,Default_Handler + + .weak UART4_IRQHandler + .thumb_set UART4_IRQHandler,Default_Handler + + .weak UART5_IRQHandler + .thumb_set UART5_IRQHandler,Default_Handler + + .weak TIM6_DAC_IRQHandler + .thumb_set TIM6_DAC_IRQHandler,Default_Handler + + .weak TIM7_IRQHandler + .thumb_set TIM7_IRQHandler,Default_Handler + + .weak DMA2_Channel1_IRQHandler + .thumb_set DMA2_Channel1_IRQHandler,Default_Handler + + .weak DMA2_Channel2_IRQHandler + .thumb_set DMA2_Channel2_IRQHandler,Default_Handler + + .weak DMA2_Channel3_IRQHandler + .thumb_set DMA2_Channel3_IRQHandler,Default_Handler + + .weak DMA2_Channel4_IRQHandler + .thumb_set DMA2_Channel4_IRQHandler,Default_Handler + + .weak DMA2_Channel5_IRQHandler + .thumb_set DMA2_Channel5_IRQHandler,Default_Handler + + .weak DFSDM1_FLT0_IRQHandler + .thumb_set DFSDM1_FLT0_IRQHandler,Default_Handler + + .weak DFSDM1_FLT1_IRQHandler + .thumb_set DFSDM1_FLT1_IRQHandler,Default_Handler + + .weak DFSDM1_FLT2_IRQHandler + .thumb_set DFSDM1_FLT2_IRQHandler,Default_Handler + + .weak COMP_IRQHandler + .thumb_set COMP_IRQHandler,Default_Handler + + .weak LPTIM1_IRQHandler + .thumb_set LPTIM1_IRQHandler,Default_Handler + + .weak LPTIM2_IRQHandler + .thumb_set LPTIM2_IRQHandler,Default_Handler + + .weak OTG_FS_IRQHandler + .thumb_set OTG_FS_IRQHandler,Default_Handler + + .weak DMA2_Channel6_IRQHandler + .thumb_set DMA2_Channel6_IRQHandler,Default_Handler + + .weak DMA2_Channel7_IRQHandler + .thumb_set DMA2_Channel7_IRQHandler,Default_Handler + + .weak LPUART1_IRQHandler + .thumb_set LPUART1_IRQHandler,Default_Handler + + .weak OCTOSPI1_IRQHandler + .thumb_set OCTOSPI1_IRQHandler,Default_Handler + + .weak I2C3_EV_IRQHandler + .thumb_set I2C3_EV_IRQHandler,Default_Handler + + .weak I2C3_ER_IRQHandler + .thumb_set I2C3_ER_IRQHandler,Default_Handler + + .weak SAI1_IRQHandler + .thumb_set SAI1_IRQHandler,Default_Handler + + .weak SAI2_IRQHandler + .thumb_set SAI2_IRQHandler,Default_Handler + + .weak OCTOSPI2_IRQHandler + .thumb_set OCTOSPI2_IRQHandler,Default_Handler + + .weak TSC_IRQHandler + .thumb_set TSC_IRQHandler,Default_Handler + + .weak RNG_IRQHandler + .thumb_set RNG_IRQHandler,Default_Handler + + .weak FPU_IRQHandler + .thumb_set FPU_IRQHandler,Default_Handler + + .weak CRS_IRQHandler + .thumb_set CRS_IRQHandler,Default_Handler + + .weak I2C4_ER_IRQHandler + .thumb_set I2C4_ER_IRQHandler,Default_Handler + + .weak I2C4_EV_IRQHandler + .thumb_set I2C4_EV_IRQHandler,Default_Handler + + .weak DCMI_IRQHandler + .thumb_set DCMI_IRQHandler,Default_Handler + + .weak DMA2D_IRQHandler + .thumb_set DMA2D_IRQHandler,Default_Handler + + .weak LTDC_IRQHandler + .thumb_set LTDC_IRQHandler,Default_Handler + + .weak LTDC_ER_IRQHandler + .thumb_set LTDC_ER_IRQHandler,Default_Handler + + .weak GFXMMU_IRQHandler + .thumb_set GFXMMU_IRQHandler,Default_Handler + + .weak DMAMUX1_OVR_IRQHandler + .thumb_set DMAMUX1_OVR_IRQHandler,Default_Handler +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_GCC_ARM/stm32l4r5xx.ld b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_GCC_ARM/stm32l4r5xx.ld new file mode 100644 index 0000000000..520228064e --- /dev/null +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_GCC_ARM/stm32l4r5xx.ld @@ -0,0 +1,160 @@ +#if !defined(MBED_APP_START) + #define MBED_APP_START 0x08000000 +#endif + +#if !defined(MBED_APP_SIZE) + #define MBED_APP_SIZE 2048K +#endif + +/* Linker script to configure memory regions. */ +MEMORY +{ + FLASH (rx) : ORIGIN = MBED_APP_START, LENGTH = MBED_APP_SIZE + SRAM1 (rwx) : ORIGIN = 0x200001BC, LENGTH = 640k - 0x1BC +} + +/* Linker script to place sections and symbol values. Should be used together + * with other linker script that defines memory regions FLASH and RAM. + * It references following symbols, which must be defined in code: + * Reset_Handler : Entry of reset handler + * + * It defines following symbols, which code can use without definition: + * __exidx_start + * __exidx_end + * __etext + * __data_start__ + * __preinit_array_start + * __preinit_array_end + * __init_array_start + * __init_array_end + * __fini_array_start + * __fini_array_end + * __data_end__ + * __bss_start__ + * __bss_end__ + * __end__ + * end + * __HeapLimit + * __StackLimit + * __StackTop + * __stack + * _estack + */ +ENTRY(Reset_Handler) + +SECTIONS +{ + .text : + { + KEEP(*(.isr_vector)) + *(.text*) + KEEP(*(.init)) + KEEP(*(.fini)) + + /* .ctors */ + *crtbegin.o(.ctors) + *crtbegin?.o(.ctors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) + *(SORT(.ctors.*)) + *(.ctors) + + /* .dtors */ + *crtbegin.o(.dtors) + *crtbegin?.o(.dtors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) + *(SORT(.dtors.*)) + *(.dtors) + + *(.rodata*) + + KEEP(*(.eh_frame*)) + } > FLASH + + .ARM.extab : + { + *(.ARM.extab* .gnu.linkonce.armextab.*) + } > FLASH + + __exidx_start = .; + .ARM.exidx : + { + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + } > FLASH + __exidx_end = .; + + __etext = .; + _sidata = .; + + .data : AT (__etext) + { + __data_start__ = .; + _sdata = .; + *(vtable) + *(.data*) + + . = ALIGN(4); + /* preinit data */ + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP(*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + + . = ALIGN(4); + /* init data */ + PROVIDE_HIDDEN (__init_array_start = .); + KEEP(*(SORT(.init_array.*))) + KEEP(*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + + . = ALIGN(4); + /* finit data */ + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP(*(SORT(.fini_array.*))) + KEEP(*(.fini_array)) + PROVIDE_HIDDEN (__fini_array_end = .); + + KEEP(*(.jcr*)) + . = ALIGN(4); + /* All data end */ + __data_end__ = .; + _edata = .; + + } > SRAM1 + + .bss : + { + . = ALIGN(4); + __bss_start__ = .; + _sbss = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + _ebss = .; + } > SRAM1 + + .heap (COPY): + { + __end__ = .; + end = __end__; + *(.heap*) + __HeapLimit = .; + } > SRAM1 + + /* .stack_dummy section doesn't contains any symbols. It is only + * used for linker to calculate size of stack sections, and assign + * values to stack symbols later */ + .stack_dummy (COPY): + { + *(.stack*) + } > SRAM1 + + /* Set stack top to end of RAM, and stack limit move down by + * size of stack_dummy section */ + __StackTop = ORIGIN(SRAM1) + LENGTH(SRAM1); + _estack = __StackTop; + __StackLimit = __StackTop - SIZEOF(.stack_dummy); + PROVIDE(__stack = __StackTop); + + /* Check if data + heap + stack exceeds RAM limit */ + ASSERT(__StackLimit >= __HeapLimit, "region RAM overflowed with stack") +} diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_IAR/startup_stm32l4r5xx.S b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_IAR/startup_stm32l4r5xx.S new file mode 100644 index 0000000000..bc63151de4 --- /dev/null +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_IAR/startup_stm32l4r5xx.S @@ -0,0 +1,683 @@ +;/********************* COPYRIGHT(c) 2017 STMicroelectronics ******************** +;* File Name : startup_stm32l4r5xx.s +;* Author : MCD Application Team +;* Description : STM32L4R5xx Ultra Low Power Devices vector +;* This module performs: +;* - Set the initial SP +;* - Set the initial PC == _iar_program_start, +;* - Set the vector table entries with the exceptions ISR +;* address. +;* - Branches to main in the C library (which eventually +;* calls main()). +;* After Reset the Cortex-M4 processor is in Thread mode, +;* priority is Privileged, and the Stack is set to Main. +;******************************************************************************** +;* +;* Redistribution and use in source and binary forms, with or without modification, +;* are permitted provided that the following conditions are met: +;* 1. Redistributions of source code must retain the above copyright notice, +;* this list of conditions and the following disclaimer. +;* 2. Redistributions in binary form must reproduce the above copyright notice, +;* this list of conditions and the following disclaimer in the documentation +;* and/or other materials provided with the distribution. +;* 3. Neither the name of STMicroelectronics nor the names of its contributors +;* may be used to endorse or promote products derived from this software +;* without specific prior written permission. +;* +;* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +;* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +;* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +;* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +;* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +;* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +;* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +;* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +;* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +;* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +;* +;******************************************************************************* +; +; +; The modules in this file are included in the libraries, and may be replaced +; by any user-defined modules that define the PUBLIC symbol _program_start or +; a user defined start symbol. +; To override the cstartup defined in the library, simply add your modified +; version to the workbench project. +; +; The vector table is normally located at address 0. +; When debugging in RAM, it can be located in RAM, aligned to at least 2^6. +; The name "__vector_table" has special meaning for C-SPY: +; it is where the SP start value is found, and the NVIC vector +; table register (VTOR) is initialized to this address if != 0. +; +; Cortex-M version +; + + MODULE ?cstartup + + ;; Forward declaration of sections. + SECTION CSTACK:DATA:NOROOT(3) + + SECTION .intvec:CODE:NOROOT(2) + + EXTERN __iar_program_start + EXTERN SystemInit + PUBLIC __vector_table + + DATA +__vector_table + DCD sfe(CSTACK) + DCD Reset_Handler ; Reset Handler + + DCD NMI_Handler ; NMI Handler + DCD HardFault_Handler ; Hard Fault Handler + DCD MemManage_Handler ; MPU Fault Handler + DCD BusFault_Handler ; Bus Fault Handler + DCD UsageFault_Handler ; Usage Fault Handler + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD SVC_Handler ; SVCall Handler + DCD DebugMon_Handler ; Debug Monitor Handler + DCD 0 ; Reserved + DCD PendSV_Handler ; PendSV Handler + DCD SysTick_Handler ; SysTick Handler + + ; External Interrupts + DCD WWDG_IRQHandler ; Window WatchDog + DCD PVD_PVM_IRQHandler ; PVD/PVM1/PVM2/PVM3/PVM4 through EXTI Line detection + DCD TAMP_STAMP_IRQHandler ; Tamper and TimeStamps through the EXTI line + DCD RTC_WKUP_IRQHandler ; RTC Wakeup through the EXTI line + DCD FLASH_IRQHandler ; FLASH + DCD RCC_IRQHandler ; RCC + DCD EXTI0_IRQHandler ; EXTI Line0 + DCD EXTI1_IRQHandler ; EXTI Line1 + DCD EXTI2_IRQHandler ; EXTI Line2 + DCD EXTI3_IRQHandler ; EXTI Line3 + DCD EXTI4_IRQHandler ; EXTI Line4 + DCD DMA1_Channel1_IRQHandler ; DMA1 Channel 1 + DCD DMA1_Channel2_IRQHandler ; DMA1 Channel 2 + DCD DMA1_Channel3_IRQHandler ; DMA1 Channel 3 + DCD DMA1_Channel4_IRQHandler ; DMA1 Channel 4 + DCD DMA1_Channel5_IRQHandler ; DMA1 Channel 5 + DCD DMA1_Channel6_IRQHandler ; DMA1 Channel 6 + DCD DMA1_Channel7_IRQHandler ; DMA1 Channel 7 + DCD ADC1_IRQHandler ; ADC1 + DCD CAN1_TX_IRQHandler ; CAN1 TX + DCD CAN1_RX0_IRQHandler ; CAN1 RX0 + DCD CAN1_RX1_IRQHandler ; CAN1 RX1 + DCD CAN1_SCE_IRQHandler ; CAN1 SCE + DCD EXTI9_5_IRQHandler ; External Line[9:5]s + DCD TIM1_BRK_TIM15_IRQHandler ; TIM1 Break and TIM15 + DCD TIM1_UP_TIM16_IRQHandler ; TIM1 Update and TIM16 + DCD TIM1_TRG_COM_TIM17_IRQHandler ; TIM1 Trigger and Commutation and TIM17 + DCD TIM1_CC_IRQHandler ; TIM1 Capture Compare + DCD TIM2_IRQHandler ; TIM2 + DCD TIM3_IRQHandler ; TIM3 + DCD TIM4_IRQHandler ; TIM4 + DCD I2C1_EV_IRQHandler ; I2C1 Event + DCD I2C1_ER_IRQHandler ; I2C1 Error + DCD I2C2_EV_IRQHandler ; I2C2 Event + DCD I2C2_ER_IRQHandler ; I2C2 Error + DCD SPI1_IRQHandler ; SPI1 + DCD SPI2_IRQHandler ; SPI2 + DCD USART1_IRQHandler ; USART1 + DCD USART2_IRQHandler ; USART2 + DCD USART3_IRQHandler ; USART3 + DCD EXTI15_10_IRQHandler ; External Line[15:10] + DCD RTC_Alarm_IRQHandler ; RTC Alarm (A and B) through EXTI Line + DCD DFSDM1_FLT3_IRQHandler ; DFSDM1 Filter 3 global Interrupt + DCD TIM8_BRK_IRQHandler ; TIM8 Break Interrupt + DCD TIM8_UP_IRQHandler ; TIM8 Update Interrupt + DCD TIM8_TRG_COM_IRQHandler ; TIM8 Trigger and Commutation Interrupt + DCD TIM8_CC_IRQHandler ; TIM8 Capture Compare Interrupt + DCD 0 ; Reserved + DCD FMC_IRQHandler ; FMC + DCD SDMMC1_IRQHandler ; SDMMC1 + DCD TIM5_IRQHandler ; TIM5 + DCD SPI3_IRQHandler ; SPI3 + DCD UART4_IRQHandler ; UART4 + DCD UART5_IRQHandler ; UART5 + DCD TIM6_DAC_IRQHandler ; TIM6 and DAC1&2 underrun errors + DCD TIM7_IRQHandler ; TIM7 + DCD DMA2_Channel1_IRQHandler ; DMA2 Channel 1 + DCD DMA2_Channel2_IRQHandler ; DMA2 Channel 2 + DCD DMA2_Channel3_IRQHandler ; DMA2 Channel 3 + DCD DMA2_Channel4_IRQHandler ; DMA2 Channel 4 + DCD DMA2_Channel5_IRQHandler ; DMA2 Channel 5 + DCD DFSDM1_FLT0_IRQHandler ; DFSDM1 Filter 0 global Interrupt + DCD DFSDM1_FLT1_IRQHandler ; DFSDM1 Filter 1 global Interrupt + DCD DFSDM1_FLT2_IRQHandler ; DFSDM1 Filter 2 global Interrupt + DCD COMP_IRQHandler ; COMP Interrupt + DCD LPTIM1_IRQHandler ; LP TIM1 interrupt + DCD LPTIM2_IRQHandler ; LP TIM2 interrupt + DCD OTG_FS_IRQHandler ; USB OTG FS + DCD DMA2_Channel6_IRQHandler ; DMA2 Channel 6 + DCD DMA2_Channel7_IRQHandler ; DMA2 Channel 7 + DCD LPUART1_IRQHandler ; LP UART 1 interrupt + DCD OCTOSPI1_IRQHandler ; OctoSPI1 global interrupt + DCD I2C3_EV_IRQHandler ; I2C3 event + DCD I2C3_ER_IRQHandler ; I2C3 error + DCD SAI1_IRQHandler ; Serial Audio Interface 1 global interrupt + DCD SAI2_IRQHandler ; Serial Audio Interface 2 global interrupt + DCD OCTOSPI2_IRQHandler ; OctoSPI2 global interrupt + DCD TSC_IRQHandler ; Touch Sense Controller global interrupt + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD RNG_IRQHandler ; RNG global interrupt + DCD FPU_IRQHandler ; FPU + DCD CRS_IRQHandler ; CRS interrupt + DCD I2C4_ER_IRQHandler ; I2C4 error + DCD I2C4_EV_IRQHandler ; I2C4 event + DCD DCMI_IRQHandler ; DCMI global interrupt + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD DMA2D_IRQHandler ; DMA2D global interrupt + DCD LTDC_IRQHandler ; LTDC global interrupt + DCD LTDC_ER_IRQHandler ; LTDC error global interrupt + DCD GFXMMU_IRQHandler ; GFXMMU global interrupt + DCD DMAMUX1_OVR_IRQHandler ; DMAMUX1 overrun global interrupt + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Default interrupt handlers. +;; + THUMB + PUBWEAK Reset_Handler + SECTION .text:CODE:NOROOT:REORDER(2) +Reset_Handler + LDR R0, =SystemInit + BLX R0 + LDR R0, =__iar_program_start + BX R0 + + PUBWEAK NMI_Handler + SECTION .text:CODE:NOROOT:REORDER(1) +NMI_Handler + B NMI_Handler + + PUBWEAK HardFault_Handler + SECTION .text:CODE:NOROOT:REORDER(1) +HardFault_Handler + B HardFault_Handler + + PUBWEAK MemManage_Handler + SECTION .text:CODE:NOROOT:REORDER(1) +MemManage_Handler + B MemManage_Handler + + PUBWEAK BusFault_Handler + SECTION .text:CODE:NOROOT:REORDER(1) +BusFault_Handler + B BusFault_Handler + + PUBWEAK UsageFault_Handler + SECTION .text:CODE:NOROOT:REORDER(1) +UsageFault_Handler + B UsageFault_Handler + + PUBWEAK SVC_Handler + SECTION .text:CODE:NOROOT:REORDER(1) +SVC_Handler + B SVC_Handler + + PUBWEAK DebugMon_Handler + SECTION .text:CODE:NOROOT:REORDER(1) +DebugMon_Handler + B DebugMon_Handler + + PUBWEAK PendSV_Handler + SECTION .text:CODE:NOROOT:REORDER(1) +PendSV_Handler + B PendSV_Handler + + PUBWEAK SysTick_Handler + SECTION .text:CODE:NOROOT:REORDER(1) +SysTick_Handler + B SysTick_Handler + + PUBWEAK WWDG_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +WWDG_IRQHandler + B WWDG_IRQHandler + + PUBWEAK PVD_PVM_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +PVD_PVM_IRQHandler + B PVD_PVM_IRQHandler + + PUBWEAK TAMP_STAMP_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +TAMP_STAMP_IRQHandler + B TAMP_STAMP_IRQHandler + + PUBWEAK RTC_WKUP_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +RTC_WKUP_IRQHandler + B RTC_WKUP_IRQHandler + + PUBWEAK FLASH_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +FLASH_IRQHandler + B FLASH_IRQHandler + + PUBWEAK RCC_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +RCC_IRQHandler + B RCC_IRQHandler + + PUBWEAK EXTI0_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +EXTI0_IRQHandler + B EXTI0_IRQHandler + + PUBWEAK EXTI1_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +EXTI1_IRQHandler + B EXTI1_IRQHandler + + PUBWEAK EXTI2_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +EXTI2_IRQHandler + B EXTI2_IRQHandler + + PUBWEAK EXTI3_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +EXTI3_IRQHandler + B EXTI3_IRQHandler + + PUBWEAK EXTI4_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +EXTI4_IRQHandler + B EXTI4_IRQHandler + + PUBWEAK DMA1_Channel1_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DMA1_Channel1_IRQHandler + B DMA1_Channel1_IRQHandler + + PUBWEAK DMA1_Channel2_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DMA1_Channel2_IRQHandler + B DMA1_Channel2_IRQHandler + + PUBWEAK DMA1_Channel3_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DMA1_Channel3_IRQHandler + B DMA1_Channel3_IRQHandler + + PUBWEAK DMA1_Channel4_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DMA1_Channel4_IRQHandler + B DMA1_Channel4_IRQHandler + + PUBWEAK DMA1_Channel5_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DMA1_Channel5_IRQHandler + B DMA1_Channel5_IRQHandler + + PUBWEAK DMA1_Channel6_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DMA1_Channel6_IRQHandler + B DMA1_Channel6_IRQHandler + + PUBWEAK DMA1_Channel7_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DMA1_Channel7_IRQHandler + B DMA1_Channel7_IRQHandler + + PUBWEAK ADC1_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +ADC1_IRQHandler + B ADC1_IRQHandler + + PUBWEAK CAN1_TX_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +CAN1_TX_IRQHandler + B CAN1_TX_IRQHandler + + PUBWEAK CAN1_RX0_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +CAN1_RX0_IRQHandler + B CAN1_RX0_IRQHandler + + PUBWEAK CAN1_RX1_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +CAN1_RX1_IRQHandler + B CAN1_RX1_IRQHandler + + PUBWEAK CAN1_SCE_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +CAN1_SCE_IRQHandler + B CAN1_SCE_IRQHandler + + PUBWEAK EXTI9_5_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +EXTI9_5_IRQHandler + B EXTI9_5_IRQHandler + + PUBWEAK TIM1_BRK_TIM15_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +TIM1_BRK_TIM15_IRQHandler + B TIM1_BRK_TIM15_IRQHandler + + PUBWEAK TIM1_UP_TIM16_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +TIM1_UP_TIM16_IRQHandler + B TIM1_UP_TIM16_IRQHandler + + PUBWEAK TIM1_TRG_COM_TIM17_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +TIM1_TRG_COM_TIM17_IRQHandler + B TIM1_TRG_COM_TIM17_IRQHandler + + PUBWEAK TIM1_CC_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +TIM1_CC_IRQHandler + B TIM1_CC_IRQHandler + + PUBWEAK TIM2_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +TIM2_IRQHandler + B TIM2_IRQHandler + + PUBWEAK TIM3_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +TIM3_IRQHandler + B TIM3_IRQHandler + + PUBWEAK TIM4_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +TIM4_IRQHandler + B TIM4_IRQHandler + + PUBWEAK I2C1_EV_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +I2C1_EV_IRQHandler + B I2C1_EV_IRQHandler + + PUBWEAK I2C1_ER_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +I2C1_ER_IRQHandler + B I2C1_ER_IRQHandler + + PUBWEAK I2C2_EV_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +I2C2_EV_IRQHandler + B I2C2_EV_IRQHandler + + PUBWEAK I2C2_ER_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +I2C2_ER_IRQHandler + B I2C2_ER_IRQHandler + + PUBWEAK SPI1_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +SPI1_IRQHandler + B SPI1_IRQHandler + + PUBWEAK SPI2_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +SPI2_IRQHandler + B SPI2_IRQHandler + + PUBWEAK USART1_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +USART1_IRQHandler + B USART1_IRQHandler + + PUBWEAK USART2_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +USART2_IRQHandler + B USART2_IRQHandler + + PUBWEAK USART3_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +USART3_IRQHandler + B USART3_IRQHandler + + PUBWEAK EXTI15_10_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +EXTI15_10_IRQHandler + B EXTI15_10_IRQHandler + + PUBWEAK RTC_Alarm_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +RTC_Alarm_IRQHandler + B RTC_Alarm_IRQHandler + + PUBWEAK DFSDM1_FLT3_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DFSDM1_FLT3_IRQHandler + B DFSDM1_FLT3_IRQHandler + + PUBWEAK TIM8_BRK_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +TIM8_BRK_IRQHandler + B TIM8_BRK_IRQHandler + + PUBWEAK TIM8_UP_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +TIM8_UP_IRQHandler + B TIM8_UP_IRQHandler + + PUBWEAK TIM8_TRG_COM_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +TIM8_TRG_COM_IRQHandler + B TIM8_TRG_COM_IRQHandler + + PUBWEAK TIM8_CC_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +TIM8_CC_IRQHandler + B TIM8_CC_IRQHandler + + PUBWEAK FMC_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +FMC_IRQHandler + B FMC_IRQHandler + + PUBWEAK SDMMC1_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +SDMMC1_IRQHandler + B SDMMC1_IRQHandler + + PUBWEAK TIM5_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +TIM5_IRQHandler + B TIM5_IRQHandler + + PUBWEAK SPI3_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +SPI3_IRQHandler + B SPI3_IRQHandler + + PUBWEAK UART4_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +UART4_IRQHandler + B UART4_IRQHandler + + PUBWEAK UART5_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +UART5_IRQHandler + B UART5_IRQHandler + + PUBWEAK TIM6_DAC_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +TIM6_DAC_IRQHandler + B TIM6_DAC_IRQHandler + + PUBWEAK TIM7_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +TIM7_IRQHandler + B TIM7_IRQHandler + + PUBWEAK DMA2_Channel1_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DMA2_Channel1_IRQHandler + B DMA2_Channel1_IRQHandler + + PUBWEAK DMA2_Channel2_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DMA2_Channel2_IRQHandler + B DMA2_Channel2_IRQHandler + + PUBWEAK DMA2_Channel3_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DMA2_Channel3_IRQHandler + B DMA2_Channel3_IRQHandler + + PUBWEAK DMA2_Channel4_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DMA2_Channel4_IRQHandler + B DMA2_Channel4_IRQHandler + + PUBWEAK DMA2_Channel5_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DMA2_Channel5_IRQHandler + B DMA2_Channel5_IRQHandler + + PUBWEAK DFSDM1_FLT0_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DFSDM1_FLT0_IRQHandler + B DFSDM1_FLT0_IRQHandler + + PUBWEAK DFSDM1_FLT1_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DFSDM1_FLT1_IRQHandler + B DFSDM1_FLT1_IRQHandler + + PUBWEAK DFSDM1_FLT2_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DFSDM1_FLT2_IRQHandler + B DFSDM1_FLT2_IRQHandler + + PUBWEAK COMP_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +COMP_IRQHandler + B COMP_IRQHandler + + PUBWEAK LPTIM1_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +LPTIM1_IRQHandler + B LPTIM1_IRQHandler + + PUBWEAK LPTIM2_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +LPTIM2_IRQHandler + B LPTIM2_IRQHandler + + PUBWEAK OTG_FS_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +OTG_FS_IRQHandler + B OTG_FS_IRQHandler + + PUBWEAK DMA2_Channel6_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DMA2_Channel6_IRQHandler + B DMA2_Channel6_IRQHandler + + PUBWEAK DMA2_Channel7_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DMA2_Channel7_IRQHandler + B DMA2_Channel7_IRQHandler + + PUBWEAK LPUART1_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +LPUART1_IRQHandler + B LPUART1_IRQHandler + + PUBWEAK OCTOSPI1_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +OCTOSPI1_IRQHandler + B OCTOSPI1_IRQHandler + + PUBWEAK I2C3_EV_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +I2C3_EV_IRQHandler + B I2C3_EV_IRQHandler + + PUBWEAK I2C3_ER_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +I2C3_ER_IRQHandler + B I2C3_ER_IRQHandler + + PUBWEAK SAI1_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +SAI1_IRQHandler + B SAI1_IRQHandler + + PUBWEAK SAI2_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +SAI2_IRQHandler + B SAI2_IRQHandler + + PUBWEAK OCTOSPI2_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +OCTOSPI2_IRQHandler + B OCTOSPI2_IRQHandler + + PUBWEAK TSC_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +TSC_IRQHandler + B TSC_IRQHandler + + PUBWEAK RNG_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +RNG_IRQHandler + B RNG_IRQHandler + + PUBWEAK FPU_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +FPU_IRQHandler + B FPU_IRQHandler + + PUBWEAK CRS_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +CRS_IRQHandler + B CRS_IRQHandler + + PUBWEAK I2C4_ER_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +I2C4_ER_IRQHandler + B I2C4_ER_IRQHandler + + PUBWEAK I2C4_EV_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +I2C4_EV_IRQHandler + B I2C4_EV_IRQHandler + + PUBWEAK DMA2D_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DMA2D_IRQHandler + B DMA2D_IRQHandler + + PUBWEAK DCMI_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DCMI_IRQHandler + B DCMI_IRQHandler + + PUBWEAK LTDC_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +LTDC_IRQHandler + B LTDC_IRQHandler + + PUBWEAK LTDC_ER_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +LTDC_ER_IRQHandler + B LTDC_ER_IRQHandler + + PUBWEAK GFXMMU_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +GFXMMU_IRQHandler + B GFXMMU_IRQHandler + + PUBWEAK DMAMUX1_OVR_IRQHandler + SECTION .text:CODE:NOROOT:REORDER(1) +DMAMUX1_OVR_IRQHandler + B DMAMUX1_OVR_IRQHandler + + END +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_IAR/stm32l4r5xx.icf b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_IAR/stm32l4r5xx.icf new file mode 100644 index 0000000000..ccf5c11558 --- /dev/null +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/TOOLCHAIN_IAR/stm32l4r5xx.icf @@ -0,0 +1,35 @@ +if (!isdefinedsymbol(MBED_APP_START)) { define symbol MBED_APP_START = 0x08000000; } +if (!isdefinedsymbol(MBED_APP_SIZE)) { define symbol MBED_APP_SIZE = 0x200000; } + +/* [ROM = 2MB = 0x200000] */ +define symbol __intvec_start__ = MBED_APP_START; +define symbol __region_ROM_start__ = MBED_APP_START; +define symbol __region_ROM_end__ = MBED_APP_START + MBED_APP_SIZE - 1; + +/* [RAM = 640KB = 0xA0000] */ +/* Vector table dynamic copy: Total: 111 vectors = 444 bytes (0x1BC) to be reserved in RAM */ +/* Reserved 448 bytes (0x1C0) to be aligned on 8 bytes (448 = 56 x 8) */ +define symbol __NVIC_start__ = 0x20000000; +define symbol __NVIC_end__ = 0x20000000 + 0x1C0 - 1; +define symbol __region_SRAM1_start__ = 0x20000000 + 0x1C0; +define symbol __region_SRAM1_end__ = 0x20000000 + 0xA0000 - 1; + +/* Memory regions */ +define memory mem with size = 4G; +define region ROM_region = mem:[from __region_ROM_start__ to __region_ROM_end__]; +define region SRAM1_region = mem:[from __region_SRAM1_start__ to __region_SRAM1_end__]; + +/* Stack and Heap */ +define symbol __size_cstack__ = 0x400; /* 1KB */ +define symbol __size_heap__ = 0x20000; /* 128KB */ +define block CSTACK with alignment = 8, size = __size_cstack__ { }; +define block HEAP with alignment = 8, size = __size_heap__ { }; +define block STACKHEAP with fixed order { block HEAP, block CSTACK }; + +initialize by copy with packing = zeros { readwrite }; +do not initialize { section .noinit }; + +place at address mem:__intvec_start__ { readonly section .intvec }; + +place in ROM_region { readonly }; +place in SRAM1_region { readwrite, block STACKHEAP }; diff --git a/features/cellular/UNITTESTS/target_h/platform/mbed_retarget.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/cmsis.h similarity index 77% rename from features/cellular/UNITTESTS/target_h/platform/mbed_retarget.h rename to targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/cmsis.h index 796e687292..bf771e5b73 100644 --- a/features/cellular/UNITTESTS/target_h/platform/mbed_retarget.h +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/cmsis.h @@ -1,6 +1,5 @@ -/* - * Copyright (c) , Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 +/* mbed Microcontroller Library + * Copyright (c) 2006-2018 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,7 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef MBED_CMSIS_H +#define MBED_CMSIS_H -#include -#define EAGAIN 11 -#define ENOTTY 25 +#include "stm32l4xx.h" +#include "cmsis_nvic.h" + +#endif diff --git a/features/cellular/UNITTESTS/at/at_cellularinformation/main.cpp b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/cmsis_nvic.h similarity index 57% rename from features/cellular/UNITTESTS/at/at_cellularinformation/main.cpp rename to targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/cmsis_nvic.h index bba3df884f..169022ec9f 100644 --- a/features/cellular/UNITTESTS/at/at_cellularinformation/main.cpp +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/cmsis_nvic.h @@ -1,6 +1,5 @@ -/* - * Copyright (c) 2015, Arm Limited and affiliates. - * SPDX-License-Identifier: Apache-2.0 +/* mbed Microcontroller Library + * Copyright (c) 2006-2018 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,15 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef MBED_CMSIS_NVIC_H +#define MBED_CMSIS_NVIC_H -#include "CppUTest/CommandLineTestRunner.h" -#include "CppUTest/TestPlugin.h" -#include "CppUTest/TestRegistry.h" -#include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char **av) -{ - return CommandLineTestRunner::RunAllTests(ac, av); -} - -IMPORT_TEST_GROUP(AT_CellularInformation); +// CORE: 16 vectors = 64 bytes from 0x00 to 0x3F +// MCU Peripherals: 95 vectors = 380 bytes from 0x40 to 0x1BB +// Total: 111 vectors = 444 bytes (0x1BC) to be reserved in RAM +#define NVIC_NUM_VECTORS 111 +#define NVIC_RAM_VECTOR_ADDRESS 0X20000000 // Vectors positioned at start of SRAM +#endif diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/objects.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/objects.h new file mode 100644 index 0000000000..8eefb96ea1 --- /dev/null +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/objects.h @@ -0,0 +1,53 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2018 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef MBED_OBJECTS_H +#define MBED_OBJECTS_H + +#include "cmsis.h" +#include "PortNames.h" +#include "PeripheralNames.h" +#include "PinNames.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct gpio_irq_s { + IRQn_Type irq_n; + uint32_t irq_index; + uint32_t event; + PinName pin; +}; + +struct port_s { + PortName port; + uint32_t mask; + PinDirection direction; + __IO uint32_t *reg_in; + __IO uint32_t *reg_out; +}; + +struct trng_s { + RNG_HandleTypeDef handle; +}; + +#include "common_objects.h" + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/stm32l4r5xx.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/stm32l4r5xx.h new file mode 100644 index 0000000000..20327ca110 --- /dev/null +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/stm32l4r5xx.h @@ -0,0 +1,20158 @@ +/** + ****************************************************************************** + * @file stm32l4r5xx.h + * @author MCD Application Team + * @brief CMSIS STM32L4R5xx Device Peripheral Access Layer Header File. + * + * This file contains: + * - Data structures and the address mapping for all peripherals + * - Peripheral's registers declarations and bits definition + * - Macros to access peripherals registers hardware + * + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2017 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/** @addtogroup CMSIS_Device + * @{ + */ + +/** @addtogroup stm32l4r5xx + * @{ + */ + +#ifndef __STM32L4R5xx_H +#define __STM32L4R5xx_H + +#ifdef __cplusplus + extern "C" { +#endif /* __cplusplus */ + +/** @addtogroup Configuration_section_for_CMSIS + * @{ + */ + +/** + * @brief Configuration of the Cortex-M4 Processor and Core Peripherals + */ +#define __CM4_REV 0x0001 /*!< Cortex-M4 revision r0p1 */ +#define __MPU_PRESENT 1 /*!< STM32L4XX provides an MPU */ +#define __NVIC_PRIO_BITS 4 /*!< STM32L4XX uses 4 Bits for the Priority Levels */ +#define __Vendor_SysTickConfig 0 /*!< Set to 1 if different SysTick Config is used */ +#define __FPU_PRESENT 1 /*!< FPU present */ + +/** + * @} + */ + +/** @addtogroup Peripheral_interrupt_number_definition + * @{ + */ + +/** + * @brief STM32L4XX Interrupt Number Definition, according to the selected device + * in @ref Library_configuration_section + */ +typedef enum +{ +/****** Cortex-M4 Processor Exceptions Numbers ****************************************************************/ + NonMaskableInt_IRQn = -14, /*!< 2 Cortex-M4 Non Maskable Interrupt */ + HardFault_IRQn = -13, /*!< 3 Cortex-M4 Hard Fault Interrupt */ + MemoryManagement_IRQn = -12, /*!< 4 Cortex-M4 Memory Management Interrupt */ + BusFault_IRQn = -11, /*!< 5 Cortex-M4 Bus Fault Interrupt */ + UsageFault_IRQn = -10, /*!< 6 Cortex-M4 Usage Fault Interrupt */ + SVCall_IRQn = -5, /*!< 11 Cortex-M4 SV Call Interrupt */ + DebugMonitor_IRQn = -4, /*!< 12 Cortex-M4 Debug Monitor Interrupt */ + PendSV_IRQn = -2, /*!< 14 Cortex-M4 Pend SV Interrupt */ + SysTick_IRQn = -1, /*!< 15 Cortex-M4 System Tick Interrupt */ +/****** STM32 specific Interrupt Numbers **********************************************************************/ + WWDG_IRQn = 0, /*!< Window WatchDog Interrupt */ + PVD_PVM_IRQn = 1, /*!< PVD/PVM1/PVM2/PVM3/PVM4 through EXTI Line detection Interrupts */ + TAMP_STAMP_IRQn = 2, /*!< Tamper and TimeStamp interrupts through the EXTI line */ + RTC_WKUP_IRQn = 3, /*!< RTC Wakeup interrupt through the EXTI line */ + FLASH_IRQn = 4, /*!< FLASH global Interrupt */ + RCC_IRQn = 5, /*!< RCC global Interrupt */ + EXTI0_IRQn = 6, /*!< EXTI Line0 Interrupt */ + EXTI1_IRQn = 7, /*!< EXTI Line1 Interrupt */ + EXTI2_IRQn = 8, /*!< EXTI Line2 Interrupt */ + EXTI3_IRQn = 9, /*!< EXTI Line3 Interrupt */ + EXTI4_IRQn = 10, /*!< EXTI Line4 Interrupt */ + DMA1_Channel1_IRQn = 11, /*!< DMA1 Channel 1 global Interrupt */ + DMA1_Channel2_IRQn = 12, /*!< DMA1 Channel 2 global Interrupt */ + DMA1_Channel3_IRQn = 13, /*!< DMA1 Channel 3 global Interrupt */ + DMA1_Channel4_IRQn = 14, /*!< DMA1 Channel 4 global Interrupt */ + DMA1_Channel5_IRQn = 15, /*!< DMA1 Channel 5 global Interrupt */ + DMA1_Channel6_IRQn = 16, /*!< DMA1 Channel 6 global Interrupt */ + DMA1_Channel7_IRQn = 17, /*!< DMA1 Channel 7 global Interrupt */ + ADC1_IRQn = 18, /*!< ADC1 global Interrupt */ + CAN1_TX_IRQn = 19, /*!< CAN1 TX Interrupt */ + CAN1_RX0_IRQn = 20, /*!< CAN1 RX0 Interrupt */ + CAN1_RX1_IRQn = 21, /*!< CAN1 RX1 Interrupt */ + CAN1_SCE_IRQn = 22, /*!< CAN1 SCE Interrupt */ + EXTI9_5_IRQn = 23, /*!< External Line[9:5] Interrupts */ + TIM1_BRK_TIM15_IRQn = 24, /*!< TIM1 Break interrupt and TIM15 global interrupt */ + TIM1_UP_TIM16_IRQn = 25, /*!< TIM1 Update Interrupt and TIM16 global interrupt */ + TIM1_TRG_COM_TIM17_IRQn = 26, /*!< TIM1 Trigger and Commutation Interrupt and TIM17 global interrupt */ + TIM1_CC_IRQn = 27, /*!< TIM1 Capture Compare Interrupt */ + TIM2_IRQn = 28, /*!< TIM2 global Interrupt */ + TIM3_IRQn = 29, /*!< TIM3 global Interrupt */ + TIM4_IRQn = 30, /*!< TIM4 global Interrupt */ + I2C1_EV_IRQn = 31, /*!< I2C1 Event Interrupt */ + I2C1_ER_IRQn = 32, /*!< I2C1 Error Interrupt */ + I2C2_EV_IRQn = 33, /*!< I2C2 Event Interrupt */ + I2C2_ER_IRQn = 34, /*!< I2C2 Error Interrupt */ + SPI1_IRQn = 35, /*!< SPI1 global Interrupt */ + SPI2_IRQn = 36, /*!< SPI2 global Interrupt */ + USART1_IRQn = 37, /*!< USART1 global Interrupt */ + USART2_IRQn = 38, /*!< USART2 global Interrupt */ + USART3_IRQn = 39, /*!< USART3 global Interrupt */ + EXTI15_10_IRQn = 40, /*!< External Line[15:10] Interrupts */ + RTC_Alarm_IRQn = 41, /*!< RTC Alarm (A and B) through EXTI Line Interrupt */ + DFSDM1_FLT3_IRQn = 42, /*!< DFSDM1 Filter 3 global Interrupt */ + TIM8_BRK_IRQn = 43, /*!< TIM8 Break Interrupt */ + TIM8_UP_IRQn = 44, /*!< TIM8 Update Interrupt */ + TIM8_TRG_COM_IRQn = 45, /*!< TIM8 Trigger and Commutation Interrupt */ + TIM8_CC_IRQn = 46, /*!< TIM8 Capture Compare Interrupt */ + FMC_IRQn = 48, /*!< FMC global Interrupt */ + SDMMC1_IRQn = 49, /*!< SDMMC1 global Interrupt */ + TIM5_IRQn = 50, /*!< TIM5 global Interrupt */ + SPI3_IRQn = 51, /*!< SPI3 global Interrupt */ + UART4_IRQn = 52, /*!< UART4 global Interrupt */ + UART5_IRQn = 53, /*!< UART5 global Interrupt */ + TIM6_DAC_IRQn = 54, /*!< TIM6 global and DAC1&2 underrun error interrupts */ + TIM7_IRQn = 55, /*!< TIM7 global interrupt */ + DMA2_Channel1_IRQn = 56, /*!< DMA2 Channel 1 global Interrupt */ + DMA2_Channel2_IRQn = 57, /*!< DMA2 Channel 2 global Interrupt */ + DMA2_Channel3_IRQn = 58, /*!< DMA2 Channel 3 global Interrupt */ + DMA2_Channel4_IRQn = 59, /*!< DMA2 Channel 4 global Interrupt */ + DMA2_Channel5_IRQn = 60, /*!< DMA2 Channel 5 global Interrupt */ + DFSDM1_FLT0_IRQn = 61, /*!< DFSDM1 Filter 0 global Interrupt */ + DFSDM1_FLT1_IRQn = 62, /*!< DFSDM1 Filter 1 global Interrupt */ + DFSDM1_FLT2_IRQn = 63, /*!< DFSDM1 Filter 2 global Interrupt */ + COMP_IRQn = 64, /*!< COMP1 and COMP2 Interrupts */ + LPTIM1_IRQn = 65, /*!< LP TIM1 interrupt */ + LPTIM2_IRQn = 66, /*!< LP TIM2 interrupt */ + OTG_FS_IRQn = 67, /*!< USB OTG FS global Interrupt */ + DMA2_Channel6_IRQn = 68, /*!< DMA2 Channel 6 global interrupt */ + DMA2_Channel7_IRQn = 69, /*!< DMA2 Channel 7 global interrupt */ + LPUART1_IRQn = 70, /*!< LP UART1 interrupt */ + OCTOSPI1_IRQn = 71, /*!< OctoSPI1 global interrupt */ + I2C3_EV_IRQn = 72, /*!< I2C3 event interrupt */ + I2C3_ER_IRQn = 73, /*!< I2C3 error interrupt */ + SAI1_IRQn = 74, /*!< Serial Audio Interface 1 global interrupt */ + SAI2_IRQn = 75, /*!< Serial Audio Interface 2 global interrupt */ + OCTOSPI2_IRQn = 76, /*!< OctoSPI2 global interrupt */ + TSC_IRQn = 77, /*!< Touch Sense Controller global interrupt */ + RNG_IRQn = 80, /*!< RNG global interrupt */ + FPU_IRQn = 81, /*!< FPU global interrupt */ + CRS_IRQn = 82, /*!< CRS global interrupt */ + I2C4_EV_IRQn = 83, /*!< I2C4 Event interrupt */ + I2C4_ER_IRQn = 84, /*!< I2C4 Error interrupt */ + DCMI_IRQn = 85, /*!< DCMI global interrupt */ + DMA2D_IRQn = 90, /*!< DMA2D global interrupt */ + DMAMUX1_OVR_IRQn = 94 /*!< DMAMUX1 overrun global interrupt */ +} IRQn_Type; + +/** + * @} + */ + +#include "core_cm4.h" /* Cortex-M4 processor and core peripherals */ +#include "system_stm32l4xx.h" +#include + +/** @addtogroup Peripheral_registers_structures + * @{ + */ + +/** + * @brief Analog to Digital Converter + */ + +typedef struct +{ + __IO uint32_t ISR; /*!< ADC interrupt and status register, Address offset: 0x00 */ + __IO uint32_t IER; /*!< ADC interrupt enable register, Address offset: 0x04 */ + __IO uint32_t CR; /*!< ADC control register, Address offset: 0x08 */ + __IO uint32_t CFGR; /*!< ADC configuration register 1, Address offset: 0x0C */ + __IO uint32_t CFGR2; /*!< ADC configuration register 2, Address offset: 0x10 */ + __IO uint32_t SMPR1; /*!< ADC sampling time register 1, Address offset: 0x14 */ + __IO uint32_t SMPR2; /*!< ADC sampling time register 2, Address offset: 0x18 */ + uint32_t RESERVED1; /*!< Reserved, 0x1C */ + __IO uint32_t TR1; /*!< ADC analog watchdog 1 threshold register, Address offset: 0x20 */ + __IO uint32_t TR2; /*!< ADC analog watchdog 2 threshold register, Address offset: 0x24 */ + __IO uint32_t TR3; /*!< ADC analog watchdog 3 threshold register, Address offset: 0x28 */ + uint32_t RESERVED2; /*!< Reserved, 0x2C */ + __IO uint32_t SQR1; /*!< ADC group regular sequencer register 1, Address offset: 0x30 */ + __IO uint32_t SQR2; /*!< ADC group regular sequencer register 2, Address offset: 0x34 */ + __IO uint32_t SQR3; /*!< ADC group regular sequencer register 3, Address offset: 0x38 */ + __IO uint32_t SQR4; /*!< ADC group regular sequencer register 4, Address offset: 0x3C */ + __IO uint32_t DR; /*!< ADC group regular data register, Address offset: 0x40 */ + uint32_t RESERVED3; /*!< Reserved, 0x44 */ + uint32_t RESERVED4; /*!< Reserved, 0x48 */ + __IO uint32_t JSQR; /*!< ADC group injected sequencer register, Address offset: 0x4C */ + uint32_t RESERVED5[4]; /*!< Reserved, 0x50 - 0x5C */ + __IO uint32_t OFR1; /*!< ADC offset register 1, Address offset: 0x60 */ + __IO uint32_t OFR2; /*!< ADC offset register 2, Address offset: 0x64 */ + __IO uint32_t OFR3; /*!< ADC offset register 3, Address offset: 0x68 */ + __IO uint32_t OFR4; /*!< ADC offset register 4, Address offset: 0x6C */ + uint32_t RESERVED6[4]; /*!< Reserved, 0x70 - 0x7C */ + __IO uint32_t JDR1; /*!< ADC group injected rank 1 data register, Address offset: 0x80 */ + __IO uint32_t JDR2; /*!< ADC group injected rank 2 data register, Address offset: 0x84 */ + __IO uint32_t JDR3; /*!< ADC group injected rank 3 data register, Address offset: 0x88 */ + __IO uint32_t JDR4; /*!< ADC group injected rank 4 data register, Address offset: 0x8C */ + uint32_t RESERVED7[4]; /*!< Reserved, 0x090 - 0x09C */ + __IO uint32_t AWD2CR; /*!< ADC analog watchdog 1 configuration register, Address offset: 0xA0 */ + __IO uint32_t AWD3CR; /*!< ADC analog watchdog 3 Configuration Register, Address offset: 0xA4 */ + uint32_t RESERVED8; /*!< Reserved, 0x0A8 */ + uint32_t RESERVED9; /*!< Reserved, 0x0AC */ + __IO uint32_t DIFSEL; /*!< ADC differential mode selection register, Address offset: 0xB0 */ + __IO uint32_t CALFACT; /*!< ADC calibration factors, Address offset: 0xB4 */ + +} ADC_TypeDef; + +typedef struct +{ + uint32_t RESERVED1; /*!< Reserved, Address offset: ADC1 base address + 0x300 */ + uint32_t RESERVED2; /*!< Reserved, Address offset: ADC1 base address + 0x304 */ + __IO uint32_t CCR; /*!< ADC common configuration register, Address offset: ADC1 base address + 0x308 */ + uint32_t RESERVED3; /*!< Reserved, Address offset: ADC1 base address + 0x30C */ +} ADC_Common_TypeDef; + +/** + * @brief DCMI + */ + +typedef struct +{ + __IO uint32_t CR; /*!< DCMI control register, Address offset: 0x00 */ + __IO uint32_t SR; /*!< DCMI status register, Address offset: 0x04 */ + __IO uint32_t RISR; /*!< DCMI raw interrupt status register, Address offset: 0x08 */ + __IO uint32_t IER; /*!< DCMI interrupt enable register, Address offset: 0x0C */ + __IO uint32_t MISR; /*!< DCMI masked interrupt status register, Address offset: 0x10 */ + __IO uint32_t ICR; /*!< DCMI interrupt clear register, Address offset: 0x14 */ + __IO uint32_t ESCR; /*!< DCMI embedded synchronization code register, Address offset: 0x18 */ + __IO uint32_t ESUR; /*!< DCMI embedded synchronization unmask register, Address offset: 0x1C */ + __IO uint32_t CWSTRTR; /*!< DCMI crop window start, Address offset: 0x20 */ + __IO uint32_t CWSIZER; /*!< DCMI crop window size, Address offset: 0x24 */ + __IO uint32_t DR; /*!< DCMI data register, Address offset: 0x28 */ +} DCMI_TypeDef; + +/** + * @brief Controller Area Network TxMailBox + */ + +typedef struct +{ + __IO uint32_t TIR; /*!< CAN TX mailbox identifier register */ + __IO uint32_t TDTR; /*!< CAN mailbox data length control and time stamp register */ + __IO uint32_t TDLR; /*!< CAN mailbox data low register */ + __IO uint32_t TDHR; /*!< CAN mailbox data high register */ +} CAN_TxMailBox_TypeDef; + +/** + * @brief Controller Area Network FIFOMailBox + */ + +typedef struct +{ + __IO uint32_t RIR; /*!< CAN receive FIFO mailbox identifier register */ + __IO uint32_t RDTR; /*!< CAN receive FIFO mailbox data length control and time stamp register */ + __IO uint32_t RDLR; /*!< CAN receive FIFO mailbox data low register */ + __IO uint32_t RDHR; /*!< CAN receive FIFO mailbox data high register */ +} CAN_FIFOMailBox_TypeDef; + +/** + * @brief Controller Area Network FilterRegister + */ + +typedef struct +{ + __IO uint32_t FR1; /*!< CAN Filter bank register 1 */ + __IO uint32_t FR2; /*!< CAN Filter bank register 1 */ +} CAN_FilterRegister_TypeDef; + +/** + * @brief Controller Area Network + */ + +typedef struct +{ + __IO uint32_t MCR; /*!< CAN master control register, Address offset: 0x00 */ + __IO uint32_t MSR; /*!< CAN master status register, Address offset: 0x04 */ + __IO uint32_t TSR; /*!< CAN transmit status register, Address offset: 0x08 */ + __IO uint32_t RF0R; /*!< CAN receive FIFO 0 register, Address offset: 0x0C */ + __IO uint32_t RF1R; /*!< CAN receive FIFO 1 register, Address offset: 0x10 */ + __IO uint32_t IER; /*!< CAN interrupt enable register, Address offset: 0x14 */ + __IO uint32_t ESR; /*!< CAN error status register, Address offset: 0x18 */ + __IO uint32_t BTR; /*!< CAN bit timing register, Address offset: 0x1C */ + uint32_t RESERVED0[88]; /*!< Reserved, 0x020 - 0x17F */ + CAN_TxMailBox_TypeDef sTxMailBox[3]; /*!< CAN Tx MailBox, Address offset: 0x180 - 0x1AC */ + CAN_FIFOMailBox_TypeDef sFIFOMailBox[2]; /*!< CAN FIFO MailBox, Address offset: 0x1B0 - 0x1CC */ + uint32_t RESERVED1[12]; /*!< Reserved, 0x1D0 - 0x1FF */ + __IO uint32_t FMR; /*!< CAN filter master register, Address offset: 0x200 */ + __IO uint32_t FM1R; /*!< CAN filter mode register, Address offset: 0x204 */ + uint32_t RESERVED2; /*!< Reserved, 0x208 */ + __IO uint32_t FS1R; /*!< CAN filter scale register, Address offset: 0x20C */ + uint32_t RESERVED3; /*!< Reserved, 0x210 */ + __IO uint32_t FFA1R; /*!< CAN filter FIFO assignment register, Address offset: 0x214 */ + uint32_t RESERVED4; /*!< Reserved, 0x218 */ + __IO uint32_t FA1R; /*!< CAN filter activation register, Address offset: 0x21C */ + uint32_t RESERVED5[8]; /*!< Reserved, 0x220-0x23F */ + CAN_FilterRegister_TypeDef sFilterRegister[28]; /*!< CAN Filter Register, Address offset: 0x240-0x31C */ +} CAN_TypeDef; + + +/** + * @brief Comparator + */ + +typedef struct +{ + __IO uint32_t CSR; /*!< COMP control and status register, Address offset: 0x00 */ +} COMP_TypeDef; + +typedef struct +{ + __IO uint32_t CSR; /*!< COMP control and status register, used for bits common to several COMP instances, Address offset: 0x00 */ +} COMP_Common_TypeDef; + +/** + * @brief CRC calculation unit + */ + +typedef struct +{ + __IO uint32_t DR; /*!< CRC Data register, Address offset: 0x00 */ + __IO uint32_t IDR; /*!< CRC Independent data register, Address offset: 0x04 */ + __IO uint32_t CR; /*!< CRC Control register, Address offset: 0x08 */ + uint32_t RESERVED2; /*!< Reserved, 0x0C */ + __IO uint32_t INIT; /*!< Initial CRC value register, Address offset: 0x10 */ + __IO uint32_t POL; /*!< CRC polynomial register, Address offset: 0x14 */ +} CRC_TypeDef; + +/** + * @brief Clock Recovery System + */ +typedef struct +{ +__IO uint32_t CR; /*!< CRS ccontrol register, Address offset: 0x00 */ +__IO uint32_t CFGR; /*!< CRS configuration register, Address offset: 0x04 */ +__IO uint32_t ISR; /*!< CRS interrupt and status register, Address offset: 0x08 */ +__IO uint32_t ICR; /*!< CRS interrupt flag clear register, Address offset: 0x0C */ +} CRS_TypeDef; + +/** + * @brief Digital to Analog Converter + */ + +typedef struct +{ + __IO uint32_t CR; /*!< DAC control register, Address offset: 0x00 */ + __IO uint32_t SWTRIGR; /*!< DAC software trigger register, Address offset: 0x04 */ + __IO uint32_t DHR12R1; /*!< DAC channel1 12-bit right-aligned data holding register, Address offset: 0x08 */ + __IO uint32_t DHR12L1; /*!< DAC channel1 12-bit left aligned data holding register, Address offset: 0x0C */ + __IO uint32_t DHR8R1; /*!< DAC channel1 8-bit right aligned data holding register, Address offset: 0x10 */ + __IO uint32_t DHR12R2; /*!< DAC channel2 12-bit right aligned data holding register, Address offset: 0x14 */ + __IO uint32_t DHR12L2; /*!< DAC channel2 12-bit left aligned data holding register, Address offset: 0x18 */ + __IO uint32_t DHR8R2; /*!< DAC channel2 8-bit right-aligned data holding register, Address offset: 0x1C */ + __IO uint32_t DHR12RD; /*!< Dual DAC 12-bit right-aligned data holding register, Address offset: 0x20 */ + __IO uint32_t DHR12LD; /*!< DUAL DAC 12-bit left aligned data holding register, Address offset: 0x24 */ + __IO uint32_t DHR8RD; /*!< DUAL DAC 8-bit right aligned data holding register, Address offset: 0x28 */ + __IO uint32_t DOR1; /*!< DAC channel1 data output register, Address offset: 0x2C */ + __IO uint32_t DOR2; /*!< DAC channel2 data output register, Address offset: 0x30 */ + __IO uint32_t SR; /*!< DAC status register, Address offset: 0x34 */ + __IO uint32_t CCR; /*!< DAC calibration control register, Address offset: 0x38 */ + __IO uint32_t MCR; /*!< DAC mode control register, Address offset: 0x3C */ + __IO uint32_t SHSR1; /*!< DAC Sample and Hold sample time register 1, Address offset: 0x40 */ + __IO uint32_t SHSR2; /*!< DAC Sample and Hold sample time register 2, Address offset: 0x44 */ + __IO uint32_t SHHR; /*!< DAC Sample and Hold hold time register, Address offset: 0x48 */ + __IO uint32_t SHRR; /*!< DAC Sample and Hold refresh time register, Address offset: 0x4C */ +} DAC_TypeDef; + +/** + * @brief DFSDM module registers + */ +typedef struct +{ + __IO uint32_t FLTCR1; /*!< DFSDM control register1, Address offset: 0x100 */ + __IO uint32_t FLTCR2; /*!< DFSDM control register2, Address offset: 0x104 */ + __IO uint32_t FLTISR; /*!< DFSDM interrupt and status register, Address offset: 0x108 */ + __IO uint32_t FLTICR; /*!< DFSDM interrupt flag clear register, Address offset: 0x10C */ + __IO uint32_t FLTJCHGR; /*!< DFSDM injected channel group selection register, Address offset: 0x110 */ + __IO uint32_t FLTFCR; /*!< DFSDM filter control register, Address offset: 0x114 */ + __IO uint32_t FLTJDATAR; /*!< DFSDM data register for injected group, Address offset: 0x118 */ + __IO uint32_t FLTRDATAR; /*!< DFSDM data register for regular group, Address offset: 0x11C */ + __IO uint32_t FLTAWHTR; /*!< DFSDM analog watchdog high threshold register, Address offset: 0x120 */ + __IO uint32_t FLTAWLTR; /*!< DFSDM analog watchdog low threshold register, Address offset: 0x124 */ + __IO uint32_t FLTAWSR; /*!< DFSDM analog watchdog status register Address offset: 0x128 */ + __IO uint32_t FLTAWCFR; /*!< DFSDM analog watchdog clear flag register Address offset: 0x12C */ + __IO uint32_t FLTEXMAX; /*!< DFSDM extreme detector maximum register, Address offset: 0x130 */ + __IO uint32_t FLTEXMIN; /*!< DFSDM extreme detector minimum register Address offset: 0x134 */ + __IO uint32_t FLTCNVTIMR; /*!< DFSDM conversion timer, Address offset: 0x138 */ +} DFSDM_Filter_TypeDef; + +/** + * @brief DFSDM channel configuration registers + */ +typedef struct +{ + __IO uint32_t CHCFGR1; /*!< DFSDM channel configuration register1, Address offset: 0x00 */ + __IO uint32_t CHCFGR2; /*!< DFSDM channel configuration register2, Address offset: 0x04 */ + __IO uint32_t CHAWSCDR; /*!< DFSDM channel analog watchdog and + short circuit detector register, Address offset: 0x08 */ + __IO uint32_t CHWDATAR; /*!< DFSDM channel watchdog filter data register, Address offset: 0x0C */ + __IO uint32_t CHDATINR; /*!< DFSDM channel data input register, Address offset: 0x10 */ + __IO uint32_t CHDLYR; /*!< DFSDM channel delay register, Address offset: 0x14 */ +} DFSDM_Channel_TypeDef; + +/** + * @brief Debug MCU + */ + +typedef struct +{ + __IO uint32_t IDCODE; /*!< MCU device ID code, Address offset: 0x00 */ + __IO uint32_t CR; /*!< Debug MCU configuration register, Address offset: 0x04 */ + __IO uint32_t APB1FZR1; /*!< Debug MCU APB1 freeze register 1, Address offset: 0x08 */ + __IO uint32_t APB1FZR2; /*!< Debug MCU APB1 freeze register 2, Address offset: 0x0C */ + __IO uint32_t APB2FZ; /*!< Debug MCU APB2 freeze register, Address offset: 0x10 */ +} DBGMCU_TypeDef; + + +/** + * @brief DMA Controller + */ + +typedef struct +{ + __IO uint32_t CCR; /*!< DMA channel x configuration register */ + __IO uint32_t CNDTR; /*!< DMA channel x number of data register */ + __IO uint32_t CPAR; /*!< DMA channel x peripheral address register */ + __IO uint32_t CMAR; /*!< DMA channel x memory address register */ +} DMA_Channel_TypeDef; + +typedef struct +{ + __IO uint32_t ISR; /*!< DMA interrupt status register, Address offset: 0x00 */ + __IO uint32_t IFCR; /*!< DMA interrupt flag clear register, Address offset: 0x04 */ +} DMA_TypeDef; + +/** + * @brief DMA Multiplexer + */ + +typedef struct +{ + __IO uint32_t CCR; /*!< DMA Multiplexer Channel x Control Register Address offset: 0x0004 * (channel x) */ +}DMAMUX_Channel_TypeDef; + +typedef struct +{ + __IO uint32_t CSR; /*!< DMA Channel Status Register Address offset: 0x0080 */ + __IO uint32_t CFR; /*!< DMA Channel Clear Flag Register Address offset: 0x0084 */ +}DMAMUX_ChannelStatus_TypeDef; + +typedef struct +{ + __IO uint32_t RGCR; /*!< DMA Request Generator x Control Register Address offset: 0x0100 + 0x0004 * (Req Gen x) */ +}DMAMUX_RequestGen_TypeDef; + +typedef struct +{ + __IO uint32_t RGSR; /*!< DMA Request Generator Status Register Address offset: 0x0140 */ + __IO uint32_t RGCFR; /*!< DMA Request Generator Clear Flag Register Address offset: 0x0144 */ +}DMAMUX_RequestGenStatus_TypeDef; + + +/** + * @brief DMA2D Controller + */ + +typedef struct +{ + __IO uint32_t CR; /*!< DMA2D Control Register, Address offset: 0x00 */ + __IO uint32_t ISR; /*!< DMA2D Interrupt Status Register, Address offset: 0x04 */ + __IO uint32_t IFCR; /*!< DMA2D Interrupt Flag Clear Register, Address offset: 0x08 */ + __IO uint32_t FGMAR; /*!< DMA2D Foreground Memory Address Register, Address offset: 0x0C */ + __IO uint32_t FGOR; /*!< DMA2D Foreground Offset Register, Address offset: 0x10 */ + __IO uint32_t BGMAR; /*!< DMA2D Background Memory Address Register, Address offset: 0x14 */ + __IO uint32_t BGOR; /*!< DMA2D Background Offset Register, Address offset: 0x18 */ + __IO uint32_t FGPFCCR; /*!< DMA2D Foreground PFC Control Register, Address offset: 0x1C */ + __IO uint32_t FGCOLR; /*!< DMA2D Foreground Color Register, Address offset: 0x20 */ + __IO uint32_t BGPFCCR; /*!< DMA2D Background PFC Control Register, Address offset: 0x24 */ + __IO uint32_t BGCOLR; /*!< DMA2D Background Color Register, Address offset: 0x28 */ + __IO uint32_t FGCMAR; /*!< DMA2D Foreground CLUT Memory Address Register, Address offset: 0x2C */ + __IO uint32_t BGCMAR; /*!< DMA2D Background CLUT Memory Address Register, Address offset: 0x30 */ + __IO uint32_t OPFCCR; /*!< DMA2D Output PFC Control Register, Address offset: 0x34 */ + __IO uint32_t OCOLR; /*!< DMA2D Output Color Register, Address offset: 0x38 */ + __IO uint32_t OMAR; /*!< DMA2D Output Memory Address Register, Address offset: 0x3C */ + __IO uint32_t OOR; /*!< DMA2D Output Offset Register, Address offset: 0x40 */ + __IO uint32_t NLR; /*!< DMA2D Number of Line Register, Address offset: 0x44 */ + __IO uint32_t LWR; /*!< DMA2D Line Watermark Register, Address offset: 0x48 */ + __IO uint32_t AMTCR; /*!< DMA2D AHB Master Timer Configuration Register, Address offset: 0x4C */ + uint32_t RESERVED[236]; /*!< Reserved, Address offset: 0x50-0x3FF */ + __IO uint32_t FGCLUT[256]; /*!< DMA2D Foreground CLUT, Address offset:0x400-0x7FF */ + __IO uint32_t BGCLUT[256]; /*!< DMA2D Background CLUT, Address offset:0x800-0xBFF */ +} DMA2D_TypeDef; + +/** + * @brief External Interrupt/Event Controller + */ + +typedef struct +{ + __IO uint32_t IMR1; /*!< EXTI Interrupt mask register 1, Address offset: 0x00 */ + __IO uint32_t EMR1; /*!< EXTI Event mask register 1, Address offset: 0x04 */ + __IO uint32_t RTSR1; /*!< EXTI Rising trigger selection register 1, Address offset: 0x08 */ + __IO uint32_t FTSR1; /*!< EXTI Falling trigger selection register 1, Address offset: 0x0C */ + __IO uint32_t SWIER1; /*!< EXTI Software interrupt event register 1, Address offset: 0x10 */ + __IO uint32_t PR1; /*!< EXTI Pending register 1, Address offset: 0x14 */ + uint32_t RESERVED1; /*!< Reserved, 0x18 */ + uint32_t RESERVED2; /*!< Reserved, 0x1C */ + __IO uint32_t IMR2; /*!< EXTI Interrupt mask register 2, Address offset: 0x20 */ + __IO uint32_t EMR2; /*!< EXTI Event mask register 2, Address offset: 0x24 */ + __IO uint32_t RTSR2; /*!< EXTI Rising trigger selection register 2, Address offset: 0x28 */ + __IO uint32_t FTSR2; /*!< EXTI Falling trigger selection register 2, Address offset: 0x2C */ + __IO uint32_t SWIER2; /*!< EXTI Software interrupt event register 2, Address offset: 0x30 */ + __IO uint32_t PR2; /*!< EXTI Pending register 2, Address offset: 0x34 */ +} EXTI_TypeDef; + + +/** + * @brief Firewall + */ + +typedef struct +{ + __IO uint32_t CSSA; /*!< Code Segment Start Address register, Address offset: 0x00 */ + __IO uint32_t CSL; /*!< Code Segment Length register, Address offset: 0x04 */ + __IO uint32_t NVDSSA; /*!< NON volatile data Segment Start Address register, Address offset: 0x08 */ + __IO uint32_t NVDSL; /*!< NON volatile data Segment Length register, Address offset: 0x0C */ + __IO uint32_t VDSSA ; /*!< Volatile data Segment Start Address register, Address offset: 0x10 */ + __IO uint32_t VDSL ; /*!< Volatile data Segment Length register, Address offset: 0x14 */ + uint32_t RESERVED1; /*!< Reserved1, Address offset: 0x18 */ + uint32_t RESERVED2; /*!< Reserved2, Address offset: 0x1C */ + __IO uint32_t CR ; /*!< Configuration register, Address offset: 0x20 */ +} FIREWALL_TypeDef; + + +/** + * @brief FLASH Registers + */ + +typedef struct +{ + __IO uint32_t ACR; /*!< FLASH access control register, Address offset: 0x00 */ + __IO uint32_t PDKEYR; /*!< FLASH power down key register, Address offset: 0x04 */ + __IO uint32_t KEYR; /*!< FLASH key register, Address offset: 0x08 */ + __IO uint32_t OPTKEYR; /*!< FLASH option key register, Address offset: 0x0C */ + __IO uint32_t SR; /*!< FLASH status register, Address offset: 0x10 */ + __IO uint32_t CR; /*!< FLASH control register, Address offset: 0x14 */ + __IO uint32_t ECCR; /*!< FLASH ECC register, Address offset: 0x18 */ + __IO uint32_t RESERVED1; /*!< Reserved1, Address offset: 0x1C */ + __IO uint32_t OPTR; /*!< FLASH option register, Address offset: 0x20 */ + __IO uint32_t PCROP1SR; /*!< FLASH bank1 PCROP start address register, Address offset: 0x24 */ + __IO uint32_t PCROP1ER; /*!< FLASH bank1 PCROP end address register, Address offset: 0x28 */ + __IO uint32_t WRP1AR; /*!< FLASH bank1 WRP area A address register, Address offset: 0x2C */ + __IO uint32_t WRP1BR; /*!< FLASH bank1 WRP area B address register, Address offset: 0x30 */ + uint32_t RESERVED2[4]; /*!< Reserved2, Address offset: 0x34-0x40 */ + __IO uint32_t PCROP2SR; /*!< FLASH bank2 PCROP start address register, Address offset: 0x44 */ + __IO uint32_t PCROP2ER; /*!< FLASH bank2 PCROP end address register, Address offset: 0x48 */ + __IO uint32_t WRP2AR; /*!< FLASH bank2 WRP area A address register, Address offset: 0x4C */ + __IO uint32_t WRP2BR; /*!< FLASH bank2 WRP area B address register, Address offset: 0x50 */ + uint32_t RESERVED3[55]; /*!< Reserved3, Address offset: 0x54-0x12C */ + __IO uint32_t CFGR; /*!< FLASH configuration register, Address offset: 0x130 */ +} FLASH_TypeDef; + + +/** + * @brief Flexible Memory Controller + */ + +typedef struct +{ + __IO uint32_t BTCR[8]; /*!< NOR/PSRAM chip-select control register(BCR) and chip-select timing register(BTR), Address offset: 0x00-1C */ +} FMC_Bank1_TypeDef; + +/** + * @brief Flexible Memory Controller Bank1E + */ + +typedef struct +{ + __IO uint32_t BWTR[7]; /*!< NOR/PSRAM write timing registers, Address offset: 0x104-0x11C */ +} FMC_Bank1E_TypeDef; + +/** + * @brief Flexible Memory Controller Bank3 + */ + +typedef struct +{ + __IO uint32_t PCR; /*!< NAND Flash control register, Address offset: 0x80 */ + __IO uint32_t SR; /*!< NAND Flash FIFO status and interrupt register, Address offset: 0x84 */ + __IO uint32_t PMEM; /*!< NAND Flash Common memory space timing register, Address offset: 0x88 */ + __IO uint32_t PATT; /*!< NAND Flash Attribute memory space timing register, Address offset: 0x8C */ + uint32_t RESERVED0; /*!< Reserved, 0x90 */ + __IO uint32_t ECCR; /*!< NAND Flash ECC result registers, Address offset: 0x94 */ +} FMC_Bank3_TypeDef; + +/** + * @brief General Purpose I/O + */ + +typedef struct +{ + __IO uint32_t MODER; /*!< GPIO port mode register, Address offset: 0x00 */ + __IO uint32_t OTYPER; /*!< GPIO port output type register, Address offset: 0x04 */ + __IO uint32_t OSPEEDR; /*!< GPIO port output speed register, Address offset: 0x08 */ + __IO uint32_t PUPDR; /*!< GPIO port pull-up/pull-down register, Address offset: 0x0C */ + __IO uint32_t IDR; /*!< GPIO port input data register, Address offset: 0x10 */ + __IO uint32_t ODR; /*!< GPIO port output data register, Address offset: 0x14 */ + __IO uint32_t BSRR; /*!< GPIO port bit set/reset register, Address offset: 0x18 */ + __IO uint32_t LCKR; /*!< GPIO port configuration lock register, Address offset: 0x1C */ + __IO uint32_t AFR[2]; /*!< GPIO alternate function registers, Address offset: 0x20-0x24 */ + __IO uint32_t BRR; /*!< GPIO Bit Reset register, Address offset: 0x28 */ + +} GPIO_TypeDef; + + +/** + * @brief Inter-integrated Circuit Interface + */ + +typedef struct +{ + __IO uint32_t CR1; /*!< I2C Control register 1, Address offset: 0x00 */ + __IO uint32_t CR2; /*!< I2C Control register 2, Address offset: 0x04 */ + __IO uint32_t OAR1; /*!< I2C Own address 1 register, Address offset: 0x08 */ + __IO uint32_t OAR2; /*!< I2C Own address 2 register, Address offset: 0x0C */ + __IO uint32_t TIMINGR; /*!< I2C Timing register, Address offset: 0x10 */ + __IO uint32_t TIMEOUTR; /*!< I2C Timeout register, Address offset: 0x14 */ + __IO uint32_t ISR; /*!< I2C Interrupt and status register, Address offset: 0x18 */ + __IO uint32_t ICR; /*!< I2C Interrupt clear register, Address offset: 0x1C */ + __IO uint32_t PECR; /*!< I2C PEC register, Address offset: 0x20 */ + __IO uint32_t RXDR; /*!< I2C Receive data register, Address offset: 0x24 */ + __IO uint32_t TXDR; /*!< I2C Transmit data register, Address offset: 0x28 */ +} I2C_TypeDef; + +/** + * @brief Independent WATCHDOG + */ + +typedef struct +{ + __IO uint32_t KR; /*!< IWDG Key register, Address offset: 0x00 */ + __IO uint32_t PR; /*!< IWDG Prescaler register, Address offset: 0x04 */ + __IO uint32_t RLR; /*!< IWDG Reload register, Address offset: 0x08 */ + __IO uint32_t SR; /*!< IWDG Status register, Address offset: 0x0C */ + __IO uint32_t WINR; /*!< IWDG Window register, Address offset: 0x10 */ +} IWDG_TypeDef; + +/** + * @brief LPTIMER + */ +typedef struct +{ + __IO uint32_t ISR; /*!< LPTIM Interrupt and Status register, Address offset: 0x00 */ + __IO uint32_t ICR; /*!< LPTIM Interrupt Clear register, Address offset: 0x04 */ + __IO uint32_t IER; /*!< LPTIM Interrupt Enable register, Address offset: 0x08 */ + __IO uint32_t CFGR; /*!< LPTIM Configuration register, Address offset: 0x0C */ + __IO uint32_t CR; /*!< LPTIM Control register, Address offset: 0x10 */ + __IO uint32_t CMP; /*!< LPTIM Compare register, Address offset: 0x14 */ + __IO uint32_t ARR; /*!< LPTIM Autoreload register, Address offset: 0x18 */ + __IO uint32_t CNT; /*!< LPTIM Counter register, Address offset: 0x1C */ + __IO uint32_t OR; /*!< LPTIM Option register, Address offset: 0x20 */ +} LPTIM_TypeDef; + +/** + * @brief Operational Amplifier (OPAMP) + */ + +typedef struct +{ + __IO uint32_t CSR; /*!< OPAMP control/status register, Address offset: 0x00 */ + __IO uint32_t OTR; /*!< OPAMP offset trimming register for normal mode, Address offset: 0x04 */ + __IO uint32_t LPOTR; /*!< OPAMP offset trimming register for low power mode, Address offset: 0x08 */ +} OPAMP_TypeDef; + +typedef struct +{ + __IO uint32_t CSR; /*!< OPAMP control/status register, used for bits common to several OPAMP instances, Address offset: 0x00 */ +} OPAMP_Common_TypeDef; + +/** + * @brief Power Control + */ + +typedef struct +{ + __IO uint32_t CR1; /*!< PWR power control register 1, Address offset: 0x00 */ + __IO uint32_t CR2; /*!< PWR power control register 2, Address offset: 0x04 */ + __IO uint32_t CR3; /*!< PWR power control register 3, Address offset: 0x08 */ + __IO uint32_t CR4; /*!< PWR power control register 4, Address offset: 0x0C */ + __IO uint32_t SR1; /*!< PWR power status register 1, Address offset: 0x10 */ + __IO uint32_t SR2; /*!< PWR power status register 2, Address offset: 0x14 */ + __IO uint32_t SCR; /*!< PWR power status reset register, Address offset: 0x18 */ + uint32_t RESERVED; /*!< Reserved, Address offset: 0x1C */ + __IO uint32_t PUCRA; /*!< Pull_up control register of portA, Address offset: 0x20 */ + __IO uint32_t PDCRA; /*!< Pull_Down control register of portA, Address offset: 0x24 */ + __IO uint32_t PUCRB; /*!< Pull_up control register of portB, Address offset: 0x28 */ + __IO uint32_t PDCRB; /*!< Pull_Down control register of portB, Address offset: 0x2C */ + __IO uint32_t PUCRC; /*!< Pull_up control register of portC, Address offset: 0x30 */ + __IO uint32_t PDCRC; /*!< Pull_Down control register of portC, Address offset: 0x34 */ + __IO uint32_t PUCRD; /*!< Pull_up control register of portD, Address offset: 0x38 */ + __IO uint32_t PDCRD; /*!< Pull_Down control register of portD, Address offset: 0x3C */ + __IO uint32_t PUCRE; /*!< Pull_up control register of portE, Address offset: 0x40 */ + __IO uint32_t PDCRE; /*!< Pull_Down control register of portE, Address offset: 0x44 */ + __IO uint32_t PUCRF; /*!< Pull_up control register of portF, Address offset: 0x48 */ + __IO uint32_t PDCRF; /*!< Pull_Down control register of portF, Address offset: 0x4C */ + __IO uint32_t PUCRG; /*!< Pull_up control register of portG, Address offset: 0x50 */ + __IO uint32_t PDCRG; /*!< Pull_Down control register of portG, Address offset: 0x54 */ + __IO uint32_t PUCRH; /*!< Pull_up control register of portH, Address offset: 0x58 */ + __IO uint32_t PDCRH; /*!< Pull_Down control register of portH, Address offset: 0x5C */ + __IO uint32_t PUCRI; /*!< Pull_up control register of portI, Address offset: 0x60 */ + __IO uint32_t PDCRI; /*!< Pull_Down control register of portI, Address offset: 0x64 */ + uint32_t RESERVED1[6]; /*!< Reserved, Address offset: 0x68-0x7C */ + __IO uint32_t CR5; /*!< PWR power control register 5, Address offset: 0x80 */ +} PWR_TypeDef; + + +/** + * @brief OCTO Serial Peripheral Interface + */ + +typedef struct +{ + __IO uint32_t CR; /*!< OCTOSPI Control register, Address offset: 0x000 */ + uint32_t RESERVED; /*!< Reserved, Address offset: 0x004 */ + __IO uint32_t DCR1; /*!< OCTOSPI Device Configuration register 1, Address offset: 0x008 */ + __IO uint32_t DCR2; /*!< OCTOSPI Device Configuration register 2, Address offset: 0x00C */ + __IO uint32_t DCR3; /*!< OCTOSPI Device Configuration register 3, Address offset: 0x010 */ + uint32_t RESERVED1[3]; /*!< Reserved, Address offset: 0x014-0x01C */ + __IO uint32_t SR; /*!< OCTOSPI Status register, Address offset: 0x020 */ + __IO uint32_t FCR; /*!< OCTOSPI Flag Clear register, Address offset: 0x024 */ + uint32_t RESERVED2[6]; /*!< Reserved, Address offset: 0x028-0x03C */ + __IO uint32_t DLR; /*!< OCTOSPI Data Length register, Address offset: 0x040 */ + uint32_t RESERVED3; /*!< Reserved, Address offset: 0x044 */ + __IO uint32_t AR; /*!< OCTOSPI Address register, Address offset: 0x048 */ + uint32_t RESERVED4; /*!< Reserved, Address offset: 0x04C */ + __IO uint32_t DR; /*!< OCTOPSI Data register, Address offset: 0x050 */ + uint32_t RESERVED5[11]; /*!< Reserved, Address offset: 0x054-0x07C */ + __IO uint32_t PSMKR; /*!< OCTOSPI Polling Status Mask register, Address offset: 0x080 */ + uint32_t RESERVED6; /*!< Reserved, Address offset: 0x084 */ + __IO uint32_t PSMAR; /*!< OCTOSPI Polling Status Match register, Address offset: 0x088 */ + uint32_t RESERVED7; /*!< Reserved, Address offset: 0x08C */ + __IO uint32_t PIR; /*!< OCTOSPI Polling Interval register, Address offset: 0x090 */ + uint32_t RESERVED8[27]; /*!< Reserved, Address offset: 0x094-0x0FC */ + __IO uint32_t CCR; /*!< OCTOSPI Communication Configuration register, Address offset: 0x100 */ + uint32_t RESERVED9; /*!< Reserved, Address offset: 0x104 */ + __IO uint32_t TCR; /*!< OCTOSPI Timing Configuration register, Address offset: 0x108 */ + uint32_t RESERVED10; /*!< Reserved, Address offset: 0x10C */ + __IO uint32_t IR; /*!< OCTOSPI Instruction register, Address offset: 0x110 */ + uint32_t RESERVED11[3]; /*!< Reserved, Address offset: 0x114-0x11C */ + __IO uint32_t ABR; /*!< OCTOSPI Alternate Bytes register, Address offset: 0x120 */ + uint32_t RESERVED12[3]; /*!< Reserved, Address offset: 0x124-0x12C */ + __IO uint32_t LPTR; /*!< OCTOSPI Low Power Timeout register, Address offset: 0x130 */ + uint32_t RESERVED13[19]; /*!< Reserved, Address offset: 0x134-0x17C */ + __IO uint32_t WCCR; /*!< OCTOSPI Write Communication Configuration register, Address offset: 0x180 */ + uint32_t RESERVED14; /*!< Reserved, Address offset: 0x184 */ + __IO uint32_t WTCR; /*!< OCTOSPI Write Timing Configuration register, Address offset: 0x188 */ + uint32_t RESERVED15; /*!< Reserved, Address offset: 0x18C */ + __IO uint32_t WIR; /*!< OCTOSPI Write Instruction register, Address offset: 0x190 */ + uint32_t RESERVED16[3]; /*!< Reserved, Address offset: 0x194-0x19C */ + __IO uint32_t WABR; /*!< OCTOSPI Write Alternate Bytes register, Address offset: 0x1A0 */ + uint32_t RESERVED17[23]; /*!< Reserved, Address offset: 0x1A4-0x1FC */ + __IO uint32_t HLCR; /*!< OCTOSPI Hyperbus Latency Configuration register, Address offset: 0x200 */ +} OCTOSPI_TypeDef; + +/** + * @brief OCTO Serial Peripheral Interface IO Manager + */ + +typedef struct +{ + uint32_t RESERVED; /*!< Reserved, Address offset: 0x00 */ + __IO uint32_t PCR[2]; /*!< OCTOSPI IO Manager Port[1:2] Configuration register, Address offset: 0x04-0x08 */ +} OCTOSPIM_TypeDef; + +/** + * @brief Reset and Clock Control + */ + +typedef struct +{ + __IO uint32_t CR; /*!< RCC clock control register, Address offset: 0x00 */ + __IO uint32_t ICSCR; /*!< RCC internal clock sources calibration register, Address offset: 0x04 */ + __IO uint32_t CFGR; /*!< RCC clock configuration register, Address offset: 0x08 */ + __IO uint32_t PLLCFGR; /*!< RCC system PLL configuration register, Address offset: 0x0C */ + __IO uint32_t PLLSAI1CFGR; /*!< RCC PLL SAI1 configuration register, Address offset: 0x10 */ + __IO uint32_t PLLSAI2CFGR; /*!< RCC PLL SAI2 configuration register, Address offset: 0x14 */ + __IO uint32_t CIER; /*!< RCC clock interrupt enable register, Address offset: 0x18 */ + __IO uint32_t CIFR; /*!< RCC clock interrupt flag register, Address offset: 0x1C */ + __IO uint32_t CICR; /*!< RCC clock interrupt clear register, Address offset: 0x20 */ + uint32_t RESERVED0; /*!< Reserved, Address offset: 0x24 */ + __IO uint32_t AHB1RSTR; /*!< RCC AHB1 peripheral reset register, Address offset: 0x28 */ + __IO uint32_t AHB2RSTR; /*!< RCC AHB2 peripheral reset register, Address offset: 0x2C */ + __IO uint32_t AHB3RSTR; /*!< RCC AHB3 peripheral reset register, Address offset: 0x30 */ + uint32_t RESERVED1; /*!< Reserved, Address offset: 0x34 */ + __IO uint32_t APB1RSTR1; /*!< RCC APB1 peripheral reset register 1, Address offset: 0x38 */ + __IO uint32_t APB1RSTR2; /*!< RCC APB1 peripheral reset register 2, Address offset: 0x3C */ + __IO uint32_t APB2RSTR; /*!< RCC APB2 peripheral reset register, Address offset: 0x40 */ + uint32_t RESERVED2; /*!< Reserved, Address offset: 0x44 */ + __IO uint32_t AHB1ENR; /*!< RCC AHB1 peripheral clocks enable register, Address offset: 0x48 */ + __IO uint32_t AHB2ENR; /*!< RCC AHB2 peripheral clocks enable register, Address offset: 0x4C */ + __IO uint32_t AHB3ENR; /*!< RCC AHB3 peripheral clocks enable register, Address offset: 0x50 */ + uint32_t RESERVED3; /*!< Reserved, Address offset: 0x54 */ + __IO uint32_t APB1ENR1; /*!< RCC APB1 peripheral clocks enable register 1, Address offset: 0x58 */ + __IO uint32_t APB1ENR2; /*!< RCC APB1 peripheral clocks enable register 2, Address offset: 0x5C */ + __IO uint32_t APB2ENR; /*!< RCC APB2 peripheral clocks enable register, Address offset: 0x60 */ + uint32_t RESERVED4; /*!< Reserved, Address offset: 0x64 */ + __IO uint32_t AHB1SMENR; /*!< RCC AHB1 peripheral clocks enable in sleep and stop modes register, Address offset: 0x68 */ + __IO uint32_t AHB2SMENR; /*!< RCC AHB2 peripheral clocks enable in sleep and stop modes register, Address offset: 0x6C */ + __IO uint32_t AHB3SMENR; /*!< RCC AHB3 peripheral clocks enable in sleep and stop modes register, Address offset: 0x70 */ + uint32_t RESERVED5; /*!< Reserved, Address offset: 0x74 */ + __IO uint32_t APB1SMENR1; /*!< RCC APB1 peripheral clocks enable in sleep mode and stop modes register 1, Address offset: 0x78 */ + __IO uint32_t APB1SMENR2; /*!< RCC APB1 peripheral clocks enable in sleep mode and stop modes register 2, Address offset: 0x7C */ + __IO uint32_t APB2SMENR; /*!< RCC APB2 peripheral clocks enable in sleep mode and stop modes register, Address offset: 0x80 */ + uint32_t RESERVED6; /*!< Reserved, Address offset: 0x84 */ + __IO uint32_t CCIPR; /*!< RCC peripherals independent clock configuration register, Address offset: 0x88 */ + uint32_t RESERVED7; /*!< Reserved, Address offset: 0x8C */ + __IO uint32_t BDCR; /*!< RCC backup domain control register, Address offset: 0x90 */ + __IO uint32_t CSR; /*!< RCC clock control & status register, Address offset: 0x94 */ + __IO uint32_t CRRCR; /*!< RCC clock recovery RC register, Address offset: 0x98 */ + __IO uint32_t CCIPR2; /*!< RCC peripherals independent clock configuration register 2, Address offset: 0x9C */ +} RCC_TypeDef; + +/** + * @brief Real-Time Clock + */ + +typedef struct +{ + __IO uint32_t TR; /*!< RTC time register, Address offset: 0x00 */ + __IO uint32_t DR; /*!< RTC date register, Address offset: 0x04 */ + __IO uint32_t CR; /*!< RTC control register, Address offset: 0x08 */ + __IO uint32_t ISR; /*!< RTC initialization and status register, Address offset: 0x0C */ + __IO uint32_t PRER; /*!< RTC prescaler register, Address offset: 0x10 */ + __IO uint32_t WUTR; /*!< RTC wakeup timer register, Address offset: 0x14 */ + uint32_t reserved; /*!< Reserved */ + __IO uint32_t ALRMAR; /*!< RTC alarm A register, Address offset: 0x1C */ + __IO uint32_t ALRMBR; /*!< RTC alarm B register, Address offset: 0x20 */ + __IO uint32_t WPR; /*!< RTC write protection register, Address offset: 0x24 */ + __IO uint32_t SSR; /*!< RTC sub second register, Address offset: 0x28 */ + __IO uint32_t SHIFTR; /*!< RTC shift control register, Address offset: 0x2C */ + __IO uint32_t TSTR; /*!< RTC time stamp time register, Address offset: 0x30 */ + __IO uint32_t TSDR; /*!< RTC time stamp date register, Address offset: 0x34 */ + __IO uint32_t TSSSR; /*!< RTC time-stamp sub second register, Address offset: 0x38 */ + __IO uint32_t CALR; /*!< RTC calibration register, Address offset: 0x3C */ + __IO uint32_t TAMPCR; /*!< RTC tamper configuration register, Address offset: 0x40 */ + __IO uint32_t ALRMASSR; /*!< RTC alarm A sub second register, Address offset: 0x44 */ + __IO uint32_t ALRMBSSR; /*!< RTC alarm B sub second register, Address offset: 0x48 */ + __IO uint32_t OR; /*!< RTC option register, Address offset: 0x4C */ + __IO uint32_t BKP0R; /*!< RTC backup register 0, Address offset: 0x50 */ + __IO uint32_t BKP1R; /*!< RTC backup register 1, Address offset: 0x54 */ + __IO uint32_t BKP2R; /*!< RTC backup register 2, Address offset: 0x58 */ + __IO uint32_t BKP3R; /*!< RTC backup register 3, Address offset: 0x5C */ + __IO uint32_t BKP4R; /*!< RTC backup register 4, Address offset: 0x60 */ + __IO uint32_t BKP5R; /*!< RTC backup register 5, Address offset: 0x64 */ + __IO uint32_t BKP6R; /*!< RTC backup register 6, Address offset: 0x68 */ + __IO uint32_t BKP7R; /*!< RTC backup register 7, Address offset: 0x6C */ + __IO uint32_t BKP8R; /*!< RTC backup register 8, Address offset: 0x70 */ + __IO uint32_t BKP9R; /*!< RTC backup register 9, Address offset: 0x74 */ + __IO uint32_t BKP10R; /*!< RTC backup register 10, Address offset: 0x78 */ + __IO uint32_t BKP11R; /*!< RTC backup register 11, Address offset: 0x7C */ + __IO uint32_t BKP12R; /*!< RTC backup register 12, Address offset: 0x80 */ + __IO uint32_t BKP13R; /*!< RTC backup register 13, Address offset: 0x84 */ + __IO uint32_t BKP14R; /*!< RTC backup register 14, Address offset: 0x88 */ + __IO uint32_t BKP15R; /*!< RTC backup register 15, Address offset: 0x8C */ + __IO uint32_t BKP16R; /*!< RTC backup register 16, Address offset: 0x90 */ + __IO uint32_t BKP17R; /*!< RTC backup register 17, Address offset: 0x94 */ + __IO uint32_t BKP18R; /*!< RTC backup register 18, Address offset: 0x98 */ + __IO uint32_t BKP19R; /*!< RTC backup register 19, Address offset: 0x9C */ + __IO uint32_t BKP20R; /*!< RTC backup register 20, Address offset: 0xA0 */ + __IO uint32_t BKP21R; /*!< RTC backup register 21, Address offset: 0xA4 */ + __IO uint32_t BKP22R; /*!< RTC backup register 22, Address offset: 0xA8 */ + __IO uint32_t BKP23R; /*!< RTC backup register 23, Address offset: 0xAC */ + __IO uint32_t BKP24R; /*!< RTC backup register 24, Address offset: 0xB0 */ + __IO uint32_t BKP25R; /*!< RTC backup register 25, Address offset: 0xB4 */ + __IO uint32_t BKP26R; /*!< RTC backup register 26, Address offset: 0xB8 */ + __IO uint32_t BKP27R; /*!< RTC backup register 27, Address offset: 0xBC */ + __IO uint32_t BKP28R; /*!< RTC backup register 28, Address offset: 0xC0 */ + __IO uint32_t BKP29R; /*!< RTC backup register 29, Address offset: 0xC4 */ + __IO uint32_t BKP30R; /*!< RTC backup register 30, Address offset: 0xC8 */ + __IO uint32_t BKP31R; /*!< RTC backup register 31, Address offset: 0xCC */ +} RTC_TypeDef; + + +/** + * @brief Serial Audio Interface + */ + +typedef struct +{ + __IO uint32_t GCR; /*!< SAI global configuration register, Address offset: 0x00 */ + uint32_t RESERVED[16]; /*!< Reserved, Address offset: 0x04 to 0x40 */ + __IO uint32_t PDMCR; /*!< SAI PDM control register, Address offset: 0x44 */ + __IO uint32_t PDMDLY; /*!< SAI PDM delay register, Address offset: 0x48 */ +} SAI_TypeDef; + +typedef struct +{ + __IO uint32_t CR1; /*!< SAI block x configuration register 1, Address offset: 0x04 */ + __IO uint32_t CR2; /*!< SAI block x configuration register 2, Address offset: 0x08 */ + __IO uint32_t FRCR; /*!< SAI block x frame configuration register, Address offset: 0x0C */ + __IO uint32_t SLOTR; /*!< SAI block x slot register, Address offset: 0x10 */ + __IO uint32_t IMR; /*!< SAI block x interrupt mask register, Address offset: 0x14 */ + __IO uint32_t SR; /*!< SAI block x status register, Address offset: 0x18 */ + __IO uint32_t CLRFR; /*!< SAI block x clear flag register, Address offset: 0x1C */ + __IO uint32_t DR; /*!< SAI block x data register, Address offset: 0x20 */ +} SAI_Block_TypeDef; + + +/** + * @brief Secure digital input/output Interface + */ + +typedef struct +{ + __IO uint32_t POWER; /*!< SDMMC power control register, Address offset: 0x00 */ + __IO uint32_t CLKCR; /*!< SDMMC clock control register, Address offset: 0x04 */ + __IO uint32_t ARG; /*!< SDMMC argument register, Address offset: 0x08 */ + __IO uint32_t CMD; /*!< SDMMC command register, Address offset: 0x0C */ + __I uint32_t RESPCMD; /*!< SDMMC command response register, Address offset: 0x10 */ + __I uint32_t RESP1; /*!< SDMMC response 1 register, Address offset: 0x14 */ + __I uint32_t RESP2; /*!< SDMMC response 2 register, Address offset: 0x18 */ + __I uint32_t RESP3; /*!< SDMMC response 3 register, Address offset: 0x1C */ + __I uint32_t RESP4; /*!< SDMMC response 4 register, Address offset: 0x20 */ + __IO uint32_t DTIMER; /*!< SDMMC data timer register, Address offset: 0x24 */ + __IO uint32_t DLEN; /*!< SDMMC data length register, Address offset: 0x28 */ + __IO uint32_t DCTRL; /*!< SDMMC data control register, Address offset: 0x2C */ + __I uint32_t DCOUNT; /*!< SDMMC data counter register, Address offset: 0x30 */ + __I uint32_t STA; /*!< SDMMC status register, Address offset: 0x34 */ + __IO uint32_t ICR; /*!< SDMMC interrupt clear register, Address offset: 0x38 */ + __IO uint32_t MASK; /*!< SDMMC mask register, Address offset: 0x3C */ + __IO uint32_t ACKTIME; /*!< SDMMC Acknowledgement timer register, Address offset: 0x40 */ + uint32_t RESERVED0[3]; /*!< Reserved, 0x44 - 0x4C - 0x4C */ + __IO uint32_t IDMACTRL; /*!< SDMMC DMA control register, Address offset: 0x50 */ + __IO uint32_t IDMABSIZE; /*!< SDMMC DMA buffer size register, Address offset: 0x54 */ + __IO uint32_t IDMABASE0; /*!< SDMMC DMA buffer 0 base address register, Address offset: 0x58 */ + __IO uint32_t IDMABASE1; /*!< SDMMC DMA buffer 1 base address register, Address offset: 0x5C */ + uint32_t RESERVED1[8]; /*!< Reserved, 0x60-0x7C */ + __IO uint32_t FIFO; /*!< SDMMC data FIFO register, Address offset: 0x80 */ +} SDMMC_TypeDef; +/** + * @brief Serial Peripheral Interface + */ + +typedef struct +{ + __IO uint32_t CR1; /*!< SPI Control register 1, Address offset: 0x00 */ + __IO uint32_t CR2; /*!< SPI Control register 2, Address offset: 0x04 */ + __IO uint32_t SR; /*!< SPI Status register, Address offset: 0x08 */ + __IO uint32_t DR; /*!< SPI data register, Address offset: 0x0C */ + __IO uint32_t CRCPR; /*!< SPI CRC polynomial register, Address offset: 0x10 */ + __IO uint32_t RXCRCR; /*!< SPI Rx CRC register, Address offset: 0x14 */ + __IO uint32_t TXCRCR; /*!< SPI Tx CRC register, Address offset: 0x18 */ +} SPI_TypeDef; + + +/** + * @brief System configuration controller + */ + +typedef struct +{ + __IO uint32_t MEMRMP; /*!< SYSCFG memory remap register, Address offset: 0x00 */ + __IO uint32_t CFGR1; /*!< SYSCFG configuration register 1, Address offset: 0x04 */ + __IO uint32_t EXTICR[4]; /*!< SYSCFG external interrupt configuration registers, Address offset: 0x08-0x14 */ + __IO uint32_t SCSR; /*!< SYSCFG SRAM2 control and status register, Address offset: 0x18 */ + __IO uint32_t CFGR2; /*!< SYSCFG configuration register 2, Address offset: 0x1C */ + __IO uint32_t SWPR; /*!< SYSCFG SRAM2 write protection register, Address offset: 0x20 */ + __IO uint32_t SKR; /*!< SYSCFG SRAM2 key register, Address offset: 0x24 */ + __IO uint32_t SWPR2; /*!< SYSCFG SRAM2 write protection register 2, Address offset: 0x28 */ +} SYSCFG_TypeDef; + + +/** + * @brief TIM + */ + +typedef struct +{ + __IO uint32_t CR1; /*!< TIM control register 1, Address offset: 0x00 */ + __IO uint32_t CR2; /*!< TIM control register 2, Address offset: 0x04 */ + __IO uint32_t SMCR; /*!< TIM slave mode control register, Address offset: 0x08 */ + __IO uint32_t DIER; /*!< TIM DMA/interrupt enable register, Address offset: 0x0C */ + __IO uint32_t SR; /*!< TIM status register, Address offset: 0x10 */ + __IO uint32_t EGR; /*!< TIM event generation register, Address offset: 0x14 */ + __IO uint32_t CCMR1; /*!< TIM capture/compare mode register 1, Address offset: 0x18 */ + __IO uint32_t CCMR2; /*!< TIM capture/compare mode register 2, Address offset: 0x1C */ + __IO uint32_t CCER; /*!< TIM capture/compare enable register, Address offset: 0x20 */ + __IO uint32_t CNT; /*!< TIM counter register, Address offset: 0x24 */ + __IO uint32_t PSC; /*!< TIM prescaler, Address offset: 0x28 */ + __IO uint32_t ARR; /*!< TIM auto-reload register, Address offset: 0x2C */ + __IO uint32_t RCR; /*!< TIM repetition counter register, Address offset: 0x30 */ + __IO uint32_t CCR1; /*!< TIM capture/compare register 1, Address offset: 0x34 */ + __IO uint32_t CCR2; /*!< TIM capture/compare register 2, Address offset: 0x38 */ + __IO uint32_t CCR3; /*!< TIM capture/compare register 3, Address offset: 0x3C */ + __IO uint32_t CCR4; /*!< TIM capture/compare register 4, Address offset: 0x40 */ + __IO uint32_t BDTR; /*!< TIM break and dead-time register, Address offset: 0x44 */ + __IO uint32_t DCR; /*!< TIM DMA control register, Address offset: 0x48 */ + __IO uint32_t DMAR; /*!< TIM DMA address for full transfer, Address offset: 0x4C */ + __IO uint32_t OR1; /*!< TIM option register 1, Address offset: 0x50 */ + __IO uint32_t CCMR3; /*!< TIM capture/compare mode register 3, Address offset: 0x54 */ + __IO uint32_t CCR5; /*!< TIM capture/compare register5, Address offset: 0x58 */ + __IO uint32_t CCR6; /*!< TIM capture/compare register6, Address offset: 0x5C */ + __IO uint32_t OR2; /*!< TIM option register 2, Address offset: 0x60 */ + __IO uint32_t OR3; /*!< TIM option register 3, Address offset: 0x64 */ +} TIM_TypeDef; + + +/** + * @brief Touch Sensing Controller (TSC) + */ + +typedef struct +{ + __IO uint32_t CR; /*!< TSC control register, Address offset: 0x00 */ + __IO uint32_t IER; /*!< TSC interrupt enable register, Address offset: 0x04 */ + __IO uint32_t ICR; /*!< TSC interrupt clear register, Address offset: 0x08 */ + __IO uint32_t ISR; /*!< TSC interrupt status register, Address offset: 0x0C */ + __IO uint32_t IOHCR; /*!< TSC I/O hysteresis control register, Address offset: 0x10 */ + uint32_t RESERVED1; /*!< Reserved, Address offset: 0x14 */ + __IO uint32_t IOASCR; /*!< TSC I/O analog switch control register, Address offset: 0x18 */ + uint32_t RESERVED2; /*!< Reserved, Address offset: 0x1C */ + __IO uint32_t IOSCR; /*!< TSC I/O sampling control register, Address offset: 0x20 */ + uint32_t RESERVED3; /*!< Reserved, Address offset: 0x24 */ + __IO uint32_t IOCCR; /*!< TSC I/O channel control register, Address offset: 0x28 */ + uint32_t RESERVED4; /*!< Reserved, Address offset: 0x2C */ + __IO uint32_t IOGCSR; /*!< TSC I/O group control status register, Address offset: 0x30 */ + __IO uint32_t IOGXCR[8]; /*!< TSC I/O group x counter register, Address offset: 0x34-50 */ +} TSC_TypeDef; + +/** + * @brief Universal Synchronous Asynchronous Receiver Transmitter + */ + +typedef struct +{ + __IO uint32_t CR1; /*!< USART Control register 1, Address offset: 0x00 */ + __IO uint32_t CR2; /*!< USART Control register 2, Address offset: 0x04 */ + __IO uint32_t CR3; /*!< USART Control register 3, Address offset: 0x08 */ + __IO uint32_t BRR; /*!< USART Baud rate register, Address offset: 0x0C */ + __IO uint16_t GTPR; /*!< USART Guard time and prescaler register, Address offset: 0x10 */ + uint16_t RESERVED2; /*!< Reserved, 0x12 */ + __IO uint32_t RTOR; /*!< USART Receiver Time Out register, Address offset: 0x14 */ + __IO uint16_t RQR; /*!< USART Request register, Address offset: 0x18 */ + uint16_t RESERVED3; /*!< Reserved, 0x1A */ + __IO uint32_t ISR; /*!< USART Interrupt and status register, Address offset: 0x1C */ + __IO uint32_t ICR; /*!< USART Interrupt flag Clear register, Address offset: 0x20 */ + __IO uint16_t RDR; /*!< USART Receive Data register, Address offset: 0x24 */ + uint16_t RESERVED4; /*!< Reserved, 0x26 */ + __IO uint16_t TDR; /*!< USART Transmit Data register, Address offset: 0x28 */ + uint16_t RESERVED5; /*!< Reserved, 0x2A */ + __IO uint32_t PRESC; /*!< USART Prescaler register, Address offset: 0x2C */ +} USART_TypeDef; + +/** + * @brief VREFBUF + */ + +typedef struct +{ + __IO uint32_t CSR; /*!< VREFBUF control and status register, Address offset: 0x00 */ + __IO uint32_t CCR; /*!< VREFBUF calibration and control register, Address offset: 0x04 */ +} VREFBUF_TypeDef; + +/** + * @brief Window WATCHDOG + */ + +typedef struct +{ + __IO uint32_t CR; /*!< WWDG Control register, Address offset: 0x00 */ + __IO uint32_t CFR; /*!< WWDG Configuration register, Address offset: 0x04 */ + __IO uint32_t SR; /*!< WWDG Status register, Address offset: 0x08 */ +} WWDG_TypeDef; + +/** + * @brief RNG + */ + +typedef struct +{ + __IO uint32_t CR; /*!< RNG control register, Address offset: 0x00 */ + __IO uint32_t SR; /*!< RNG status register, Address offset: 0x04 */ + __IO uint32_t DR; /*!< RNG data register, Address offset: 0x08 */ +} RNG_TypeDef; + +/** + * @brief USB_OTG_Core_register + */ +typedef struct +{ + __IO uint32_t GOTGCTL; /*!< USB_OTG Control and Status Register 000h*/ + __IO uint32_t GOTGINT; /*!< USB_OTG Interrupt Register 004h*/ + __IO uint32_t GAHBCFG; /*!< Core AHB Configuration Register 008h*/ + __IO uint32_t GUSBCFG; /*!< Core USB Configuration Register 00Ch*/ + __IO uint32_t GRSTCTL; /*!< Core Reset Register 010h*/ + __IO uint32_t GINTSTS; /*!< Core Interrupt Register 014h*/ + __IO uint32_t GINTMSK; /*!< Core Interrupt Mask Register 018h*/ + __IO uint32_t GRXSTSR; /*!< Receive Sts Q Read Register 01Ch*/ + __IO uint32_t GRXSTSP; /*!< Receive Sts Q Read & POP Register 020h*/ + __IO uint32_t GRXFSIZ; /* Receive FIFO Size Register 024h*/ + __IO uint32_t DIEPTXF0_HNPTXFSIZ; /*!< EP0 / Non Periodic Tx FIFO Size Register 028h*/ + __IO uint32_t HNPTXSTS; /*!< Non Periodic Tx FIFO/Queue Sts reg 02Ch*/ + uint32_t Reserved30[2]; /* Reserved 030h*/ + __IO uint32_t GCCFG; /* General Purpose IO Register 038h*/ + __IO uint32_t CID; /* User ID Register 03Ch*/ + __IO uint32_t GSNPSID; /* USB_OTG core ID 040h*/ + __IO uint32_t GHWCFG1; /* User HW config1 044h*/ + __IO uint32_t GHWCFG2; /* User HW config2 048h*/ + __IO uint32_t GHWCFG3; /* User HW config3 04Ch*/ + uint32_t Reserved6; /* Reserved 050h*/ + __IO uint32_t GLPMCFG; /* LPM Register 054h*/ + __IO uint32_t GPWRDN; /* Power Down Register 058h*/ + __IO uint32_t GDFIFOCFG; /* DFIFO Software Config Register 05Ch*/ + __IO uint32_t GADPCTL; /* ADP Timer, Control and Status Register 60Ch*/ + uint32_t Reserved43[39]; /* Reserved 058h-0FFh*/ + __IO uint32_t HPTXFSIZ; /* Host Periodic Tx FIFO Size Reg 100h*/ + __IO uint32_t DIEPTXF[0x0F]; /* dev Periodic Transmit FIFO */ +} USB_OTG_GlobalTypeDef; + +/** + * @brief USB_OTG_device_Registers + */ +typedef struct +{ + __IO uint32_t DCFG; /* dev Configuration Register 800h*/ + __IO uint32_t DCTL; /* dev Control Register 804h*/ + __IO uint32_t DSTS; /* dev Status Register (RO) 808h*/ + uint32_t Reserved0C; /* Reserved 80Ch*/ + __IO uint32_t DIEPMSK; /* dev IN Endpoint Mask 810h*/ + __IO uint32_t DOEPMSK; /* dev OUT Endpoint Mask 814h*/ + __IO uint32_t DAINT; /* dev All Endpoints Itr Reg 818h*/ + __IO uint32_t DAINTMSK; /* dev All Endpoints Itr Mask 81Ch*/ + uint32_t Reserved20; /* Reserved 820h*/ + uint32_t Reserved9; /* Reserved 824h*/ + __IO uint32_t DVBUSDIS; /* dev VBUS discharge Register 828h*/ + __IO uint32_t DVBUSPULSE; /* dev VBUS Pulse Register 82Ch*/ + __IO uint32_t DTHRCTL; /* dev thr 830h*/ + __IO uint32_t DIEPEMPMSK; /* dev empty msk 834h*/ + __IO uint32_t DEACHINT; /* dedicated EP interrupt 838h*/ + __IO uint32_t DEACHMSK; /* dedicated EP msk 83Ch*/ + uint32_t Reserved40; /* dedicated EP mask 840h*/ + __IO uint32_t DINEP1MSK; /* dedicated EP mask 844h*/ + uint32_t Reserved44[15]; /* Reserved 844-87Ch*/ + __IO uint32_t DOUTEP1MSK; /* dedicated EP msk 884h*/ +} USB_OTG_DeviceTypeDef; + +/** + * @brief USB_OTG_IN_Endpoint-Specific_Register + */ +typedef struct +{ + __IO uint32_t DIEPCTL; /* dev IN Endpoint Control Reg 900h + (ep_num * 20h) + 00h*/ + uint32_t Reserved04; /* Reserved 900h + (ep_num * 20h) + 04h*/ + __IO uint32_t DIEPINT; /* dev IN Endpoint Itr Reg 900h + (ep_num * 20h) + 08h*/ + uint32_t Reserved0C; /* Reserved 900h + (ep_num * 20h) + 0Ch*/ + __IO uint32_t DIEPTSIZ; /* IN Endpoint Txfer Size 900h + (ep_num * 20h) + 10h*/ + __IO uint32_t DIEPDMA; /* IN Endpoint DMA Address Reg 900h + (ep_num * 20h) + 14h*/ + __IO uint32_t DTXFSTS; /*IN Endpoint Tx FIFO Status Reg 900h + (ep_num * 20h) + 18h*/ + uint32_t Reserved18; /* Reserved 900h+(ep_num*20h)+1Ch-900h+ (ep_num * 20h) + 1Ch*/ +} USB_OTG_INEndpointTypeDef; + +/** + * @brief USB_OTG_OUT_Endpoint-Specific_Registers + */ +typedef struct +{ + __IO uint32_t DOEPCTL; /* dev OUT Endpoint Control Reg B00h + (ep_num * 20h) + 00h*/ + uint32_t Reserved04; /* Reserved B00h + (ep_num * 20h) + 04h*/ + __IO uint32_t DOEPINT; /* dev OUT Endpoint Itr Reg B00h + (ep_num * 20h) + 08h*/ + uint32_t Reserved0C; /* Reserved B00h + (ep_num * 20h) + 0Ch*/ + __IO uint32_t DOEPTSIZ; /* dev OUT Endpoint Txfer Size B00h + (ep_num * 20h) + 10h*/ + __IO uint32_t DOEPDMA; /* dev OUT Endpoint DMA Address B00h + (ep_num * 20h) + 14h*/ + uint32_t Reserved18[2]; /* Reserved B00h + (ep_num * 20h) + 18h - B00h + (ep_num * 20h) + 1Ch*/ +} USB_OTG_OUTEndpointTypeDef; + +/** + * @brief USB_OTG_Host_Mode_Register_Structures + */ +typedef struct +{ + __IO uint32_t HCFG; /* Host Configuration Register 400h*/ + __IO uint32_t HFIR; /* Host Frame Interval Register 404h*/ + __IO uint32_t HFNUM; /* Host Frame Nbr/Frame Remaining 408h*/ + uint32_t Reserved40C; /* Reserved 40Ch*/ + __IO uint32_t HPTXSTS; /* Host Periodic Tx FIFO/ Queue Status 410h*/ + __IO uint32_t HAINT; /* Host All Channels Interrupt Register 414h*/ + __IO uint32_t HAINTMSK; /* Host All Channels Interrupt Mask 418h*/ +} USB_OTG_HostTypeDef; + +/** + * @brief USB_OTG_Host_Channel_Specific_Registers + */ +typedef struct +{ + __IO uint32_t HCCHAR; + __IO uint32_t HCSPLT; + __IO uint32_t HCINT; + __IO uint32_t HCINTMSK; + __IO uint32_t HCTSIZ; + __IO uint32_t HCDMA; + uint32_t Reserved[2]; +} USB_OTG_HostChannelTypeDef; + +/** + * @} + */ + +/** @addtogroup Peripheral_memory_map + * @{ + */ +#define FLASH_BASE ((uint32_t)0x08000000U) /*!< FLASH(up to 2 MB) base address */ +#define SRAM1_BASE ((uint32_t)0x20000000U) /*!< SRAM1(up to 192 KB) base address */ +#define SRAM2_BASE ((uint32_t)0x10000000U) /*!< SRAM2(64 KB) base address */ +#define SRAM3_BASE ((uint32_t)0x20040000U) /*!< SRAM3(384 KB) base address */ +#define PERIPH_BASE ((uint32_t)0x40000000U) /*!< Peripheral base address */ +#define FMC_BASE ((uint32_t)0x60000000U) /*!< FMC base address */ +#define OCTOSPI1_BASE ((uint32_t)0x90000000U) /*!< OCTOSPI1 memories accessible over AHB base address */ +#define OCTOSPI2_BASE ((uint32_t)0x70000000U) /*!< OCTOSPI2 memories accessible over AHB base address */ + +#define FMC_R_BASE ((uint32_t)0xA0000000U) /*!< FMC control registers base address */ +#define OCTOSPI1_R_BASE ((uint32_t)0xA0001000U) /*!< OCTOSPI1 control registers base address */ +#define OCTOSPI2_R_BASE ((uint32_t)0xA0001400U) /*!< OCTOSPI2 control registers base address */ +#define SRAM1_BB_BASE ((uint32_t)0x22000000U) /*!< SRAM1(96 KB) base address in the bit-band region */ +#define PERIPH_BB_BASE ((uint32_t)0x42000000U) /*!< Peripheral base address in the bit-band region */ + +/* Legacy defines */ +#define SRAM_BASE SRAM1_BASE +#define SRAM_BB_BASE SRAM1_BB_BASE + +#define SRAM1_SIZE_MAX ((uint32_t)0x00030000U) /*!< maximum SRAM1 size (up to 192 KBytes) */ +#define SRAM2_SIZE ((uint32_t)0x00010000U) /*!< SRAM2 size (64 KBytes) */ +#define SRAM3_SIZE ((uint32_t)0x00060000U) /*!< SRAM3 size (384 KBytes) */ + +/*!< Peripheral memory map */ +#define APB1PERIPH_BASE PERIPH_BASE +#define APB2PERIPH_BASE (PERIPH_BASE + 0x00010000U) +#define AHB1PERIPH_BASE (PERIPH_BASE + 0x00020000U) +#define AHB2PERIPH_BASE (PERIPH_BASE + 0x08000000U) + +#define FMC_BANK1 FMC_BASE +#define FMC_BANK1_1 FMC_BANK1 +#define FMC_BANK1_2 (FMC_BANK1 + 0x04000000U) +#define FMC_BANK1_3 (FMC_BANK1 + 0x08000000U) +#define FMC_BANK1_4 (FMC_BANK1 + 0x0C000000U) +#define FMC_BANK3 (FMC_BASE + 0x20000000U) + +/*!< APB1 peripherals */ +#define TIM2_BASE (APB1PERIPH_BASE + 0x0000U) +#define TIM3_BASE (APB1PERIPH_BASE + 0x0400U) +#define TIM4_BASE (APB1PERIPH_BASE + 0x0800U) +#define TIM5_BASE (APB1PERIPH_BASE + 0x0C00U) +#define TIM6_BASE (APB1PERIPH_BASE + 0x1000U) +#define TIM7_BASE (APB1PERIPH_BASE + 0x1400U) +#define RTC_BASE (APB1PERIPH_BASE + 0x2800U) +#define WWDG_BASE (APB1PERIPH_BASE + 0x2C00U) +#define IWDG_BASE (APB1PERIPH_BASE + 0x3000U) +#define SPI2_BASE (APB1PERIPH_BASE + 0x3800U) +#define SPI3_BASE (APB1PERIPH_BASE + 0x3C00U) +#define USART2_BASE (APB1PERIPH_BASE + 0x4400U) +#define USART3_BASE (APB1PERIPH_BASE + 0x4800U) +#define UART4_BASE (APB1PERIPH_BASE + 0x4C00U) +#define UART5_BASE (APB1PERIPH_BASE + 0x5000U) +#define I2C1_BASE (APB1PERIPH_BASE + 0x5400U) +#define I2C2_BASE (APB1PERIPH_BASE + 0x5800U) +#define I2C3_BASE (APB1PERIPH_BASE + 0x5C00U) +#define CRS_BASE (APB1PERIPH_BASE + 0x6000U) +#define CAN1_BASE (APB1PERIPH_BASE + 0x6400U) +#define I2C4_BASE (APB1PERIPH_BASE + 0x8400U) +#define PWR_BASE (APB1PERIPH_BASE + 0x7000U) +#define DAC_BASE (APB1PERIPH_BASE + 0x7400U) +#define DAC1_BASE (APB1PERIPH_BASE + 0x7400U) +#define OPAMP_BASE (APB1PERIPH_BASE + 0x7800U) +#define OPAMP1_BASE (APB1PERIPH_BASE + 0x7800U) +#define OPAMP2_BASE (APB1PERIPH_BASE + 0x7810U) +#define LPTIM1_BASE (APB1PERIPH_BASE + 0x7C00U) +#define LPUART1_BASE (APB1PERIPH_BASE + 0x8000U) +#define LPTIM2_BASE (APB1PERIPH_BASE + 0x9400U) + + +/*!< APB2 peripherals */ +#define SYSCFG_BASE (APB2PERIPH_BASE + 0x0000U) +#define VREFBUF_BASE (APB2PERIPH_BASE + 0x0030U) +#define COMP1_BASE (APB2PERIPH_BASE + 0x0200U) +#define COMP2_BASE (APB2PERIPH_BASE + 0x0204U) +#define EXTI_BASE (APB2PERIPH_BASE + 0x0400U) +#define FIREWALL_BASE (APB2PERIPH_BASE + 0x1C00U) +#define TIM1_BASE (APB2PERIPH_BASE + 0x2C00U) +#define SPI1_BASE (APB2PERIPH_BASE + 0x3000U) +#define TIM8_BASE (APB2PERIPH_BASE + 0x3400U) +#define USART1_BASE (APB2PERIPH_BASE + 0x3800U) +#define TIM15_BASE (APB2PERIPH_BASE + 0x4000U) +#define TIM16_BASE (APB2PERIPH_BASE + 0x4400U) +#define TIM17_BASE (APB2PERIPH_BASE + 0x4800U) +#define SAI1_BASE (APB2PERIPH_BASE + 0x5400U) +#define SAI1_Block_A_BASE (SAI1_BASE + 0x004) +#define SAI1_Block_B_BASE (SAI1_BASE + 0x024) +#define SAI2_BASE (APB2PERIPH_BASE + 0x5800U) +#define SAI2_Block_A_BASE (SAI2_BASE + 0x004) +#define SAI2_Block_B_BASE (SAI2_BASE + 0x024) +#define DFSDM1_BASE (APB2PERIPH_BASE + 0x6000U) +#define DFSDM1_Channel0_BASE (DFSDM1_BASE + 0x00) +#define DFSDM1_Channel1_BASE (DFSDM1_BASE + 0x20) +#define DFSDM1_Channel2_BASE (DFSDM1_BASE + 0x40) +#define DFSDM1_Channel3_BASE (DFSDM1_BASE + 0x60) +#define DFSDM1_Channel4_BASE (DFSDM1_BASE + 0x80) +#define DFSDM1_Channel5_BASE (DFSDM1_BASE + 0xA0) +#define DFSDM1_Channel6_BASE (DFSDM1_BASE + 0xC0) +#define DFSDM1_Channel7_BASE (DFSDM1_BASE + 0xE0) +#define DFSDM1_Filter0_BASE (DFSDM1_BASE + 0x100) +#define DFSDM1_Filter1_BASE (DFSDM1_BASE + 0x180) +#define DFSDM1_Filter2_BASE (DFSDM1_BASE + 0x200) +#define DFSDM1_Filter3_BASE (DFSDM1_BASE + 0x280) + +/*!< AHB1 peripherals */ +#define DMA1_BASE (AHB1PERIPH_BASE) +#define DMA2_BASE (AHB1PERIPH_BASE + 0x0400U) +#define DMAMUX1_BASE (AHB1PERIPH_BASE + 0x0800U) +#define RCC_BASE (AHB1PERIPH_BASE + 0x1000U) +#define FLASH_R_BASE (AHB1PERIPH_BASE + 0x2000U) +#define CRC_BASE (AHB1PERIPH_BASE + 0x3000U) +#define TSC_BASE (AHB1PERIPH_BASE + 0x4000U) +#define DMA2D_BASE (AHB1PERIPH_BASE + 0xB000U) + + +#define DMA1_Channel1_BASE (DMA1_BASE + 0x0008U) +#define DMA1_Channel2_BASE (DMA1_BASE + 0x001CU) +#define DMA1_Channel3_BASE (DMA1_BASE + 0x0030U) +#define DMA1_Channel4_BASE (DMA1_BASE + 0x0044U) +#define DMA1_Channel5_BASE (DMA1_BASE + 0x0058U) +#define DMA1_Channel6_BASE (DMA1_BASE + 0x006CU) +#define DMA1_Channel7_BASE (DMA1_BASE + 0x0080U) + + +#define DMA2_Channel1_BASE (DMA2_BASE + 0x0008U) +#define DMA2_Channel2_BASE (DMA2_BASE + 0x001CU) +#define DMA2_Channel3_BASE (DMA2_BASE + 0x0030U) +#define DMA2_Channel4_BASE (DMA2_BASE + 0x0044U) +#define DMA2_Channel5_BASE (DMA2_BASE + 0x0058U) +#define DMA2_Channel6_BASE (DMA2_BASE + 0x006CU) +#define DMA2_Channel7_BASE (DMA2_BASE + 0x0080U) + +#define DMAMUX1_Channel0_BASE (DMAMUX1_BASE) +#define DMAMUX1_Channel1_BASE (DMAMUX1_BASE + 0x00000004) +#define DMAMUX1_Channel2_BASE (DMAMUX1_BASE + 0x00000008) +#define DMAMUX1_Channel3_BASE (DMAMUX1_BASE + 0x0000000C) +#define DMAMUX1_Channel4_BASE (DMAMUX1_BASE + 0x00000010) +#define DMAMUX1_Channel5_BASE (DMAMUX1_BASE + 0x00000014) +#define DMAMUX1_Channel6_BASE (DMAMUX1_BASE + 0x00000018) +#define DMAMUX1_Channel7_BASE (DMAMUX1_BASE + 0x0000001C) +#define DMAMUX1_Channel8_BASE (DMAMUX1_BASE + 0x00000020) +#define DMAMUX1_Channel9_BASE (DMAMUX1_BASE + 0x00000024) +#define DMAMUX1_Channel10_BASE (DMAMUX1_BASE + 0x00000028) +#define DMAMUX1_Channel11_BASE (DMAMUX1_BASE + 0x0000002C) +#define DMAMUX1_Channel12_BASE (DMAMUX1_BASE + 0x00000030) +#define DMAMUX1_Channel13_BASE (DMAMUX1_BASE + 0x00000034) + +#define DMAMUX1_RequestGenerator0_BASE (DMAMUX1_BASE + 0x00000100) +#define DMAMUX1_RequestGenerator1_BASE (DMAMUX1_BASE + 0x00000104) +#define DMAMUX1_RequestGenerator2_BASE (DMAMUX1_BASE + 0x00000108) +#define DMAMUX1_RequestGenerator3_BASE (DMAMUX1_BASE + 0x0000010C) + +#define DMAMUX1_ChannelStatus_BASE (DMAMUX1_BASE + 0x00000080) +#define DMAMUX1_RequestGenStatus_BASE (DMAMUX1_BASE + 0x00000140) + +/*!< AHB2 peripherals */ +#define GPIOA_BASE (AHB2PERIPH_BASE + 0x0000U) +#define GPIOB_BASE (AHB2PERIPH_BASE + 0x0400U) +#define GPIOC_BASE (AHB2PERIPH_BASE + 0x0800U) +#define GPIOD_BASE (AHB2PERIPH_BASE + 0x0C00U) +#define GPIOE_BASE (AHB2PERIPH_BASE + 0x1000U) +#define GPIOF_BASE (AHB2PERIPH_BASE + 0x1400U) +#define GPIOG_BASE (AHB2PERIPH_BASE + 0x1800U) +#define GPIOH_BASE (AHB2PERIPH_BASE + 0x1C00U) +#define GPIOI_BASE (AHB2PERIPH_BASE + 0x2000U) + +#define USBOTG_BASE (AHB2PERIPH_BASE + 0x08000000U) + +#define ADC1_BASE (AHB2PERIPH_BASE + 0x08040000U) +#define ADC1_COMMON_BASE (AHB2PERIPH_BASE + 0x08040300U) + +#define DCMI_BASE (AHB2PERIPH_BASE + 0x08050000U) + +#define RNG_BASE (AHB2PERIPH_BASE + 0x08060800U) + +#define OCTOSPIM_BASE (AHB2PERIPH_BASE + 0x08061C00U) +#define SDMMC1_BASE (AHB2PERIPH_BASE + 0x08062400U) + +/*!< FMC Banks registers base address */ +#define FMC_Bank1_R_BASE (FMC_R_BASE + 0x0000U) +#define FMC_Bank1E_R_BASE (FMC_R_BASE + 0x0104U) +#define FMC_Bank3_R_BASE (FMC_R_BASE + 0x0080U) + +/* Debug MCU registers base address */ +#define DBGMCU_BASE ((uint32_t)0xE0042000U) + +/*!< USB registers base address */ +#define USB_OTG_FS_PERIPH_BASE ((uint32_t)0x50000000U) + +#define USB_OTG_GLOBAL_BASE ((uint32_t)0x00000000U) +#define USB_OTG_DEVICE_BASE ((uint32_t)0x00000800U) +#define USB_OTG_IN_ENDPOINT_BASE ((uint32_t)0x00000900U) +#define USB_OTG_OUT_ENDPOINT_BASE ((uint32_t)0x00000B00U) +#define USB_OTG_EP_REG_SIZE ((uint32_t)0x00000020U) +#define USB_OTG_HOST_BASE ((uint32_t)0x00000400U) +#define USB_OTG_HOST_PORT_BASE ((uint32_t)0x00000440U) +#define USB_OTG_HOST_CHANNEL_BASE ((uint32_t)0x00000500U) +#define USB_OTG_HOST_CHANNEL_SIZE ((uint32_t)0x00000020U) +#define USB_OTG_PCGCCTL_BASE ((uint32_t)0x00000E00U) +#define USB_OTG_FIFO_BASE ((uint32_t)0x00001000U) +#define USB_OTG_FIFO_SIZE ((uint32_t)0x00001000U) + + +#define PACKAGE_BASE ((uint32_t)0x1FFF7500U) /*!< Package data register base address */ +#define UID_BASE ((uint32_t)0x1FFF7590U) /*!< Unique device ID register base address */ +#define FLASHSIZE_BASE ((uint32_t)0x1FFF75E0U) /*!< Flash size data register base address */ +/** + * @} + */ + +/** @addtogroup Peripheral_declaration + * @{ + */ +#define TIM2 ((TIM_TypeDef *) TIM2_BASE) +#define TIM3 ((TIM_TypeDef *) TIM3_BASE) +#define TIM4 ((TIM_TypeDef *) TIM4_BASE) +#define TIM5 ((TIM_TypeDef *) TIM5_BASE) +#define TIM6 ((TIM_TypeDef *) TIM6_BASE) +#define TIM7 ((TIM_TypeDef *) TIM7_BASE) +#define RTC ((RTC_TypeDef *) RTC_BASE) +#define WWDG ((WWDG_TypeDef *) WWDG_BASE) +#define IWDG ((IWDG_TypeDef *) IWDG_BASE) +#define SPI2 ((SPI_TypeDef *) SPI2_BASE) +#define SPI3 ((SPI_TypeDef *) SPI3_BASE) +#define USART2 ((USART_TypeDef *) USART2_BASE) +#define USART3 ((USART_TypeDef *) USART3_BASE) +#define UART4 ((USART_TypeDef *) UART4_BASE) +#define UART5 ((USART_TypeDef *) UART5_BASE) +#define I2C1 ((I2C_TypeDef *) I2C1_BASE) +#define I2C2 ((I2C_TypeDef *) I2C2_BASE) +#define I2C3 ((I2C_TypeDef *) I2C3_BASE) +#define CRS ((CRS_TypeDef *) CRS_BASE) +//#define CAN ((CAN_TypeDef *) CAN1_BASE) // MBED FIX : already defined in mbed API +#define CAN1 ((CAN_TypeDef *) CAN1_BASE) +#define I2C4 ((I2C_TypeDef *) I2C4_BASE) +#define PWR ((PWR_TypeDef *) PWR_BASE) +#define DAC ((DAC_TypeDef *) DAC1_BASE) +#define DAC1 ((DAC_TypeDef *) DAC1_BASE) +#define OPAMP ((OPAMP_TypeDef *) OPAMP_BASE) +#define OPAMP1 ((OPAMP_TypeDef *) OPAMP1_BASE) +#define OPAMP2 ((OPAMP_TypeDef *) OPAMP2_BASE) +#define OPAMP12_COMMON ((OPAMP_Common_TypeDef *) OPAMP1_BASE) +#define LPTIM1 ((LPTIM_TypeDef *) LPTIM1_BASE) +#define LPUART1 ((USART_TypeDef *) LPUART1_BASE) +#define LPTIM2 ((LPTIM_TypeDef *) LPTIM2_BASE) + +#define SYSCFG ((SYSCFG_TypeDef *) SYSCFG_BASE) +#define VREFBUF ((VREFBUF_TypeDef *) VREFBUF_BASE) +#define COMP1 ((COMP_TypeDef *) COMP1_BASE) +#define COMP2 ((COMP_TypeDef *) COMP2_BASE) +#define COMP12_COMMON ((COMP_Common_TypeDef *) COMP2_BASE) +#define EXTI ((EXTI_TypeDef *) EXTI_BASE) +#define FIREWALL ((FIREWALL_TypeDef *) FIREWALL_BASE) +#define TIM1 ((TIM_TypeDef *) TIM1_BASE) +#define SPI1 ((SPI_TypeDef *) SPI1_BASE) +#define TIM8 ((TIM_TypeDef *) TIM8_BASE) +#define USART1 ((USART_TypeDef *) USART1_BASE) +#define TIM15 ((TIM_TypeDef *) TIM15_BASE) +#define TIM16 ((TIM_TypeDef *) TIM16_BASE) +#define TIM17 ((TIM_TypeDef *) TIM17_BASE) +#define SAI1 ((SAI_TypeDef *) SAI1_BASE) +#define SAI1_Block_A ((SAI_Block_TypeDef *)SAI1_Block_A_BASE) +#define SAI1_Block_B ((SAI_Block_TypeDef *)SAI1_Block_B_BASE) +#define SAI2 ((SAI_TypeDef *) SAI2_BASE) +#define SAI2_Block_A ((SAI_Block_TypeDef *)SAI2_Block_A_BASE) +#define SAI2_Block_B ((SAI_Block_TypeDef *)SAI2_Block_B_BASE) +#define DFSDM1_Channel0 ((DFSDM_Channel_TypeDef *) DFSDM1_Channel0_BASE) +#define DFSDM1_Channel1 ((DFSDM_Channel_TypeDef *) DFSDM1_Channel1_BASE) +#define DFSDM1_Channel2 ((DFSDM_Channel_TypeDef *) DFSDM1_Channel2_BASE) +#define DFSDM1_Channel3 ((DFSDM_Channel_TypeDef *) DFSDM1_Channel3_BASE) +#define DFSDM1_Channel4 ((DFSDM_Channel_TypeDef *) DFSDM1_Channel4_BASE) +#define DFSDM1_Channel5 ((DFSDM_Channel_TypeDef *) DFSDM1_Channel5_BASE) +#define DFSDM1_Channel6 ((DFSDM_Channel_TypeDef *) DFSDM1_Channel6_BASE) +#define DFSDM1_Channel7 ((DFSDM_Channel_TypeDef *) DFSDM1_Channel7_BASE) +#define DFSDM1_Filter0 ((DFSDM_Filter_TypeDef *) DFSDM1_Filter0_BASE) +#define DFSDM1_Filter1 ((DFSDM_Filter_TypeDef *) DFSDM1_Filter1_BASE) +#define DFSDM1_Filter2 ((DFSDM_Filter_TypeDef *) DFSDM1_Filter2_BASE) +#define DFSDM1_Filter3 ((DFSDM_Filter_TypeDef *) DFSDM1_Filter3_BASE) +/* Aliases to keep compatibility after DFSDM renaming */ +#define DFSDM_Channel0 DFSDM1_Channel0 +#define DFSDM_Channel1 DFSDM1_Channel1 +#define DFSDM_Channel2 DFSDM1_Channel2 +#define DFSDM_Channel3 DFSDM1_Channel3 +#define DFSDM_Channel4 DFSDM1_Channel4 +#define DFSDM_Channel5 DFSDM1_Channel5 +#define DFSDM_Channel6 DFSDM1_Channel6 +#define DFSDM_Channel7 DFSDM1_Channel7 +#define DFSDM_Filter0 DFSDM1_Filter0 +#define DFSDM_Filter1 DFSDM1_Filter1 +#define DFSDM_Filter2 DFSDM1_Filter2 +#define DFSDM_Filter3 DFSDM1_Filter3 +#define DMA1 ((DMA_TypeDef *) DMA1_BASE) +#define DMA2 ((DMA_TypeDef *) DMA2_BASE) +#define DMAMUX1 ((DMAMUX_Channel_TypeDef *) DMAMUX1_BASE) +#define RCC ((RCC_TypeDef *) RCC_BASE) +#define FLASH ((FLASH_TypeDef *) FLASH_R_BASE) +#define CRC ((CRC_TypeDef *) CRC_BASE) +#define TSC ((TSC_TypeDef *) TSC_BASE) + +#define GPIOA ((GPIO_TypeDef *) GPIOA_BASE) +#define GPIOB ((GPIO_TypeDef *) GPIOB_BASE) +#define GPIOC ((GPIO_TypeDef *) GPIOC_BASE) +#define GPIOD ((GPIO_TypeDef *) GPIOD_BASE) +#define GPIOE ((GPIO_TypeDef *) GPIOE_BASE) +#define GPIOF ((GPIO_TypeDef *) GPIOF_BASE) +#define GPIOG ((GPIO_TypeDef *) GPIOG_BASE) +#define GPIOH ((GPIO_TypeDef *) GPIOH_BASE) +#define GPIOI ((GPIO_TypeDef *) GPIOI_BASE) +#define ADC1 ((ADC_TypeDef *) ADC1_BASE) +#define ADC1_COMMON ((ADC_Common_TypeDef *) ADC1_COMMON_BASE) +#define DCMI ((DCMI_TypeDef *) DCMI_BASE) +#define DMA2D ((DMA2D_TypeDef *)DMA2D_BASE) +#define RNG ((RNG_TypeDef *) RNG_BASE) +#define SDMMC1 ((SDMMC_TypeDef *) SDMMC1_BASE) + + +#define DMA1_Channel1 ((DMA_Channel_TypeDef *) DMA1_Channel1_BASE) +#define DMA1_Channel2 ((DMA_Channel_TypeDef *) DMA1_Channel2_BASE) +#define DMA1_Channel3 ((DMA_Channel_TypeDef *) DMA1_Channel3_BASE) +#define DMA1_Channel4 ((DMA_Channel_TypeDef *) DMA1_Channel4_BASE) +#define DMA1_Channel5 ((DMA_Channel_TypeDef *) DMA1_Channel5_BASE) +#define DMA1_Channel6 ((DMA_Channel_TypeDef *) DMA1_Channel6_BASE) +#define DMA1_Channel7 ((DMA_Channel_TypeDef *) DMA1_Channel7_BASE) + + +#define DMA2_Channel1 ((DMA_Channel_TypeDef *) DMA2_Channel1_BASE) +#define DMA2_Channel2 ((DMA_Channel_TypeDef *) DMA2_Channel2_BASE) +#define DMA2_Channel3 ((DMA_Channel_TypeDef *) DMA2_Channel3_BASE) +#define DMA2_Channel4 ((DMA_Channel_TypeDef *) DMA2_Channel4_BASE) +#define DMA2_Channel5 ((DMA_Channel_TypeDef *) DMA2_Channel5_BASE) +#define DMA2_Channel6 ((DMA_Channel_TypeDef *) DMA2_Channel6_BASE) +#define DMA2_Channel7 ((DMA_Channel_TypeDef *) DMA2_Channel7_BASE) + +#define DMAMUX1_Channel0 ((DMAMUX_Channel_TypeDef *) DMAMUX1_Channel0_BASE) +#define DMAMUX1_Channel1 ((DMAMUX_Channel_TypeDef *) DMAMUX1_Channel1_BASE) +#define DMAMUX1_Channel2 ((DMAMUX_Channel_TypeDef *) DMAMUX1_Channel2_BASE) +#define DMAMUX1_Channel3 ((DMAMUX_Channel_TypeDef *) DMAMUX1_Channel3_BASE) +#define DMAMUX1_Channel4 ((DMAMUX_Channel_TypeDef *) DMAMUX1_Channel4_BASE) +#define DMAMUX1_Channel5 ((DMAMUX_Channel_TypeDef *) DMAMUX1_Channel5_BASE) +#define DMAMUX1_Channel6 ((DMAMUX_Channel_TypeDef *) DMAMUX1_Channel6_BASE) +#define DMAMUX1_Channel7 ((DMAMUX_Channel_TypeDef *) DMAMUX1_Channel7_BASE) +#define DMAMUX1_Channel8 ((DMAMUX_Channel_TypeDef *) DMAMUX1_Channel8_BASE) +#define DMAMUX1_Channel9 ((DMAMUX_Channel_TypeDef *) DMAMUX1_Channel9_BASE) +#define DMAMUX1_Channel10 ((DMAMUX_Channel_TypeDef *) DMAMUX1_Channel10_BASE) +#define DMAMUX1_Channel11 ((DMAMUX_Channel_TypeDef *) DMAMUX1_Channel11_BASE) +#define DMAMUX1_Channel12 ((DMAMUX_Channel_TypeDef *) DMAMUX1_Channel12_BASE) +#define DMAMUX1_Channel13 ((DMAMUX_Channel_TypeDef *) DMAMUX1_Channel13_BASE) + +#define DMAMUX1_RequestGenerator0 ((DMAMUX_RequestGen_TypeDef *) DMAMUX1_RequestGenerator0_BASE) +#define DMAMUX1_RequestGenerator1 ((DMAMUX_RequestGen_TypeDef *) DMAMUX1_RequestGenerator1_BASE) +#define DMAMUX1_RequestGenerator2 ((DMAMUX_RequestGen_TypeDef *) DMAMUX1_RequestGenerator2_BASE) +#define DMAMUX1_RequestGenerator3 ((DMAMUX_RequestGen_TypeDef *) DMAMUX1_RequestGenerator3_BASE) + +#define DMAMUX1_ChannelStatus ((DMAMUX_ChannelStatus_TypeDef *) DMAMUX1_ChannelStatus_BASE) +#define DMAMUX1_RequestGenStatus ((DMAMUX_RequestGenStatus_TypeDef *) DMAMUX1_RequestGenStatus_BASE) + + +#define FMC_Bank1_R ((FMC_Bank1_TypeDef *) FMC_Bank1_R_BASE) +#define FMC_Bank1E_R ((FMC_Bank1E_TypeDef *) FMC_Bank1E_R_BASE) +#define FMC_Bank3_R ((FMC_Bank3_TypeDef *) FMC_Bank3_R_BASE) + +#define OCTOSPI1 ((OCTOSPI_TypeDef *) OCTOSPI1_R_BASE) +#define OCTOSPI2 ((OCTOSPI_TypeDef *) OCTOSPI2_R_BASE) +#define OCTOSPIM ((OCTOSPIM_TypeDef *) OCTOSPIM_BASE) + +#define DBGMCU ((DBGMCU_TypeDef *) DBGMCU_BASE) + +#define USB_OTG_FS ((USB_OTG_GlobalTypeDef *) USB_OTG_FS_PERIPH_BASE) +/** + * @} + */ + +/** @addtogroup Exported_constants + * @{ + */ + +/** @addtogroup Peripheral_Registers_Bits_Definition + * @{ + */ + +/******************************************************************************/ +/* Peripheral Registers_Bits_Definition */ +/******************************************************************************/ + +/******************************************************************************/ +/* */ +/* Analog to Digital Converter */ +/* */ +/******************************************************************************/ + +/* + * @brief Specific device feature definitions (not present on all devices in the STM32L4 serie) + */ + +/******************** Bit definition for ADC_ISR register *******************/ +#define ADC_ISR_ADRDY_Pos (0U) +#define ADC_ISR_ADRDY_Msk (0x1U << ADC_ISR_ADRDY_Pos) /*!< 0x00000001 */ +#define ADC_ISR_ADRDY ADC_ISR_ADRDY_Msk /*!< ADC ready flag */ +#define ADC_ISR_EOSMP_Pos (1U) +#define ADC_ISR_EOSMP_Msk (0x1U << ADC_ISR_EOSMP_Pos) /*!< 0x00000002 */ +#define ADC_ISR_EOSMP ADC_ISR_EOSMP_Msk /*!< ADC group regular end of sampling flag */ +#define ADC_ISR_EOC_Pos (2U) +#define ADC_ISR_EOC_Msk (0x1U << ADC_ISR_EOC_Pos) /*!< 0x00000004 */ +#define ADC_ISR_EOC ADC_ISR_EOC_Msk /*!< ADC group regular end of unitary conversion flag */ +#define ADC_ISR_EOS_Pos (3U) +#define ADC_ISR_EOS_Msk (0x1U << ADC_ISR_EOS_Pos) /*!< 0x00000008 */ +#define ADC_ISR_EOS ADC_ISR_EOS_Msk /*!< ADC group regular end of sequence conversions flag */ +#define ADC_ISR_OVR_Pos (4U) +#define ADC_ISR_OVR_Msk (0x1U << ADC_ISR_OVR_Pos) /*!< 0x00000010 */ +#define ADC_ISR_OVR ADC_ISR_OVR_Msk /*!< ADC group regular overrun flag */ +#define ADC_ISR_JEOC_Pos (5U) +#define ADC_ISR_JEOC_Msk (0x1U << ADC_ISR_JEOC_Pos) /*!< 0x00000020 */ +#define ADC_ISR_JEOC ADC_ISR_JEOC_Msk /*!< ADC group injected end of unitary conversion flag */ +#define ADC_ISR_JEOS_Pos (6U) +#define ADC_ISR_JEOS_Msk (0x1U << ADC_ISR_JEOS_Pos) /*!< 0x00000040 */ +#define ADC_ISR_JEOS ADC_ISR_JEOS_Msk /*!< ADC group injected end of sequence conversions flag */ +#define ADC_ISR_AWD1_Pos (7U) +#define ADC_ISR_AWD1_Msk (0x1U << ADC_ISR_AWD1_Pos) /*!< 0x00000080 */ +#define ADC_ISR_AWD1 ADC_ISR_AWD1_Msk /*!< ADC analog watchdog 1 flag */ +#define ADC_ISR_AWD2_Pos (8U) +#define ADC_ISR_AWD2_Msk (0x1U << ADC_ISR_AWD2_Pos) /*!< 0x00000100 */ +#define ADC_ISR_AWD2 ADC_ISR_AWD2_Msk /*!< ADC analog watchdog 2 flag */ +#define ADC_ISR_AWD3_Pos (9U) +#define ADC_ISR_AWD3_Msk (0x1U << ADC_ISR_AWD3_Pos) /*!< 0x00000200 */ +#define ADC_ISR_AWD3 ADC_ISR_AWD3_Msk /*!< ADC analog watchdog 3 flag */ +#define ADC_ISR_JQOVF_Pos (10U) +#define ADC_ISR_JQOVF_Msk (0x1U << ADC_ISR_JQOVF_Pos) /*!< 0x00000400 */ +#define ADC_ISR_JQOVF ADC_ISR_JQOVF_Msk /*!< ADC group injected contexts queue overflow flag */ + +/******************** Bit definition for ADC_IER register *******************/ +#define ADC_IER_ADRDYIE_Pos (0U) +#define ADC_IER_ADRDYIE_Msk (0x1U << ADC_IER_ADRDYIE_Pos) /*!< 0x00000001 */ +#define ADC_IER_ADRDYIE ADC_IER_ADRDYIE_Msk /*!< ADC ready interrupt */ +#define ADC_IER_EOSMPIE_Pos (1U) +#define ADC_IER_EOSMPIE_Msk (0x1U << ADC_IER_EOSMPIE_Pos) /*!< 0x00000002 */ +#define ADC_IER_EOSMPIE ADC_IER_EOSMPIE_Msk /*!< ADC group regular end of sampling interrupt */ +#define ADC_IER_EOCIE_Pos (2U) +#define ADC_IER_EOCIE_Msk (0x1U << ADC_IER_EOCIE_Pos) /*!< 0x00000004 */ +#define ADC_IER_EOCIE ADC_IER_EOCIE_Msk /*!< ADC group regular end of unitary conversion interrupt */ +#define ADC_IER_EOSIE_Pos (3U) +#define ADC_IER_EOSIE_Msk (0x1U << ADC_IER_EOSIE_Pos) /*!< 0x00000008 */ +#define ADC_IER_EOSIE ADC_IER_EOSIE_Msk /*!< ADC group regular end of sequence conversions interrupt */ +#define ADC_IER_OVRIE_Pos (4U) +#define ADC_IER_OVRIE_Msk (0x1U << ADC_IER_OVRIE_Pos) /*!< 0x00000010 */ +#define ADC_IER_OVRIE ADC_IER_OVRIE_Msk /*!< ADC group regular overrun interrupt */ +#define ADC_IER_JEOCIE_Pos (5U) +#define ADC_IER_JEOCIE_Msk (0x1U << ADC_IER_JEOCIE_Pos) /*!< 0x00000020 */ +#define ADC_IER_JEOCIE ADC_IER_JEOCIE_Msk /*!< ADC group injected end of unitary conversion interrupt */ +#define ADC_IER_JEOSIE_Pos (6U) +#define ADC_IER_JEOSIE_Msk (0x1U << ADC_IER_JEOSIE_Pos) /*!< 0x00000040 */ +#define ADC_IER_JEOSIE ADC_IER_JEOSIE_Msk /*!< ADC group injected end of sequence conversions interrupt */ +#define ADC_IER_AWD1IE_Pos (7U) +#define ADC_IER_AWD1IE_Msk (0x1U << ADC_IER_AWD1IE_Pos) /*!< 0x00000080 */ +#define ADC_IER_AWD1IE ADC_IER_AWD1IE_Msk /*!< ADC analog watchdog 1 interrupt */ +#define ADC_IER_AWD2IE_Pos (8U) +#define ADC_IER_AWD2IE_Msk (0x1U << ADC_IER_AWD2IE_Pos) /*!< 0x00000100 */ +#define ADC_IER_AWD2IE ADC_IER_AWD2IE_Msk /*!< ADC analog watchdog 2 interrupt */ +#define ADC_IER_AWD3IE_Pos (9U) +#define ADC_IER_AWD3IE_Msk (0x1U << ADC_IER_AWD3IE_Pos) /*!< 0x00000200 */ +#define ADC_IER_AWD3IE ADC_IER_AWD3IE_Msk /*!< ADC analog watchdog 3 interrupt */ +#define ADC_IER_JQOVFIE_Pos (10U) +#define ADC_IER_JQOVFIE_Msk (0x1U << ADC_IER_JQOVFIE_Pos) /*!< 0x00000400 */ +#define ADC_IER_JQOVFIE ADC_IER_JQOVFIE_Msk /*!< ADC group injected contexts queue overflow interrupt */ + +/* Legacy defines */ +#define ADC_IER_ADRDY (ADC_IER_ADRDYIE) +#define ADC_IER_EOSMP (ADC_IER_EOSMPIE) +#define ADC_IER_EOC (ADC_IER_EOCIE) +#define ADC_IER_EOS (ADC_IER_EOSIE) +#define ADC_IER_OVR (ADC_IER_OVRIE) +#define ADC_IER_JEOC (ADC_IER_JEOCIE) +#define ADC_IER_JEOS (ADC_IER_JEOSIE) +#define ADC_IER_AWD1 (ADC_IER_AWD1IE) +#define ADC_IER_AWD2 (ADC_IER_AWD2IE) +#define ADC_IER_AWD3 (ADC_IER_AWD3IE) +#define ADC_IER_JQOVF (ADC_IER_JQOVFIE) + +/******************** Bit definition for ADC_CR register ********************/ +#define ADC_CR_ADEN_Pos (0U) +#define ADC_CR_ADEN_Msk (0x1U << ADC_CR_ADEN_Pos) /*!< 0x00000001 */ +#define ADC_CR_ADEN ADC_CR_ADEN_Msk /*!< ADC enable */ +#define ADC_CR_ADDIS_Pos (1U) +#define ADC_CR_ADDIS_Msk (0x1U << ADC_CR_ADDIS_Pos) /*!< 0x00000002 */ +#define ADC_CR_ADDIS ADC_CR_ADDIS_Msk /*!< ADC disable */ +#define ADC_CR_ADSTART_Pos (2U) +#define ADC_CR_ADSTART_Msk (0x1U << ADC_CR_ADSTART_Pos) /*!< 0x00000004 */ +#define ADC_CR_ADSTART ADC_CR_ADSTART_Msk /*!< ADC group regular conversion start */ +#define ADC_CR_JADSTART_Pos (3U) +#define ADC_CR_JADSTART_Msk (0x1U << ADC_CR_JADSTART_Pos) /*!< 0x00000008 */ +#define ADC_CR_JADSTART ADC_CR_JADSTART_Msk /*!< ADC group injected conversion start */ +#define ADC_CR_ADSTP_Pos (4U) +#define ADC_CR_ADSTP_Msk (0x1U << ADC_CR_ADSTP_Pos) /*!< 0x00000010 */ +#define ADC_CR_ADSTP ADC_CR_ADSTP_Msk /*!< ADC group regular conversion stop */ +#define ADC_CR_JADSTP_Pos (5U) +#define ADC_CR_JADSTP_Msk (0x1U << ADC_CR_JADSTP_Pos) /*!< 0x00000020 */ +#define ADC_CR_JADSTP ADC_CR_JADSTP_Msk /*!< ADC group injected conversion stop */ +#define ADC_CR_ADVREGEN_Pos (28U) +#define ADC_CR_ADVREGEN_Msk (0x1U << ADC_CR_ADVREGEN_Pos) /*!< 0x10000000 */ +#define ADC_CR_ADVREGEN ADC_CR_ADVREGEN_Msk /*!< ADC voltage regulator enable */ +#define ADC_CR_DEEPPWD_Pos (29U) +#define ADC_CR_DEEPPWD_Msk (0x1U << ADC_CR_DEEPPWD_Pos) /*!< 0x20000000 */ +#define ADC_CR_DEEPPWD ADC_CR_DEEPPWD_Msk /*!< ADC deep power down enable */ +#define ADC_CR_ADCALDIF_Pos (30U) +#define ADC_CR_ADCALDIF_Msk (0x1U << ADC_CR_ADCALDIF_Pos) /*!< 0x40000000 */ +#define ADC_CR_ADCALDIF ADC_CR_ADCALDIF_Msk /*!< ADC differential mode for calibration */ +#define ADC_CR_ADCAL_Pos (31U) +#define ADC_CR_ADCAL_Msk (0x1U << ADC_CR_ADCAL_Pos) /*!< 0x80000000 */ +#define ADC_CR_ADCAL ADC_CR_ADCAL_Msk /*!< ADC calibration */ + +/******************** Bit definition for ADC_CFGR register ******************/ +#define ADC_CFGR_DMAEN_Pos (0U) +#define ADC_CFGR_DMAEN_Msk (0x1U << ADC_CFGR_DMAEN_Pos) /*!< 0x00000001 */ +#define ADC_CFGR_DMAEN ADC_CFGR_DMAEN_Msk /*!< ADC DMA transfer enable */ +#define ADC_CFGR_DMACFG_Pos (1U) +#define ADC_CFGR_DMACFG_Msk (0x1U << ADC_CFGR_DMACFG_Pos) /*!< 0x00000002 */ +#define ADC_CFGR_DMACFG ADC_CFGR_DMACFG_Msk /*!< ADC DMA transfer configuration */ + +#define ADC_CFGR_DFSDMCFG_Pos (2U) +#define ADC_CFGR_DFSDMCFG_Msk (0x1U << ADC_CFGR_DFSDMCFG_Pos) /*!< 0x00000004 */ +#define ADC_CFGR_DFSDMCFG ADC_CFGR_DFSDMCFG_Msk /*!< ADC DFSDM mode configuration */ + +#define ADC_CFGR_RES_Pos (3U) +#define ADC_CFGR_RES_Msk (0x3U << ADC_CFGR_RES_Pos) /*!< 0x00000018 */ +#define ADC_CFGR_RES ADC_CFGR_RES_Msk /*!< ADC data resolution */ +#define ADC_CFGR_RES_0 (0x1U << ADC_CFGR_RES_Pos) /*!< 0x00000008 */ +#define ADC_CFGR_RES_1 (0x2U << ADC_CFGR_RES_Pos) /*!< 0x00000010 */ + +#define ADC_CFGR_ALIGN_Pos (5U) +#define ADC_CFGR_ALIGN_Msk (0x1U << ADC_CFGR_ALIGN_Pos) /*!< 0x00000020 */ +#define ADC_CFGR_ALIGN ADC_CFGR_ALIGN_Msk /*!< ADC data alignement */ + +#define ADC_CFGR_EXTSEL_Pos (6U) +#define ADC_CFGR_EXTSEL_Msk (0xFU << ADC_CFGR_EXTSEL_Pos) /*!< 0x000003C0 */ +#define ADC_CFGR_EXTSEL ADC_CFGR_EXTSEL_Msk /*!< ADC group regular external trigger source */ +#define ADC_CFGR_EXTSEL_0 (0x1U << ADC_CFGR_EXTSEL_Pos) /*!< 0x00000040 */ +#define ADC_CFGR_EXTSEL_1 (0x2U << ADC_CFGR_EXTSEL_Pos) /*!< 0x00000080 */ +#define ADC_CFGR_EXTSEL_2 (0x4U << ADC_CFGR_EXTSEL_Pos) /*!< 0x00000100 */ +#define ADC_CFGR_EXTSEL_3 (0x8U << ADC_CFGR_EXTSEL_Pos) /*!< 0x00000200 */ + +#define ADC_CFGR_EXTEN_Pos (10U) +#define ADC_CFGR_EXTEN_Msk (0x3U << ADC_CFGR_EXTEN_Pos) /*!< 0x00000C00 */ +#define ADC_CFGR_EXTEN ADC_CFGR_EXTEN_Msk /*!< ADC group regular external trigger polarity */ +#define ADC_CFGR_EXTEN_0 (0x1U << ADC_CFGR_EXTEN_Pos) /*!< 0x00000400 */ +#define ADC_CFGR_EXTEN_1 (0x2U << ADC_CFGR_EXTEN_Pos) /*!< 0x00000800 */ + +#define ADC_CFGR_OVRMOD_Pos (12U) +#define ADC_CFGR_OVRMOD_Msk (0x1U << ADC_CFGR_OVRMOD_Pos) /*!< 0x00001000 */ +#define ADC_CFGR_OVRMOD ADC_CFGR_OVRMOD_Msk /*!< ADC group regular overrun configuration */ +#define ADC_CFGR_CONT_Pos (13U) +#define ADC_CFGR_CONT_Msk (0x1U << ADC_CFGR_CONT_Pos) /*!< 0x00002000 */ +#define ADC_CFGR_CONT ADC_CFGR_CONT_Msk /*!< ADC group regular continuous conversion mode */ +#define ADC_CFGR_AUTDLY_Pos (14U) +#define ADC_CFGR_AUTDLY_Msk (0x1U << ADC_CFGR_AUTDLY_Pos) /*!< 0x00004000 */ +#define ADC_CFGR_AUTDLY ADC_CFGR_AUTDLY_Msk /*!< ADC low power auto wait */ + +#define ADC_CFGR_DISCEN_Pos (16U) +#define ADC_CFGR_DISCEN_Msk (0x1U << ADC_CFGR_DISCEN_Pos) /*!< 0x00010000 */ +#define ADC_CFGR_DISCEN ADC_CFGR_DISCEN_Msk /*!< ADC group regular sequencer discontinuous mode */ + +#define ADC_CFGR_DISCNUM_Pos (17U) +#define ADC_CFGR_DISCNUM_Msk (0x7U << ADC_CFGR_DISCNUM_Pos) /*!< 0x000E0000 */ +#define ADC_CFGR_DISCNUM ADC_CFGR_DISCNUM_Msk /*!< ADC group regular sequencer discontinuous number of ranks */ +#define ADC_CFGR_DISCNUM_0 (0x1U << ADC_CFGR_DISCNUM_Pos) /*!< 0x00020000 */ +#define ADC_CFGR_DISCNUM_1 (0x2U << ADC_CFGR_DISCNUM_Pos) /*!< 0x00040000 */ +#define ADC_CFGR_DISCNUM_2 (0x4U << ADC_CFGR_DISCNUM_Pos) /*!< 0x00080000 */ + +#define ADC_CFGR_JDISCEN_Pos (20U) +#define ADC_CFGR_JDISCEN_Msk (0x1U << ADC_CFGR_JDISCEN_Pos) /*!< 0x00100000 */ +#define ADC_CFGR_JDISCEN ADC_CFGR_JDISCEN_Msk /*!< ADC group injected sequencer discontinuous mode */ +#define ADC_CFGR_JQM_Pos (21U) +#define ADC_CFGR_JQM_Msk (0x1U << ADC_CFGR_JQM_Pos) /*!< 0x00200000 */ +#define ADC_CFGR_JQM ADC_CFGR_JQM_Msk /*!< ADC group injected contexts queue mode */ +#define ADC_CFGR_AWD1SGL_Pos (22U) +#define ADC_CFGR_AWD1SGL_Msk (0x1U << ADC_CFGR_AWD1SGL_Pos) /*!< 0x00400000 */ +#define ADC_CFGR_AWD1SGL ADC_CFGR_AWD1SGL_Msk /*!< ADC analog watchdog 1 monitoring a single channel or all channels */ +#define ADC_CFGR_AWD1EN_Pos (23U) +#define ADC_CFGR_AWD1EN_Msk (0x1U << ADC_CFGR_AWD1EN_Pos) /*!< 0x00800000 */ +#define ADC_CFGR_AWD1EN ADC_CFGR_AWD1EN_Msk /*!< ADC analog watchdog 1 enable on scope ADC group regular */ +#define ADC_CFGR_JAWD1EN_Pos (24U) +#define ADC_CFGR_JAWD1EN_Msk (0x1U << ADC_CFGR_JAWD1EN_Pos) /*!< 0x01000000 */ +#define ADC_CFGR_JAWD1EN ADC_CFGR_JAWD1EN_Msk /*!< ADC analog watchdog 1 enable on scope ADC group injected */ +#define ADC_CFGR_JAUTO_Pos (25U) +#define ADC_CFGR_JAUTO_Msk (0x1U << ADC_CFGR_JAUTO_Pos) /*!< 0x02000000 */ +#define ADC_CFGR_JAUTO ADC_CFGR_JAUTO_Msk /*!< ADC group injected automatic trigger mode */ + +#define ADC_CFGR_AWD1CH_Pos (26U) +#define ADC_CFGR_AWD1CH_Msk (0x1FU << ADC_CFGR_AWD1CH_Pos) /*!< 0x7C000000 */ +#define ADC_CFGR_AWD1CH ADC_CFGR_AWD1CH_Msk /*!< ADC analog watchdog 1 monitored channel selection */ +#define ADC_CFGR_AWD1CH_0 (0x01U << ADC_CFGR_AWD1CH_Pos) /*!< 0x04000000 */ +#define ADC_CFGR_AWD1CH_1 (0x02U << ADC_CFGR_AWD1CH_Pos) /*!< 0x08000000 */ +#define ADC_CFGR_AWD1CH_2 (0x04U << ADC_CFGR_AWD1CH_Pos) /*!< 0x10000000 */ +#define ADC_CFGR_AWD1CH_3 (0x08U << ADC_CFGR_AWD1CH_Pos) /*!< 0x20000000 */ +#define ADC_CFGR_AWD1CH_4 (0x10U << ADC_CFGR_AWD1CH_Pos) /*!< 0x40000000 */ + +#define ADC_CFGR_JQDIS_Pos (31U) +#define ADC_CFGR_JQDIS_Msk (0x1U << ADC_CFGR_JQDIS_Pos) /*!< 0x80000000 */ +#define ADC_CFGR_JQDIS ADC_CFGR_JQDIS_Msk /*!< ADC group injected contexts queue disable */ + +/******************** Bit definition for ADC_CFGR2 register *****************/ +#define ADC_CFGR2_ROVSE_Pos (0U) +#define ADC_CFGR2_ROVSE_Msk (0x1U << ADC_CFGR2_ROVSE_Pos) /*!< 0x00000001 */ +#define ADC_CFGR2_ROVSE ADC_CFGR2_ROVSE_Msk /*!< ADC oversampler enable on scope ADC group regular */ +#define ADC_CFGR2_JOVSE_Pos (1U) +#define ADC_CFGR2_JOVSE_Msk (0x1U << ADC_CFGR2_JOVSE_Pos) /*!< 0x00000002 */ +#define ADC_CFGR2_JOVSE ADC_CFGR2_JOVSE_Msk /*!< ADC oversampler enable on scope ADC group injected */ + +#define ADC_CFGR2_OVSR_Pos (2U) +#define ADC_CFGR2_OVSR_Msk (0x7U << ADC_CFGR2_OVSR_Pos) /*!< 0x0000001C */ +#define ADC_CFGR2_OVSR ADC_CFGR2_OVSR_Msk /*!< ADC oversampling ratio */ +#define ADC_CFGR2_OVSR_0 (0x1U << ADC_CFGR2_OVSR_Pos) /*!< 0x00000004 */ +#define ADC_CFGR2_OVSR_1 (0x2U << ADC_CFGR2_OVSR_Pos) /*!< 0x00000008 */ +#define ADC_CFGR2_OVSR_2 (0x4U << ADC_CFGR2_OVSR_Pos) /*!< 0x00000010 */ + +#define ADC_CFGR2_OVSS_Pos (5U) +#define ADC_CFGR2_OVSS_Msk (0xFU << ADC_CFGR2_OVSS_Pos) /*!< 0x000001E0 */ +#define ADC_CFGR2_OVSS ADC_CFGR2_OVSS_Msk /*!< ADC oversampling shift */ +#define ADC_CFGR2_OVSS_0 (0x1U << ADC_CFGR2_OVSS_Pos) /*!< 0x00000020 */ +#define ADC_CFGR2_OVSS_1 (0x2U << ADC_CFGR2_OVSS_Pos) /*!< 0x00000040 */ +#define ADC_CFGR2_OVSS_2 (0x4U << ADC_CFGR2_OVSS_Pos) /*!< 0x00000080 */ +#define ADC_CFGR2_OVSS_3 (0x8U << ADC_CFGR2_OVSS_Pos) /*!< 0x00000100 */ + +#define ADC_CFGR2_TROVS_Pos (9U) +#define ADC_CFGR2_TROVS_Msk (0x1U << ADC_CFGR2_TROVS_Pos) /*!< 0x00000200 */ +#define ADC_CFGR2_TROVS ADC_CFGR2_TROVS_Msk /*!< ADC oversampling discontinuous mode (triggered mode) for ADC group regular */ +#define ADC_CFGR2_ROVSM_Pos (10U) +#define ADC_CFGR2_ROVSM_Msk (0x1U << ADC_CFGR2_ROVSM_Pos) /*!< 0x00000400 */ +#define ADC_CFGR2_ROVSM ADC_CFGR2_ROVSM_Msk /*!< ADC oversampling mode managing interlaced conversions of ADC group regular and group injected */ + +/******************** Bit definition for ADC_SMPR1 register *****************/ +#define ADC_SMPR1_SMP0_Pos (0U) +#define ADC_SMPR1_SMP0_Msk (0x7U << ADC_SMPR1_SMP0_Pos) /*!< 0x00000007 */ +#define ADC_SMPR1_SMP0 ADC_SMPR1_SMP0_Msk /*!< ADC channel 0 sampling time selection */ +#define ADC_SMPR1_SMP0_0 (0x1U << ADC_SMPR1_SMP0_Pos) /*!< 0x00000001 */ +#define ADC_SMPR1_SMP0_1 (0x2U << ADC_SMPR1_SMP0_Pos) /*!< 0x00000002 */ +#define ADC_SMPR1_SMP0_2 (0x4U << ADC_SMPR1_SMP0_Pos) /*!< 0x00000004 */ + +#define ADC_SMPR1_SMP1_Pos (3U) +#define ADC_SMPR1_SMP1_Msk (0x7U << ADC_SMPR1_SMP1_Pos) /*!< 0x00000038 */ +#define ADC_SMPR1_SMP1 ADC_SMPR1_SMP1_Msk /*!< ADC channel 1 sampling time selection */ +#define ADC_SMPR1_SMP1_0 (0x1U << ADC_SMPR1_SMP1_Pos) /*!< 0x00000008 */ +#define ADC_SMPR1_SMP1_1 (0x2U << ADC_SMPR1_SMP1_Pos) /*!< 0x00000010 */ +#define ADC_SMPR1_SMP1_2 (0x4U << ADC_SMPR1_SMP1_Pos) /*!< 0x00000020 */ + +#define ADC_SMPR1_SMP2_Pos (6U) +#define ADC_SMPR1_SMP2_Msk (0x7U << ADC_SMPR1_SMP2_Pos) /*!< 0x000001C0 */ +#define ADC_SMPR1_SMP2 ADC_SMPR1_SMP2_Msk /*!< ADC channel 2 sampling time selection */ +#define ADC_SMPR1_SMP2_0 (0x1U << ADC_SMPR1_SMP2_Pos) /*!< 0x00000040 */ +#define ADC_SMPR1_SMP2_1 (0x2U << ADC_SMPR1_SMP2_Pos) /*!< 0x00000080 */ +#define ADC_SMPR1_SMP2_2 (0x4U << ADC_SMPR1_SMP2_Pos) /*!< 0x00000100 */ + +#define ADC_SMPR1_SMP3_Pos (9U) +#define ADC_SMPR1_SMP3_Msk (0x7U << ADC_SMPR1_SMP3_Pos) /*!< 0x00000E00 */ +#define ADC_SMPR1_SMP3 ADC_SMPR1_SMP3_Msk /*!< ADC channel 3 sampling time selection */ +#define ADC_SMPR1_SMP3_0 (0x1U << ADC_SMPR1_SMP3_Pos) /*!< 0x00000200 */ +#define ADC_SMPR1_SMP3_1 (0x2U << ADC_SMPR1_SMP3_Pos) /*!< 0x00000400 */ +#define ADC_SMPR1_SMP3_2 (0x4U << ADC_SMPR1_SMP3_Pos) /*!< 0x00000800 */ + +#define ADC_SMPR1_SMP4_Pos (12U) +#define ADC_SMPR1_SMP4_Msk (0x7U << ADC_SMPR1_SMP4_Pos) /*!< 0x00007000 */ +#define ADC_SMPR1_SMP4 ADC_SMPR1_SMP4_Msk /*!< ADC channel 4 sampling time selection */ +#define ADC_SMPR1_SMP4_0 (0x1U << ADC_SMPR1_SMP4_Pos) /*!< 0x00001000 */ +#define ADC_SMPR1_SMP4_1 (0x2U << ADC_SMPR1_SMP4_Pos) /*!< 0x00002000 */ +#define ADC_SMPR1_SMP4_2 (0x4U << ADC_SMPR1_SMP4_Pos) /*!< 0x00004000 */ + +#define ADC_SMPR1_SMP5_Pos (15U) +#define ADC_SMPR1_SMP5_Msk (0x7U << ADC_SMPR1_SMP5_Pos) /*!< 0x00038000 */ +#define ADC_SMPR1_SMP5 ADC_SMPR1_SMP5_Msk /*!< ADC channel 5 sampling time selection */ +#define ADC_SMPR1_SMP5_0 (0x1U << ADC_SMPR1_SMP5_Pos) /*!< 0x00008000 */ +#define ADC_SMPR1_SMP5_1 (0x2U << ADC_SMPR1_SMP5_Pos) /*!< 0x00010000 */ +#define ADC_SMPR1_SMP5_2 (0x4U << ADC_SMPR1_SMP5_Pos) /*!< 0x00020000 */ + +#define ADC_SMPR1_SMP6_Pos (18U) +#define ADC_SMPR1_SMP6_Msk (0x7U << ADC_SMPR1_SMP6_Pos) /*!< 0x001C0000 */ +#define ADC_SMPR1_SMP6 ADC_SMPR1_SMP6_Msk /*!< ADC channel 6 sampling time selection */ +#define ADC_SMPR1_SMP6_0 (0x1U << ADC_SMPR1_SMP6_Pos) /*!< 0x00040000 */ +#define ADC_SMPR1_SMP6_1 (0x2U << ADC_SMPR1_SMP6_Pos) /*!< 0x00080000 */ +#define ADC_SMPR1_SMP6_2 (0x4U << ADC_SMPR1_SMP6_Pos) /*!< 0x00100000 */ + +#define ADC_SMPR1_SMP7_Pos (21U) +#define ADC_SMPR1_SMP7_Msk (0x7U << ADC_SMPR1_SMP7_Pos) /*!< 0x00E00000 */ +#define ADC_SMPR1_SMP7 ADC_SMPR1_SMP7_Msk /*!< ADC channel 7 sampling time selection */ +#define ADC_SMPR1_SMP7_0 (0x1U << ADC_SMPR1_SMP7_Pos) /*!< 0x00200000 */ +#define ADC_SMPR1_SMP7_1 (0x2U << ADC_SMPR1_SMP7_Pos) /*!< 0x00400000 */ +#define ADC_SMPR1_SMP7_2 (0x4U << ADC_SMPR1_SMP7_Pos) /*!< 0x00800000 */ + +#define ADC_SMPR1_SMP8_Pos (24U) +#define ADC_SMPR1_SMP8_Msk (0x7U << ADC_SMPR1_SMP8_Pos) /*!< 0x07000000 */ +#define ADC_SMPR1_SMP8 ADC_SMPR1_SMP8_Msk /*!< ADC channel 8 sampling time selection */ +#define ADC_SMPR1_SMP8_0 (0x1U << ADC_SMPR1_SMP8_Pos) /*!< 0x01000000 */ +#define ADC_SMPR1_SMP8_1 (0x2U << ADC_SMPR1_SMP8_Pos) /*!< 0x02000000 */ +#define ADC_SMPR1_SMP8_2 (0x4U << ADC_SMPR1_SMP8_Pos) /*!< 0x04000000 */ + +#define ADC_SMPR1_SMP9_Pos (27U) +#define ADC_SMPR1_SMP9_Msk (0x7U << ADC_SMPR1_SMP9_Pos) /*!< 0x38000000 */ +#define ADC_SMPR1_SMP9 ADC_SMPR1_SMP9_Msk /*!< ADC channel 9 sampling time selection */ +#define ADC_SMPR1_SMP9_0 (0x1U << ADC_SMPR1_SMP9_Pos) /*!< 0x08000000 */ +#define ADC_SMPR1_SMP9_1 (0x2U << ADC_SMPR1_SMP9_Pos) /*!< 0x10000000 */ +#define ADC_SMPR1_SMP9_2 (0x4U << ADC_SMPR1_SMP9_Pos) /*!< 0x20000000 */ + +#define ADC_SMPR1_SMPPLUS_Pos (31U) +#define ADC_SMPR1_SMPPLUS_Msk (0x1U << ADC_SMPR1_SMPPLUS_Pos) /*!< 0x80000000 */ +#define ADC_SMPR1_SMPPLUS ADC_SMPR1_SMPPLUS_Msk /*!< ADC channels sampling time additional setting */ + +/******************** Bit definition for ADC_SMPR2 register *****************/ +#define ADC_SMPR2_SMP10_Pos (0U) +#define ADC_SMPR2_SMP10_Msk (0x7U << ADC_SMPR2_SMP10_Pos) /*!< 0x00000007 */ +#define ADC_SMPR2_SMP10 ADC_SMPR2_SMP10_Msk /*!< ADC channel 10 sampling time selection */ +#define ADC_SMPR2_SMP10_0 (0x1U << ADC_SMPR2_SMP10_Pos) /*!< 0x00000001 */ +#define ADC_SMPR2_SMP10_1 (0x2U << ADC_SMPR2_SMP10_Pos) /*!< 0x00000002 */ +#define ADC_SMPR2_SMP10_2 (0x4U << ADC_SMPR2_SMP10_Pos) /*!< 0x00000004 */ + +#define ADC_SMPR2_SMP11_Pos (3U) +#define ADC_SMPR2_SMP11_Msk (0x7U << ADC_SMPR2_SMP11_Pos) /*!< 0x00000038 */ +#define ADC_SMPR2_SMP11 ADC_SMPR2_SMP11_Msk /*!< ADC channel 11 sampling time selection */ +#define ADC_SMPR2_SMP11_0 (0x1U << ADC_SMPR2_SMP11_Pos) /*!< 0x00000008 */ +#define ADC_SMPR2_SMP11_1 (0x2U << ADC_SMPR2_SMP11_Pos) /*!< 0x00000010 */ +#define ADC_SMPR2_SMP11_2 (0x4U << ADC_SMPR2_SMP11_Pos) /*!< 0x00000020 */ + +#define ADC_SMPR2_SMP12_Pos (6U) +#define ADC_SMPR2_SMP12_Msk (0x7U << ADC_SMPR2_SMP12_Pos) /*!< 0x000001C0 */ +#define ADC_SMPR2_SMP12 ADC_SMPR2_SMP12_Msk /*!< ADC channel 12 sampling time selection */ +#define ADC_SMPR2_SMP12_0 (0x1U << ADC_SMPR2_SMP12_Pos) /*!< 0x00000040 */ +#define ADC_SMPR2_SMP12_1 (0x2U << ADC_SMPR2_SMP12_Pos) /*!< 0x00000080 */ +#define ADC_SMPR2_SMP12_2 (0x4U << ADC_SMPR2_SMP12_Pos) /*!< 0x00000100 */ + +#define ADC_SMPR2_SMP13_Pos (9U) +#define ADC_SMPR2_SMP13_Msk (0x7U << ADC_SMPR2_SMP13_Pos) /*!< 0x00000E00 */ +#define ADC_SMPR2_SMP13 ADC_SMPR2_SMP13_Msk /*!< ADC channel 13 sampling time selection */ +#define ADC_SMPR2_SMP13_0 (0x1U << ADC_SMPR2_SMP13_Pos) /*!< 0x00000200 */ +#define ADC_SMPR2_SMP13_1 (0x2U << ADC_SMPR2_SMP13_Pos) /*!< 0x00000400 */ +#define ADC_SMPR2_SMP13_2 (0x4U << ADC_SMPR2_SMP13_Pos) /*!< 0x00000800 */ + +#define ADC_SMPR2_SMP14_Pos (12U) +#define ADC_SMPR2_SMP14_Msk (0x7U << ADC_SMPR2_SMP14_Pos) /*!< 0x00007000 */ +#define ADC_SMPR2_SMP14 ADC_SMPR2_SMP14_Msk /*!< ADC channel 14 sampling time selection */ +#define ADC_SMPR2_SMP14_0 (0x1U << ADC_SMPR2_SMP14_Pos) /*!< 0x00001000 */ +#define ADC_SMPR2_SMP14_1 (0x2U << ADC_SMPR2_SMP14_Pos) /*!< 0x00002000 */ +#define ADC_SMPR2_SMP14_2 (0x4U << ADC_SMPR2_SMP14_Pos) /*!< 0x00004000 */ + +#define ADC_SMPR2_SMP15_Pos (15U) +#define ADC_SMPR2_SMP15_Msk (0x7U << ADC_SMPR2_SMP15_Pos) /*!< 0x00038000 */ +#define ADC_SMPR2_SMP15 ADC_SMPR2_SMP15_Msk /*!< ADC channel 15 sampling time selection */ +#define ADC_SMPR2_SMP15_0 (0x1U << ADC_SMPR2_SMP15_Pos) /*!< 0x00008000 */ +#define ADC_SMPR2_SMP15_1 (0x2U << ADC_SMPR2_SMP15_Pos) /*!< 0x00010000 */ +#define ADC_SMPR2_SMP15_2 (0x4U << ADC_SMPR2_SMP15_Pos) /*!< 0x00020000 */ + +#define ADC_SMPR2_SMP16_Pos (18U) +#define ADC_SMPR2_SMP16_Msk (0x7U << ADC_SMPR2_SMP16_Pos) /*!< 0x001C0000 */ +#define ADC_SMPR2_SMP16 ADC_SMPR2_SMP16_Msk /*!< ADC channel 16 sampling time selection */ +#define ADC_SMPR2_SMP16_0 (0x1U << ADC_SMPR2_SMP16_Pos) /*!< 0x00040000 */ +#define ADC_SMPR2_SMP16_1 (0x2U << ADC_SMPR2_SMP16_Pos) /*!< 0x00080000 */ +#define ADC_SMPR2_SMP16_2 (0x4U << ADC_SMPR2_SMP16_Pos) /*!< 0x00100000 */ + +#define ADC_SMPR2_SMP17_Pos (21U) +#define ADC_SMPR2_SMP17_Msk (0x7U << ADC_SMPR2_SMP17_Pos) /*!< 0x00E00000 */ +#define ADC_SMPR2_SMP17 ADC_SMPR2_SMP17_Msk /*!< ADC channel 17 sampling time selection */ +#define ADC_SMPR2_SMP17_0 (0x1U << ADC_SMPR2_SMP17_Pos) /*!< 0x00200000 */ +#define ADC_SMPR2_SMP17_1 (0x2U << ADC_SMPR2_SMP17_Pos) /*!< 0x00400000 */ +#define ADC_SMPR2_SMP17_2 (0x4U << ADC_SMPR2_SMP17_Pos) /*!< 0x00800000 */ + +#define ADC_SMPR2_SMP18_Pos (24U) +#define ADC_SMPR2_SMP18_Msk (0x7U << ADC_SMPR2_SMP18_Pos) /*!< 0x07000000 */ +#define ADC_SMPR2_SMP18 ADC_SMPR2_SMP18_Msk /*!< ADC channel 18 sampling time selection */ +#define ADC_SMPR2_SMP18_0 (0x1U << ADC_SMPR2_SMP18_Pos) /*!< 0x01000000 */ +#define ADC_SMPR2_SMP18_1 (0x2U << ADC_SMPR2_SMP18_Pos) /*!< 0x02000000 */ +#define ADC_SMPR2_SMP18_2 (0x4U << ADC_SMPR2_SMP18_Pos) /*!< 0x04000000 */ + +/******************** Bit definition for ADC_TR1 register *******************/ +#define ADC_TR1_LT1_Pos (0U) +#define ADC_TR1_LT1_Msk (0xFFFU << ADC_TR1_LT1_Pos) /*!< 0x00000FFF */ +#define ADC_TR1_LT1 ADC_TR1_LT1_Msk /*!< ADC analog watchdog 1 threshold low */ +#define ADC_TR1_LT1_0 (0x001U << ADC_TR1_LT1_Pos) /*!< 0x00000001 */ +#define ADC_TR1_LT1_1 (0x002U << ADC_TR1_LT1_Pos) /*!< 0x00000002 */ +#define ADC_TR1_LT1_2 (0x004U << ADC_TR1_LT1_Pos) /*!< 0x00000004 */ +#define ADC_TR1_LT1_3 (0x008U << ADC_TR1_LT1_Pos) /*!< 0x00000008 */ +#define ADC_TR1_LT1_4 (0x010U << ADC_TR1_LT1_Pos) /*!< 0x00000010 */ +#define ADC_TR1_LT1_5 (0x020U << ADC_TR1_LT1_Pos) /*!< 0x00000020 */ +#define ADC_TR1_LT1_6 (0x040U << ADC_TR1_LT1_Pos) /*!< 0x00000040 */ +#define ADC_TR1_LT1_7 (0x080U << ADC_TR1_LT1_Pos) /*!< 0x00000080 */ +#define ADC_TR1_LT1_8 (0x100U << ADC_TR1_LT1_Pos) /*!< 0x00000100 */ +#define ADC_TR1_LT1_9 (0x200U << ADC_TR1_LT1_Pos) /*!< 0x00000200 */ +#define ADC_TR1_LT1_10 (0x400U << ADC_TR1_LT1_Pos) /*!< 0x00000400 */ +#define ADC_TR1_LT1_11 (0x800U << ADC_TR1_LT1_Pos) /*!< 0x00000800 */ + +#define ADC_TR1_HT1_Pos (16U) +#define ADC_TR1_HT1_Msk (0xFFFU << ADC_TR1_HT1_Pos) /*!< 0x0FFF0000 */ +#define ADC_TR1_HT1 ADC_TR1_HT1_Msk /*!< ADC Analog watchdog 1 threshold high */ +#define ADC_TR1_HT1_0 (0x001U << ADC_TR1_HT1_Pos) /*!< 0x00010000 */ +#define ADC_TR1_HT1_1 (0x002U << ADC_TR1_HT1_Pos) /*!< 0x00020000 */ +#define ADC_TR1_HT1_2 (0x004U << ADC_TR1_HT1_Pos) /*!< 0x00040000 */ +#define ADC_TR1_HT1_3 (0x008U << ADC_TR1_HT1_Pos) /*!< 0x00080000 */ +#define ADC_TR1_HT1_4 (0x010U << ADC_TR1_HT1_Pos) /*!< 0x00100000 */ +#define ADC_TR1_HT1_5 (0x020U << ADC_TR1_HT1_Pos) /*!< 0x00200000 */ +#define ADC_TR1_HT1_6 (0x040U << ADC_TR1_HT1_Pos) /*!< 0x00400000 */ +#define ADC_TR1_HT1_7 (0x080U << ADC_TR1_HT1_Pos) /*!< 0x00800000 */ +#define ADC_TR1_HT1_8 (0x100U << ADC_TR1_HT1_Pos) /*!< 0x01000000 */ +#define ADC_TR1_HT1_9 (0x200U << ADC_TR1_HT1_Pos) /*!< 0x02000000 */ +#define ADC_TR1_HT1_10 (0x400U << ADC_TR1_HT1_Pos) /*!< 0x04000000 */ +#define ADC_TR1_HT1_11 (0x800U << ADC_TR1_HT1_Pos) /*!< 0x08000000 */ + +/******************** Bit definition for ADC_TR2 register *******************/ +#define ADC_TR2_LT2_Pos (0U) +#define ADC_TR2_LT2_Msk (0xFFU << ADC_TR2_LT2_Pos) /*!< 0x000000FF */ +#define ADC_TR2_LT2 ADC_TR2_LT2_Msk /*!< ADC analog watchdog 2 threshold low */ +#define ADC_TR2_LT2_0 (0x01U << ADC_TR2_LT2_Pos) /*!< 0x00000001 */ +#define ADC_TR2_LT2_1 (0x02U << ADC_TR2_LT2_Pos) /*!< 0x00000002 */ +#define ADC_TR2_LT2_2 (0x04U << ADC_TR2_LT2_Pos) /*!< 0x00000004 */ +#define ADC_TR2_LT2_3 (0x08U << ADC_TR2_LT2_Pos) /*!< 0x00000008 */ +#define ADC_TR2_LT2_4 (0x10U << ADC_TR2_LT2_Pos) /*!< 0x00000010 */ +#define ADC_TR2_LT2_5 (0x20U << ADC_TR2_LT2_Pos) /*!< 0x00000020 */ +#define ADC_TR2_LT2_6 (0x40U << ADC_TR2_LT2_Pos) /*!< 0x00000040 */ +#define ADC_TR2_LT2_7 (0x80U << ADC_TR2_LT2_Pos) /*!< 0x00000080 */ + +#define ADC_TR2_HT2_Pos (16U) +#define ADC_TR2_HT2_Msk (0xFFU << ADC_TR2_HT2_Pos) /*!< 0x00FF0000 */ +#define ADC_TR2_HT2 ADC_TR2_HT2_Msk /*!< ADC analog watchdog 2 threshold high */ +#define ADC_TR2_HT2_0 (0x01U << ADC_TR2_HT2_Pos) /*!< 0x00010000 */ +#define ADC_TR2_HT2_1 (0x02U << ADC_TR2_HT2_Pos) /*!< 0x00020000 */ +#define ADC_TR2_HT2_2 (0x04U << ADC_TR2_HT2_Pos) /*!< 0x00040000 */ +#define ADC_TR2_HT2_3 (0x08U << ADC_TR2_HT2_Pos) /*!< 0x00080000 */ +#define ADC_TR2_HT2_4 (0x10U << ADC_TR2_HT2_Pos) /*!< 0x00100000 */ +#define ADC_TR2_HT2_5 (0x20U << ADC_TR2_HT2_Pos) /*!< 0x00200000 */ +#define ADC_TR2_HT2_6 (0x40U << ADC_TR2_HT2_Pos) /*!< 0x00400000 */ +#define ADC_TR2_HT2_7 (0x80U << ADC_TR2_HT2_Pos) /*!< 0x00800000 */ + +/******************** Bit definition for ADC_TR3 register *******************/ +#define ADC_TR3_LT3_Pos (0U) +#define ADC_TR3_LT3_Msk (0xFFU << ADC_TR3_LT3_Pos) /*!< 0x000000FF */ +#define ADC_TR3_LT3 ADC_TR3_LT3_Msk /*!< ADC analog watchdog 3 threshold low */ +#define ADC_TR3_LT3_0 (0x01U << ADC_TR3_LT3_Pos) /*!< 0x00000001 */ +#define ADC_TR3_LT3_1 (0x02U << ADC_TR3_LT3_Pos) /*!< 0x00000002 */ +#define ADC_TR3_LT3_2 (0x04U << ADC_TR3_LT3_Pos) /*!< 0x00000004 */ +#define ADC_TR3_LT3_3 (0x08U << ADC_TR3_LT3_Pos) /*!< 0x00000008 */ +#define ADC_TR3_LT3_4 (0x10U << ADC_TR3_LT3_Pos) /*!< 0x00000010 */ +#define ADC_TR3_LT3_5 (0x20U << ADC_TR3_LT3_Pos) /*!< 0x00000020 */ +#define ADC_TR3_LT3_6 (0x40U << ADC_TR3_LT3_Pos) /*!< 0x00000040 */ +#define ADC_TR3_LT3_7 (0x80U << ADC_TR3_LT3_Pos) /*!< 0x00000080 */ + +#define ADC_TR3_HT3_Pos (16U) +#define ADC_TR3_HT3_Msk (0xFFU << ADC_TR3_HT3_Pos) /*!< 0x00FF0000 */ +#define ADC_TR3_HT3 ADC_TR3_HT3_Msk /*!< ADC analog watchdog 3 threshold high */ +#define ADC_TR3_HT3_0 (0x01U << ADC_TR3_HT3_Pos) /*!< 0x00010000 */ +#define ADC_TR3_HT3_1 (0x02U << ADC_TR3_HT3_Pos) /*!< 0x00020000 */ +#define ADC_TR3_HT3_2 (0x04U << ADC_TR3_HT3_Pos) /*!< 0x00040000 */ +#define ADC_TR3_HT3_3 (0x08U << ADC_TR3_HT3_Pos) /*!< 0x00080000 */ +#define ADC_TR3_HT3_4 (0x10U << ADC_TR3_HT3_Pos) /*!< 0x00100000 */ +#define ADC_TR3_HT3_5 (0x20U << ADC_TR3_HT3_Pos) /*!< 0x00200000 */ +#define ADC_TR3_HT3_6 (0x40U << ADC_TR3_HT3_Pos) /*!< 0x00400000 */ +#define ADC_TR3_HT3_7 (0x80U << ADC_TR3_HT3_Pos) /*!< 0x00800000 */ + +/******************** Bit definition for ADC_SQR1 register ******************/ +#define ADC_SQR1_L_Pos (0U) +#define ADC_SQR1_L_Msk (0xFU << ADC_SQR1_L_Pos) /*!< 0x0000000F */ +#define ADC_SQR1_L ADC_SQR1_L_Msk /*!< ADC group regular sequencer scan length */ +#define ADC_SQR1_L_0 (0x1U << ADC_SQR1_L_Pos) /*!< 0x00000001 */ +#define ADC_SQR1_L_1 (0x2U << ADC_SQR1_L_Pos) /*!< 0x00000002 */ +#define ADC_SQR1_L_2 (0x4U << ADC_SQR1_L_Pos) /*!< 0x00000004 */ +#define ADC_SQR1_L_3 (0x8U << ADC_SQR1_L_Pos) /*!< 0x00000008 */ + +#define ADC_SQR1_SQ1_Pos (6U) +#define ADC_SQR1_SQ1_Msk (0x1FU << ADC_SQR1_SQ1_Pos) /*!< 0x000007C0 */ +#define ADC_SQR1_SQ1 ADC_SQR1_SQ1_Msk /*!< ADC group regular sequencer rank 1 */ +#define ADC_SQR1_SQ1_0 (0x01U << ADC_SQR1_SQ1_Pos) /*!< 0x00000040 */ +#define ADC_SQR1_SQ1_1 (0x02U << ADC_SQR1_SQ1_Pos) /*!< 0x00000080 */ +#define ADC_SQR1_SQ1_2 (0x04U << ADC_SQR1_SQ1_Pos) /*!< 0x00000100 */ +#define ADC_SQR1_SQ1_3 (0x08U << ADC_SQR1_SQ1_Pos) /*!< 0x00000200 */ +#define ADC_SQR1_SQ1_4 (0x10U << ADC_SQR1_SQ1_Pos) /*!< 0x00000400 */ + +#define ADC_SQR1_SQ2_Pos (12U) +#define ADC_SQR1_SQ2_Msk (0x1FU << ADC_SQR1_SQ2_Pos) /*!< 0x0001F000 */ +#define ADC_SQR1_SQ2 ADC_SQR1_SQ2_Msk /*!< ADC group regular sequencer rank 2 */ +#define ADC_SQR1_SQ2_0 (0x01U << ADC_SQR1_SQ2_Pos) /*!< 0x00001000 */ +#define ADC_SQR1_SQ2_1 (0x02U << ADC_SQR1_SQ2_Pos) /*!< 0x00002000 */ +#define ADC_SQR1_SQ2_2 (0x04U << ADC_SQR1_SQ2_Pos) /*!< 0x00004000 */ +#define ADC_SQR1_SQ2_3 (0x08U << ADC_SQR1_SQ2_Pos) /*!< 0x00008000 */ +#define ADC_SQR1_SQ2_4 (0x10U << ADC_SQR1_SQ2_Pos) /*!< 0x00010000 */ + +#define ADC_SQR1_SQ3_Pos (18U) +#define ADC_SQR1_SQ3_Msk (0x1FU << ADC_SQR1_SQ3_Pos) /*!< 0x007C0000 */ +#define ADC_SQR1_SQ3 ADC_SQR1_SQ3_Msk /*!< ADC group regular sequencer rank 3 */ +#define ADC_SQR1_SQ3_0 (0x01U << ADC_SQR1_SQ3_Pos) /*!< 0x00040000 */ +#define ADC_SQR1_SQ3_1 (0x02U << ADC_SQR1_SQ3_Pos) /*!< 0x00080000 */ +#define ADC_SQR1_SQ3_2 (0x04U << ADC_SQR1_SQ3_Pos) /*!< 0x00100000 */ +#define ADC_SQR1_SQ3_3 (0x08U << ADC_SQR1_SQ3_Pos) /*!< 0x00200000 */ +#define ADC_SQR1_SQ3_4 (0x10U << ADC_SQR1_SQ3_Pos) /*!< 0x00400000 */ + +#define ADC_SQR1_SQ4_Pos (24U) +#define ADC_SQR1_SQ4_Msk (0x1FU << ADC_SQR1_SQ4_Pos) /*!< 0x1F000000 */ +#define ADC_SQR1_SQ4 ADC_SQR1_SQ4_Msk /*!< ADC group regular sequencer rank 4 */ +#define ADC_SQR1_SQ4_0 (0x01U << ADC_SQR1_SQ4_Pos) /*!< 0x01000000 */ +#define ADC_SQR1_SQ4_1 (0x02U << ADC_SQR1_SQ4_Pos) /*!< 0x02000000 */ +#define ADC_SQR1_SQ4_2 (0x04U << ADC_SQR1_SQ4_Pos) /*!< 0x04000000 */ +#define ADC_SQR1_SQ4_3 (0x08U << ADC_SQR1_SQ4_Pos) /*!< 0x08000000 */ +#define ADC_SQR1_SQ4_4 (0x10U << ADC_SQR1_SQ4_Pos) /*!< 0x10000000 */ + +/******************** Bit definition for ADC_SQR2 register ******************/ +#define ADC_SQR2_SQ5_Pos (0U) +#define ADC_SQR2_SQ5_Msk (0x1FU << ADC_SQR2_SQ5_Pos) /*!< 0x0000001F */ +#define ADC_SQR2_SQ5 ADC_SQR2_SQ5_Msk /*!< ADC group regular sequencer rank 5 */ +#define ADC_SQR2_SQ5_0 (0x01U << ADC_SQR2_SQ5_Pos) /*!< 0x00000001 */ +#define ADC_SQR2_SQ5_1 (0x02U << ADC_SQR2_SQ5_Pos) /*!< 0x00000002 */ +#define ADC_SQR2_SQ5_2 (0x04U << ADC_SQR2_SQ5_Pos) /*!< 0x00000004 */ +#define ADC_SQR2_SQ5_3 (0x08U << ADC_SQR2_SQ5_Pos) /*!< 0x00000008 */ +#define ADC_SQR2_SQ5_4 (0x10U << ADC_SQR2_SQ5_Pos) /*!< 0x00000010 */ + +#define ADC_SQR2_SQ6_Pos (6U) +#define ADC_SQR2_SQ6_Msk (0x1FU << ADC_SQR2_SQ6_Pos) /*!< 0x000007C0 */ +#define ADC_SQR2_SQ6 ADC_SQR2_SQ6_Msk /*!< ADC group regular sequencer rank 6 */ +#define ADC_SQR2_SQ6_0 (0x01U << ADC_SQR2_SQ6_Pos) /*!< 0x00000040 */ +#define ADC_SQR2_SQ6_1 (0x02U << ADC_SQR2_SQ6_Pos) /*!< 0x00000080 */ +#define ADC_SQR2_SQ6_2 (0x04U << ADC_SQR2_SQ6_Pos) /*!< 0x00000100 */ +#define ADC_SQR2_SQ6_3 (0x08U << ADC_SQR2_SQ6_Pos) /*!< 0x00000200 */ +#define ADC_SQR2_SQ6_4 (0x10U << ADC_SQR2_SQ6_Pos) /*!< 0x00000400 */ + +#define ADC_SQR2_SQ7_Pos (12U) +#define ADC_SQR2_SQ7_Msk (0x1FU << ADC_SQR2_SQ7_Pos) /*!< 0x0001F000 */ +#define ADC_SQR2_SQ7 ADC_SQR2_SQ7_Msk /*!< ADC group regular sequencer rank 7 */ +#define ADC_SQR2_SQ7_0 (0x01U << ADC_SQR2_SQ7_Pos) /*!< 0x00001000 */ +#define ADC_SQR2_SQ7_1 (0x02U << ADC_SQR2_SQ7_Pos) /*!< 0x00002000 */ +#define ADC_SQR2_SQ7_2 (0x04U << ADC_SQR2_SQ7_Pos) /*!< 0x00004000 */ +#define ADC_SQR2_SQ7_3 (0x08U << ADC_SQR2_SQ7_Pos) /*!< 0x00008000 */ +#define ADC_SQR2_SQ7_4 (0x10U << ADC_SQR2_SQ7_Pos) /*!< 0x00010000 */ + +#define ADC_SQR2_SQ8_Pos (18U) +#define ADC_SQR2_SQ8_Msk (0x1FU << ADC_SQR2_SQ8_Pos) /*!< 0x007C0000 */ +#define ADC_SQR2_SQ8 ADC_SQR2_SQ8_Msk /*!< ADC group regular sequencer rank 8 */ +#define ADC_SQR2_SQ8_0 (0x01U << ADC_SQR2_SQ8_Pos) /*!< 0x00040000 */ +#define ADC_SQR2_SQ8_1 (0x02U << ADC_SQR2_SQ8_Pos) /*!< 0x00080000 */ +#define ADC_SQR2_SQ8_2 (0x04U << ADC_SQR2_SQ8_Pos) /*!< 0x00100000 */ +#define ADC_SQR2_SQ8_3 (0x08U << ADC_SQR2_SQ8_Pos) /*!< 0x00200000 */ +#define ADC_SQR2_SQ8_4 (0x10U << ADC_SQR2_SQ8_Pos) /*!< 0x00400000 */ + +#define ADC_SQR2_SQ9_Pos (24U) +#define ADC_SQR2_SQ9_Msk (0x1FU << ADC_SQR2_SQ9_Pos) /*!< 0x1F000000 */ +#define ADC_SQR2_SQ9 ADC_SQR2_SQ9_Msk /*!< ADC group regular sequencer rank 9 */ +#define ADC_SQR2_SQ9_0 (0x01U << ADC_SQR2_SQ9_Pos) /*!< 0x01000000 */ +#define ADC_SQR2_SQ9_1 (0x02U << ADC_SQR2_SQ9_Pos) /*!< 0x02000000 */ +#define ADC_SQR2_SQ9_2 (0x04U << ADC_SQR2_SQ9_Pos) /*!< 0x04000000 */ +#define ADC_SQR2_SQ9_3 (0x08U << ADC_SQR2_SQ9_Pos) /*!< 0x08000000 */ +#define ADC_SQR2_SQ9_4 (0x10U << ADC_SQR2_SQ9_Pos) /*!< 0x10000000 */ + +/******************** Bit definition for ADC_SQR3 register ******************/ +#define ADC_SQR3_SQ10_Pos (0U) +#define ADC_SQR3_SQ10_Msk (0x1FU << ADC_SQR3_SQ10_Pos) /*!< 0x0000001F */ +#define ADC_SQR3_SQ10 ADC_SQR3_SQ10_Msk /*!< ADC group regular sequencer rank 10 */ +#define ADC_SQR3_SQ10_0 (0x01U << ADC_SQR3_SQ10_Pos) /*!< 0x00000001 */ +#define ADC_SQR3_SQ10_1 (0x02U << ADC_SQR3_SQ10_Pos) /*!< 0x00000002 */ +#define ADC_SQR3_SQ10_2 (0x04U << ADC_SQR3_SQ10_Pos) /*!< 0x00000004 */ +#define ADC_SQR3_SQ10_3 (0x08U << ADC_SQR3_SQ10_Pos) /*!< 0x00000008 */ +#define ADC_SQR3_SQ10_4 (0x10U << ADC_SQR3_SQ10_Pos) /*!< 0x00000010 */ + +#define ADC_SQR3_SQ11_Pos (6U) +#define ADC_SQR3_SQ11_Msk (0x1FU << ADC_SQR3_SQ11_Pos) /*!< 0x000007C0 */ +#define ADC_SQR3_SQ11 ADC_SQR3_SQ11_Msk /*!< ADC group regular sequencer rank 11 */ +#define ADC_SQR3_SQ11_0 (0x01U << ADC_SQR3_SQ11_Pos) /*!< 0x00000040 */ +#define ADC_SQR3_SQ11_1 (0x02U << ADC_SQR3_SQ11_Pos) /*!< 0x00000080 */ +#define ADC_SQR3_SQ11_2 (0x04U << ADC_SQR3_SQ11_Pos) /*!< 0x00000100 */ +#define ADC_SQR3_SQ11_3 (0x08U << ADC_SQR3_SQ11_Pos) /*!< 0x00000200 */ +#define ADC_SQR3_SQ11_4 (0x10U << ADC_SQR3_SQ11_Pos) /*!< 0x00000400 */ + +#define ADC_SQR3_SQ12_Pos (12U) +#define ADC_SQR3_SQ12_Msk (0x1FU << ADC_SQR3_SQ12_Pos) /*!< 0x0001F000 */ +#define ADC_SQR3_SQ12 ADC_SQR3_SQ12_Msk /*!< ADC group regular sequencer rank 12 */ +#define ADC_SQR3_SQ12_0 (0x01U << ADC_SQR3_SQ12_Pos) /*!< 0x00001000 */ +#define ADC_SQR3_SQ12_1 (0x02U << ADC_SQR3_SQ12_Pos) /*!< 0x00002000 */ +#define ADC_SQR3_SQ12_2 (0x04U << ADC_SQR3_SQ12_Pos) /*!< 0x00004000 */ +#define ADC_SQR3_SQ12_3 (0x08U << ADC_SQR3_SQ12_Pos) /*!< 0x00008000 */ +#define ADC_SQR3_SQ12_4 (0x10U << ADC_SQR3_SQ12_Pos) /*!< 0x00010000 */ + +#define ADC_SQR3_SQ13_Pos (18U) +#define ADC_SQR3_SQ13_Msk (0x1FU << ADC_SQR3_SQ13_Pos) /*!< 0x007C0000 */ +#define ADC_SQR3_SQ13 ADC_SQR3_SQ13_Msk /*!< ADC group regular sequencer rank 13 */ +#define ADC_SQR3_SQ13_0 (0x01U << ADC_SQR3_SQ13_Pos) /*!< 0x00040000 */ +#define ADC_SQR3_SQ13_1 (0x02U << ADC_SQR3_SQ13_Pos) /*!< 0x00080000 */ +#define ADC_SQR3_SQ13_2 (0x04U << ADC_SQR3_SQ13_Pos) /*!< 0x00100000 */ +#define ADC_SQR3_SQ13_3 (0x08U << ADC_SQR3_SQ13_Pos) /*!< 0x00200000 */ +#define ADC_SQR3_SQ13_4 (0x10U << ADC_SQR3_SQ13_Pos) /*!< 0x00400000 */ + +#define ADC_SQR3_SQ14_Pos (24U) +#define ADC_SQR3_SQ14_Msk (0x1FU << ADC_SQR3_SQ14_Pos) /*!< 0x1F000000 */ +#define ADC_SQR3_SQ14 ADC_SQR3_SQ14_Msk /*!< ADC group regular sequencer rank 14 */ +#define ADC_SQR3_SQ14_0 (0x01U << ADC_SQR3_SQ14_Pos) /*!< 0x01000000 */ +#define ADC_SQR3_SQ14_1 (0x02U << ADC_SQR3_SQ14_Pos) /*!< 0x02000000 */ +#define ADC_SQR3_SQ14_2 (0x04U << ADC_SQR3_SQ14_Pos) /*!< 0x04000000 */ +#define ADC_SQR3_SQ14_3 (0x08U << ADC_SQR3_SQ14_Pos) /*!< 0x08000000 */ +#define ADC_SQR3_SQ14_4 (0x10U << ADC_SQR3_SQ14_Pos) /*!< 0x10000000 */ + +/******************** Bit definition for ADC_SQR4 register ******************/ +#define ADC_SQR4_SQ15_Pos (0U) +#define ADC_SQR4_SQ15_Msk (0x1FU << ADC_SQR4_SQ15_Pos) /*!< 0x0000001F */ +#define ADC_SQR4_SQ15 ADC_SQR4_SQ15_Msk /*!< ADC group regular sequencer rank 15 */ +#define ADC_SQR4_SQ15_0 (0x01U << ADC_SQR4_SQ15_Pos) /*!< 0x00000001 */ +#define ADC_SQR4_SQ15_1 (0x02U << ADC_SQR4_SQ15_Pos) /*!< 0x00000002 */ +#define ADC_SQR4_SQ15_2 (0x04U << ADC_SQR4_SQ15_Pos) /*!< 0x00000004 */ +#define ADC_SQR4_SQ15_3 (0x08U << ADC_SQR4_SQ15_Pos) /*!< 0x00000008 */ +#define ADC_SQR4_SQ15_4 (0x10U << ADC_SQR4_SQ15_Pos) /*!< 0x00000010 */ + +#define ADC_SQR4_SQ16_Pos (6U) +#define ADC_SQR4_SQ16_Msk (0x1FU << ADC_SQR4_SQ16_Pos) /*!< 0x000007C0 */ +#define ADC_SQR4_SQ16 ADC_SQR4_SQ16_Msk /*!< ADC group regular sequencer rank 16 */ +#define ADC_SQR4_SQ16_0 (0x01U << ADC_SQR4_SQ16_Pos) /*!< 0x00000040 */ +#define ADC_SQR4_SQ16_1 (0x02U << ADC_SQR4_SQ16_Pos) /*!< 0x00000080 */ +#define ADC_SQR4_SQ16_2 (0x04U << ADC_SQR4_SQ16_Pos) /*!< 0x00000100 */ +#define ADC_SQR4_SQ16_3 (0x08U << ADC_SQR4_SQ16_Pos) /*!< 0x00000200 */ +#define ADC_SQR4_SQ16_4 (0x10U << ADC_SQR4_SQ16_Pos) /*!< 0x00000400 */ + +/******************** Bit definition for ADC_DR register ********************/ +#define ADC_DR_RDATA_Pos (0U) +#define ADC_DR_RDATA_Msk (0xFFFFU << ADC_DR_RDATA_Pos) /*!< 0x0000FFFF */ +#define ADC_DR_RDATA ADC_DR_RDATA_Msk /*!< ADC group regular conversion data */ +#define ADC_DR_RDATA_0 (0x0001U << ADC_DR_RDATA_Pos) /*!< 0x00000001 */ +#define ADC_DR_RDATA_1 (0x0002U << ADC_DR_RDATA_Pos) /*!< 0x00000002 */ +#define ADC_DR_RDATA_2 (0x0004U << ADC_DR_RDATA_Pos) /*!< 0x00000004 */ +#define ADC_DR_RDATA_3 (0x0008U << ADC_DR_RDATA_Pos) /*!< 0x00000008 */ +#define ADC_DR_RDATA_4 (0x0010U << ADC_DR_RDATA_Pos) /*!< 0x00000010 */ +#define ADC_DR_RDATA_5 (0x0020U << ADC_DR_RDATA_Pos) /*!< 0x00000020 */ +#define ADC_DR_RDATA_6 (0x0040U << ADC_DR_RDATA_Pos) /*!< 0x00000040 */ +#define ADC_DR_RDATA_7 (0x0080U << ADC_DR_RDATA_Pos) /*!< 0x00000080 */ +#define ADC_DR_RDATA_8 (0x0100U << ADC_DR_RDATA_Pos) /*!< 0x00000100 */ +#define ADC_DR_RDATA_9 (0x0200U << ADC_DR_RDATA_Pos) /*!< 0x00000200 */ +#define ADC_DR_RDATA_10 (0x0400U << ADC_DR_RDATA_Pos) /*!< 0x00000400 */ +#define ADC_DR_RDATA_11 (0x0800U << ADC_DR_RDATA_Pos) /*!< 0x00000800 */ +#define ADC_DR_RDATA_12 (0x1000U << ADC_DR_RDATA_Pos) /*!< 0x00001000 */ +#define ADC_DR_RDATA_13 (0x2000U << ADC_DR_RDATA_Pos) /*!< 0x00002000 */ +#define ADC_DR_RDATA_14 (0x4000U << ADC_DR_RDATA_Pos) /*!< 0x00004000 */ +#define ADC_DR_RDATA_15 (0x8000U << ADC_DR_RDATA_Pos) /*!< 0x00008000 */ + +/******************** Bit definition for ADC_JSQR register ******************/ +#define ADC_JSQR_JL_Pos (0U) +#define ADC_JSQR_JL_Msk (0x3U << ADC_JSQR_JL_Pos) /*!< 0x00000003 */ +#define ADC_JSQR_JL ADC_JSQR_JL_Msk /*!< ADC group injected sequencer scan length */ +#define ADC_JSQR_JL_0 (0x1U << ADC_JSQR_JL_Pos) /*!< 0x00000001 */ +#define ADC_JSQR_JL_1 (0x2U << ADC_JSQR_JL_Pos) /*!< 0x00000002 */ + +#define ADC_JSQR_JEXTSEL_Pos (2U) +#define ADC_JSQR_JEXTSEL_Msk (0xFU << ADC_JSQR_JEXTSEL_Pos) /*!< 0x0000003C */ +#define ADC_JSQR_JEXTSEL ADC_JSQR_JEXTSEL_Msk /*!< ADC group injected external trigger source */ +#define ADC_JSQR_JEXTSEL_0 (0x1U << ADC_JSQR_JEXTSEL_Pos) /*!< 0x00000004 */ +#define ADC_JSQR_JEXTSEL_1 (0x2U << ADC_JSQR_JEXTSEL_Pos) /*!< 0x00000008 */ +#define ADC_JSQR_JEXTSEL_2 (0x4U << ADC_JSQR_JEXTSEL_Pos) /*!< 0x00000010 */ +#define ADC_JSQR_JEXTSEL_3 (0x8U << ADC_JSQR_JEXTSEL_Pos) /*!< 0x00000020 */ + +#define ADC_JSQR_JEXTEN_Pos (6U) +#define ADC_JSQR_JEXTEN_Msk (0x3U << ADC_JSQR_JEXTEN_Pos) /*!< 0x000000C0 */ +#define ADC_JSQR_JEXTEN ADC_JSQR_JEXTEN_Msk /*!< ADC group injected external trigger polarity */ +#define ADC_JSQR_JEXTEN_0 (0x1U << ADC_JSQR_JEXTEN_Pos) /*!< 0x00000040 */ +#define ADC_JSQR_JEXTEN_1 (0x2U << ADC_JSQR_JEXTEN_Pos) /*!< 0x00000080 */ + +#define ADC_JSQR_JSQ1_Pos (8U) +#define ADC_JSQR_JSQ1_Msk (0x1FU << ADC_JSQR_JSQ1_Pos) /*!< 0x00001F00 */ +#define ADC_JSQR_JSQ1 ADC_JSQR_JSQ1_Msk /*!< ADC group injected sequencer rank 1 */ +#define ADC_JSQR_JSQ1_0 (0x01U << ADC_JSQR_JSQ1_Pos) /*!< 0x00000100 */ +#define ADC_JSQR_JSQ1_1 (0x02U << ADC_JSQR_JSQ1_Pos) /*!< 0x00000200 */ +#define ADC_JSQR_JSQ1_2 (0x04U << ADC_JSQR_JSQ1_Pos) /*!< 0x00000400 */ +#define ADC_JSQR_JSQ1_3 (0x08U << ADC_JSQR_JSQ1_Pos) /*!< 0x00000800 */ +#define ADC_JSQR_JSQ1_4 (0x10U << ADC_JSQR_JSQ1_Pos) /*!< 0x00001000 */ + +#define ADC_JSQR_JSQ2_Pos (14U) +#define ADC_JSQR_JSQ2_Msk (0x1FU << ADC_JSQR_JSQ2_Pos) /*!< 0x0007C000 */ +#define ADC_JSQR_JSQ2 ADC_JSQR_JSQ2_Msk /*!< ADC group injected sequencer rank 2 */ +#define ADC_JSQR_JSQ2_0 (0x01U << ADC_JSQR_JSQ2_Pos) /*!< 0x00004000 */ +#define ADC_JSQR_JSQ2_1 (0x02U << ADC_JSQR_JSQ2_Pos) /*!< 0x00008000 */ +#define ADC_JSQR_JSQ2_2 (0x04U << ADC_JSQR_JSQ2_Pos) /*!< 0x00010000 */ +#define ADC_JSQR_JSQ2_3 (0x08U << ADC_JSQR_JSQ2_Pos) /*!< 0x00020000 */ +#define ADC_JSQR_JSQ2_4 (0x10U << ADC_JSQR_JSQ2_Pos) /*!< 0x00040000 */ + +#define ADC_JSQR_JSQ3_Pos (20U) +#define ADC_JSQR_JSQ3_Msk (0x1FU << ADC_JSQR_JSQ3_Pos) /*!< 0x01F00000 */ +#define ADC_JSQR_JSQ3 ADC_JSQR_JSQ3_Msk /*!< ADC group injected sequencer rank 3 */ +#define ADC_JSQR_JSQ3_0 (0x01U << ADC_JSQR_JSQ3_Pos) /*!< 0x00100000 */ +#define ADC_JSQR_JSQ3_1 (0x02U << ADC_JSQR_JSQ3_Pos) /*!< 0x00200000 */ +#define ADC_JSQR_JSQ3_2 (0x04U << ADC_JSQR_JSQ3_Pos) /*!< 0x00400000 */ +#define ADC_JSQR_JSQ3_3 (0x08U << ADC_JSQR_JSQ3_Pos) /*!< 0x00800000 */ +#define ADC_JSQR_JSQ3_4 (0x10U << ADC_JSQR_JSQ3_Pos) /*!< 0x01000000 */ + +#define ADC_JSQR_JSQ4_Pos (26U) +#define ADC_JSQR_JSQ4_Msk (0x1FU << ADC_JSQR_JSQ4_Pos) /*!< 0x7C000000 */ +#define ADC_JSQR_JSQ4 ADC_JSQR_JSQ4_Msk /*!< ADC group injected sequencer rank 4 */ +#define ADC_JSQR_JSQ4_0 (0x01U << ADC_JSQR_JSQ4_Pos) /*!< 0x04000000 */ +#define ADC_JSQR_JSQ4_1 (0x02U << ADC_JSQR_JSQ4_Pos) /*!< 0x08000000 */ +#define ADC_JSQR_JSQ4_2 (0x04U << ADC_JSQR_JSQ4_Pos) /*!< 0x10000000 */ +#define ADC_JSQR_JSQ4_3 (0x08U << ADC_JSQR_JSQ4_Pos) /*!< 0x20000000 */ +#define ADC_JSQR_JSQ4_4 (0x10U << ADC_JSQR_JSQ4_Pos) /*!< 0x40000000 */ + +/******************** Bit definition for ADC_OFR1 register ******************/ +#define ADC_OFR1_OFFSET1_Pos (0U) +#define ADC_OFR1_OFFSET1_Msk (0xFFFU << ADC_OFR1_OFFSET1_Pos) /*!< 0x00000FFF */ +#define ADC_OFR1_OFFSET1 ADC_OFR1_OFFSET1_Msk /*!< ADC offset number 1 offset level */ +#define ADC_OFR1_OFFSET1_0 (0x001U << ADC_OFR1_OFFSET1_Pos) /*!< 0x00000001 */ +#define ADC_OFR1_OFFSET1_1 (0x002U << ADC_OFR1_OFFSET1_Pos) /*!< 0x00000002 */ +#define ADC_OFR1_OFFSET1_2 (0x004U << ADC_OFR1_OFFSET1_Pos) /*!< 0x00000004 */ +#define ADC_OFR1_OFFSET1_3 (0x008U << ADC_OFR1_OFFSET1_Pos) /*!< 0x00000008 */ +#define ADC_OFR1_OFFSET1_4 (0x010U << ADC_OFR1_OFFSET1_Pos) /*!< 0x00000010 */ +#define ADC_OFR1_OFFSET1_5 (0x020U << ADC_OFR1_OFFSET1_Pos) /*!< 0x00000020 */ +#define ADC_OFR1_OFFSET1_6 (0x040U << ADC_OFR1_OFFSET1_Pos) /*!< 0x00000040 */ +#define ADC_OFR1_OFFSET1_7 (0x080U << ADC_OFR1_OFFSET1_Pos) /*!< 0x00000080 */ +#define ADC_OFR1_OFFSET1_8 (0x100U << ADC_OFR1_OFFSET1_Pos) /*!< 0x00000100 */ +#define ADC_OFR1_OFFSET1_9 (0x200U << ADC_OFR1_OFFSET1_Pos) /*!< 0x00000200 */ +#define ADC_OFR1_OFFSET1_10 (0x400U << ADC_OFR1_OFFSET1_Pos) /*!< 0x00000400 */ +#define ADC_OFR1_OFFSET1_11 (0x800U << ADC_OFR1_OFFSET1_Pos) /*!< 0x00000800 */ + +#define ADC_OFR1_OFFSET1_CH_Pos (26U) +#define ADC_OFR1_OFFSET1_CH_Msk (0x1FU << ADC_OFR1_OFFSET1_CH_Pos) /*!< 0x7C000000 */ +#define ADC_OFR1_OFFSET1_CH ADC_OFR1_OFFSET1_CH_Msk /*!< ADC offset number 1 channel selection */ +#define ADC_OFR1_OFFSET1_CH_0 (0x01U << ADC_OFR1_OFFSET1_CH_Pos) /*!< 0x04000000 */ +#define ADC_OFR1_OFFSET1_CH_1 (0x02U << ADC_OFR1_OFFSET1_CH_Pos) /*!< 0x08000000 */ +#define ADC_OFR1_OFFSET1_CH_2 (0x04U << ADC_OFR1_OFFSET1_CH_Pos) /*!< 0x10000000 */ +#define ADC_OFR1_OFFSET1_CH_3 (0x08U << ADC_OFR1_OFFSET1_CH_Pos) /*!< 0x20000000 */ +#define ADC_OFR1_OFFSET1_CH_4 (0x10U << ADC_OFR1_OFFSET1_CH_Pos) /*!< 0x40000000 */ + +#define ADC_OFR1_OFFSET1_EN_Pos (31U) +#define ADC_OFR1_OFFSET1_EN_Msk (0x1U << ADC_OFR1_OFFSET1_EN_Pos) /*!< 0x80000000 */ +#define ADC_OFR1_OFFSET1_EN ADC_OFR1_OFFSET1_EN_Msk /*!< ADC offset number 1 enable */ + +/******************** Bit definition for ADC_OFR2 register ******************/ +#define ADC_OFR2_OFFSET2_Pos (0U) +#define ADC_OFR2_OFFSET2_Msk (0xFFFU << ADC_OFR2_OFFSET2_Pos) /*!< 0x00000FFF */ +#define ADC_OFR2_OFFSET2 ADC_OFR2_OFFSET2_Msk /*!< ADC offset number 2 offset level */ +#define ADC_OFR2_OFFSET2_0 (0x001U << ADC_OFR2_OFFSET2_Pos) /*!< 0x00000001 */ +#define ADC_OFR2_OFFSET2_1 (0x002U << ADC_OFR2_OFFSET2_Pos) /*!< 0x00000002 */ +#define ADC_OFR2_OFFSET2_2 (0x004U << ADC_OFR2_OFFSET2_Pos) /*!< 0x00000004 */ +#define ADC_OFR2_OFFSET2_3 (0x008U << ADC_OFR2_OFFSET2_Pos) /*!< 0x00000008 */ +#define ADC_OFR2_OFFSET2_4 (0x010U << ADC_OFR2_OFFSET2_Pos) /*!< 0x00000010 */ +#define ADC_OFR2_OFFSET2_5 (0x020U << ADC_OFR2_OFFSET2_Pos) /*!< 0x00000020 */ +#define ADC_OFR2_OFFSET2_6 (0x040U << ADC_OFR2_OFFSET2_Pos) /*!< 0x00000040 */ +#define ADC_OFR2_OFFSET2_7 (0x080U << ADC_OFR2_OFFSET2_Pos) /*!< 0x00000080 */ +#define ADC_OFR2_OFFSET2_8 (0x100U << ADC_OFR2_OFFSET2_Pos) /*!< 0x00000100 */ +#define ADC_OFR2_OFFSET2_9 (0x200U << ADC_OFR2_OFFSET2_Pos) /*!< 0x00000200 */ +#define ADC_OFR2_OFFSET2_10 (0x400U << ADC_OFR2_OFFSET2_Pos) /*!< 0x00000400 */ +#define ADC_OFR2_OFFSET2_11 (0x800U << ADC_OFR2_OFFSET2_Pos) /*!< 0x00000800 */ + +#define ADC_OFR2_OFFSET2_CH_Pos (26U) +#define ADC_OFR2_OFFSET2_CH_Msk (0x1FU << ADC_OFR2_OFFSET2_CH_Pos) /*!< 0x7C000000 */ +#define ADC_OFR2_OFFSET2_CH ADC_OFR2_OFFSET2_CH_Msk /*!< ADC offset number 2 channel selection */ +#define ADC_OFR2_OFFSET2_CH_0 (0x01U << ADC_OFR2_OFFSET2_CH_Pos) /*!< 0x04000000 */ +#define ADC_OFR2_OFFSET2_CH_1 (0x02U << ADC_OFR2_OFFSET2_CH_Pos) /*!< 0x08000000 */ +#define ADC_OFR2_OFFSET2_CH_2 (0x04U << ADC_OFR2_OFFSET2_CH_Pos) /*!< 0x10000000 */ +#define ADC_OFR2_OFFSET2_CH_3 (0x08U << ADC_OFR2_OFFSET2_CH_Pos) /*!< 0x20000000 */ +#define ADC_OFR2_OFFSET2_CH_4 (0x10U << ADC_OFR2_OFFSET2_CH_Pos) /*!< 0x40000000 */ + +#define ADC_OFR2_OFFSET2_EN_Pos (31U) +#define ADC_OFR2_OFFSET2_EN_Msk (0x1U << ADC_OFR2_OFFSET2_EN_Pos) /*!< 0x80000000 */ +#define ADC_OFR2_OFFSET2_EN ADC_OFR2_OFFSET2_EN_Msk /*!< ADC offset number 2 enable */ + +/******************** Bit definition for ADC_OFR3 register ******************/ +#define ADC_OFR3_OFFSET3_Pos (0U) +#define ADC_OFR3_OFFSET3_Msk (0xFFFU << ADC_OFR3_OFFSET3_Pos) /*!< 0x00000FFF */ +#define ADC_OFR3_OFFSET3 ADC_OFR3_OFFSET3_Msk /*!< ADC offset number 3 offset level */ +#define ADC_OFR3_OFFSET3_0 (0x001U << ADC_OFR3_OFFSET3_Pos) /*!< 0x00000001 */ +#define ADC_OFR3_OFFSET3_1 (0x002U << ADC_OFR3_OFFSET3_Pos) /*!< 0x00000002 */ +#define ADC_OFR3_OFFSET3_2 (0x004U << ADC_OFR3_OFFSET3_Pos) /*!< 0x00000004 */ +#define ADC_OFR3_OFFSET3_3 (0x008U << ADC_OFR3_OFFSET3_Pos) /*!< 0x00000008 */ +#define ADC_OFR3_OFFSET3_4 (0x010U << ADC_OFR3_OFFSET3_Pos) /*!< 0x00000010 */ +#define ADC_OFR3_OFFSET3_5 (0x020U << ADC_OFR3_OFFSET3_Pos) /*!< 0x00000020 */ +#define ADC_OFR3_OFFSET3_6 (0x040U << ADC_OFR3_OFFSET3_Pos) /*!< 0x00000040 */ +#define ADC_OFR3_OFFSET3_7 (0x080U << ADC_OFR3_OFFSET3_Pos) /*!< 0x00000080 */ +#define ADC_OFR3_OFFSET3_8 (0x100U << ADC_OFR3_OFFSET3_Pos) /*!< 0x00000100 */ +#define ADC_OFR3_OFFSET3_9 (0x200U << ADC_OFR3_OFFSET3_Pos) /*!< 0x00000200 */ +#define ADC_OFR3_OFFSET3_10 (0x400U << ADC_OFR3_OFFSET3_Pos) /*!< 0x00000400 */ +#define ADC_OFR3_OFFSET3_11 (0x800U << ADC_OFR3_OFFSET3_Pos) /*!< 0x00000800 */ + +#define ADC_OFR3_OFFSET3_CH_Pos (26U) +#define ADC_OFR3_OFFSET3_CH_Msk (0x1FU << ADC_OFR3_OFFSET3_CH_Pos) /*!< 0x7C000000 */ +#define ADC_OFR3_OFFSET3_CH ADC_OFR3_OFFSET3_CH_Msk /*!< ADC offset number 3 channel selection */ +#define ADC_OFR3_OFFSET3_CH_0 (0x01U << ADC_OFR3_OFFSET3_CH_Pos) /*!< 0x04000000 */ +#define ADC_OFR3_OFFSET3_CH_1 (0x02U << ADC_OFR3_OFFSET3_CH_Pos) /*!< 0x08000000 */ +#define ADC_OFR3_OFFSET3_CH_2 (0x04U << ADC_OFR3_OFFSET3_CH_Pos) /*!< 0x10000000 */ +#define ADC_OFR3_OFFSET3_CH_3 (0x08U << ADC_OFR3_OFFSET3_CH_Pos) /*!< 0x20000000 */ +#define ADC_OFR3_OFFSET3_CH_4 (0x10U << ADC_OFR3_OFFSET3_CH_Pos) /*!< 0x40000000 */ + +#define ADC_OFR3_OFFSET3_EN_Pos (31U) +#define ADC_OFR3_OFFSET3_EN_Msk (0x1U << ADC_OFR3_OFFSET3_EN_Pos) /*!< 0x80000000 */ +#define ADC_OFR3_OFFSET3_EN ADC_OFR3_OFFSET3_EN_Msk /*!< ADC offset number 3 enable */ + +/******************** Bit definition for ADC_OFR4 register ******************/ +#define ADC_OFR4_OFFSET4_Pos (0U) +#define ADC_OFR4_OFFSET4_Msk (0xFFFU << ADC_OFR4_OFFSET4_Pos) /*!< 0x00000FFF */ +#define ADC_OFR4_OFFSET4 ADC_OFR4_OFFSET4_Msk /*!< ADC offset number 4 offset level */ +#define ADC_OFR4_OFFSET4_0 (0x001U << ADC_OFR4_OFFSET4_Pos) /*!< 0x00000001 */ +#define ADC_OFR4_OFFSET4_1 (0x002U << ADC_OFR4_OFFSET4_Pos) /*!< 0x00000002 */ +#define ADC_OFR4_OFFSET4_2 (0x004U << ADC_OFR4_OFFSET4_Pos) /*!< 0x00000004 */ +#define ADC_OFR4_OFFSET4_3 (0x008U << ADC_OFR4_OFFSET4_Pos) /*!< 0x00000008 */ +#define ADC_OFR4_OFFSET4_4 (0x010U << ADC_OFR4_OFFSET4_Pos) /*!< 0x00000010 */ +#define ADC_OFR4_OFFSET4_5 (0x020U << ADC_OFR4_OFFSET4_Pos) /*!< 0x00000020 */ +#define ADC_OFR4_OFFSET4_6 (0x040U << ADC_OFR4_OFFSET4_Pos) /*!< 0x00000040 */ +#define ADC_OFR4_OFFSET4_7 (0x080U << ADC_OFR4_OFFSET4_Pos) /*!< 0x00000080 */ +#define ADC_OFR4_OFFSET4_8 (0x100U << ADC_OFR4_OFFSET4_Pos) /*!< 0x00000100 */ +#define ADC_OFR4_OFFSET4_9 (0x200U << ADC_OFR4_OFFSET4_Pos) /*!< 0x00000200 */ +#define ADC_OFR4_OFFSET4_10 (0x400U << ADC_OFR4_OFFSET4_Pos) /*!< 0x00000400 */ +#define ADC_OFR4_OFFSET4_11 (0x800U << ADC_OFR4_OFFSET4_Pos) /*!< 0x00000800 */ + +#define ADC_OFR4_OFFSET4_CH_Pos (26U) +#define ADC_OFR4_OFFSET4_CH_Msk (0x1FU << ADC_OFR4_OFFSET4_CH_Pos) /*!< 0x7C000000 */ +#define ADC_OFR4_OFFSET4_CH ADC_OFR4_OFFSET4_CH_Msk /*!< ADC offset number 4 channel selection */ +#define ADC_OFR4_OFFSET4_CH_0 (0x01U << ADC_OFR4_OFFSET4_CH_Pos) /*!< 0x04000000 */ +#define ADC_OFR4_OFFSET4_CH_1 (0x02U << ADC_OFR4_OFFSET4_CH_Pos) /*!< 0x08000000 */ +#define ADC_OFR4_OFFSET4_CH_2 (0x04U << ADC_OFR4_OFFSET4_CH_Pos) /*!< 0x10000000 */ +#define ADC_OFR4_OFFSET4_CH_3 (0x08U << ADC_OFR4_OFFSET4_CH_Pos) /*!< 0x20000000 */ +#define ADC_OFR4_OFFSET4_CH_4 (0x10U << ADC_OFR4_OFFSET4_CH_Pos) /*!< 0x40000000 */ + +#define ADC_OFR4_OFFSET4_EN_Pos (31U) +#define ADC_OFR4_OFFSET4_EN_Msk (0x1U << ADC_OFR4_OFFSET4_EN_Pos) /*!< 0x80000000 */ +#define ADC_OFR4_OFFSET4_EN ADC_OFR4_OFFSET4_EN_Msk /*!< ADC offset number 4 enable */ + +/******************** Bit definition for ADC_JDR1 register ******************/ +#define ADC_JDR1_JDATA_Pos (0U) +#define ADC_JDR1_JDATA_Msk (0xFFFFU << ADC_JDR1_JDATA_Pos) /*!< 0x0000FFFF */ +#define ADC_JDR1_JDATA ADC_JDR1_JDATA_Msk /*!< ADC group injected sequencer rank 1 conversion data */ +#define ADC_JDR1_JDATA_0 (0x0001U << ADC_JDR1_JDATA_Pos) /*!< 0x00000001 */ +#define ADC_JDR1_JDATA_1 (0x0002U << ADC_JDR1_JDATA_Pos) /*!< 0x00000002 */ +#define ADC_JDR1_JDATA_2 (0x0004U << ADC_JDR1_JDATA_Pos) /*!< 0x00000004 */ +#define ADC_JDR1_JDATA_3 (0x0008U << ADC_JDR1_JDATA_Pos) /*!< 0x00000008 */ +#define ADC_JDR1_JDATA_4 (0x0010U << ADC_JDR1_JDATA_Pos) /*!< 0x00000010 */ +#define ADC_JDR1_JDATA_5 (0x0020U << ADC_JDR1_JDATA_Pos) /*!< 0x00000020 */ +#define ADC_JDR1_JDATA_6 (0x0040U << ADC_JDR1_JDATA_Pos) /*!< 0x00000040 */ +#define ADC_JDR1_JDATA_7 (0x0080U << ADC_JDR1_JDATA_Pos) /*!< 0x00000080 */ +#define ADC_JDR1_JDATA_8 (0x0100U << ADC_JDR1_JDATA_Pos) /*!< 0x00000100 */ +#define ADC_JDR1_JDATA_9 (0x0200U << ADC_JDR1_JDATA_Pos) /*!< 0x00000200 */ +#define ADC_JDR1_JDATA_10 (0x0400U << ADC_JDR1_JDATA_Pos) /*!< 0x00000400 */ +#define ADC_JDR1_JDATA_11 (0x0800U << ADC_JDR1_JDATA_Pos) /*!< 0x00000800 */ +#define ADC_JDR1_JDATA_12 (0x1000U << ADC_JDR1_JDATA_Pos) /*!< 0x00001000 */ +#define ADC_JDR1_JDATA_13 (0x2000U << ADC_JDR1_JDATA_Pos) /*!< 0x00002000 */ +#define ADC_JDR1_JDATA_14 (0x4000U << ADC_JDR1_JDATA_Pos) /*!< 0x00004000 */ +#define ADC_JDR1_JDATA_15 (0x8000U << ADC_JDR1_JDATA_Pos) /*!< 0x00008000 */ + +/******************** Bit definition for ADC_JDR2 register ******************/ +#define ADC_JDR2_JDATA_Pos (0U) +#define ADC_JDR2_JDATA_Msk (0xFFFFU << ADC_JDR2_JDATA_Pos) /*!< 0x0000FFFF */ +#define ADC_JDR2_JDATA ADC_JDR2_JDATA_Msk /*!< ADC group injected sequencer rank 2 conversion data */ +#define ADC_JDR2_JDATA_0 (0x0001U << ADC_JDR2_JDATA_Pos) /*!< 0x00000001 */ +#define ADC_JDR2_JDATA_1 (0x0002U << ADC_JDR2_JDATA_Pos) /*!< 0x00000002 */ +#define ADC_JDR2_JDATA_2 (0x0004U << ADC_JDR2_JDATA_Pos) /*!< 0x00000004 */ +#define ADC_JDR2_JDATA_3 (0x0008U << ADC_JDR2_JDATA_Pos) /*!< 0x00000008 */ +#define ADC_JDR2_JDATA_4 (0x0010U << ADC_JDR2_JDATA_Pos) /*!< 0x00000010 */ +#define ADC_JDR2_JDATA_5 (0x0020U << ADC_JDR2_JDATA_Pos) /*!< 0x00000020 */ +#define ADC_JDR2_JDATA_6 (0x0040U << ADC_JDR2_JDATA_Pos) /*!< 0x00000040 */ +#define ADC_JDR2_JDATA_7 (0x0080U << ADC_JDR2_JDATA_Pos) /*!< 0x00000080 */ +#define ADC_JDR2_JDATA_8 (0x0100U << ADC_JDR2_JDATA_Pos) /*!< 0x00000100 */ +#define ADC_JDR2_JDATA_9 (0x0200U << ADC_JDR2_JDATA_Pos) /*!< 0x00000200 */ +#define ADC_JDR2_JDATA_10 (0x0400U << ADC_JDR2_JDATA_Pos) /*!< 0x00000400 */ +#define ADC_JDR2_JDATA_11 (0x0800U << ADC_JDR2_JDATA_Pos) /*!< 0x00000800 */ +#define ADC_JDR2_JDATA_12 (0x1000U << ADC_JDR2_JDATA_Pos) /*!< 0x00001000 */ +#define ADC_JDR2_JDATA_13 (0x2000U << ADC_JDR2_JDATA_Pos) /*!< 0x00002000 */ +#define ADC_JDR2_JDATA_14 (0x4000U << ADC_JDR2_JDATA_Pos) /*!< 0x00004000 */ +#define ADC_JDR2_JDATA_15 (0x8000U << ADC_JDR2_JDATA_Pos) /*!< 0x00008000 */ + +/******************** Bit definition for ADC_JDR3 register ******************/ +#define ADC_JDR3_JDATA_Pos (0U) +#define ADC_JDR3_JDATA_Msk (0xFFFFU << ADC_JDR3_JDATA_Pos) /*!< 0x0000FFFF */ +#define ADC_JDR3_JDATA ADC_JDR3_JDATA_Msk /*!< ADC group injected sequencer rank 3 conversion data */ +#define ADC_JDR3_JDATA_0 (0x0001U << ADC_JDR3_JDATA_Pos) /*!< 0x00000001 */ +#define ADC_JDR3_JDATA_1 (0x0002U << ADC_JDR3_JDATA_Pos) /*!< 0x00000002 */ +#define ADC_JDR3_JDATA_2 (0x0004U << ADC_JDR3_JDATA_Pos) /*!< 0x00000004 */ +#define ADC_JDR3_JDATA_3 (0x0008U << ADC_JDR3_JDATA_Pos) /*!< 0x00000008 */ +#define ADC_JDR3_JDATA_4 (0x0010U << ADC_JDR3_JDATA_Pos) /*!< 0x00000010 */ +#define ADC_JDR3_JDATA_5 (0x0020U << ADC_JDR3_JDATA_Pos) /*!< 0x00000020 */ +#define ADC_JDR3_JDATA_6 (0x0040U << ADC_JDR3_JDATA_Pos) /*!< 0x00000040 */ +#define ADC_JDR3_JDATA_7 (0x0080U << ADC_JDR3_JDATA_Pos) /*!< 0x00000080 */ +#define ADC_JDR3_JDATA_8 (0x0100U << ADC_JDR3_JDATA_Pos) /*!< 0x00000100 */ +#define ADC_JDR3_JDATA_9 (0x0200U << ADC_JDR3_JDATA_Pos) /*!< 0x00000200 */ +#define ADC_JDR3_JDATA_10 (0x0400U << ADC_JDR3_JDATA_Pos) /*!< 0x00000400 */ +#define ADC_JDR3_JDATA_11 (0x0800U << ADC_JDR3_JDATA_Pos) /*!< 0x00000800 */ +#define ADC_JDR3_JDATA_12 (0x1000U << ADC_JDR3_JDATA_Pos) /*!< 0x00001000 */ +#define ADC_JDR3_JDATA_13 (0x2000U << ADC_JDR3_JDATA_Pos) /*!< 0x00002000 */ +#define ADC_JDR3_JDATA_14 (0x4000U << ADC_JDR3_JDATA_Pos) /*!< 0x00004000 */ +#define ADC_JDR3_JDATA_15 (0x8000U << ADC_JDR3_JDATA_Pos) /*!< 0x00008000 */ + +/******************** Bit definition for ADC_JDR4 register ******************/ +#define ADC_JDR4_JDATA_Pos (0U) +#define ADC_JDR4_JDATA_Msk (0xFFFFU << ADC_JDR4_JDATA_Pos) /*!< 0x0000FFFF */ +#define ADC_JDR4_JDATA ADC_JDR4_JDATA_Msk /*!< ADC group injected sequencer rank 4 conversion data */ +#define ADC_JDR4_JDATA_0 (0x0001U << ADC_JDR4_JDATA_Pos) /*!< 0x00000001 */ +#define ADC_JDR4_JDATA_1 (0x0002U << ADC_JDR4_JDATA_Pos) /*!< 0x00000002 */ +#define ADC_JDR4_JDATA_2 (0x0004U << ADC_JDR4_JDATA_Pos) /*!< 0x00000004 */ +#define ADC_JDR4_JDATA_3 (0x0008U << ADC_JDR4_JDATA_Pos) /*!< 0x00000008 */ +#define ADC_JDR4_JDATA_4 (0x0010U << ADC_JDR4_JDATA_Pos) /*!< 0x00000010 */ +#define ADC_JDR4_JDATA_5 (0x0020U << ADC_JDR4_JDATA_Pos) /*!< 0x00000020 */ +#define ADC_JDR4_JDATA_6 (0x0040U << ADC_JDR4_JDATA_Pos) /*!< 0x00000040 */ +#define ADC_JDR4_JDATA_7 (0x0080U << ADC_JDR4_JDATA_Pos) /*!< 0x00000080 */ +#define ADC_JDR4_JDATA_8 (0x0100U << ADC_JDR4_JDATA_Pos) /*!< 0x00000100 */ +#define ADC_JDR4_JDATA_9 (0x0200U << ADC_JDR4_JDATA_Pos) /*!< 0x00000200 */ +#define ADC_JDR4_JDATA_10 (0x0400U << ADC_JDR4_JDATA_Pos) /*!< 0x00000400 */ +#define ADC_JDR4_JDATA_11 (0x0800U << ADC_JDR4_JDATA_Pos) /*!< 0x00000800 */ +#define ADC_JDR4_JDATA_12 (0x1000U << ADC_JDR4_JDATA_Pos) /*!< 0x00001000 */ +#define ADC_JDR4_JDATA_13 (0x2000U << ADC_JDR4_JDATA_Pos) /*!< 0x00002000 */ +#define ADC_JDR4_JDATA_14 (0x4000U << ADC_JDR4_JDATA_Pos) /*!< 0x00004000 */ +#define ADC_JDR4_JDATA_15 (0x8000U << ADC_JDR4_JDATA_Pos) /*!< 0x00008000 */ + +/******************** Bit definition for ADC_AWD2CR register ****************/ +#define ADC_AWD2CR_AWD2CH_Pos (0U) +#define ADC_AWD2CR_AWD2CH_Msk (0x7FFFFU << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x0007FFFF */ +#define ADC_AWD2CR_AWD2CH ADC_AWD2CR_AWD2CH_Msk /*!< ADC analog watchdog 2 monitored channel selection */ +#define ADC_AWD2CR_AWD2CH_0 (0x00001U << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00000001 */ +#define ADC_AWD2CR_AWD2CH_1 (0x00002U << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00000002 */ +#define ADC_AWD2CR_AWD2CH_2 (0x00004U << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00000004 */ +#define ADC_AWD2CR_AWD2CH_3 (0x00008U << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00000008 */ +#define ADC_AWD2CR_AWD2CH_4 (0x00010U << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00000010 */ +#define ADC_AWD2CR_AWD2CH_5 (0x00020U << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00000020 */ +#define ADC_AWD2CR_AWD2CH_6 (0x00040U << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00000040 */ +#define ADC_AWD2CR_AWD2CH_7 (0x00080U << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00000080 */ +#define ADC_AWD2CR_AWD2CH_8 (0x00100U << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00000100 */ +#define ADC_AWD2CR_AWD2CH_9 (0x00200U << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00000200 */ +#define ADC_AWD2CR_AWD2CH_10 (0x00400U << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00000400 */ +#define ADC_AWD2CR_AWD2CH_11 (0x00800U << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00000800 */ +#define ADC_AWD2CR_AWD2CH_12 (0x01000U << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00001000 */ +#define ADC_AWD2CR_AWD2CH_13 (0x02000U << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00002000 */ +#define ADC_AWD2CR_AWD2CH_14 (0x04000U << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00004000 */ +#define ADC_AWD2CR_AWD2CH_15 (0x08000U << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00008000 */ +#define ADC_AWD2CR_AWD2CH_16 (0x10000U << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00010000 */ +#define ADC_AWD2CR_AWD2CH_17 (0x20000U << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00020000 */ +#define ADC_AWD2CR_AWD2CH_18 (0x40000U << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00040000 */ + +/******************** Bit definition for ADC_AWD3CR register ****************/ +#define ADC_AWD3CR_AWD3CH_Pos (0U) +#define ADC_AWD3CR_AWD3CH_Msk (0x7FFFFU << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x0007FFFF */ +#define ADC_AWD3CR_AWD3CH ADC_AWD3CR_AWD3CH_Msk /*!< ADC analog watchdog 3 monitored channel selection */ +#define ADC_AWD3CR_AWD3CH_0 (0x00001U << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00000001 */ +#define ADC_AWD3CR_AWD3CH_1 (0x00002U << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00000002 */ +#define ADC_AWD3CR_AWD3CH_2 (0x00004U << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00000004 */ +#define ADC_AWD3CR_AWD3CH_3 (0x00008U << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00000008 */ +#define ADC_AWD3CR_AWD3CH_4 (0x00010U << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00000010 */ +#define ADC_AWD3CR_AWD3CH_5 (0x00020U << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00000020 */ +#define ADC_AWD3CR_AWD3CH_6 (0x00040U << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00000040 */ +#define ADC_AWD3CR_AWD3CH_7 (0x00080U << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00000080 */ +#define ADC_AWD3CR_AWD3CH_8 (0x00100U << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00000100 */ +#define ADC_AWD3CR_AWD3CH_9 (0x00200U << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00000200 */ +#define ADC_AWD3CR_AWD3CH_10 (0x00400U << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00000400 */ +#define ADC_AWD3CR_AWD3CH_11 (0x00800U << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00000800 */ +#define ADC_AWD3CR_AWD3CH_12 (0x01000U << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00001000 */ +#define ADC_AWD3CR_AWD3CH_13 (0x02000U << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00002000 */ +#define ADC_AWD3CR_AWD3CH_14 (0x04000U << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00004000 */ +#define ADC_AWD3CR_AWD3CH_15 (0x08000U << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00008000 */ +#define ADC_AWD3CR_AWD3CH_16 (0x10000U << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00010000 */ +#define ADC_AWD3CR_AWD3CH_17 (0x20000U << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00020000 */ +#define ADC_AWD3CR_AWD3CH_18 (0x40000U << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00040000 */ + +/******************** Bit definition for ADC_DIFSEL register ****************/ +#define ADC_DIFSEL_DIFSEL_Pos (0U) +#define ADC_DIFSEL_DIFSEL_Msk (0x7FFFFU << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x0007FFFF */ +#define ADC_DIFSEL_DIFSEL ADC_DIFSEL_DIFSEL_Msk /*!< ADC channel differential or single-ended mode */ +#define ADC_DIFSEL_DIFSEL_0 (0x00001U << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x00000001 */ +#define ADC_DIFSEL_DIFSEL_1 (0x00002U << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x00000002 */ +#define ADC_DIFSEL_DIFSEL_2 (0x00004U << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x00000004 */ +#define ADC_DIFSEL_DIFSEL_3 (0x00008U << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x00000008 */ +#define ADC_DIFSEL_DIFSEL_4 (0x00010U << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x00000010 */ +#define ADC_DIFSEL_DIFSEL_5 (0x00020U << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x00000020 */ +#define ADC_DIFSEL_DIFSEL_6 (0x00040U << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x00000040 */ +#define ADC_DIFSEL_DIFSEL_7 (0x00080U << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x00000080 */ +#define ADC_DIFSEL_DIFSEL_8 (0x00100U << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x00000100 */ +#define ADC_DIFSEL_DIFSEL_9 (0x00200U << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x00000200 */ +#define ADC_DIFSEL_DIFSEL_10 (0x00400U << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x00000400 */ +#define ADC_DIFSEL_DIFSEL_11 (0x00800U << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x00000800 */ +#define ADC_DIFSEL_DIFSEL_12 (0x01000U << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x00001000 */ +#define ADC_DIFSEL_DIFSEL_13 (0x02000U << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x00002000 */ +#define ADC_DIFSEL_DIFSEL_14 (0x04000U << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x00004000 */ +#define ADC_DIFSEL_DIFSEL_15 (0x08000U << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x00008000 */ +#define ADC_DIFSEL_DIFSEL_16 (0x10000U << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x00010000 */ +#define ADC_DIFSEL_DIFSEL_17 (0x20000U << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x00020000 */ +#define ADC_DIFSEL_DIFSEL_18 (0x40000U << ADC_DIFSEL_DIFSEL_Pos) /*!< 0x00040000 */ + +/******************** Bit definition for ADC_CALFACT register ***************/ +#define ADC_CALFACT_CALFACT_S_Pos (0U) +#define ADC_CALFACT_CALFACT_S_Msk (0x7FU << ADC_CALFACT_CALFACT_S_Pos) /*!< 0x0000007F */ +#define ADC_CALFACT_CALFACT_S ADC_CALFACT_CALFACT_S_Msk /*!< ADC calibration factor in single-ended mode */ +#define ADC_CALFACT_CALFACT_S_0 (0x01U << ADC_CALFACT_CALFACT_S_Pos) /*!< 0x00000001 */ +#define ADC_CALFACT_CALFACT_S_1 (0x02U << ADC_CALFACT_CALFACT_S_Pos) /*!< 0x00000002 */ +#define ADC_CALFACT_CALFACT_S_2 (0x04U << ADC_CALFACT_CALFACT_S_Pos) /*!< 0x00000004 */ +#define ADC_CALFACT_CALFACT_S_3 (0x08U << ADC_CALFACT_CALFACT_S_Pos) /*!< 0x00000008 */ +#define ADC_CALFACT_CALFACT_S_4 (0x10U << ADC_CALFACT_CALFACT_S_Pos) /*!< 0x00000010 */ +#define ADC_CALFACT_CALFACT_S_5 (0x20U << ADC_CALFACT_CALFACT_S_Pos) /*!< 0x00000020 */ +#define ADC_CALFACT_CALFACT_S_6 (0x40U << ADC_CALFACT_CALFACT_S_Pos) /*!< 0x00000040 */ + +#define ADC_CALFACT_CALFACT_D_Pos (16U) +#define ADC_CALFACT_CALFACT_D_Msk (0x7FU << ADC_CALFACT_CALFACT_D_Pos) /*!< 0x007F0000 */ +#define ADC_CALFACT_CALFACT_D ADC_CALFACT_CALFACT_D_Msk /*!< ADC calibration factor in differential mode */ +#define ADC_CALFACT_CALFACT_D_0 (0x01U << ADC_CALFACT_CALFACT_D_Pos) /*!< 0x00010000 */ +#define ADC_CALFACT_CALFACT_D_1 (0x02U << ADC_CALFACT_CALFACT_D_Pos) /*!< 0x00020000 */ +#define ADC_CALFACT_CALFACT_D_2 (0x04U << ADC_CALFACT_CALFACT_D_Pos) /*!< 0x00040000 */ +#define ADC_CALFACT_CALFACT_D_3 (0x08U << ADC_CALFACT_CALFACT_D_Pos) /*!< 0x00080000 */ +#define ADC_CALFACT_CALFACT_D_4 (0x10U << ADC_CALFACT_CALFACT_D_Pos) /*!< 0x00100000 */ +#define ADC_CALFACT_CALFACT_D_5 (0x20U << ADC_CALFACT_CALFACT_D_Pos) /*!< 0x00200000 */ +#define ADC_CALFACT_CALFACT_D_6 (0x40U << ADC_CALFACT_CALFACT_D_Pos) /*!< 0x00400000 */ + +/************************* ADC Common registers *****************************/ +/******************** Bit definition for ADC_CCR register *******************/ +#define ADC_CCR_CKMODE_Pos (16U) +#define ADC_CCR_CKMODE_Msk (0x3U << ADC_CCR_CKMODE_Pos) /*!< 0x00030000 */ +#define ADC_CCR_CKMODE ADC_CCR_CKMODE_Msk /*!< ADC common clock source and prescaler (prescaler only for clock source synchronous) */ +#define ADC_CCR_CKMODE_0 (0x1U << ADC_CCR_CKMODE_Pos) /*!< 0x00010000 */ +#define ADC_CCR_CKMODE_1 (0x2U << ADC_CCR_CKMODE_Pos) /*!< 0x00020000 */ + +#define ADC_CCR_PRESC_Pos (18U) +#define ADC_CCR_PRESC_Msk (0xFU << ADC_CCR_PRESC_Pos) /*!< 0x003C0000 */ +#define ADC_CCR_PRESC ADC_CCR_PRESC_Msk /*!< ADC common clock prescaler, only for clock source asynchronous */ +#define ADC_CCR_PRESC_0 (0x1U << ADC_CCR_PRESC_Pos) /*!< 0x00040000 */ +#define ADC_CCR_PRESC_1 (0x2U << ADC_CCR_PRESC_Pos) /*!< 0x00080000 */ +#define ADC_CCR_PRESC_2 (0x4U << ADC_CCR_PRESC_Pos) /*!< 0x00100000 */ +#define ADC_CCR_PRESC_3 (0x8U << ADC_CCR_PRESC_Pos) /*!< 0x00200000 */ + +#define ADC_CCR_VREFEN_Pos (22U) +#define ADC_CCR_VREFEN_Msk (0x1U << ADC_CCR_VREFEN_Pos) /*!< 0x00400000 */ +#define ADC_CCR_VREFEN ADC_CCR_VREFEN_Msk /*!< ADC internal path to VrefInt enable */ +#define ADC_CCR_TSEN_Pos (23U) +#define ADC_CCR_TSEN_Msk (0x1U << ADC_CCR_TSEN_Pos) /*!< 0x00800000 */ +#define ADC_CCR_TSEN ADC_CCR_TSEN_Msk /*!< ADC internal path to temperature sensor enable */ +#define ADC_CCR_VBATEN_Pos (24U) +#define ADC_CCR_VBATEN_Msk (0x1U << ADC_CCR_VBATEN_Pos) /*!< 0x01000000 */ +#define ADC_CCR_VBATEN ADC_CCR_VBATEN_Msk /*!< ADC internal path to battery voltage enable */ + +/******************************************************************************/ +/* */ +/* Controller Area Network */ +/* */ +/******************************************************************************/ +/*!*/ +#define DAC_CR_CEN1_Pos (14U) +#define DAC_CR_CEN1_Msk (0x1U << DAC_CR_CEN1_Pos) /*!< 0x00004000 */ +#define DAC_CR_CEN1 DAC_CR_CEN1_Msk /*!*/ + +#define DAC_CR_HFSEL_Pos (15U) +#define DAC_CR_HFSEL_Msk (0x1U << DAC_CR_HFSEL_Pos) /*!< 0x00008000 */ +#define DAC_CR_HFSEL DAC_CR_HFSEL_Msk /*!*/ + +#define DAC_CR_EN2_Pos (16U) +#define DAC_CR_EN2_Msk (0x1U << DAC_CR_EN2_Pos) /*!< 0x00010000 */ +#define DAC_CR_EN2 DAC_CR_EN2_Msk /*!*/ +#define DAC_CR_CEN2_Pos (30U) +#define DAC_CR_CEN2_Msk (0x1U << DAC_CR_CEN2_Pos) /*!< 0x40000000 */ +#define DAC_CR_CEN2 DAC_CR_CEN2_Msk /*!*/ + +/***************** Bit definition for DAC_SWTRIGR register ******************/ +#define DAC_SWTRIGR_SWTRIG1_Pos (0U) +#define DAC_SWTRIGR_SWTRIG1_Msk (0x1U << DAC_SWTRIGR_SWTRIG1_Pos) /*!< 0x00000001 */ +#define DAC_SWTRIGR_SWTRIG1 DAC_SWTRIGR_SWTRIG1_Msk /*!
© COPYRIGHT(c) 2017 STMicroelectronics
+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/** @addtogroup CMSIS + * @{ + */ + +/** @addtogroup stm32l4xx + * @{ + */ + +#ifndef __STM32L4xx_H +#define __STM32L4xx_H + +#ifdef __cplusplus + extern "C" { +#endif /* __cplusplus */ + +/** @addtogroup Library_configuration_section + * @{ + */ + +/** + * @brief STM32 Family + */ +#if !defined (STM32L4) +#define STM32L4 +#endif /* STM32L4 */ + +/* Uncomment the line below according to the target STM32L4 device used in your + application + */ + +#if !defined (STM32L431xx) && !defined (STM32L432xx) && !defined (STM32L433xx) && !defined (STM32L442xx) && !defined (STM32L443xx) && \ + !defined (STM32L451xx) && !defined (STM32L452xx) && !defined (STM32L462xx) && \ + !defined (STM32L471xx) && !defined (STM32L475xx) && !defined (STM32L476xx) && !defined (STM32L485xx) && !defined (STM32L486xx) && \ + !defined (STM32L496xx) && !defined (STM32L4A6xx) && \ + !defined (STM32L4R5xx) && !defined (STM32L4R7xx) && !defined (STM32L4R9xx) && !defined (STM32L4S5xx) && !defined (STM32L4S7xx) && !defined (STM32L4S9xx) + /* #define STM32L431xx */ /*!< STM32L431xx Devices */ + /* #define STM32L432xx */ /*!< STM32L432xx Devices */ + /* #define STM32L433xx */ /*!< STM32L433xx Devices */ + /* #define STM32L442xx */ /*!< STM32L442xx Devices */ + /* #define STM32L443xx */ /*!< STM32L443xx Devices */ + /* #define STM32L451xx */ /*!< STM32L451xx Devices */ + /* #define STM32L452xx */ /*!< STM32L452xx Devices */ + /* #define STM32L462xx */ /*!< STM32L462xx Devices */ + /* #define STM32L471xx */ /*!< STM32L471xx Devices */ + /* #define STM32L475xx */ /*!< STM32L475xx Devices */ + /* #define STM32L476xx */ /*!< STM32L476xx Devices */ + /* #define STM32L485xx */ /*!< STM32L485xx Devices */ + /* #define STM32L486xx */ /*!< STM32L486xx Devices */ + /* #define STM32L496xx */ /*!< STM32L496xx Devices */ + /* #define STM32L4A6xx */ /*!< STM32L4A6xx Devices */ + #define STM32L4R5xx /*!< STM32L4R5xx Devices */ + /* #define STM32L4R7xx */ /*!< STM32L4R7xx Devices */ + /* #define STM32L4R9xx */ /*!< STM32L4R9xx Devices */ + /* #define STM32L4S5xx */ /*!< STM32L4S5xx Devices */ + /* #define STM32L4S7xx */ /*!< STM32L4S7xx Devices */ + /* #define STM32L4S9xx */ /*!< STM32L4S9xx Devices */ +#endif + +/* Tip: To avoid modifying this file each time you need to switch between these + devices, you can define the device in your toolchain compiler preprocessor. + */ +#if !defined (USE_HAL_DRIVER) +/** + * @brief Comment the line below if you will not use the peripherals drivers. + In this case, these drivers will not be included and the application code will + be based on direct access to peripherals registers + */ + #define USE_HAL_DRIVER +#endif /* USE_HAL_DRIVER */ + +/** + * @brief CMSIS Device version number + */ +#define __STM32L4_CMSIS_VERSION_MAIN (0x01) /*!< [31:24] main version */ +#define __STM32L4_CMSIS_VERSION_SUB1 (0x04) /*!< [23:16] sub1 version */ +#define __STM32L4_CMSIS_VERSION_SUB2 (0x02) /*!< [15:8] sub2 version */ +#define __STM32L4_CMSIS_VERSION_RC (0x00) /*!< [7:0] release candidate */ +#define __STM32L4_CMSIS_VERSION ((__STM32L4_CMSIS_VERSION_MAIN << 24)\ + |(__STM32L4_CMSIS_VERSION_SUB1 << 16)\ + |(__STM32L4_CMSIS_VERSION_SUB2 << 8 )\ + |(__STM32L4_CMSIS_VERSION_RC)) + +/** + * @} + */ + +/** @addtogroup Device_Included + * @{ + */ + +#if defined(STM32L431xx) + #include "stm32l431xx.h" +#elif defined(STM32L432xx) + #include "stm32l432xx.h" +#elif defined(STM32L433xx) + #include "stm32l433xx.h" +#elif defined(STM32L442xx) + #include "stm32l442xx.h" +#elif defined(STM32L443xx) + #include "stm32l443xx.h" +#elif defined(STM32L451xx) + #include "stm32l451xx.h" +#elif defined(STM32L452xx) + #include "stm32l452xx.h" +#elif defined(STM32L462xx) + #include "stm32l462xx.h" +#elif defined(STM32L471xx) + #include "stm32l471xx.h" +#elif defined(STM32L475xx) + #include "stm32l475xx.h" +#elif defined(STM32L476xx) + #include "stm32l476xx.h" +#elif defined(STM32L485xx) + #include "stm32l485xx.h" +#elif defined(STM32L486xx) + #include "stm32l486xx.h" +#elif defined(STM32L496xx) + #include "stm32l496xx.h" +#elif defined(STM32L4A6xx) + #include "stm32l4a6xx.h" +#elif defined(STM32L4R5xx) + #include "stm32l4r5xx.h" +#elif defined(STM32L4R7xx) + #include "stm32l4r7xx.h" +#elif defined(STM32L4R9xx) + #include "stm32l4r9xx.h" +#elif defined(STM32L4S5xx) + #include "stm32l4s5xx.h" +#elif defined(STM32L4S7xx) + #include "stm32l4s7xx.h" +#elif defined(STM32L4S9xx) + #include "stm32l4s9xx.h" +#else + #error "Please select first the target STM32L4xx device used in your application (in stm32l4xx.h file)" +#endif + +/** + * @} + */ + +/** @addtogroup Exported_types + * @{ + */ +typedef enum +{ + RESET = 0, + SET = !RESET +} FlagStatus, ITStatus; + +typedef enum +{ + DISABLE = 0, + ENABLE = !DISABLE +} FunctionalState; +#define IS_FUNCTIONAL_STATE(STATE) (((STATE) == DISABLE) || ((STATE) == ENABLE)) + +typedef enum +{ + ERROR = 0, + SUCCESS = !ERROR +} ErrorStatus; + +/** + * @} + */ + + +/** @addtogroup Exported_macros + * @{ + */ +#define SET_BIT(REG, BIT) ((REG) |= (BIT)) + +#define CLEAR_BIT(REG, BIT) ((REG) &= ~(BIT)) + +#define READ_BIT(REG, BIT) ((REG) & (BIT)) + +#define CLEAR_REG(REG) ((REG) = (0x0)) + +#define WRITE_REG(REG, VAL) ((REG) = (VAL)) + +#define READ_REG(REG) ((REG)) + +#define MODIFY_REG(REG, CLEARMASK, SETMASK) WRITE_REG((REG), (((READ_REG(REG)) & (~(CLEARMASK))) | (SETMASK))) + +#define POSITION_VAL(VAL) (__CLZ(__RBIT(VAL))) + + +/** + * @} + */ + +#if defined (USE_HAL_DRIVER) + #include "stm32l4xx_hal.h" +#endif /* USE_HAL_DRIVER */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* __STM32L4xx_H */ +/** + * @} + */ + +/** + * @} + */ + + + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/system_stm32l4xx.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/system_stm32l4xx.h new file mode 100644 index 0000000000..4bbc092679 --- /dev/null +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/system_stm32l4xx.h @@ -0,0 +1,125 @@ +/** + ****************************************************************************** + * @file system_stm32l4xx.h + * @author MCD Application Team + * @brief CMSIS Cortex-M4 Device System Source File for STM32L4xx devices. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2017 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/** @addtogroup CMSIS + * @{ + */ + +/** @addtogroup stm32l4xx_system + * @{ + */ + +/** + * @brief Define to prevent recursive inclusion + */ +#ifndef __SYSTEM_STM32L4XX_H +#define __SYSTEM_STM32L4XX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/** @addtogroup STM32L4xx_System_Includes + * @{ + */ + +/** + * @} + */ + + +/** @addtogroup STM32L4xx_System_Exported_Variables + * @{ + */ + /* The SystemCoreClock variable is updated in three ways: + 1) by calling CMSIS function SystemCoreClockUpdate() + 2) by calling HAL API function HAL_RCC_GetSysClockFreq() + 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency + Note: If you use this function to configure the system clock; then there + is no need to call the 2 first functions listed above, since SystemCoreClock + variable is updated automatically. + */ +extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */ + +extern const uint8_t AHBPrescTable[16]; /*!< AHB prescalers table values */ +extern const uint8_t APBPrescTable[8]; /*!< APB prescalers table values */ +extern const uint32_t MSIRangeTable[12]; /*!< MSI ranges table values */ + +/** + * @} + */ + +/** @addtogroup STM32L4xx_System_Exported_Constants + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32L4xx_System_Exported_Macros + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32L4xx_System_Exported_Functions + * @{ + */ + +extern void SystemInit(void); +extern void SystemCoreClockUpdate(void); +extern void SetSysClock(void); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /*__SYSTEM_STM32L4XX_H */ + +/** + * @} + */ + +/** + * @} + */ +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/us_ticker_data.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/us_ticker_data.h new file mode 100644 index 0000000000..cb7f2bb9a9 --- /dev/null +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4R5xI/device/us_ticker_data.h @@ -0,0 +1,43 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2018 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef __US_TICKER_DATA_H +#define __US_TICKER_DATA_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "stm32l4xx.h" +#include "stm32l4xx_ll_tim.h" +#include "cmsis_nvic.h" + +#define TIM_MST TIM5 +#define TIM_MST_IRQ TIM5_IRQn +#define TIM_MST_RCC __HAL_RCC_TIM5_CLK_ENABLE() +#define TIM_MST_DBGMCU_FREEZE __HAL_DBGMCU_FREEZE_TIM5() + +#define TIM_MST_RESET_ON __HAL_RCC_TIM5_FORCE_RESET() +#define TIM_MST_RESET_OFF __HAL_RCC_TIM5_RELEASE_RESET() + +#define TIM_MST_BIT_WIDTH 32 // 16 or 32 + +#define TIM_MST_PCLK 1 // Select the peripheral clock number (1 or 2) + +#ifdef __cplusplus +} +#endif + +#endif // __US_TICKER_DATA_H diff --git a/targets/TARGET_STM/TARGET_STM32L4/analogin_device.c b/targets/TARGET_STM/TARGET_STM32L4/analogin_device.c index e545581489..453b3d564a 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/analogin_device.c +++ b/targets/TARGET_STM/TARGET_STM32L4/analogin_device.c @@ -82,6 +82,9 @@ void analogin_init(analogin_t *obj, PinName pin) obj->handle.Init.DMAContinuousRequests = DISABLE; obj->handle.Init.Overrun = ADC_OVR_DATA_OVERWRITTEN; // DR register is overwritten with the last conversion result in case of overrun obj->handle.Init.OversamplingMode = DISABLE; // No oversampling +#if defined(ADC_CFGR_DFSDMCFG) &&defined(DFSDM1_Channel0) + obj->handle.Init.DFSDMConfig = 0; +#endif // Enable ADC clock __HAL_RCC_ADC_CLK_ENABLE(); diff --git a/targets/TARGET_STM/TARGET_STM32L4/common_objects.h b/targets/TARGET_STM/TARGET_STM32L4/common_objects.h index 9ee16729ea..043a2474ef 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32L4/common_objects.h @@ -143,8 +143,4 @@ struct can_s { }; #endif -/* STM32L4 HAL doesn't provide this API called in rtc_api.c */ -#define __HAL_RCC_RTC_CLKPRESCALER(__RTCCLKSource__) - #endif - diff --git a/targets/TARGET_STM/gpio_irq_api.c b/targets/TARGET_STM/gpio_irq_api.c index b3d1cd200f..55a572f097 100644 --- a/targets/TARGET_STM/gpio_irq_api.c +++ b/targets/TARGET_STM/gpio_irq_api.c @@ -27,7 +27,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************* */ -#include +#include #include "cmsis.h" #include "gpio_irq_api.h" #include "pinmap.h" @@ -268,11 +268,11 @@ void gpio_irq_free(gpio_irq_t *obj) uint32_t gpio_idx = pin_lines_desc[STM_PIN(obj->pin)].gpio_idx; gpio_channel_t *gpio_channel = &channels[obj->irq_index]; - gpio_irq_disable(obj); gpio_channel->pin_mask &= ~(1 << gpio_idx); gpio_channel->channel_ids[gpio_idx] = 0; gpio_channel->channel_gpio[gpio_idx] = 0; gpio_channel->channel_pin[gpio_idx] = 0; + gpio_irq_disable(obj); } void gpio_irq_set(gpio_irq_t *obj, gpio_irq_event event, uint32_t enable) @@ -325,10 +325,20 @@ void gpio_irq_enable(gpio_irq_t *obj) void gpio_irq_disable(gpio_irq_t *obj) { + const uint32_t pin_index = STM_PIN(obj->pin); + const uint32_t gpio_idx = pin_lines_desc[pin_index].gpio_idx; + const uint32_t pin_mask = 1 << gpio_idx; + const uint32_t irq_index = pin_lines_desc[pin_index].irq_index; + const gpio_channel_t *const gpio_channel = &channels[irq_index]; + /* Clear EXTI line configuration */ - LL_EXTI_DisableRisingTrig_0_31(1 << STM_PIN(obj->pin)); - LL_EXTI_DisableFallingTrig_0_31(1 << STM_PIN(obj->pin)); - LL_EXTI_DisableIT_0_31(1 << STM_PIN(obj->pin)); - NVIC_DisableIRQ(obj->irq_n); - NVIC_ClearPendingIRQ(obj->irq_n); + LL_EXTI_DisableRisingTrig_0_31(1 << pin_index); + LL_EXTI_DisableFallingTrig_0_31(1 << pin_index); + LL_EXTI_DisableIT_0_31(1 << pin_index); + + const bool no_more_pins_on_vector = (gpio_channel->pin_mask & ~pin_mask) == 0; + if (no_more_pins_on_vector) { + NVIC_DisableIRQ(obj->irq_n); + NVIC_ClearPendingIRQ(obj->irq_n); + } } diff --git a/targets/TARGET_STM/lp_ticker.c b/targets/TARGET_STM/lp_ticker.c index f4df8b776f..0d0caa9793 100644 --- a/targets/TARGET_STM/lp_ticker.c +++ b/targets/TARGET_STM/lp_ticker.c @@ -145,9 +145,6 @@ void lp_ticker_init(void) __HAL_LPTIM_ENABLE_IT(&LptimHandle, LPTIM_IT_CMPM); HAL_LPTIM_Counter_Start(&LptimHandle, 0xFFFF); - - /* Need to write a compare value in order to get LPTIM_FLAG_CMPOK in set_interrupt */ - __HAL_LPTIM_COMPARE_SET(&LptimHandle, 0); } static void LPTIM1_IRQHandler(void) @@ -194,14 +191,14 @@ void lp_ticker_set_interrupt(timestamp_t timestamp) LptimHandle.Instance = LPTIM1; irq_handler = (void (*)(void))lp_ticker_irq_handler; + __HAL_LPTIM_CLEAR_FLAG(&LptimHandle, LPTIM_FLAG_CMPOK); + __HAL_LPTIM_COMPARE_SET(&LptimHandle, timestamp); /* CMPOK is set by hardware to inform application that the APB bus write operation to the LPTIM_CMP register has been successfully completed */ /* Any successive write before the CMPOK flag be set, will lead to unpredictable results */ while (__HAL_LPTIM_GET_FLAG(&LptimHandle, LPTIM_FLAG_CMPOK) == RESET) { } - __HAL_LPTIM_CLEAR_FLAG(&LptimHandle, LPTIM_FLAG_CMPOK); - __HAL_LPTIM_CLEAR_FLAG(&LptimHandle, LPTIM_FLAG_CMPM); - __HAL_LPTIM_COMPARE_SET(&LptimHandle, timestamp); + lp_ticker_clear_interrupt(); NVIC_EnableIRQ(LPTIM1_IRQn); } @@ -209,6 +206,7 @@ void lp_ticker_set_interrupt(timestamp_t timestamp) void lp_ticker_fire_interrupt(void) { lp_Fired = 1; + irq_handler = (void (*)(void))lp_ticker_irq_handler; NVIC_SetPendingIRQ(LPTIM1_IRQn); NVIC_EnableIRQ(LPTIM1_IRQn); } @@ -217,9 +215,6 @@ void lp_ticker_disable_interrupt(void) { NVIC_DisableIRQ(LPTIM1_IRQn); LptimHandle.Instance = LPTIM1; - /* Waiting last write operation completion */ - while (__HAL_LPTIM_GET_FLAG(&LptimHandle, LPTIM_FLAG_CMPOK) == RESET) { - } } void lp_ticker_clear_interrupt(void) @@ -263,7 +258,6 @@ uint32_t lp_ticker_read(void) void lp_ticker_set_interrupt(timestamp_t timestamp) { - lp_ticker_disable_interrupt(); rtc_set_wake_up_timer(timestamp); } diff --git a/targets/TARGET_STM/mbed_overrides.c b/targets/TARGET_STM/mbed_overrides.c index 9f794ed339..4166cef34e 100644 --- a/targets/TARGET_STM/mbed_overrides.c +++ b/targets/TARGET_STM/mbed_overrides.c @@ -54,5 +54,21 @@ void mbed_sdk_init() SetSysClock(); SystemCoreClockUpdate(); + /* Start LSI clock for RTC */ +#if DEVICE_RTC +#if !MBED_CONF_TARGET_LSE_AVAILABLE + RCC_OscInitTypeDef RCC_OscInitStruct = {0}; + + if (__HAL_RCC_GET_RTC_SOURCE() != RCC_RTCCLKSOURCE_NO_CLK) { + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; + RCC_OscInitStruct.LSIState = RCC_LSI_ON; + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + error("Init : cannot initialize LSI\n"); + } + } +#endif /* ! MBED_CONF_TARGET_LSE_AVAILABLE */ +#endif /* DEVICE_RTC */ + mbed_sdk_inited = 1; } diff --git a/targets/TARGET_STM/mbed_rtx.h b/targets/TARGET_STM/mbed_rtx.h index bd37f4adfe..2d1271a368 100644 --- a/targets/TARGET_STM/mbed_rtx.h +++ b/targets/TARGET_STM/mbed_rtx.h @@ -36,10 +36,10 @@ #endif /* toolchains */ #elif (defined(TARGET_STM32F051R8) ||\ - defined(TARGET_STM32F100RB) ||\ - defined(TARGET_STM32L031K6) ||\ - defined(TARGET_STM32L053C8) ||\ - defined(TARGET_STM32L053R8)) + defined(TARGET_STM32F100RB) ||\ + defined(TARGET_STM32L031K6) ||\ + defined(TARGET_STM32L053C8) ||\ + defined(TARGET_STM32L053R8)) #define INITIAL_SP (0x20002000UL) #elif (defined(TARGET_STM32F303K8) ||\ @@ -73,13 +73,11 @@ #elif defined(TARGET_STM32L443RC) #define INITIAL_SP (0x2000C000UL) -#elif defined(TARGET_STM32L432KC) ||\ - defined (TARGET_STM32L433RC) -#define INITIAL_SP (0x20010000UL) - #elif (defined(TARGET_STM32F303RE) ||\ defined(TARGET_STM32F303ZE) ||\ - defined(TARGET_STM32F401VC)) + defined(TARGET_STM32F401VC) ||\ + defined(TARGET_STM32L432KC) ||\ + defined(TARGET_STM32L433RC)) #define INITIAL_SP (0x20010000UL) #elif defined(TARGET_STM32L152RE) @@ -120,6 +118,9 @@ defined(TARGET_STM32F769NI)) #define INITIAL_SP (0x20080000UL) +#elif defined(TARGET_STM32L4R5ZI) +#define INITIAL_SP (0x200A0000UL) + #else #error "INITIAL_SP is not defined for this target in the mbed_rtx.h file" #endif diff --git a/targets/TARGET_STM/rtc_api.c b/targets/TARGET_STM/rtc_api.c index e88e9cd28d..90d902accf 100644 --- a/targets/TARGET_STM/rtc_api.c +++ b/targets/TARGET_STM/rtc_api.c @@ -60,14 +60,12 @@ void rtc_init(void) #if MBED_CONF_TARGET_LSE_AVAILABLE RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE; - RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // Mandatory, otherwise the PLL is reconfigured! + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; RCC_OscInitStruct.LSEState = RCC_LSE_ON; - if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { error("Cannot initialize RTC with LSE\n"); } - __HAL_RCC_RTC_CLKPRESCALER(RCC_RTCCLKSOURCE_LSE); __HAL_RCC_RTC_CONFIG(RCC_RTCCLKSOURCE_LSE); PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC; @@ -76,19 +74,13 @@ void rtc_init(void) error("PeriphClkInitStruct RTC failed with LSE\n"); } #else /* MBED_CONF_TARGET_LSE_AVAILABLE */ - // Reset Backup domain - __HAL_RCC_BACKUPRESET_FORCE(); - __HAL_RCC_BACKUPRESET_RELEASE(); - - // Enable LSI clock RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI; - RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // Mandatory, otherwise the PLL is reconfigured! + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; RCC_OscInitStruct.LSIState = RCC_LSI_ON; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { error("Cannot initialize RTC with LSI\n"); } - __HAL_RCC_RTC_CLKPRESCALER(RCC_RTCCLKSOURCE_LSI); __HAL_RCC_RTC_CONFIG(RCC_RTCCLKSOURCE_LSI); PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC; @@ -116,14 +108,14 @@ void rtc_init(void) #endif /* TARGET_STM32F1 */ if (HAL_RTC_Init(&RtcHandle) != HAL_OK) { - error("RTC initialization failed"); + error("RTC initialization failed\n"); } #if !(TARGET_STM32F1) && !(TARGET_STM32F2) /* STM32F1 : there are no shadow registers */ /* STM32F2 : shadow registers can not be bypassed */ if (HAL_RTCEx_EnableBypassShadow(&RtcHandle) != HAL_OK) { - error("EnableBypassShadow error"); + error("EnableBypassShadow error\n"); } #endif /* TARGET_STM32F1 || TARGET_STM32F2 */ } @@ -389,6 +381,7 @@ void rtc_set_wake_up_timer(timestamp_t timestamp) } RtcHandle.Instance = RTC; + HAL_RTCEx_DeactivateWakeUpTimer(&RtcHandle); if (HAL_RTCEx_SetWakeUpTimer_IT(&RtcHandle, WakeUpCounter, RTC_WAKEUPCLOCK_RTCCLK_DIV4) != HAL_OK) { error("rtc_set_wake_up_timer init error\n"); } @@ -410,10 +403,7 @@ void rtc_fire_interrupt(void) void rtc_deactivate_wake_up_timer(void) { RtcHandle.Instance = RTC; - __HAL_RTC_WRITEPROTECTION_DISABLE(&RtcHandle); - __HAL_RTC_WAKEUPTIMER_DISABLE(&RtcHandle); - __HAL_RTC_WAKEUPTIMER_DISABLE_IT(&RtcHandle, RTC_IT_WUT); - __HAL_RTC_WRITEPROTECTION_ENABLE(&RtcHandle); + HAL_RTCEx_DeactivateWakeUpTimer(&RtcHandle); NVIC_DisableIRQ(RTC_WKUP_IRQn); } diff --git a/targets/TARGET_STM/serial_api.c b/targets/TARGET_STM/serial_api.c index 9ad3d70ba8..37c848664e 100644 --- a/targets/TARGET_STM/serial_api.c +++ b/targets/TARGET_STM/serial_api.c @@ -354,7 +354,7 @@ void serial_baud(serial_t *obj, int baudrate) if (!__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY)) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE; - RCC_OscInitStruct.HSIState = RCC_LSE_ON; + RCC_OscInitStruct.LSEState = RCC_LSE_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_OFF; HAL_RCC_OscConfig(&RCC_OscInitStruct); } diff --git a/targets/TARGET_STM/sleep.c b/targets/TARGET_STM/sleep.c index 50759eb74b..631e283915 100644 --- a/targets/TARGET_STM/sleep.c +++ b/targets/TARGET_STM/sleep.c @@ -158,6 +158,7 @@ void hal_sleep(void) } extern int serial_is_tx_ongoing(void); +extern int mbed_sdk_inited; void hal_deepsleep(void) { @@ -200,6 +201,10 @@ void hal_deepsleep(void) HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI); #endif /* TARGET_STM32L4 */ + /* Prevent HAL_GetTick() from using ticker_read_us() to read the + * us_ticker timestamp until the us_ticker context is restored. */ + mbed_sdk_inited = 0; + // Verify Clock Out of Deep Sleep ForceClockOutofDeepSleep(); @@ -214,6 +219,10 @@ void hal_deepsleep(void) restore_timer_ctx(); + /* us_ticker context restored, allow HAL_GetTick() to read the us_ticker + * timestamp via ticker_read_us() again. */ + mbed_sdk_inited = 1; + // Enable IRQs core_util_critical_section_exit(); } diff --git a/targets/TARGET_Silicon_Labs/TARGET_EFM32/crc_api.c b/targets/TARGET_Silicon_Labs/TARGET_EFM32/crc_api.c index 4e7c71de0c..68ed6c77f0 100644 --- a/targets/TARGET_Silicon_Labs/TARGET_EFM32/crc_api.c +++ b/targets/TARGET_Silicon_Labs/TARGET_EFM32/crc_api.c @@ -34,6 +34,7 @@ #include "em_gpcrc.h" static bool revOutput = false; +static bool enableWordInput = false; static uint32_t final_xor; bool hal_crc_is_supported(const crc_mbed_config_t *config) @@ -75,21 +76,24 @@ void hal_crc_compute_partial_start(const crc_mbed_config_t *config) // defined by the mbed API. Emlib does the reversal on the poly, but // not on the initial value. if (config->width == 16) { + enableWordInput = false; crc_init.initValue = __RBIT(config->initial_xor) >> 16; } else { + enableWordInput = true; crc_init.initValue = __RBIT(config->initial_xor); } // GPCRC operates on bit-reversed inputs and outputs vs the standard // defined by the mbed API, so reflect_in/out needs to be negated. if (config->reflect_in) { - crc_init.reverseByteOrder = false; crc_init.reverseBits = false; } else { - crc_init.reverseByteOrder = true; crc_init.reverseBits = true; } + // Input is little-endian + crc_init.reverseByteOrder = false; + // Disable byte mode to be able to run a faster U32 input version crc_init.enableByteMode = false; @@ -109,19 +113,30 @@ void hal_crc_compute_partial(const uint8_t *data, const size_t size) return; } - if (((uint32_t)data & 0x3) != 0 || size < 4) { - // Unaligned or very small input, run a bytewise CRC + if (!enableWordInput || size < sizeof(uint32_t)) { + // Input to a non-word-sized poly, or too small data size for a word input for (size_t i = 0; i < size; i++) { GPCRC_InputU8(GPCRC, data[i]); } } else { - // Aligned input, run 32-bit inputs as long as possible to make go faster. size_t i = 0; - for (; i < (size & (~0x3)); i+=4) { - GPCRC_InputU32(GPCRC, *((uint32_t*)(&data[i]))); - } - for (; i < size; i++) { + + // If input is unaligned, take off as many bytes as needed to align + while (((uint32_t)(data + i) & 0x3) != 0) { GPCRC_InputU8(GPCRC, data[i]); + i++; + } + + // If enough input remaining to do word-sized writes, do so + while ((size - i) >= sizeof(uint32_t)) { + GPCRC_InputU32(GPCRC, *((uint32_t*)(&data[i]))); + i += sizeof(uint32_t); + } + + // Do byte input to pick off the last remaining bytes + while (i < size) { + GPCRC_InputU8(GPCRC, data[i]); + i++; } } } diff --git a/targets/TARGET_Silicon_Labs/TARGET_EFM32/pwmout_api.c b/targets/TARGET_Silicon_Labs/TARGET_EFM32/pwmout_api.c index 759c1533d3..9553d1e4a5 100644 --- a/targets/TARGET_Silicon_Labs/TARGET_EFM32/pwmout_api.c +++ b/targets/TARGET_Silicon_Labs/TARGET_EFM32/pwmout_api.c @@ -302,7 +302,7 @@ void pwmout_period(pwmout_t *obj, float seconds) } //Check if anything changed - if(((PWM_TIMER->CTRL & ~_TIMER_CTRL_PRESC_MASK) == (pwm_prescaler_div << _TIMER_CTRL_PRESC_SHIFT)) && (TIMER_TopGet(PWM_TIMER) == cycles)) return; + if(((PWM_TIMER->CTRL & _TIMER_CTRL_PRESC_MASK) == (pwm_prescaler_div << _TIMER_CTRL_PRESC_SHIFT)) && (TIMER_TopGet(PWM_TIMER) == cycles)) return; //Save previous period for recalculation of duty cycles uint32_t previous_period_cycles = PWM_TIMER->TOPB; diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500/device/TOOLCHAIN_IAR/W7500_Flash.icf b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500/device/TOOLCHAIN_IAR/W7500_Flash.icf index dd71139d17..b73571e33d 100644 --- a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500/device/TOOLCHAIN_IAR/W7500_Flash.icf +++ b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500/device/TOOLCHAIN_IAR/W7500_Flash.icf @@ -8,9 +8,9 @@ define symbol __ICFEDIT_region_ROM_start__ = 0x00000000; define symbol __ICFEDIT_region_ROM_end__ = 0x00020000; define symbol __ICFEDIT_region_RAM_start__ = 0x20000000; define symbol __ICFEDIT_region_RAM_end__ = 0x20004000; -/*-Sizes-*/ +/*-Heap 1/4 of ram and stack 1/8-*/ define symbol __ICFEDIT_size_cstack__ = 0x00000400; -define symbol __ICFEDIT_size_heap__ = 0x00000400; +define symbol __ICFEDIT_size_heap__ = 0x00001000; /**** End of ICF editor section. ###ICF###*/ @@ -28,4 +28,4 @@ place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; place in ROM_region { readonly }; place in RAM_region { readwrite, - block CSTACK, block HEAP }; \ No newline at end of file + block CSTACK, block HEAP }; diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500ECO/device/TOOLCHAIN_IAR/W7500_Flash.icf b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500ECO/device/TOOLCHAIN_IAR/W7500_Flash.icf index dd71139d17..b73571e33d 100644 --- a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500ECO/device/TOOLCHAIN_IAR/W7500_Flash.icf +++ b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500ECO/device/TOOLCHAIN_IAR/W7500_Flash.icf @@ -8,9 +8,9 @@ define symbol __ICFEDIT_region_ROM_start__ = 0x00000000; define symbol __ICFEDIT_region_ROM_end__ = 0x00020000; define symbol __ICFEDIT_region_RAM_start__ = 0x20000000; define symbol __ICFEDIT_region_RAM_end__ = 0x20004000; -/*-Sizes-*/ +/*-Heap 1/4 of ram and stack 1/8-*/ define symbol __ICFEDIT_size_cstack__ = 0x00000400; -define symbol __ICFEDIT_size_heap__ = 0x00000400; +define symbol __ICFEDIT_size_heap__ = 0x00001000; /**** End of ICF editor section. ###ICF###*/ @@ -28,4 +28,4 @@ place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; place in ROM_region { readonly }; place in RAM_region { readwrite, - block CSTACK, block HEAP }; \ No newline at end of file + block CSTACK, block HEAP }; diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500P/device/TOOLCHAIN_IAR/W7500_Flash.icf b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500P/device/TOOLCHAIN_IAR/W7500_Flash.icf index dd71139d17..b73571e33d 100644 --- a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500P/device/TOOLCHAIN_IAR/W7500_Flash.icf +++ b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500P/device/TOOLCHAIN_IAR/W7500_Flash.icf @@ -8,9 +8,9 @@ define symbol __ICFEDIT_region_ROM_start__ = 0x00000000; define symbol __ICFEDIT_region_ROM_end__ = 0x00020000; define symbol __ICFEDIT_region_RAM_start__ = 0x20000000; define symbol __ICFEDIT_region_RAM_end__ = 0x20004000; -/*-Sizes-*/ +/*-Heap 1/4 of ram and stack 1/8-*/ define symbol __ICFEDIT_size_cstack__ = 0x00000400; -define symbol __ICFEDIT_size_heap__ = 0x00000400; +define symbol __ICFEDIT_size_heap__ = 0x00001000; /**** End of ICF editor section. ###ICF###*/ @@ -28,4 +28,4 @@ place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; place in ROM_region { readonly }; place in RAM_region { readwrite, - block CSTACK, block HEAP }; \ No newline at end of file + block CSTACK, block HEAP }; diff --git a/targets/targets.json b/targets/targets.json index 705a70adf9..984379eeb4 100755 --- a/targets/targets.json +++ b/targets/targets.json @@ -243,7 +243,7 @@ "extra_labels": ["NXP", "LPC176X", "MBED_LPC1768", "NXP_EMAC"], "supported_toolchains": ["ARM", "uARM", "GCC_ARM", "GCC_CR", "IAR"], "detect_code": ["1010"], - "device_has": ["USTICKER", "ANALOGIN", "ANALOGOUT", "CAN", "DEBUG_AWARENESS", "EMAC", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "LOCALFILESYSTEM", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "SEMIHOST", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES", "FLASH"], + "device_has": ["RTC", "USTICKER", "ANALOGIN", "ANALOGOUT", "CAN", "DEBUG_AWARENESS", "EMAC", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "LOCALFILESYSTEM", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "SEMIHOST", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES", "FLASH"], "release_versions": ["2", "5"], "device_name": "LPC1768", "bootloader_supported": true, @@ -753,7 +753,12 @@ }, "stdio_uart_rx": { "help": "default RX STDIO pins is defined in PinNames.h file, but it can be overridden" - } + }, + "lpticker_delay_ticks": { + "help": "https://os.mbed.com/docs/latest/porting/low-power-ticker.html", + "value": 1, + "macro_name": "LPTICKER_DELAY_TICKS" + } }, "device_has": ["USTICKER", "LPTICKER", "RTC", "ANALOGIN", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "SERIAL", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH", "STDIO_MESSAGES"] }, @@ -882,11 +887,6 @@ "help": "Mask value : USE_PLL_HSE_EXTC | USE_PLL_HSE_XTAL (need HW patch) | USE_PLL_HSI", "value": "USE_PLL_HSE_EXTC|USE_PLL_HSI", "macro_name": "CLOCK_SOURCE" - }, - "lpticker_delay_ticks": { - "help": "For targets with low frequency system clock, set lpticker_delay_ticks value to 1", - "value": 1, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "detect_code": ["0755"], @@ -905,11 +905,6 @@ "help": "Mask value : USE_PLL_HSE_EXTC | USE_PLL_HSE_XTAL (need HW patch) | USE_PLL_HSI", "value": "USE_PLL_HSE_EXTC|USE_PLL_HSI", "macro_name": "CLOCK_SOURCE" - }, - "lpticker_delay_ticks": { - "help": "For targets with low frequency system clock, set lpticker_delay_ticks value to 1", - "value": 1, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "detect_code": ["0730"], @@ -928,11 +923,6 @@ "help": "Mask value : USE_PLL_HSE_EXTC | USE_PLL_HSE_XTAL (need HW patch) | USE_PLL_HSI", "value": "USE_PLL_HSE_EXTC|USE_PLL_HSI", "macro_name": "CLOCK_SOURCE" - }, - "lpticker_delay_ticks": { - "help": "For targets with low frequency system clock, set lpticker_delay_ticks value to 1", - "value": 1, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "detect_code": ["0750"], @@ -1131,11 +1121,6 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "detect_code": ["0744"], @@ -1261,11 +1246,6 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "detect_code": ["0743"], @@ -1288,11 +1268,6 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "detect_code": ["0743"], @@ -1443,11 +1418,6 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "macros_add": ["USBHOST_OTHER"], @@ -1479,11 +1449,6 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "macros_add": ["TRANSACTION_QUEUE_SIZE_SPI=2", "USBHOST_OTHER", "MBEDTLS_CONFIG_HW_SUPPORT"], @@ -1518,11 +1483,6 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "supported_form_factors": ["ARDUINO"], @@ -1552,13 +1512,9 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, + "overrides": {"lpticker_delay_ticks": 4}, "detect_code": ["0780"], "device_has_add": ["CRC", "SERIAL_FC", "FLASH"], "default_lib": "small", @@ -1580,13 +1536,9 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, + "overrides": {"lpticker_delay_ticks": 4}, "detect_code": ["0790"], "device_has_add": ["CRC", "SERIAL_FC", "FLASH"], "default_lib": "small", @@ -1607,13 +1559,9 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, + "overrides": {"lpticker_delay_ticks": 4}, "detect_code": ["0715"], "device_has_add": ["ANALOGOUT", "CRC", "SERIAL_FC", "SERIAL_ASYNCH", "FLASH"], "default_lib": "small", @@ -1634,13 +1582,9 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, + "overrides": {"lpticker_delay_ticks": 4}, "detect_code": ["0760"], "device_has_add": ["ANALOGOUT", "CRC", "SERIAL_FC", "SERIAL_ASYNCH", "TRNG", "FLASH"], "release_versions": ["2", "5"], @@ -1656,11 +1600,6 @@ "help": "Mask value : USE_PLL_HSE_EXTC | USE_PLL_HSE_XTAL (need HW patch) | USE_PLL_HSI", "value": "USE_PLL_HSE_EXTC|USE_PLL_HSI", "macro_name": "CLOCK_SOURCE" - }, - "lpticker_delay_ticks": { - "help": "For targets with low frequency system clock, set lpticker_delay_ticks value to 1", - "value": 1, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "detect_code": ["0710"], @@ -1682,11 +1621,6 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "detect_code": ["0770"], @@ -1709,11 +1643,6 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "detect_code": ["0779"], @@ -1756,11 +1685,6 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "detect_code": ["0765"], @@ -1802,11 +1726,6 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "detect_code": ["0827"], @@ -2014,14 +1933,12 @@ "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, - "overrides": {"lse_available": 0}, + "overrides": { + "lse_available": 0, + "lpticker_delay_ticks": 4 + }, "device_has_add": ["ANALOGOUT", "CRC", "SERIAL_FC", "FLASH"], "default_lib": "small", "release_versions": ["2"], @@ -2041,13 +1958,9 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, + "overrides": {"lpticker_delay_ticks": 4}, "detect_code": ["0833"], "device_has_add": ["ANALOGOUT", "SERIAL_FC", "SERIAL_ASYNCH", "TRNG", "FLASH"], "release_versions": ["2", "5"], @@ -2081,11 +1994,6 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "detect_code": ["0815"], @@ -2115,11 +2023,6 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "detect_code": ["0817"], @@ -2144,11 +2047,6 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "supported_form_factors": ["ARDUINO"], @@ -2172,11 +2070,6 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "detect_code": ["0820"], @@ -3443,7 +3336,7 @@ }, "EFR32MG1_BRD4150": { "inherits": ["EFR32MG1P132F256GM48"], - "device_has": ["ANALOGIN", "CRC", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "LPTICKER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_ASYNCH", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH", "STDIO_MESSAGES", "USTICKER", "FLASH"], + "device_has": ["802_15_4_PHY", "ANALOGIN", "CRC", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "LPTICKER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_ASYNCH", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH", "STDIO_MESSAGES", "USTICKER", "FLASH"], "forced_reset_timeout": 2, "config": { "hf_clock_src": { @@ -3482,11 +3375,14 @@ "macro_name": "EFM_BC_EN" } }, + "overrides": { + "network-default-interface-type": "MESH" + }, "public": false }, "TB_SENSE_1": { "inherits": ["EFR32MG1P233F256GM48"], - "device_has": ["ANALOGIN", "CRC", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "LPTICKER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_ASYNCH", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH", "STDIO_MESSAGES", "USTICKER", "FLASH"], + "device_has": ["802_15_4_PHY", "ANALOGIN", "CRC", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "LPTICKER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_ASYNCH", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH", "STDIO_MESSAGES", "USTICKER", "FLASH"], "forced_reset_timeout": 5, "config": { "hf_clock_src": { @@ -3519,6 +3415,9 @@ "value": "cmuHFRCOFreq_32M0Hz", "macro_name": "HFRCO_FREQUENCY_ENUM" } + }, + "overrides": { + "network-default-interface-type": "MESH" } }, "EFM32PG12B500F1024GL125": { @@ -3588,7 +3487,7 @@ "TB_SENSE_12": { "inherits": ["EFR32MG12P332F1024GL125"], "device_name": "EFR32MG12P332F1024GL125", - "device_has": ["ANALOGIN", "CRC", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "LPTICKER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_ASYNCH", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH", "STDIO_MESSAGES", "USTICKER", "TRNG", "FLASH"], + "device_has": ["802_15_4_PHY", "ANALOGIN", "CRC", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "LPTICKER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_ASYNCH", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH", "STDIO_MESSAGES", "USTICKER", "TRNG", "FLASH"], "forced_reset_timeout": 5, "config": { "hf_clock_src": { @@ -3621,6 +3520,9 @@ "value": "cmuHFRCOFreq_32M0Hz", "macro_name": "HFRCO_FREQUENCY_ENUM" } + }, + "overrides": { + "network-default-interface-type": "MESH" } }, "EFM32GG11B820F2048GL192": { @@ -3680,6 +3582,9 @@ "value": "PG13", "macro_name": "QSPI_FLASH_EN" } + }, + "overrides": { + "network-default-interface-type": "ETHERNET" } }, "WIZWIKI_W7500": { @@ -3885,7 +3790,7 @@ "SLEEP", "SPI", "SPI_ASYNCH", - "STCLK_OFF_DURING_SLEEP", + "SYSTICK_CLK_OFF_DURING_SLEEP", "TRNG", "USTICKER" ], @@ -3990,7 +3895,7 @@ "SLEEP", "SPI", "SPI_ASYNCH", - "STCLK_OFF_DURING_SLEEP", + "SYSTICK_CLK_OFF_DURING_SLEEP", "TRNG", "USTICKER", "QSPI" @@ -4038,7 +3943,7 @@ "default_toolchain": "GCC_ARM", "extra_labels_add": ["STM32F1", "STM32F103C8"], "supported_toolchains": ["GCC_ARM"], - "device_has_add": [], + "device_has_add": ["CAN", "SERIAL_FC", "SERIAL_ASYNCH", "FLASH"], "device_has_remove": ["STDIO_MESSAGES", "LPTICKER"] }, "NUMAKER_PFM_NUC472": { @@ -4270,11 +4175,6 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "detect_code": ["0822"], @@ -4296,11 +4196,6 @@ "lpticker_lptim": { "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", "value": 1 - }, - "lpticker_delay_ticks": { - "help": "In case of lpticker_lptim=1, set lpticker_delay_ticks=3", - "value": 3, - "macro_name": "LPTICKER_DELAY_TICKS" } }, "detect_code": ["0823"], @@ -4311,16 +4206,39 @@ "NUCLEO_L496ZG_P": { "inherits": ["NUCLEO_L496ZG"], "detect_code": ["0828"] + }, + "NUCLEO_L4R5ZI": { + "inherits": ["FAMILY_STM32"], + "supported_form_factors": ["ARDUINO", "MORPHO"], + "core": "Cortex-M4F", + "extra_labels_add": ["STM32L4", "STM32L4R5ZI", "STM32L4R5xI"], + "config": { + "clock_source": { + "help": "Mask value : USE_PLL_HSE_EXTC (need HW patch) | USE_PLL_HSE_XTAL (need HW patch) | USE_PLL_HSI | USE_PLL_MSI", + "value": "USE_PLL_MSI", + "macro_name": "CLOCK_SOURCE" + }, + "lpticker_lptim": { + "help": "This target supports LPTIM. Set value 1 to use LPTIM for LPTICKER, or 0 to use RTC wakeup timer", + "value": 1 + } }, + "detect_code": ["0776"], + "device_has_add": ["ANALOGOUT", "CAN", "CRC", "SERIAL_ASYNCH", "SERIAL_FC", "TRNG", "FLASH"], + "release_versions": ["2", "5"], + "device_name": "STM32L4R5ZI", + "bootloader_supported": true + }, "VBLUNO52": { "supported_form_factors": ["ARDUINO"], "inherits": ["MCU_NRF52832"], "release_versions": ["5"], "device_name": "nRF52832_xxAA" }, - "NUMAKER_PFM_M487": { + "MCU_M480": { "core": "Cortex-M4F", "default_toolchain": "ARM", + "public": false, "extra_labels": ["NUVOTON", "M480", "FLASH_CMSIS_ALGO","NUVOTON_EMAC"], "is_disk_virtual": true, "supported_toolchains": ["ARM", "uARM", "GCC_ARM", "IAR"], @@ -4354,12 +4272,19 @@ "macros_add": ["MBEDTLS_CONFIG_HW_SUPPORT", "LPTICKER_DELAY_TICKS=3"], "device_has": ["USTICKER", "LPTICKER", "RTC", "ANALOGIN", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "SERIAL", "SERIAL_ASYNCH", "SERIAL_FC", "STDIO_MESSAGES", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH", "TRNG", "FLASH", "CAN", "EMAC"], "release_versions": ["5"], - "device_name": "M487JIDAE", "bootloader_supported": true, "overrides": { "network-default-interface-type": "ETHERNET" } }, + "NUMAKER_PFM_M487": { + "inherits": ["MCU_M480"], + "device_name": "M487JIDAE" + }, + "NUMAKER_IOT_M487": { + "inherits": ["MCU_M480"], + "device_name": "M487JIDAE" + }, "TMPM066": { "inherits": ["Target"], "core": "Cortex-M0", diff --git a/tools/bootloaders/MTB_MTS_DRAGONFLY/LICENSE.txt b/tools/bootloaders/MTB_MTS_DRAGONFLY/LICENSE.txt new file mode 100644 index 0000000000..d648fd563a --- /dev/null +++ b/tools/bootloaders/MTB_MTS_DRAGONFLY/LICENSE.txt @@ -0,0 +1,49 @@ +Permissive Binary License + +Version 1.0, September 2015 + +Redistribution. Redistribution and use in binary form, without +modification, are permitted provided that the following conditions are +met: + +1) Redistributions must reproduce the above copyright notice and the + following disclaimer in the documentation and/or other materials + provided with the distribution. + +2) Unless to the extent explicitly permitted by law, no reverse + engineering, decompilation, or disassembly of this software is + permitted. + +3) Redistribution as part of a software development kit must include the + accompanying file named “DEPENDENCIES” and any dependencies listed in + that file. + +4) Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +Limited patent license. The copyright holders (and contributors) grant a +worldwide, non-exclusive, no-charge, royalty-free patent license to +make, have made, use, offer to sell, sell, import, and otherwise +transfer this software, where such license applies only to those patent +claims licensable by the copyright holders (and contributors) that are +necessarily infringed by this software. This patent license shall not +apply to any combinations that include this software. No hardware is +licensed hereunder. + +If you institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the software +itself infringes your patent(s), then your rights granted under this +license shall terminate as of the date such litigation is filed. + +DISCLAIMER. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND +CONTRIBUTORS "AS IS." ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT +NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tools/bootloaders/MTS_DRAGONFLY_F411RE/LICENSE.txt b/tools/bootloaders/MTS_DRAGONFLY_F411RE/LICENSE.txt new file mode 100644 index 0000000000..d648fd563a --- /dev/null +++ b/tools/bootloaders/MTS_DRAGONFLY_F411RE/LICENSE.txt @@ -0,0 +1,49 @@ +Permissive Binary License + +Version 1.0, September 2015 + +Redistribution. Redistribution and use in binary form, without +modification, are permitted provided that the following conditions are +met: + +1) Redistributions must reproduce the above copyright notice and the + following disclaimer in the documentation and/or other materials + provided with the distribution. + +2) Unless to the extent explicitly permitted by law, no reverse + engineering, decompilation, or disassembly of this software is + permitted. + +3) Redistribution as part of a software development kit must include the + accompanying file named “DEPENDENCIES” and any dependencies listed in + that file. + +4) Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +Limited patent license. The copyright holders (and contributors) grant a +worldwide, non-exclusive, no-charge, royalty-free patent license to +make, have made, use, offer to sell, sell, import, and otherwise +transfer this software, where such license applies only to those patent +claims licensable by the copyright holders (and contributors) that are +necessarily infringed by this software. This patent license shall not +apply to any combinations that include this software. No hardware is +licensed hereunder. + +If you institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the software +itself infringes your patent(s), then your rights granted under this +license shall terminate as of the date such litigation is filed. + +DISCLAIMER. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND +CONTRIBUTORS "AS IS." ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT +NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tools/bootloaders/MTS_MDOT_F411RE/LICENSE.txt b/tools/bootloaders/MTS_MDOT_F411RE/LICENSE.txt new file mode 100644 index 0000000000..d648fd563a --- /dev/null +++ b/tools/bootloaders/MTS_MDOT_F411RE/LICENSE.txt @@ -0,0 +1,49 @@ +Permissive Binary License + +Version 1.0, September 2015 + +Redistribution. Redistribution and use in binary form, without +modification, are permitted provided that the following conditions are +met: + +1) Redistributions must reproduce the above copyright notice and the + following disclaimer in the documentation and/or other materials + provided with the distribution. + +2) Unless to the extent explicitly permitted by law, no reverse + engineering, decompilation, or disassembly of this software is + permitted. + +3) Redistribution as part of a software development kit must include the + accompanying file named “DEPENDENCIES” and any dependencies listed in + that file. + +4) Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +Limited patent license. The copyright holders (and contributors) grant a +worldwide, non-exclusive, no-charge, royalty-free patent license to +make, have made, use, offer to sell, sell, import, and otherwise +transfer this software, where such license applies only to those patent +claims licensable by the copyright holders (and contributors) that are +necessarily infringed by this software. This patent license shall not +apply to any combinations that include this software. No hardware is +licensed hereunder. + +If you institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the software +itself infringes your patent(s), then your rights granted under this +license shall terminate as of the date such litigation is filed. + +DISCLAIMER. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND +CONTRIBUTORS "AS IS." ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT +NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tools/bootloaders/REALTEK_RTL8195AM/LICENSE b/tools/bootloaders/REALTEK_RTL8195AM/LICENSE new file mode 100644 index 0000000000..591ac29615 --- /dev/null +++ b/tools/bootloaders/REALTEK_RTL8195AM/LICENSE @@ -0,0 +1,49 @@ +Permissive Binary License + +Version 1.0, September 2015 + +Redistribution. Redistribution and use in binary form, without +modification, are permitted provided that the following conditions are +met: + +1) Redistributions must reproduce the above copyright notice and the + following disclaimer in the documentation and/or other materials + provided with the distribution. + +2) Unless to the extent explicitly permitted by law, no reverse + engineering, decompilation, or disassembly of this software is + permitted. + +3) Redistribution as part of a software development kit must include the + accompanying file named "DEPENDENCIES" and any dependencies listed in + that file. + +4) Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +Limited patent license. The copyright holders (and contributors) grant a +worldwide, non-exclusive, no-charge, royalty-free patent license to +make, have made, use, offer to sell, sell, import, and otherwise +transfer this software, where such license applies only to those patent +claims licensable by the copyright holders (and contributors) that are +necessarily infringed by this software. This patent license shall not +apply to any combinations that include this software. No hardware is +licensed hereunder. + +If you institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the software +itself infringes your patent(s), then your rights granted under this +license shall terminate as of the date such litigation is filed. + +DISCLAIMER. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND +CONTRIBUTORS "AS IS." ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT +NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/tools/bootloaders/REALTEK_RTL8195AM/ram_1.bin b/tools/bootloaders/REALTEK_RTL8195AM/ram_1.bin index 5179455fb5..3a229b4341 100644 Binary files a/tools/bootloaders/REALTEK_RTL8195AM/ram_1.bin and b/tools/bootloaders/REALTEK_RTL8195AM/ram_1.bin differ diff --git a/tools/build_api.py b/tools/build_api.py index 4a3de865d3..0f25ffa775 100644 --- a/tools/build_api.py +++ b/tools/build_api.py @@ -1357,4 +1357,4 @@ def merge_build_data(filename, toolchain_report, app_type): if 'type' not in build[0]: build[0]['type'] = app_type build_data['builds'].insert(0, build[0]) - dump(build_data, open(filename, "wb"), indent=4, separators=(',', ': ')) + dump(build_data, open(filename, "w"), indent=4, separators=(',', ': ')) diff --git a/tools/device_management.py b/tools/device_management.py index c2ece1c1b0..7893634633 100644 --- a/tools/device_management.py +++ b/tools/device_management.py @@ -44,6 +44,15 @@ from tools.options import extract_mcus class MbedExtendedArgs(MainArgumentParser): + + def __init__(self, *args, **kwargs): + MainArgumentParser.__init__(self, *args, **kwargs) + self.parser.prog = "mbed device-management" + self.parser.description = ( + "Create or transform a manifest. " + "Use {} [command] -h for help on each command." + ).format(self.parser.prog) + def _addCreateArgs(self, parser, exclusions=[]): if 'payload' not in exclusions: parser.add_argument( diff --git a/tools/export/embitz/__init__.py b/tools/export/embitz/__init__.py index 9d4ebac9b1..7588da6e74 100644 --- a/tools/export/embitz/__init__.py +++ b/tools/export/embitz/__init__.py @@ -64,17 +64,13 @@ class EmBitz(Exporter): l, _ = splitext(basename(lib)) libraries.append(l[3:]) - - if self.resources.linker_script is None: - self.resources.linker_script = '' - ctx = { 'name': self.project_name, 'target': self.target, 'toolchain': self.toolchain.name, 'source_files': source_files, 'include_paths': self.resources.inc_dirs, - 'script_file': self.resources.linker_script, + 'script_file': self.resources.linker_script or '', 'library_paths': self.resources.lib_dirs, 'libraries': libraries, 'symbols': self.toolchain.get_symbols(), diff --git a/tools/export/mcuxpresso/__init__.py b/tools/export/mcuxpresso/__init__.py index 5c84716353..d840b6deb1 100644 --- a/tools/export/mcuxpresso/__init__.py +++ b/tools/export/mcuxpresso/__init__.py @@ -56,7 +56,7 @@ class MCUXpresso(GNUARMEclipse): @classmethod def is_target_supported(cls, target_name): - # targes suppoerted when .cproject templatefile exists + # target is supported when *_cproject.tmpl template file exists if exists(cls.TEMPLATE_DIR + '/mcuxpresso/' + target_name + '_cproject.tmpl'): target = TARGET_MAP[target_name] return apply_supported_whitelist( diff --git a/tools/export/mcuxpresso/lpc1769_cproject.tmpl b/tools/export/mcuxpresso/lpc1769_cproject.tmpl new file mode 100644 index 0000000000..4dbd4572c6 --- /dev/null +++ b/tools/export/mcuxpresso/lpc1769_cproject.tmpl @@ -0,0 +1,77 @@ +{% extends "mcuxpresso/.cproject.tmpl" %} + +{% block cpu_config %}<?xml version="1.0" encoding="UTF-8"?> +<TargetConfig> +<Properties property_0="" property_1="" property_2="" property_3="NXP" property_4="LPC1769" property_count="5" version="1"/> +<infoList vendor="NXP"> +<info chip="LPC1769" match_id="0x00013f37,0x26013F37,0x26113F37" name="LPC1769" package="lpc17_lqfp100.xml"> +<chip> +<name>LPC1769</name> +<family>LPC17xx</family> +<vendor>NXP (formerly Philips)</vendor> +<reset board="None" core="Real" sys="Real"/> +<clock changeable="TRUE" freq="20MHz" is_accurate="TRUE"/> +<memory can_program="true" id="Flash" is_ro="true" type="Flash"/> +<memory id="RAM" type="RAM"/> +<memory id="Periph" is_volatile="true" type="Peripheral"/> +<memoryInstance derived_from="Flash" id="MFlash512" location="0x00000000" size="0x80000"/> +<memoryInstance derived_from="RAM" id="RamLoc32" location="0x10000000" size="0x8000"/> +<memoryInstance derived_from="RAM" id="RamAHB32" location="0x2007c000" size="0x8000"/> +<prog_flash blocksz="0x1000" location="0" maxprgbuff="0x1000" progwithcode="TRUE" size="0x10000"/> +<prog_flash blocksz="0x8000" location="0x10000" maxprgbuff="0x1000" progwithcode="TRUE" size="0x70000"/> +<peripheralInstance derived_from="LPC17_NVIC" determined="infoFile" id="NVIC" location="0xE000E000"/> +<peripheralInstance derived_from="TIMER" determined="infoFile" enable="SYSCTL.PCONP.PCTIM0&amp;0x1" id="TIMER0" location="0x40004000"/> +<peripheralInstance derived_from="TIMER" determined="infoFile" enable="SYSCTL.PCONP.PCTIM1&amp;0x1" id="TIMER1" location="0x40008000"/> +<peripheralInstance derived_from="TIMER" determined="infoFile" enable="SYSCTL.PCONP.PCTIM2&amp;0x1" id="TIMER2" location="0x40090000"/> +<peripheralInstance derived_from="TIMER" determined="infoFile" enable="SYSCTL.PCONP.PCTIM3&amp;0x1" id="TIMER3" location="0x40094000"/> +<peripheralInstance derived_from="LPC17_RIT" determined="infoFile" enable="SYSCTL.PCONP.PCRIT&amp;0x1" id="RIT" location="0x400B0000"/> +<peripheralInstance derived_from="FGPIO" determined="infoFile" enable="SYSCTL.PCONP.PCGPIO&amp;0x1" id="GPIO0" location="0x2009C000"/> +<peripheralInstance derived_from="FGPIO" determined="infoFile" enable="SYSCTL.PCONP.PCGPIO&amp;0x1" id="GPIO1" location="0x2009C020"/> +<peripheralInstance derived_from="FGPIO" determined="infoFile" enable="SYSCTL.PCONP.PCGPIO&amp;0x1" id="GPIO2" location="0x2009C040"/> +<peripheralInstance derived_from="FGPIO" determined="infoFile" enable="SYSCTL.PCONP.PCGPIO&amp;0x1" id="GPIO3" location="0x2009C060"/> +<peripheralInstance derived_from="FGPIO" determined="infoFile" enable="SYSCTL.PCONP.PCGPIO&amp;0x1" id="GPIO4" location="0x2009C080"/> +<peripheralInstance derived_from="LPC17_I2S" determined="infoFile" enable="SYSCTL.PCONP&amp;0x08000000" id="I2S" location="0x400A8000"/> +<peripheralInstance derived_from="LPC17_SYSCTL" determined="infoFile" id="SYSCTL" location="0x400FC000"/> +<peripheralInstance derived_from="LPC17_DAC" determined="infoFile" enable="PCB.PINSEL1.P0_26&amp;0x2=2" id="DAC" location="0x4008C000"/> +<peripheralInstance derived_from="LPC17xx_UART" determined="infoFile" enable="SYSCTL.PCONP.PCUART0&amp;0x1" id="UART0" location="0x4000C000"/> +<peripheralInstance derived_from="LPC17xx_UART_MODEM" determined="infoFile" enable="SYSCTL.PCONP.PCUART1&amp;0x1" id="UART1" location="0x40010000"/> +<peripheralInstance derived_from="LPC17xx_UART" determined="infoFile" enable="SYSCTL.PCONP.PCUART2&amp;0x1" id="UART2" location="0x40098000"/> +<peripheralInstance derived_from="LPC17xx_UART" determined="infoFile" enable="SYSCTL.PCONP.PCUART3&amp;0x1" id="UART3" location="0x4009C000"/> +<peripheralInstance derived_from="SPI" determined="infoFile" enable="SYSCTL.PCONP.PCSPI&amp;0x1" id="SPI" location="0x40020000"/> +<peripheralInstance derived_from="LPC17_SSP" determined="infoFile" enable="SYSCTL.PCONP.PCSSP0&amp;0x1" id="SSP0" location="0x40088000"/> +<peripheralInstance derived_from="LPC17_SSP" determined="infoFile" enable="SYSCTL.PCONP.PCSSP1&amp;0x1" id="SSP1" location="0x40030000"/> +<peripheralInstance derived_from="LPC17_ADC" determined="infoFile" enable="SYSCTL.PCONP.PCAD&amp;0x1" id="ADC" location="0x40034000"/> +<peripheralInstance derived_from="LPC17_USBINTST" determined="infoFile" enable="USBCLKCTL.USBClkCtrl&amp;0x12" id="USBINTSTAT" location="0x400fc1c0"/> +<peripheralInstance derived_from="LPC17_USB_CLK_CTL" determined="infoFile" id="USBCLKCTL" location="0x5000cff4"/> +<peripheralInstance derived_from="LPC17_USBDEV" determined="infoFile" enable="USBCLKCTL.USBClkSt&amp;0x12=0x12" id="USBDEV" location="0x5000C200"/> +<peripheralInstance derived_from="LPC17_PWM" determined="infoFile" enable="SYSCTL.PCONP.PWM1&amp;0x1" id="PWM" location="0x40018000"/> +<peripheralInstance derived_from="LPC17_I2C" determined="infoFile" enable="SYSCTL.PCONP.PCI2C0&amp;0x1" id="I2C0" location="0x4001C000"/> +<peripheralInstance derived_from="LPC17_I2C" determined="infoFile" enable="SYSCTL.PCONP.PCI2C1&amp;0x1" id="I2C1" location="0x4005C000"/> +<peripheralInstance derived_from="LPC17_I2C" determined="infoFile" enable="SYSCTL.PCONP.PCI2C2&amp;0x1" id="I2C2" location="0x400A0000"/> +<peripheralInstance derived_from="LPC17_DMA" determined="infoFile" enable="SYSCTL.PCONP.PCGPDMA&amp;0x1" id="DMA" location="0x50004000"/> +<peripheralInstance derived_from="LPC17_ENET" determined="infoFile" enable="SYSCTL.PCONP.PCENET&amp;0x1" id="ENET" location="0x50000000"/> +<peripheralInstance derived_from="CM3_DCR" determined="infoFile" id="DCR" location="0xE000EDF0"/> +<peripheralInstance derived_from="LPC17_PCB" determined="infoFile" id="PCB" location="0x4002c000"/> +<peripheralInstance derived_from="LPC17_QEI" determined="infoFile" enable="SYSCTL.PCONP.PCQEI&amp;0x1" id="QEI" location="0x400bc000"/> +<peripheralInstance derived_from="LPC17_USBHOST" determined="infoFile" enable="USBCLKCTL.USBClkSt&amp;0x11=0x11" id="USBHOST" location="0x5000C000"/> +<peripheralInstance derived_from="LPC17_USBOTG" determined="infoFile" enable="USBCLKCTL.USBClkSt&amp;0x1c=0x1c" id="USBOTG" location="0x5000C000"/> +<peripheralInstance derived_from="LPC17_RTC" determined="infoFile" enable="SYSCTL.PCONP.PCRTC&amp;0x1" id="RTC" location="0x40024000"/> +<peripheralInstance derived_from="MPU" determined="infoFile" id="MPU" location="0xE000ED90"/> +<peripheralInstance derived_from="LPC1x_WDT" determined="infoFile" id="WDT" location="0x40000000"/> +<peripheralInstance derived_from="LPC17_FLASHCFG" determined="infoFile" id="FLASHACCEL" location="0x400FC000"/> +<peripheralInstance derived_from="GPIO_INT" determined="infoFile" id="GPIOINTMAP" location="0x40028080"/> +<peripheralInstance derived_from="LPC17_CANAFR" determined="infoFile" enable="SYSCTL.PCONP.PCCAN1&amp;0x1|SYSCTL.PCONP.PCCAN2&amp;0x1" id="CANAFR" location="0x4003C000"/> +<peripheralInstance derived_from="LPC17_CANCEN" determined="infoFile" enable="SYSCTL.PCONP.PCCAN1&amp;0x1|SYSCTL.PCONP.PCCAN2&amp;0x1" id="CANCEN" location="0x40040000"/> +<peripheralInstance derived_from="LPC17_CANWAKESLEEP" determined="infoFile" id="CANWAKESLEEP" location="0x400FC110"/> +<peripheralInstance derived_from="LPC17_CANCON" determined="infoFile" enable="SYSCTL.PCONP.PCCAN1&amp;0x1" id="CANCON1" location="0x40044000"/> +<peripheralInstance derived_from="LPC17_CANCON" determined="infoFile" enable="SYSCTL.PCONP.PCCAN2&amp;0x1" id="CANCON2" location="0x40048000"/> +<peripheralInstance derived_from="LPC17_MCPWM" determined="infoFile" enable="SYSCTL.PCONP.PCMCPWM&amp;0x1" id="MCPWM" location="0x400B8000"/> +</chip> +<processor> +<name gcc_name="cortex-m3">Cortex-M3</name> +<family>Cortex-M</family> +</processor> +<link href="nxp_lpcxxxx_peripheral.xme" show="embed" type="simple"/> +</info> +</infoList> +</TargetConfig>{% endblock %} diff --git a/tools/export/sw4stm32/__init__.py b/tools/export/sw4stm32/__init__.py index a3416603ff..3d3a73070e 100644 --- a/tools/export/sw4stm32/__init__.py +++ b/tools/export/sw4stm32/__init__.py @@ -288,6 +288,11 @@ class Sw4STM32(GNUARMEclipse): 'name': 'NUCLEO-L496ZG', 'mcuId': 'STM32L496ZGTx' }, + 'NUCLEO_L4R5ZI': + { + 'name': 'NUCLEO-L4R5ZI', + 'mcuId': 'STM32L4R5ZITx' + } } @classmethod diff --git a/tools/run_icetea.py b/tools/run_icetea.py index bf2706f035..80eb9caef0 100644 --- a/tools/run_icetea.py +++ b/tools/run_icetea.py @@ -166,15 +166,18 @@ def get_application_list(icetea_json_output, tests_by_name): def icetea_tests(target, tcdir, verbose): + if not os.path.exists(tcdir): + raise Exception("Icetea run error: No TEST_APPS folder in {}".format(os.path.curdir)) + command = ['icetea', '--tcdir', tcdir, '--list', '--json', '--platform_filter', target] \ + (['-v'] if verbose else []) stdout, stderr, returncode = run_cmd(command) if returncode != 0: - raise Exception( - "Error when running icetea. \ncwd:{} \nCommand:'{}' \noutput:{}".format(os.getcwd(), ' '.join(command), - stderr.decode())) + additional_information = "\ncwd:{} \nCommand:'{}' \noutput:{}".format(os.getcwd(), ' '.join(command), + stderr.decode()) + raise Exception("Error when running icetea. {}".format(additional_information)) return json.loads(stdout) diff --git a/tools/targets/lint.py b/tools/targets/lint.py index 1c09bad995..2ab915a610 100644 --- a/tools/targets/lint.py +++ b/tools/targets/lint.py @@ -82,7 +82,7 @@ DEVICE_HAS_ALLOWED = ["ANALOGIN", "ANALOGOUT", "CAN", "ETHERNET", "EMAC", "LPTICKER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "TRNG","SERIAL", "SERIAL_ASYNCH", "SERIAL_FC", "SLEEP", "SPI", "SPI_ASYNCH", "SPISLAVE", - "STORAGE", "STCLK_OFF_DURING_SLEEP"] + "STORAGE", "SYSTICK_CLK_OFF_DURING_SLEEP"] def check_device_has(dict): for name in dict.get("device_has", []): if name not in DEVICE_HAS_ALLOWED: diff --git a/tools/test/examples/examples.json b/tools/test/examples/examples.json index ef75b3c50e..0a8bf8c6f5 100644 --- a/tools/test/examples/examples.json +++ b/tools/test/examples/examples.json @@ -29,8 +29,8 @@ "targets" : ["K64F", "NUCLEO_F429ZI"], "toolchains" : ["GCC_ARM", "ARM"], "exporters": [], - "compile" : false, - "export": false, + "compile" : true, + "export": true, "auto-update" : true }, { @@ -229,6 +229,69 @@ "compile" : true, "export": true, "auto-update" : true - } + }, + { + "name": "mbed-os-example-filesystem", + "github":"https://github.com/ARMmbed/mbed-os-example-filesystem", + "mbed": [ + "https://os.mbed.com/teams/mbed-os-examples/code/mbed-os-example-filesystem" + ], + "test-repo-source": "github", + "features" : [], + "targets" : ["K82F"], + "toolchains" : [], + "exporters": [], + "compile" : true, + "export": true, + "auto-update" : true + }, + { + "name": "mbed-os-example-mesh-minimal", + "github":"https://github.com/ARMmbed/mbed-os-example-mesh-minimal", + "mbed": [ + "https://os.mbed.com/teams/mbed-os-examples/code/mbed-os-example-mesh-minimal" + ], + "test-repo-source": "github", + "features" : [], + "targets" : ["DISCO_F469NI", "DISCO_F746NG", "K64F", "K66F", + "NUCLEO_F429ZI", "NUCLEO_F439ZI", "NUCLEO_F746ZG", + "NUCLEO_F756ZG", "NUCLEO_F767ZI", + "NUMAKER_PFM_NUC472", "UBLOX_EVK_ODIN_W2"], + "toolchains" : [], + "exporters": [], + "compile" : true, + "export": true, + "auto-update" : true + }, + { + "name": "mbed-os-example-bootloader", + "github":"https://github.com/ARMmbed/mbed-os-example-bootloader", + "mbed": [ + "https://os.mbed.com/teams/mbed-os-examples/code/mbed-os-example-bootloader" + ], + "test-repo-source": "github", + "features" : [], + "targets" : ["K64F", "NUCLEO_F429ZI", "UBLOX_EVK_ODIN_W2"], + "toolchains" : [], + "exporters": [], + "compile" : true, + "export": true, + "auto-update" : true + }, + { + "name": "mbed-os-example-nfc", + "github": "https://github.com/ARMmbed/mbed-os-example-nfc", + "mbed": [ + "https://os.mbed.com/teams/mbed-os-examples/code/mbed-os-example-nfc-SmartPoster" + ], + "test-repo-source": "mbed", + "features" : [], + "targets" : ["NUCLEO_F401RE", "DISCO_L475VG_IOT01A"], + "toolchains" : [], + "exporters": [], + "compile" : true, + "export": true, + "auto-update" : true + } ] } diff --git a/tools/test_configs/NanostackMACTester.json b/tools/test_configs/NanostackMACTester.json new file mode 100644 index 0000000000..f23f200df3 --- /dev/null +++ b/tools/test_configs/NanostackMACTester.json @@ -0,0 +1,19 @@ +{ + "macros": ["MBED_TRACE_LINE_LENGTH=200", "OS_TASKCNT=4", "OS_IDLESTKSIZE=32", "MBED_CONF_MBED_TRACE_ENABLE=1"], + "target_overrides": { + "KW24D": { + "mcr20a.provide-default": true + }, + "*": { + "nanostack.configuration": "lowpan_host", + "platform.stdio-convert-newlines": true, + "platform.stdio-baud-rate": 115200, + "mbed-mesh-api.heap-size": 6000, + "nanostack-hal.event_loop_thread_stack_size": 2000, + "mbed-trace.enable": true, + "nsapi.default-stack": "LWIP", + "target.device_has_add": ["802_15_4_PHY"], + "atmel-rf.provide-default": true + } + } +} diff --git a/tools/test_configs/config_paths.json b/tools/test_configs/config_paths.json index 74d1819332..e8684f6f88 100644 --- a/tools/test_configs/config_paths.json +++ b/tools/test_configs/config_paths.json @@ -13,5 +13,6 @@ "6LOWPAN_ROUTER" : "6lowpanInterface_router.json", "THREAD_END_DEVICE" : "ThreadInterface_end_device.json", "THREAD_ROUTER" : "ThreadInterface_router.json", - "NO_NETWORK": "no_network.json" + "NO_NETWORK": "no_network.json", + "NANOSTACK_MAC_TESTER": "NanostackMACTester.json" } diff --git a/tools/test_configs/target_configs.json b/tools/test_configs/target_configs.json index ad294bda6f..a55f72d568 100644 --- a/tools/test_configs/target_configs.json +++ b/tools/test_configs/target_configs.json @@ -9,11 +9,11 @@ }, "K64F": { "default_test_configuration": "HEAPBLOCKDEVICE_AND_ETHERNET", - "test_configurations": ["HEAPBLOCKDEVICE_AND_ETHERNET", "MAC_TESTER", "ESP8266_WIFI", "ETHERNET"] + "test_configurations": ["HEAPBLOCKDEVICE_AND_ETHERNET", "NANOSTACK_MAC_TESTER", "ESP8266_WIFI", "ETHERNET"] }, "NUCLEO_F429ZI": { "default_test_configuration": "HEAPBLOCKDEVICE_AND_ETHERNET", - "test_configurations": ["HEAPBLOCKDEVICE_AND_ETHERNET", "MAC_TESTER"] + "test_configurations": ["HEAPBLOCKDEVICE_AND_ETHERNET", "NANOSTACK_MAC_TESTER"] }, "DISCO_L475VG_IOT01A": { "default_test_configuration": "NONE", @@ -46,5 +46,13 @@ "KW24D": { "default_test_configuration": "NO_NETWORK", "test_configurations": ["6LOWPAN_HOST", "6LOWPAN_ROUTER", "THREAD_END_DEVICE", "THREAD_ROUTER"] + }, + "TB_SENSE_12": { + "default_test_configuration": "NO_NETWORK", + "test_configurations": ["6LOWPAN_HOST", "6LOWPAN_ROUTER", "THREAD_END_DEVICE", "THREAD_ROUTER"] + }, + "TB_SENSE_1": { + "default_test_configuration": "NO_NETWORK", + "test_configurations": ["6LOWPAN_HOST", "6LOWPAN_ROUTER", "THREAD_END_DEVICE", "THREAD_ROUTER"] } } diff --git a/tools/toolchains/arm.py b/tools/toolchains/arm.py index d37c94e92b..1829fff5c3 100644 --- a/tools/toolchains/arm.py +++ b/tools/toolchains/arm.py @@ -121,7 +121,7 @@ class ARM(mbedToolchain): "file": "", "line": "", "col": "", - "severity": "ERROR", + "severity": "WARNING", }) def _get_toolchain_labels(self): @@ -424,9 +424,9 @@ class ARMC6(ARM_STD): build_dir = kwargs['build_dir'] secure_file = join(build_dir, "cmse_lib.o") self.flags["ld"] += ["--import_cmse_lib_out=%s" % secure_file] - # Add linking time preprocessor macro __DOMAIN_NS + # Add linking time preprocessor macro DOMAIN_NS if target.core == "Cortex-M23-NS" or self.target.core == "Cortex-M33-NS": - define_string = self.make_ld_define("__DOMAIN_NS", "0x1") + define_string = self.make_ld_define("DOMAIN_NS", "0x1") self.flags["ld"].append(define_string) asm_cpu = { diff --git a/tools/toolchains/gcc.py b/tools/toolchains/gcc.py index f094fb9702..e1354ab01d 100644 --- a/tools/toolchains/gcc.py +++ b/tools/toolchains/gcc.py @@ -97,7 +97,7 @@ class GCC(mbedToolchain): "-Wl,--out-implib=%s" % join(build_dir, "cmse_lib.o") ]) elif target.core == "Cortex-M23-NS" or target.core == "Cortex-M33-NS": - self.flags["ld"].append("-D__DOMAIN_NS=1") + self.flags["ld"].append("-DDOMAIN_NS=1") self.flags["common"] += self.cpu @@ -140,7 +140,7 @@ class GCC(mbedToolchain): "file": "", "line": "", "col": "", - "severity": "ERROR", + "severity": "Warning", }) def is_not_supported_error(self, output): diff --git a/tools/toolchains/iar.py b/tools/toolchains/iar.py index b54487869a..00655df552 100644 --- a/tools/toolchains/iar.py +++ b/tools/toolchains/iar.py @@ -112,7 +112,7 @@ class IAR(mbedToolchain): "file": "", "line": "", "col": "", - "severity": "ERROR", + "severity": "Warning", }) @@ -167,7 +167,7 @@ class IAR(mbedToolchain): opts = ['-D%s' % d for d in defines] if for_asm: config_macros = self.config.get_config_data_macros() - macros_cmd = ['"-D%s"' % d.replace('"', '').replace('//','/\/') for d in config_macros] + macros_cmd = ['"-D%s"' % d for d in config_macros if not '"' in d] if self.RESPONSE_FILES: via_file = self.make_option_file( macros_cmd, "asm_macros_{}.xcl")