From 12b07e0ad0a71ce3dac9031a935994c555782b2c Mon Sep 17 00:00:00 2001 From: Valerii Koval Date: Fri, 14 Jul 2017 13:11:18 +0300 Subject: [PATCH 1/3] Add an example with unit testing and mbed framework --- unit-testing/mbed-blink/.gitignore | 4 ++ unit-testing/mbed-blink/.travis.yml | 61 ++++++++++++++++++++++ unit-testing/mbed-blink/README.rst | 26 +++++++++ unit-testing/mbed-blink/lib/readme.txt | 36 +++++++++++++ unit-testing/mbed-blink/platformio.ini | 17 ++++++ unit-testing/mbed-blink/src/main.cpp | 22 ++++++++ unit-testing/mbed-blink/test/test_main.cpp | 47 +++++++++++++++++ 7 files changed, 213 insertions(+) create mode 100644 unit-testing/mbed-blink/.gitignore create mode 100644 unit-testing/mbed-blink/.travis.yml create mode 100644 unit-testing/mbed-blink/README.rst create mode 100644 unit-testing/mbed-blink/lib/readme.txt create mode 100644 unit-testing/mbed-blink/platformio.ini create mode 100644 unit-testing/mbed-blink/src/main.cpp create mode 100644 unit-testing/mbed-blink/test/test_main.cpp diff --git a/unit-testing/mbed-blink/.gitignore b/unit-testing/mbed-blink/.gitignore new file mode 100644 index 0000000..e05273b --- /dev/null +++ b/unit-testing/mbed-blink/.gitignore @@ -0,0 +1,4 @@ +.pioenvs +.clang_complete +.gcc-flags.json +.piolibdeps \ No newline at end of file diff --git a/unit-testing/mbed-blink/.travis.yml b/unit-testing/mbed-blink/.travis.yml new file mode 100644 index 0000000..2ca2ac6 --- /dev/null +++ b/unit-testing/mbed-blink/.travis.yml @@ -0,0 +1,61 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < http://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < http://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < http://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choice one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: Local Unit Testing, process native environment on CI machine +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# +# script: +# - platformio test -e native + + + +# +# Template #2 Remote Unit Testing, process environments on remote machine +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# +# script: +# - platformio remote test diff --git a/unit-testing/mbed-blink/README.rst b/unit-testing/mbed-blink/README.rst new file mode 100644 index 0000000..cccae28 --- /dev/null +++ b/unit-testing/mbed-blink/README.rst @@ -0,0 +1,26 @@ +.. Copyright (c) 2014-present PlatformIO + 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. + +How to test PlatformIO based project +==================================== + +1. `Install PlatformIO Core `_ +2. Download `examples source code `_ +3. Extract ZIP archive +4. Run these commands: + +.. code-block:: bash + + # Change directory to example + > cd platformio-examples/unit-testing/mbed-blink + + # Test project + > platformio test diff --git a/unit-testing/mbed-blink/lib/readme.txt b/unit-testing/mbed-blink/lib/readme.txt new file mode 100644 index 0000000..dbadc3d --- /dev/null +++ b/unit-testing/mbed-blink/lib/readme.txt @@ -0,0 +1,36 @@ + +This directory is intended for the project specific (private) libraries. +PlatformIO will compile them to static libraries and link to executable file. + +The source code of each library should be placed in separate directory, like +"lib/private_lib/[here are source files]". + +For example, see how can be organized `Foo` and `Bar` libraries: + +|--lib +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| |--Foo +| | |- Foo.c +| | |- Foo.h +| |- readme.txt --> THIS FILE +|- platformio.ini +|--src + |- main.c + +Then in `src/main.c` you should use: + +#include +#include + +// rest H/C/CPP code + +PlatformIO will find your libraries automatically, configure preprocessor's +include paths and build them. + +More information about PlatformIO Library Dependency Finder +- http://docs.platformio.org/page/librarymanager/ldf.html diff --git a/unit-testing/mbed-blink/platformio.ini b/unit-testing/mbed-blink/platformio.ini new file mode 100644 index 0000000..074e103 --- /dev/null +++ b/unit-testing/mbed-blink/platformio.ini @@ -0,0 +1,17 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter, extra scripting +; Upload options: custom port, speed and extra flags +; Library options: dependencies, extra library storages +; +; Please visit documentation for the other options and examples +; http://docs.platformio.org/page/projectconf.html + +; +; Embedded platforms +; + +[env:nucleo_f401re] +platform = ststm32 +framework = mbed +board = nucleo_f401re diff --git a/unit-testing/mbed-blink/src/main.cpp b/unit-testing/mbed-blink/src/main.cpp new file mode 100644 index 0000000..2b01af1 --- /dev/null +++ b/unit-testing/mbed-blink/src/main.cpp @@ -0,0 +1,22 @@ +/* + * Blink + * Turns on an LED on for one second, + * then off for one second, repeatedly. + */ + +#include "mbed.h" + +#ifndef UNIT_TEST + +DigitalOut myled(LED1); + +int main() { + while(1) { + myled = 1; + wait(1); + myled = 0; + wait(1); + } +} + +#endif diff --git a/unit-testing/mbed-blink/test/test_main.cpp b/unit-testing/mbed-blink/test/test_main.cpp new file mode 100644 index 0000000..78726da --- /dev/null +++ b/unit-testing/mbed-blink/test/test_main.cpp @@ -0,0 +1,47 @@ +#include +#include + +#ifdef UNIT_TEST + +DigitalOut myled(LED1); + +// void setUp(void) { +// // set stuff up here +// } + +// void tearDown(void) { +// // clean stuff up here +// } + +void test_pin_is_connected(void) { + TEST_ASSERT_EQUAL(myled.is_connected(), 1); +} + +void test_led_state_high(void) { + myled.write(1); + TEST_ASSERT_EQUAL(myled.read(), 1); +} + +void test_led_state_low(void) { + myled.write(0); + TEST_ASSERT_EQUAL(myled.read(), 0); +} + +int main() { + UNITY_BEGIN(); + RUN_TEST(test_pin_is_connected); + + for (int i = 0; i < 5; ++i){ + RUN_TEST(test_led_state_high); + wait_ms(500); + RUN_TEST(test_led_state_low); + wait_ms(500); + i++; + } + + UNITY_END(); // stop unit testing + + while(1){} +} + +#endif From dc9ee5401cead81eebc693dcd4ea4b7e0d21e9b5 Mon Sep 17 00:00:00 2001 From: Valerii Koval Date: Tue, 18 Jul 2017 22:01:26 +0300 Subject: [PATCH 2/3] Update example with mbed framework --- .../.gitignore | 0 .../.travis.yml | 0 .../README.rst | 8 +- .../lib/readme.txt | 6 +- mbed/mbed-ble-thermometer/platformio.ini | 32 + mbed/mbed-ble-thermometer/src/main.cpp | 105 +++ mbed/mbed-events/.gitignore | 3 + .../.travis.yml | 2 +- .../README.rst | 8 +- .../lib/readme.txt | 6 +- mbed/mbed-events/platformio.ini | 105 +++ mbed/mbed-events/src/main.cpp | 15 + mbed/mbed-filesystem/.gitignore | 3 + mbed/mbed-filesystem/.travis.yml | 65 ++ mbed/mbed-filesystem/README.rst | 38 + mbed/mbed-filesystem/lib/readme.txt | 38 + mbed/mbed-filesystem/platformio.ini | 71 ++ mbed/mbed-filesystem/src/main.cpp | 81 ++ .../lib/HTTPClient/HTTPClient.cpp | 739 ------------------ .../lib/HTTPClient/HTTPClient.h | 159 ---- .../lib/HTTPClient/IHTTPData.h | 105 --- .../lib/HTTPClient/data/HTTPMap.cpp | 200 ----- .../lib/HTTPClient/data/HTTPMap.h | 71 -- .../lib/HTTPClient/data/HTTPText.cpp | 104 --- .../lib/HTTPClient/data/HTTPText.h | 72 -- mbed/mbed-http-client/src/main.cpp | 79 -- mbed/mbed-rtos-ethernet-tls/.gitignore | 3 + mbed/mbed-rtos-ethernet-tls/.travis.yml | 65 ++ mbed/mbed-rtos-ethernet-tls/README.rst | 38 + mbed/mbed-rtos-ethernet-tls/lib/readme.txt | 38 + .../platformio.ini | 18 +- mbed/mbed-rtos-ethernet-tls/src/main.cpp | 435 +++++++++++ .../src/mbedtls_entropy_config.h | 38 + mbed/mbed-rtos-ethernet/.gitignore | 3 + mbed/mbed-rtos-ethernet/.travis.yml | 65 ++ mbed/mbed-rtos-ethernet/README.rst | 38 + .../lib/NTPClient/NTPClient.cpp | 163 ++++ .../lib/NTPClient/NTPClient.h | 102 +++ mbed/mbed-rtos-ethernet/lib/readme.txt | 38 + .../platformio.ini | 16 +- mbed/mbed-rtos-ethernet/src/main.cpp | 38 + mbed/mbed-rtos/README.rst | 6 +- mbed/mbed-rtos/platformio.ini | 40 +- mbed/mbed-rtos/src/main.cpp | 54 +- mbed/microbit-hello-world/.gitignore | 2 - mbed/microbit-hello-world/src/main.cpp | 18 - 46 files changed, 1726 insertions(+), 1607 deletions(-) rename mbed/{mbed-http-client => mbed-ble-thermometer}/.gitignore (100%) rename mbed/{mbed-http-client => mbed-ble-thermometer}/.travis.yml (100%) rename mbed/{microbit-hello-world => mbed-ble-thermometer}/README.rst (83%) rename mbed/{mbed-http-client => mbed-ble-thermometer}/lib/readme.txt (84%) create mode 100644 mbed/mbed-ble-thermometer/platformio.ini create mode 100644 mbed/mbed-ble-thermometer/src/main.cpp create mode 100644 mbed/mbed-events/.gitignore rename mbed/{microbit-hello-world => mbed-events}/.travis.yml (95%) rename mbed/{mbed-http-client => mbed-events}/README.rst (84%) rename mbed/{microbit-hello-world => mbed-events}/lib/readme.txt (84%) create mode 100644 mbed/mbed-events/platformio.ini create mode 100644 mbed/mbed-events/src/main.cpp create mode 100644 mbed/mbed-filesystem/.gitignore create mode 100644 mbed/mbed-filesystem/.travis.yml create mode 100644 mbed/mbed-filesystem/README.rst create mode 100644 mbed/mbed-filesystem/lib/readme.txt create mode 100644 mbed/mbed-filesystem/platformio.ini create mode 100644 mbed/mbed-filesystem/src/main.cpp delete mode 100644 mbed/mbed-http-client/lib/HTTPClient/HTTPClient.cpp delete mode 100644 mbed/mbed-http-client/lib/HTTPClient/HTTPClient.h delete mode 100644 mbed/mbed-http-client/lib/HTTPClient/IHTTPData.h delete mode 100644 mbed/mbed-http-client/lib/HTTPClient/data/HTTPMap.cpp delete mode 100644 mbed/mbed-http-client/lib/HTTPClient/data/HTTPMap.h delete mode 100644 mbed/mbed-http-client/lib/HTTPClient/data/HTTPText.cpp delete mode 100644 mbed/mbed-http-client/lib/HTTPClient/data/HTTPText.h delete mode 100644 mbed/mbed-http-client/src/main.cpp create mode 100644 mbed/mbed-rtos-ethernet-tls/.gitignore create mode 100644 mbed/mbed-rtos-ethernet-tls/.travis.yml create mode 100644 mbed/mbed-rtos-ethernet-tls/README.rst create mode 100644 mbed/mbed-rtos-ethernet-tls/lib/readme.txt rename mbed/{mbed-http-client => mbed-rtos-ethernet-tls}/platformio.ini (66%) create mode 100644 mbed/mbed-rtos-ethernet-tls/src/main.cpp create mode 100644 mbed/mbed-rtos-ethernet-tls/src/mbedtls_entropy_config.h create mode 100644 mbed/mbed-rtos-ethernet/.gitignore create mode 100644 mbed/mbed-rtos-ethernet/.travis.yml create mode 100644 mbed/mbed-rtos-ethernet/README.rst create mode 100644 mbed/mbed-rtos-ethernet/lib/NTPClient/NTPClient.cpp create mode 100644 mbed/mbed-rtos-ethernet/lib/NTPClient/NTPClient.h create mode 100644 mbed/mbed-rtos-ethernet/lib/readme.txt rename mbed/{microbit-hello-world => mbed-rtos-ethernet}/platformio.ini (59%) create mode 100644 mbed/mbed-rtos-ethernet/src/main.cpp delete mode 100644 mbed/microbit-hello-world/.gitignore delete mode 100755 mbed/microbit-hello-world/src/main.cpp diff --git a/mbed/mbed-http-client/.gitignore b/mbed/mbed-ble-thermometer/.gitignore similarity index 100% rename from mbed/mbed-http-client/.gitignore rename to mbed/mbed-ble-thermometer/.gitignore diff --git a/mbed/mbed-http-client/.travis.yml b/mbed/mbed-ble-thermometer/.travis.yml similarity index 100% rename from mbed/mbed-http-client/.travis.yml rename to mbed/mbed-ble-thermometer/.travis.yml diff --git a/mbed/microbit-hello-world/README.rst b/mbed/mbed-ble-thermometer/README.rst similarity index 83% rename from mbed/microbit-hello-world/README.rst rename to mbed/mbed-ble-thermometer/README.rst index 8fafb26..3a82420 100644 --- a/mbed/microbit-hello-world/README.rst +++ b/mbed/mbed-ble-thermometer/README.rst @@ -20,7 +20,7 @@ How to build PlatformIO based project .. code-block:: bash # Change directory to example - > cd platformio-examples/mbed/microbit-hello-world + > cd platformio-examples/mbed/mbed-ble-thermometer # Build project > platformio run @@ -28,5 +28,11 @@ How to build PlatformIO based project # Upload firmware > platformio run --target upload + # Build specific environment + > platformio run -e nrf52_dk + + # Upload firmware for the specific environment + > platformio run -e nrf52_dk --target upload + # Clean build files > platformio run --target clean diff --git a/mbed/mbed-http-client/lib/readme.txt b/mbed/mbed-ble-thermometer/lib/readme.txt similarity index 84% rename from mbed/mbed-http-client/lib/readme.txt rename to mbed/mbed-ble-thermometer/lib/readme.txt index dbadc3d..4b6209e 100644 --- a/mbed/mbed-http-client/lib/readme.txt +++ b/mbed/mbed-ble-thermometer/lib/readme.txt @@ -32,5 +32,7 @@ Then in `src/main.c` you should use: PlatformIO will find your libraries automatically, configure preprocessor's include paths and build them. -More information about PlatformIO Library Dependency Finder -- http://docs.platformio.org/page/librarymanager/ldf.html +See additional options for PlatformIO Library Dependency Finder `lib_*`: + +http://docs.platformio.org/page/projectconf.html#lib-install + diff --git a/mbed/mbed-ble-thermometer/platformio.ini b/mbed/mbed-ble-thermometer/platformio.ini new file mode 100644 index 0000000..0b2c416 --- /dev/null +++ b/mbed/mbed-ble-thermometer/platformio.ini @@ -0,0 +1,32 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter, extra scripting +; Upload options: custom port, speed and extra flags +; Library options: dependencies, extra library storages +; +; Please visit documentation for the other options and examples +; http://docs.platformio.org/page/projectconf.html + +[env:nrf51_dk] +platform = nordicnrf51 +framework = mbed +board = nrf51_dk +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT + +[env:nrf51_dongle] +platform = nordicnrf51 +framework = mbed +board = nrf51_dongle +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT + +[env:nrf52_dk] +platform = nordicnrf52 +framework = mbed +board = nrf52_dk +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT + +[env:delta_dfbm_nq620] +platform = nordicnrf52 +framework = mbed +board = delta_dfbm_nq620 +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT diff --git a/mbed/mbed-ble-thermometer/src/main.cpp b/mbed/mbed-ble-thermometer/src/main.cpp new file mode 100644 index 0000000..48c3b76 --- /dev/null +++ b/mbed/mbed-ble-thermometer/src/main.cpp @@ -0,0 +1,105 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 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. + */ + +#include +#include +#include "mbed.h" +#include "ble/BLE.h" +#include "ble/services/HealthThermometerService.h" + +DigitalOut led1(LED1, 1); + +const static char DEVICE_NAME[] = "PIOTherm"; +static const uint16_t uuid16_list[] = {GattService::UUID_HEALTH_THERMOMETER_SERVICE}; + +static float currentTemperature = 39.6; +static HealthThermometerService *thermometerServicePtr; + +static EventQueue eventQueue(/* event count */ 16 * EVENTS_EVENT_SIZE); + +/* Restart Advertising on disconnection*/ +void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *) +{ + BLE::Instance().gap().startAdvertising(); +} + +void updateSensorValue(void) { + /* Do blocking calls or whatever is necessary for sensor polling. + In our case, we simply update the Temperature measurement. */ + currentTemperature = (currentTemperature + 0.1 > 43.0) ? 39.6 : currentTemperature + 0.1; + thermometerServicePtr->updateTemperature(currentTemperature); +} + +void periodicCallback(void) +{ + led1 = !led1; /* Do blinky on LED1 while we're waiting for BLE events */ + + if (BLE::Instance().gap().getState().connected) { + eventQueue.call(updateSensorValue); + } +} + +void onBleInitError(BLE &ble, ble_error_t error) +{ + /* Initialization error handling should go here */ +} + +void bleInitComplete(BLE::InitializationCompleteCallbackContext *params) +{ + BLE& ble = params->ble; + ble_error_t error = params->error; + + if (error != BLE_ERROR_NONE) { + onBleInitError(ble, error); + return; + } + + if (ble.getInstanceID() != BLE::DEFAULT_INSTANCE) { + return; + } + + ble.gap().onDisconnection(disconnectionCallback); + + /* Setup primary service. */ + thermometerServicePtr = new HealthThermometerService(ble, currentTemperature, HealthThermometerService::LOCATION_EAR); + + /* setup advertising */ + ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); + ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list)); + ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::THERMOMETER_EAR); + ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME)); + ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); + ble.gap().setAdvertisingInterval(1000); /* 1000ms */ + ble.gap().startAdvertising(); +} + +void scheduleBleEventsProcessing(BLE::OnEventsToProcessCallbackContext* context) { + BLE &ble = BLE::Instance(); + eventQueue.call(Callback(&ble, &BLE::processEvents)); +} + +int main() +{ + eventQueue.call_every(500, periodicCallback); + + BLE &ble = BLE::Instance(); + ble.onEventsToProcess(scheduleBleEventsProcessing); + ble.init(bleInitComplete); + + eventQueue.dispatch_forever(); + + return 0; +} diff --git a/mbed/mbed-events/.gitignore b/mbed/mbed-events/.gitignore new file mode 100644 index 0000000..5402c18 --- /dev/null +++ b/mbed/mbed-events/.gitignore @@ -0,0 +1,3 @@ +.pioenvs +.clang_complete +.gcc-flags.json diff --git a/mbed/microbit-hello-world/.travis.yml b/mbed/mbed-events/.travis.yml similarity index 95% rename from mbed/microbit-hello-world/.travis.yml rename to mbed/mbed-events/.travis.yml index 2c4ff5c..593d7ef 100644 --- a/mbed/microbit-hello-world/.travis.yml +++ b/mbed/mbed-events/.travis.yml @@ -14,7 +14,7 @@ # < http://docs.platformio.org/page/userguide/cmd_ci.html > # # -# Please choice one of the following templates (proposed below) and uncomment +# Please choose one of the following templates (proposed below) and uncomment # it (remove "# " before each line) or use own configuration according to the # Travis CI documentation (see above). # diff --git a/mbed/mbed-http-client/README.rst b/mbed/mbed-events/README.rst similarity index 84% rename from mbed/mbed-http-client/README.rst rename to mbed/mbed-events/README.rst index 3f83a1f..104d739 100644 --- a/mbed/mbed-http-client/README.rst +++ b/mbed/mbed-events/README.rst @@ -20,7 +20,7 @@ How to build PlatformIO based project .. code-block:: bash # Change directory to example - > cd platformio-examples/mbed/mbed-http-client + > cd platformio-examples/mbed/mbed-events # Build project > platformio run @@ -28,5 +28,11 @@ How to build PlatformIO based project # Upload firmware > platformio run --target upload + # Build specific environment + > platformio run -e nrf52_dk + + # Upload firmware for the specific environment + > platformio run -e nrf52_dk --target upload + # Clean build files > platformio run --target clean diff --git a/mbed/microbit-hello-world/lib/readme.txt b/mbed/mbed-events/lib/readme.txt similarity index 84% rename from mbed/microbit-hello-world/lib/readme.txt rename to mbed/mbed-events/lib/readme.txt index dbadc3d..4b6209e 100644 --- a/mbed/microbit-hello-world/lib/readme.txt +++ b/mbed/mbed-events/lib/readme.txt @@ -32,5 +32,7 @@ Then in `src/main.c` you should use: PlatformIO will find your libraries automatically, configure preprocessor's include paths and build them. -More information about PlatformIO Library Dependency Finder -- http://docs.platformio.org/page/librarymanager/ldf.html +See additional options for PlatformIO Library Dependency Finder `lib_*`: + +http://docs.platformio.org/page/projectconf.html#lib-install + diff --git a/mbed/mbed-events/platformio.ini b/mbed/mbed-events/platformio.ini new file mode 100644 index 0000000..8a67eca --- /dev/null +++ b/mbed/mbed-events/platformio.ini @@ -0,0 +1,105 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter, extra scripting +; Upload options: custom port, speed and extra flags +; Library options: dependencies, extra library storages +; +; Please visit documentation for the other options and examples +; http://docs.platformio.org/page/projectconf.html + +# NXP LPC Platform +[env:lpc11u35] +platform = nxplpc +framework = mbed +board = lpc11u35 + +[env:lpc1768] +platform = nxplpc +framework = mbed +board = lpc1768 +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT + +# Nordic nRF51 Platform +[env:redBearLab] +platform = nordicnrf51 +framework = mbed +board = redBearLab + +# Nordic nRF52 Platform +[env:nrf52_dk] +platform = nordicnrf52 +framework = mbed +board = nrf52_dk + +[env:delta_dfbm_nq620] +platform = nordicnrf52 +framework = mbed +board = delta_dfbm_nq620 +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT + +# Freescale FRDM Platform +[env:frdm_kl25z] +platform = freescalekinetis +framework = mbed +board = frdm_kl25z + +[env:frdm_k64f] +platform = freescalekinetis +framework = mbed +board = frdm_k64f +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT + +# Maxim32 Platform +[env:max32600mbed] +platform = maxim32 +framework = mbed +board = max32600mbed + +[env:maxwsnenv] +platform = maxim32 +framework = mbed +board = maxwsnenv +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT + +# ST STM32 Platform +[env:nucleo_f401re] +platform = ststm32 +framework = mbed +board = nucleo_f401re + +[env:mote_l152rc] +platform = ststm32 +framework = mbed +board = mote_l152rc +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT + +# Teensy Platform +[env:teensy31] +platform = teensy +framework = mbed +board = teensy31 +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT + +# Silicon Labs EFM32 Platform +[env:efm32hg_stk3400] +platform = siliconlabsefm32 +framework = mbed +board = efm32hg_stk3400 + +[env:efm32wg_stk3800] +platform = siliconlabsefm32 +framework = mbed +board = efm32wg_stk3800 +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT + +# WIZNet7500 Platform +[env:wizwiki_w7500] +platform = wiznet7500 +framework = mbed +board = wizwiki_w7500 + +[env:wizwiki_w7500eco] +platform = wiznet7500 +framework = mbed +board = wizwiki_w7500eco +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT diff --git a/mbed/mbed-events/src/main.cpp b/mbed/mbed-events/src/main.cpp new file mode 100644 index 0000000..8762cd4 --- /dev/null +++ b/mbed/mbed-events/src/main.cpp @@ -0,0 +1,15 @@ +#include "mbed_events.h" +#include + +int main() { + // creates a queue with the default size + EventQueue queue; + + // events are simple callbacks + queue.call(printf, "called immediately\n"); + queue.call_in(2000, printf, "called in 2 seconds\n"); + queue.call_every(1000, printf, "called every 1 seconds\n"); + + // events are executed by the dispatch method + queue.dispatch(); +} diff --git a/mbed/mbed-filesystem/.gitignore b/mbed/mbed-filesystem/.gitignore new file mode 100644 index 0000000..5402c18 --- /dev/null +++ b/mbed/mbed-filesystem/.gitignore @@ -0,0 +1,3 @@ +.pioenvs +.clang_complete +.gcc-flags.json diff --git a/mbed/mbed-filesystem/.travis.yml b/mbed/mbed-filesystem/.travis.yml new file mode 100644 index 0000000..593d7ef --- /dev/null +++ b/mbed/mbed-filesystem/.travis.yml @@ -0,0 +1,65 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < http://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < http://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < http://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to by used as a library with examples +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/mbed/mbed-filesystem/README.rst b/mbed/mbed-filesystem/README.rst new file mode 100644 index 0000000..91a671d --- /dev/null +++ b/mbed/mbed-filesystem/README.rst @@ -0,0 +1,38 @@ +.. Copyright (c) 2014-present PlatformIO + 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. + +How to build PlatformIO based project +===================================== + +1. `Install PlatformIO Core `_ +2. Download `examples source code `_ +3. Extract ZIP archive +4. Run these commands: + +.. code-block:: bash + + # Change directory to example + > cd platformio-examples/mbed/mbed-filesystem + + # Build project + > platformio run + + # Upload firmware + > platformio run --target upload + + # Build specific environment + > platformio run -e nucleo_f767zi + + # Upload firmware for the specific environment + > platformio run -e nucleo_f767zi --target upload + + # Clean build files + > platformio run --target clean diff --git a/mbed/mbed-filesystem/lib/readme.txt b/mbed/mbed-filesystem/lib/readme.txt new file mode 100644 index 0000000..4b6209e --- /dev/null +++ b/mbed/mbed-filesystem/lib/readme.txt @@ -0,0 +1,38 @@ + +This directory is intended for the project specific (private) libraries. +PlatformIO will compile them to static libraries and link to executable file. + +The source code of each library should be placed in separate directory, like +"lib/private_lib/[here are source files]". + +For example, see how can be organized `Foo` and `Bar` libraries: + +|--lib +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| |--Foo +| | |- Foo.c +| | |- Foo.h +| |- readme.txt --> THIS FILE +|- platformio.ini +|--src + |- main.c + +Then in `src/main.c` you should use: + +#include +#include + +// rest H/C/CPP code + +PlatformIO will find your libraries automatically, configure preprocessor's +include paths and build them. + +See additional options for PlatformIO Library Dependency Finder `lib_*`: + +http://docs.platformio.org/page/projectconf.html#lib-install + diff --git a/mbed/mbed-filesystem/platformio.ini b/mbed/mbed-filesystem/platformio.ini new file mode 100644 index 0000000..3d1ad86 --- /dev/null +++ b/mbed/mbed-filesystem/platformio.ini @@ -0,0 +1,71 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter, extra scripting +; Upload options: custom port, speed and extra flags +; Library options: dependencies, extra library storages +; +; Please visit documentation for the other options and examples +; http://docs.platformio.org/page/projectconf.html + +# NXP LPC Platform +[env:lpc11u35] +platform = nxplpc +framework = mbed +board = lpc11u35 +build_flags = -DPIO_FRAMEWORK_MBED_FILESYSTEM_PRESENT + +# Nordic nRF51 Platform +[env:redBearLab] +platform = nordicnrf51 +framework = mbed +board = redBearLab +build_flags = -DPIO_FRAMEWORK_MBED_FILESYSTEM_PRESENT + +# Nordic nRF52 Platform +[env:nrf52_dk] +platform = nordicnrf52 +framework = mbed +board = nrf52_dk +build_flags = -DPIO_FRAMEWORK_MBED_FILESYSTEM_PRESENT + +# Freescale FRDM Platform +[env:frdm_kl25z] +platform = freescalekinetis +framework = mbed +board = frdm_kl25z +build_flags = -DPIO_FRAMEWORK_MBED_FILESYSTEM_PRESENT + +# Maxim32 Platform +[env:max32600mbed] +platform = maxim32 +framework = mbed +board = max32600mbed +build_flags = -DPIO_FRAMEWORK_MBED_FILESYSTEM_PRESENT + +# ST STM32 Platform +[env:nucleo_f767zi] +platform = ststm32 +framework = mbed +board = nucleo_f767zi +build_flags = -DPIO_FRAMEWORK_MBED_FILESYSTEM_PRESENT + +# Teensy Platform +[env:teensy31] +platform = teensy +framework = mbed +board = teensy31 +build_flags = -DPIO_FRAMEWORK_MBED_FILESYSTEM_PRESENT + +# Silicon Labs EFM32 Platform +[env:efm32hg_stk3400] +platform = siliconlabsefm32 +framework = mbed +board = efm32hg_stk3400 +build_flags = -DPIO_FRAMEWORK_MBED_FILESYSTEM_PRESENT + +# WIZNet7500 Platform +[env:wizwiki_w7500] +platform = wiznet7500 +framework = mbed +board = wizwiki_w7500 +build_flags = -DPIO_FRAMEWORK_MBED_FILESYSTEM_PRESENT diff --git a/mbed/mbed-filesystem/src/main.cpp b/mbed/mbed-filesystem/src/main.cpp new file mode 100644 index 0000000..b25dfd9 --- /dev/null +++ b/mbed/mbed-filesystem/src/main.cpp @@ -0,0 +1,81 @@ +#include "mbed.h" +#include "FATFileSystem.h" +#include "HeapBlockDevice.h" +#include +#include + +HeapBlockDevice bd(128 * 512, 512); +FATFileSystem fs("fs"); + +void return_error(int ret_val){ + if (ret_val) + printf("Failure. %d\r\n", ret_val); + else + printf("done.\r\n"); +} + +void errno_error(void* ret_val){ + if (ret_val == NULL) + printf(" Failure. %d \r\n", errno); + else + printf(" done.\r\n"); +} + +int main() { + int error = 0; + printf("Welcome to the filesystem example.\r\n" + "Formatting a FAT, RAM-backed filesystem. "); + error = FATFileSystem::format(&bd); + return_error(error); + + printf("Mounting the filesystem on \"/fs\". "); + error = fs.mount(&bd); + return_error(error); + + printf("Opening a new file, numbers.txt."); + FILE* fd = fopen("/fs/numbers.txt", "w"); + errno_error(fd); + + for (int i = 0; i < 20; i++){ + printf("Writing decimal numbers to a file (%d/20)\r", i); + fprintf(fd, "%d\r\n", i); + } + printf("Writing decimal numbers to a file (20/20) done.\r\n"); + + printf("Closing file."); + fclose(fd); + printf(" done.\r\n"); + + printf("Re-opening file read-only."); + fd = fopen("/fs/numbers.txt", "r"); + errno_error(fd); + + printf("Dumping file to screen.\r\n"); + char buff[16] = {0}; + while (!feof(fd)){ + int size = fread(&buff[0], 1, 15, fd); + fwrite(&buff[0], 1, size, stdout); + } + printf("EOF.\r\n"); + + printf("Closing file."); + fclose(fd); + printf(" done.\r\n"); + + printf("Opening root directory."); + DIR* dir = opendir("/fs/"); + errno_error(fd); + + struct dirent* de; + printf("Printing all filenames:\r\n"); + while((de = readdir(dir)) != NULL){ + printf(" %s\r\n", &(de->d_name)[0]); + } + + printf("Closeing root directory. "); + error = closedir(dir); + return_error(error); + printf("Filesystem Demo complete.\r\n"); + + while (true) {} +} diff --git a/mbed/mbed-http-client/lib/HTTPClient/HTTPClient.cpp b/mbed/mbed-http-client/lib/HTTPClient/HTTPClient.cpp deleted file mode 100644 index 0a6abd3..0000000 --- a/mbed/mbed-http-client/lib/HTTPClient/HTTPClient.cpp +++ /dev/null @@ -1,739 +0,0 @@ -/* HTTPClient.cpp */ -/* Copyright (C) 2012 mbed.org, MIT License - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software - * and associated documentation files (the "Software"), to deal in the Software without restriction, - * including without limitation the rights to use, copy, modify, merge, publish, distribute, - * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or - * substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING - * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -//Debug is disabled by default -#if 0 -//Enable debug -#include -#define DBG(x, ...) std::printf("[HTTPClient : DBG]"x"\r\n", ##__VA_ARGS__); -#define WARN(x, ...) std::printf("[HTTPClient : WARN]"x"\r\n", ##__VA_ARGS__); -#define ERR(x, ...) std::printf("[HTTPClient : ERR]"x"\r\n", ##__VA_ARGS__); - -#else -//Disable debug -#define DBG(x, ...) -#define WARN(x, ...) -#define ERR(x, ...) - -#endif - -#define HTTP_PORT 80 - -#define OK 0 - -#define MIN(x,y) (((x)<(y))?(x):(y)) -#define MAX(x,y) (((x)>(y))?(x):(y)) - -#define CHUNK_SIZE 256 - -#include - -#include "HTTPClient.h" - -HTTPClient::HTTPClient() : -m_sock(), m_basicAuthUser(NULL), m_basicAuthPassword(NULL), m_httpResponseCode(0) -{ - -} - -HTTPClient::~HTTPClient() -{ - -} - -#if 0 -void HTTPClient::basicAuth(const char* user, const char* password) //Basic Authentification -{ - m_basicAuthUser = user; - m_basicAuthPassword = password; -} -#endif - -HTTPResult HTTPClient::get(const char* url, IHTTPDataIn* pDataIn, int timeout /*= HTTP_CLIENT_DEFAULT_TIMEOUT*/) //Blocking -{ - return connect(url, HTTP_GET, NULL, pDataIn, timeout); -} - -HTTPResult HTTPClient::get(const char* url, char* result, size_t maxResultLen, int timeout /*= HTTP_CLIENT_DEFAULT_TIMEOUT*/) //Blocking -{ - HTTPText str(result, maxResultLen); - return get(url, &str, timeout); -} - -HTTPResult HTTPClient::post(const char* url, const IHTTPDataOut& dataOut, IHTTPDataIn* pDataIn, int timeout /*= HTTP_CLIENT_DEFAULT_TIMEOUT*/) //Blocking -{ - return connect(url, HTTP_POST, (IHTTPDataOut*)&dataOut, pDataIn, timeout); -} - -HTTPResult HTTPClient::put(const char* url, const IHTTPDataOut& dataOut, IHTTPDataIn* pDataIn, int timeout /*= HTTP_CLIENT_DEFAULT_TIMEOUT*/) //Blocking -{ - return connect(url, HTTP_PUT, (IHTTPDataOut*)&dataOut, pDataIn, timeout); -} - -HTTPResult HTTPClient::del(const char* url, IHTTPDataIn* pDataIn, int timeout /*= HTTP_CLIENT_DEFAULT_TIMEOUT*/) //Blocking -{ - return connect(url, HTTP_DELETE, NULL, pDataIn, timeout); -} - - -int HTTPClient::getHTTPResponseCode() -{ - return m_httpResponseCode; -} - -#define CHECK_CONN_ERR(ret) \ - do{ \ - if(ret) { \ - m_sock.close(); \ - ERR("Connection error (%d)", ret); \ - return HTTP_CONN; \ - } \ - } while(0) - -#define PRTCL_ERR() \ - do{ \ - m_sock.close(); \ - ERR("Protocol error"); \ - return HTTP_PRTCL; \ - } while(0) - -HTTPResult HTTPClient::connect(const char* url, HTTP_METH method, IHTTPDataOut* pDataOut, IHTTPDataIn* pDataIn, int timeout) //Execute request -{ - m_httpResponseCode = 0; //Invalidate code - m_timeout = timeout; - - pDataIn->writeReset(); - if( pDataOut ) - { - pDataOut->readReset(); - } - - char scheme[8]; - uint16_t port; - char host[32]; - char path[64]; - //First we need to parse the url (http[s]://host[:port][/[path]]) -- HTTPS not supported (yet?) - HTTPResult res = parseURL(url, scheme, sizeof(scheme), host, sizeof(host), &port, path, sizeof(path)); - if(res != HTTP_OK) - { - ERR("parseURL returned %d", res); - return res; - } - - if(port == 0) //TODO do handle HTTPS->443 - { - port = 80; - } - - DBG("Scheme: %s", scheme); - DBG("Host: %s", host); - DBG("Port: %d", port); - DBG("Path: %s", path); - - //Connect - DBG("Connecting socket to server"); - int ret = m_sock.connect(host, port); - if (ret < 0) - { - m_sock.close(); - ERR("Could not connect"); - return HTTP_CONN; - } - - //Send request - DBG("Sending request"); - char buf[CHUNK_SIZE]; - const char* meth = (method==HTTP_GET)?"GET":(method==HTTP_POST)?"POST":(method==HTTP_PUT)?"PUT":(method==HTTP_DELETE)?"DELETE":""; - snprintf(buf, sizeof(buf), "%s %s HTTP/1.1\r\nHost: %s\r\n", meth, path, host); //Write request - ret = send(buf); - if(ret) - { - m_sock.close(); - ERR("Could not write request"); - return HTTP_CONN; - } - - //Send all headers - - //Send default headers - DBG("Sending headers"); - if( pDataOut != NULL ) - { - if( pDataOut->getIsChunked() ) - { - ret = send("Transfer-Encoding: chunked\r\n"); - CHECK_CONN_ERR(ret); - } - else - { - snprintf(buf, sizeof(buf), "Content-Length: %d\r\n", pDataOut->getDataLen()); - ret = send(buf); - CHECK_CONN_ERR(ret); - } - char type[48]; - if( pDataOut->getDataType(type, 48) == HTTP_OK ) - { - snprintf(buf, sizeof(buf), "Content-Type: %s\r\n", type); - ret = send(buf); - CHECK_CONN_ERR(ret); - } - - //Send specific headers - while( pDataOut->getHeader(buf, sizeof(buf) - 3) ) //must have space left for CRLF + 0 terminating char - { - size_t headerlen = strlen(buf); - snprintf(buf + headerlen, sizeof(buf) - headerlen, "\r\n"); - ret = send(buf); - CHECK_CONN_ERR(ret); - } - } - - //Send specific headers - while( pDataIn->getHeader(buf, sizeof(buf) - 3) ) - { - size_t headerlen = strlen(buf); - snprintf(buf + headerlen, sizeof(buf) - headerlen, "\r\n"); - ret = send(buf); - CHECK_CONN_ERR(ret); - } - - //Close headers - DBG("Headers sent"); - ret = send("\r\n"); - CHECK_CONN_ERR(ret); - - size_t trfLen; - - //Send data (if available) - if( pDataOut != NULL ) - { - DBG("Sending data"); - while(true) - { - size_t writtenLen = 0; - pDataOut->read(buf, CHUNK_SIZE, &trfLen); - if( pDataOut->getIsChunked() ) - { - //Write chunk header - char chunkHeader[16]; - snprintf(chunkHeader, sizeof(chunkHeader), "%X\r\n", trfLen); //In hex encoding - ret = send(chunkHeader); - CHECK_CONN_ERR(ret); - } - else if( trfLen == 0 ) - { - break; - } - if( trfLen != 0 ) - { - ret = send(buf, trfLen); - CHECK_CONN_ERR(ret); - } - - if( pDataOut->getIsChunked() ) - { - ret = send("\r\n"); //Chunk-terminating CRLF - CHECK_CONN_ERR(ret); - } - else - { - writtenLen += trfLen; - if( writtenLen >= pDataOut->getDataLen() ) - { - break; - } - } - - if( trfLen == 0 ) - { - break; - } - } - } - - //Receive response - DBG("Receiving response"); - ret = recv(buf, 1, CHUNK_SIZE - 1, &trfLen); //Read n bytes - CHECK_CONN_ERR(ret); - - buf[trfLen] = '\0'; - - //Make sure we got the first response line - char* crlfPtr = NULL; - while( true ) - { - crlfPtr = strstr(buf, "\r\n"); - if(crlfPtr == NULL) - { - if( trfLen < CHUNK_SIZE - 1 ) - { - size_t newTrfLen; - ret = recv(buf + trfLen, 1, CHUNK_SIZE - trfLen - 1, &newTrfLen); - trfLen += newTrfLen; - buf[trfLen] = '\0'; - DBG("Read %d chars; In buf: [%s]", newTrfLen, buf); - CHECK_CONN_ERR(ret); - continue; - } - else - { - PRTCL_ERR(); - } - } - break; - } - - int crlfPos = crlfPtr - buf; - buf[crlfPos] = '\0'; - - //Parse HTTP response - //if( sscanf(buf, "HTTP/%*d.%*d %d %*[^\r\n]", &m_httpResponseCode) != 1 ) - if(crlfPos > 13) - { - buf[13] = '\0'; - } - if( sscanf(buf, "HTTP/%*d.%*d %d", &m_httpResponseCode) != 1 ) //Kludge for newlib nano - { - //Cannot match string, error - ERR("Not a correct HTTP answer : %s\n", buf); - PRTCL_ERR(); - } - - if( (m_httpResponseCode < 200) || (m_httpResponseCode >= 300) ) - { - //Did not return a 2xx code; TODO fetch headers/(&data?) anyway and implement a mean of writing/reading headers - WARN("Response code %d", m_httpResponseCode); - PRTCL_ERR(); - } - - DBG("Reading headers"); - - memmove(buf, &buf[crlfPos+2], trfLen - (crlfPos + 2) + 1); //Be sure to move NULL-terminating char as well - trfLen -= (crlfPos + 2); - - size_t recvContentLength = 0; - bool recvChunked = false; - bool recvLengthUnknown = true; - //Now get headers - while( true ) - { - crlfPtr = strstr(buf, "\r\n"); - if(crlfPtr == NULL) - { - if( trfLen < CHUNK_SIZE - 1 ) - { - size_t newTrfLen; - ret = recv(buf + trfLen, 1, CHUNK_SIZE - trfLen - 1, &newTrfLen); - trfLen += newTrfLen; - buf[trfLen] = '\0'; - DBG("Read %d chars; In buf: [%s]", newTrfLen, buf); - CHECK_CONN_ERR(ret); - continue; - } - else - { - PRTCL_ERR(); - } - } - - crlfPos = crlfPtr - buf; - - if(crlfPos == 0) //End of headers - { - DBG("Headers read"); - memmove(buf, &buf[2], trfLen - 2 + 1); //Be sure to move NULL-terminating char as well - trfLen -= 2; - break; - } - - buf[crlfPos] = '\0'; - - char key[32]; - char value[32]; - - //key[31] = '\0'; - //value[31] = '\0'; - - memset(key, 0, 32); - memset(value, 0, 32); - - //int n = sscanf(buf, "%31[^:]: %31[^\r\n]", key, value); - - int n = 0; - - char* keyEnd = strchr(buf, ':'); - if(keyEnd != NULL) - { - *keyEnd = '\0'; - if(strlen(buf) < 32) - { - strcpy(key, buf); - n++; - char* valueStart = keyEnd + 2; - if( (valueStart - buf) < crlfPos ) - { - if(strlen(valueStart) < 32) - { - strcpy(value, valueStart); - n++; - } - } - } - } - if ( n == 2 ) - { - DBG("Read header : %s: %s\n", key, value); - if( !strcmp(key, "Content-Length") ) - { - sscanf(value, "%d", &recvContentLength); - recvLengthUnknown = false; - pDataIn->setDataLen(recvContentLength); - } - else if( !strcmp(key, "Transfer-Encoding") ) - { - if( !strcmp(value, "Chunked") || !strcmp(value, "chunked") ) - { - recvChunked = true; - recvLengthUnknown = false; - pDataIn->setIsChunked(true); - } - } - else if( !strcmp(key, "Content-Type") ) - { - pDataIn->setDataType(value); - } - - memmove(buf, &buf[crlfPos+2], trfLen - (crlfPos + 2) + 1); //Be sure to move NULL-terminating char as well - trfLen -= (crlfPos + 2); - - } - else - { - ERR("Could not parse header"); - PRTCL_ERR(); - } - - } - - //Receive data - DBG("Receiving data"); - while(true) - { - size_t readLen = 0; - - if( recvChunked ) - { - //Read chunk header - bool foundCrlf; - do - { - foundCrlf = false; - crlfPos=0; - buf[trfLen]=0; - if(trfLen >= 2) - { - for(; crlfPos < trfLen - 2; crlfPos++) - { - if( buf[crlfPos] == '\r' && buf[crlfPos + 1] == '\n' ) - { - foundCrlf = true; - break; - } - } - } - if(!foundCrlf) //Try to read more - { - if( trfLen < CHUNK_SIZE ) - { - size_t newTrfLen; - ret = recv(buf + trfLen, 0, CHUNK_SIZE - trfLen - 1, &newTrfLen); - trfLen += newTrfLen; - CHECK_CONN_ERR(ret); - continue; - } - else - { - PRTCL_ERR(); - } - } - } while(!foundCrlf); - buf[crlfPos] = '\0'; - int n = sscanf(buf, "%x", &readLen); - if(n!=1) - { - ERR("Could not read chunk length"); - PRTCL_ERR(); - } - - memmove(buf, &buf[crlfPos+2], trfLen - (crlfPos + 2)); //Not need to move NULL-terminating char any more - trfLen -= (crlfPos + 2); - - if( readLen == 0 ) - { - //Last chunk - break; - } - } - else - { - readLen = recvContentLength; - } - - DBG("Retrieving %d bytes (%d bytes in buffer)", readLen, trfLen); - - do - { - if(recvLengthUnknown ) - { - readLen = trfLen; - } - pDataIn->write(buf, MIN(trfLen, readLen)); - if(!recvLengthUnknown) - { - if( trfLen > readLen ) - { - memmove(buf, &buf[readLen], trfLen - readLen); - trfLen -= readLen; - readLen = 0; - } - else - { - readLen -= trfLen; - } - } - else - { - trfLen = 0; - } - - if(readLen || recvLengthUnknown) - { - ret = recv(buf, 1, CHUNK_SIZE - trfLen - 1, &trfLen); - if(recvLengthUnknown && (ret == HTTP_CLOSED)) - { - //Write and exit - pDataIn->write(buf, trfLen); - break; - } - CHECK_CONN_ERR(ret); - if(recvLengthUnknown && (trfLen == 0)) - { - break; - } - } - } while(readLen || recvLengthUnknown); - - if( recvChunked ) - { - if(trfLen < 2) - { - size_t newTrfLen; - //Read missing chars to find end of chunk - ret = recv(buf + trfLen, 2 - trfLen, CHUNK_SIZE - trfLen - 1, &newTrfLen); - CHECK_CONN_ERR(ret); - trfLen += newTrfLen; - } - if( (buf[0] != '\r') || (buf[1] != '\n') ) - { - ERR("Format error"); - PRTCL_ERR(); - } - memmove(buf, &buf[2], trfLen - 2); - trfLen -= 2; - } - else - { - break; - } - - } - - m_sock.close(); - DBG("Completed HTTP transaction"); - - return HTTP_OK; -} - -HTTPResult HTTPClient::recv(char* buf, size_t minLen, size_t maxLen, size_t* pReadLen) //0 on success, err code on failure -{ - DBG("Trying to read between %d and %d bytes", minLen, maxLen); - size_t readLen = 0; - - if(!m_sock.is_connected()) - { - WARN("Connection was closed by server"); - return HTTP_CLOSED; //Connection was closed by server - } - - int ret; - while(readLen < maxLen) - { - if(readLen < minLen) - { - DBG("Trying to read at most %d bytes [Blocking]", minLen - readLen); - m_sock.set_blocking(false, m_timeout); - ret = m_sock.receive_all(buf + readLen, minLen - readLen); - } - else - { - DBG("Trying to read at most %d bytes [Not blocking]", maxLen - readLen); - m_sock.set_blocking(false, 0); - ret = m_sock.receive(buf + readLen, maxLen - readLen); - } - - if( ret > 0) - { - readLen += ret; - } - else if( ret == 0 ) - { - break; - } - else - { - if(!m_sock.is_connected()) - { - ERR("Connection error (recv returned %d)", ret); - *pReadLen = readLen; - return HTTP_CONN; - } - else - { - break; - } - } - - if(!m_sock.is_connected()) - { - break; - } - } - DBG("Read %d bytes", readLen); - *pReadLen = readLen; - return HTTP_OK; -} - -HTTPResult HTTPClient::send(char* buf, size_t len) //0 on success, err code on failure -{ - if(len == 0) - { - len = strlen(buf); - } - DBG("Trying to write %d bytes", len); - size_t writtenLen = 0; - - if(!m_sock.is_connected()) - { - WARN("Connection was closed by server"); - return HTTP_CLOSED; //Connection was closed by server - } - - m_sock.set_blocking(false, m_timeout); - int ret = m_sock.send_all(buf, len); - if(ret > 0) - { - writtenLen += ret; - } - else if( ret == 0 ) - { - WARN("Connection was closed by server"); - return HTTP_CLOSED; //Connection was closed by server - } - else - { - ERR("Connection error (send returned %d)", ret); - return HTTP_CONN; - } - - DBG("Written %d bytes", writtenLen); - return HTTP_OK; -} - -HTTPResult HTTPClient::parseURL(const char* url, char* scheme, size_t maxSchemeLen, char* host, size_t maxHostLen, uint16_t* port, char* path, size_t maxPathLen) //Parse URL -{ - char* schemePtr = (char*) url; - char* hostPtr = (char*) strstr(url, "://"); - if(hostPtr == NULL) - { - WARN("Could not find host"); - return HTTP_PARSE; //URL is invalid - } - - if( maxSchemeLen < hostPtr - schemePtr + 1 ) //including NULL-terminating char - { - WARN("Scheme str is too small (%d >= %d)", maxSchemeLen, hostPtr - schemePtr + 1); - return HTTP_PARSE; - } - memcpy(scheme, schemePtr, hostPtr - schemePtr); - scheme[hostPtr - schemePtr] = '\0'; - - hostPtr+=3; - - size_t hostLen = 0; - - char* portPtr = strchr(hostPtr, ':'); - if( portPtr != NULL ) - { - hostLen = portPtr - hostPtr; - portPtr++; - if( sscanf(portPtr, "%hu", port) != 1) - { - WARN("Could not find port"); - return HTTP_PARSE; - } - } - else - { - *port=0; - } - char* pathPtr = strchr(hostPtr, '/'); - if( hostLen == 0 ) - { - hostLen = pathPtr - hostPtr; - } - - if( maxHostLen < hostLen + 1 ) //including NULL-terminating char - { - WARN("Host str is too small (%d >= %d)", maxHostLen, hostLen + 1); - return HTTP_PARSE; - } - memcpy(host, hostPtr, hostLen); - host[hostLen] = '\0'; - - size_t pathLen; - char* fragmentPtr = strchr(hostPtr, '#'); - if(fragmentPtr != NULL) - { - pathLen = fragmentPtr - pathPtr; - } - else - { - pathLen = strlen(pathPtr); - } - - if( maxPathLen < pathLen + 1 ) //including NULL-terminating char - { - WARN("Path str is too small (%d >= %d)", maxPathLen, pathLen + 1); - return HTTP_PARSE; - } - memcpy(path, pathPtr, pathLen); - path[pathLen] = '\0'; - - return HTTP_OK; -} diff --git a/mbed/mbed-http-client/lib/HTTPClient/HTTPClient.h b/mbed/mbed-http-client/lib/HTTPClient/HTTPClient.h deleted file mode 100644 index 25301c3..0000000 --- a/mbed/mbed-http-client/lib/HTTPClient/HTTPClient.h +++ /dev/null @@ -1,159 +0,0 @@ -/* HTTPClient.h */ -/* Copyright (C) 2012 mbed.org, MIT License - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software - * and associated documentation files (the "Software"), to deal in the Software without restriction, - * including without limitation the rights to use, copy, modify, merge, publish, distribute, - * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or - * substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING - * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -/** \file -HTTP Client header file -*/ - -#ifndef HTTP_CLIENT_H -#define HTTP_CLIENT_H - -#include "TCPSocketConnection.h" - -#define HTTP_CLIENT_DEFAULT_TIMEOUT 15000 - -class HTTPData; - -#include "IHTTPData.h" -#include "mbed.h" - -///HTTP client results -enum HTTPResult -{ - HTTP_PROCESSING, /// - -using std::size_t; - -class IHTTPData -{ - protected: - /** Get a specific header - * - */ - virtual bool getHeader(char* header, size_t maxHeaderLen) { return false; } -}; - -///This is a simple interface for HTTP data storage (impl examples are Key/Value Pairs, File, etc...) -class IHTTPDataOut : public IHTTPData -{ -protected: - friend class HTTPClient; - - /** Reset stream to its beginning - * Called by the HTTPClient on each new request - */ - virtual void readReset() = 0; - - /** Read a piece of data to be transmitted - * @param buf Pointer to the buffer on which to copy the data - * @param len Length of the buffer - * @param pReadLen Pointer to the variable on which the actual copied data length will be stored - */ - virtual int read(char* buf, size_t len, size_t* pReadLen) = 0; - - /** Get MIME type - * @param type Internet media type from Content-Type header - */ - virtual int getDataType(char* type, size_t maxTypeLen) = 0; //Internet media type for Content-Type header - - /** Determine whether the HTTP client should chunk the data - * Used for Transfer-Encoding header - */ - virtual bool getIsChunked() = 0; - - /** If the data is not chunked, get its size - * Used for Content-Length header - */ - virtual size_t getDataLen() = 0; - -}; - -///This is a simple interface for HTTP data storage (impl examples are Key/Value Pairs, File, etc...) -class IHTTPDataIn : public IHTTPData -{ -protected: - friend class HTTPClient; - - /** Reset stream to its beginning - * Called by the HTTPClient on each new request - */ - virtual void writeReset() = 0; - - /** Write a piece of data transmitted by the server - * @param buf Pointer to the buffer from which to copy the data - * @param len Length of the buffer - */ - virtual int write(const char* buf, size_t len) = 0; - - /** Set MIME type - * @param type Internet media type from Content-Type header - */ - virtual void setDataType(const char* type) = 0; - - /** Determine whether the data is chunked - * Recovered from Transfer-Encoding header - */ - virtual void setIsChunked(bool chunked) = 0; - - /** If the data is not chunked, set its size - * From Content-Length header - */ - virtual void setDataLen(size_t len) = 0; - -}; - -#endif diff --git a/mbed/mbed-http-client/lib/HTTPClient/data/HTTPMap.cpp b/mbed/mbed-http-client/lib/HTTPClient/data/HTTPMap.cpp deleted file mode 100644 index 5eb4c52..0000000 --- a/mbed/mbed-http-client/lib/HTTPClient/data/HTTPMap.cpp +++ /dev/null @@ -1,200 +0,0 @@ -/* HTTPMap.cpp */ -/* Copyright (C) 2012 mbed.org, MIT License - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software - * and associated documentation files (the "Software"), to deal in the Software without restriction, - * including without limitation the rights to use, copy, modify, merge, publish, distribute, - * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or - * substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING - * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "HTTPMap.h" - -#include - -#include - -#define OK 0 - -using std::strncpy; - -HTTPMap::HTTPMap() : m_pos(0), m_count(0) -{ - -} - -void HTTPMap::put(const char* key, const char* value) -{ - if(m_count >= HTTPMAP_TABLE_SIZE) - { - return; - } - m_keys[m_count] = key; - m_values[m_count] = value; - m_count++; -} - -void HTTPMap::clear() -{ - m_count = 0; - m_pos = 0; -} - -/*virtual*/ void HTTPMap::readReset() -{ - m_pos = 0; -} - -/*virtual*/ int HTTPMap::read(char* buf, size_t len, size_t* pReadLen) -{ - if(m_pos >= m_count) - { - *pReadLen = 0; - m_pos = 0; - return OK; - } - - //URL encode - char* out = buf; - const char* in = m_keys[m_pos]; - if( (m_pos != 0) && (out - buf < len - 1) ) - { - *out='&'; - out++; - } - - while( (*in != '\0') && (out - buf < len - 3) ) - { - if (std::isalnum(*in) || *in == '-' || *in == '_' || *in == '.' || *in == '~') - { - *out = *in; - out++; - } - else if( *in == ' ' ) - { - *out='+'; - out++; - } - else - { - char hex[] = "0123456789abcdef"; - *out='%'; - out++; - *out=hex[(*in>>4)&0xf]; - out++; - *out=hex[(*in)&0xf]; - out++; - } - in++; - } - - if( out - buf < len - 1 ) - { - *out='='; - out++; - } - - in = m_values[m_pos]; - while( (*in != '\0') && (out - buf < len - 3) ) - { - if (std::isalnum(*in) || *in == '-' || *in == '_' || *in == '.' || *in == '~') - { - *out = *in; - out++; - } - else if( *in == ' ' ) - { - *out='+'; - out++; - } - else - { - char hex[] = "0123456789abcdef"; - *out='%'; - out++; - *out=hex[(*in>>4)&0xf]; - out++; - *out=hex[(*in)&0xf]; - out++; - } - in++; - } - - *pReadLen = out - buf; - - m_pos++; - return OK; -} - -/*virtual*/ int HTTPMap::getDataType(char* type, size_t maxTypeLen) //Internet media type for Content-Type header -{ - strncpy(type, "application/x-www-form-urlencoded", maxTypeLen-1); - type[maxTypeLen-1] = '\0'; - return OK; -} - -/*virtual*/ bool HTTPMap::getIsChunked() //For Transfer-Encoding header -{ - return false; ////Data is computed one key/value pair at a time -} - -/*virtual*/ size_t HTTPMap::getDataLen() //For Content-Length header -{ - size_t count = 0; - for(size_t i = 0; i< m_count; i++) - { - //URL encode - const char* in = m_keys[i]; - if( i != 0 ) - { - count++; - } - - while( (*in != '\0') ) - { - if (std::isalnum(*in) || *in == '-' || *in == '_' || *in == '.' || *in == '~') - { - count++; - } - else if( *in == ' ' ) - { - count++; - } - else - { - count+=3; - } - in++; - } - - count ++; - - in = m_values[i]; - while( (*in != '\0') ) - { - if (std::isalnum(*in) || *in == '-' || *in == '_' || *in == '.' || *in == '~') - { - count++; - } - else if( *in == ' ' ) - { - count++; - } - else - { - count+=3; - } - in++; - } - } - return count; -} diff --git a/mbed/mbed-http-client/lib/HTTPClient/data/HTTPMap.h b/mbed/mbed-http-client/lib/HTTPClient/data/HTTPMap.h deleted file mode 100644 index c843377..0000000 --- a/mbed/mbed-http-client/lib/HTTPClient/data/HTTPMap.h +++ /dev/null @@ -1,71 +0,0 @@ -/* HTTPMap.h */ -/* Copyright (C) 2012 mbed.org, MIT License - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software - * and associated documentation files (the "Software"), to deal in the Software without restriction, - * including without limitation the rights to use, copy, modify, merge, publish, distribute, - * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or - * substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING - * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - - -#ifndef HTTPMAP_H_ -#define HTTPMAP_H_ - -#include "../IHTTPData.h" - -#define HTTPMAP_TABLE_SIZE 32 - -/** Map of key/value pairs - * Used to transmit POST data using the application/x-www-form-urlencoded encoding - */ -class HTTPMap: public IHTTPDataOut -{ -public: - /** - Instantiates HTTPMap - It supports at most 32 key/values pairs - */ - HTTPMap(); - - /** Put Key/Value pair - The references to the parameters must remain valid as long as the clear() function is not called - @param key The key to use - @param value The corresponding value - */ - void put(const char* key, const char* value); - - /** Clear table - */ - void clear(); - -protected: - //IHTTPDataIn - virtual void readReset(); - - virtual int read(char* buf, size_t len, size_t* pReadLen); - - virtual int getDataType(char* type, size_t maxTypeLen); //Internet media type for Content-Type header - - virtual bool getIsChunked(); //For Transfer-Encoding header - - virtual size_t getDataLen(); //For Content-Length header - -private: - const char* m_keys[HTTPMAP_TABLE_SIZE]; - const char* m_values[HTTPMAP_TABLE_SIZE]; - - size_t m_pos; - size_t m_count; -}; - -#endif /* HTTPMAP_H_ */ diff --git a/mbed/mbed-http-client/lib/HTTPClient/data/HTTPText.cpp b/mbed/mbed-http-client/lib/HTTPClient/data/HTTPText.cpp deleted file mode 100644 index 18cd420..0000000 --- a/mbed/mbed-http-client/lib/HTTPClient/data/HTTPText.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/* HTTPText.cpp */ -/* Copyright (C) 2012 mbed.org, MIT License - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software - * and associated documentation files (the "Software"), to deal in the Software without restriction, - * including without limitation the rights to use, copy, modify, merge, publish, distribute, - * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or - * substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING - * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "HTTPText.h" - -#include - -#define OK 0 - -using std::memcpy; -using std::strncpy; -using std::strlen; - -#define MIN(x,y) (((x)<(y))?(x):(y)) - -HTTPText::HTTPText(char* str) : m_str(str), m_pos(0) -{ - m_size = strlen(str) + 1; -} - -HTTPText::HTTPText(char* str, size_t size) : m_str(str), m_size(size), m_pos(0) -{ - -} - -//IHTTPDataIn -/*virtual*/ void HTTPText::readReset() -{ - m_pos = 0; -} - -/*virtual*/ int HTTPText::read(char* buf, size_t len, size_t* pReadLen) -{ - *pReadLen = MIN(len, m_size - 1 - m_pos); - memcpy(buf, m_str + m_pos, *pReadLen); - m_pos += *pReadLen; - return OK; -} - -/*virtual*/ int HTTPText::getDataType(char* type, size_t maxTypeLen) //Internet media type for Content-Type header -{ - strncpy(type, "text/plain", maxTypeLen-1); - type[maxTypeLen-1] = '\0'; - return OK; -} - -/*virtual*/ bool HTTPText::getIsChunked() //For Transfer-Encoding header -{ - return false; -} - -/*virtual*/ size_t HTTPText::getDataLen() //For Content-Length header -{ - return m_size - 1; -} - -//IHTTPDataOut -/*virtual*/ void HTTPText::writeReset() -{ - m_pos = 0; -} - -/*virtual*/ int HTTPText::write(const char* buf, size_t len) -{ - size_t writeLen = MIN(len, m_size - 1 - m_pos); - memcpy(m_str + m_pos, buf, writeLen); - m_pos += writeLen; - m_str[m_pos] = '\0'; - return OK; -} - -/*virtual*/ void HTTPText::setDataType(const char* type) //Internet media type from Content-Type header -{ - -} - -/*virtual*/ void HTTPText::setIsChunked(bool chunked) //From Transfer-Encoding header -{ - -} - -/*virtual*/ void HTTPText::setDataLen(size_t len) //From Content-Length header, or if the transfer is chunked, next chunk length -{ - -} - - - diff --git a/mbed/mbed-http-client/lib/HTTPClient/data/HTTPText.h b/mbed/mbed-http-client/lib/HTTPClient/data/HTTPText.h deleted file mode 100644 index f55ff76..0000000 --- a/mbed/mbed-http-client/lib/HTTPClient/data/HTTPText.h +++ /dev/null @@ -1,72 +0,0 @@ -/* HTTPText.h */ -/* Copyright (C) 2012 mbed.org, MIT License - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software - * and associated documentation files (the "Software"), to deal in the Software without restriction, - * including without limitation the rights to use, copy, modify, merge, publish, distribute, - * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or - * substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING - * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - - -#ifndef HTTPTEXT_H_ -#define HTTPTEXT_H_ - -#include "../IHTTPData.h" - -/** A data endpoint to store text -*/ -class HTTPText : public IHTTPDataIn, public IHTTPDataOut -{ -public: - /** Create an HTTPText instance for output - * @param str String to be transmitted - */ - HTTPText(char* str); - - /** Create an HTTPText instance for input - * @param str Buffer to store the incoming string - * @param size Size of the buffer - */ - HTTPText(char* str, size_t size); - -protected: - //IHTTPDataIn - virtual void readReset(); - - virtual int read(char* buf, size_t len, size_t* pReadLen); - - virtual int getDataType(char* type, size_t maxTypeLen); //Internet media type for Content-Type header - - virtual bool getIsChunked(); //For Transfer-Encoding header - - virtual size_t getDataLen(); //For Content-Length header - - //IHTTPDataOut - virtual void writeReset(); - - virtual int write(const char* buf, size_t len); - - virtual void setDataType(const char* type); //Internet media type from Content-Type header - - virtual void setIsChunked(bool chunked); //From Transfer-Encoding header - - virtual void setDataLen(size_t len); //From Content-Length header, or if the transfer is chunked, next chunk length - -private: - char* m_str; - size_t m_size; - - size_t m_pos; -}; - -#endif /* HTTPTEXT_H_ */ diff --git a/mbed/mbed-http-client/src/main.cpp b/mbed/mbed-http-client/src/main.cpp deleted file mode 100644 index 654ee36..0000000 --- a/mbed/mbed-http-client/src/main.cpp +++ /dev/null @@ -1,79 +0,0 @@ -#include "mbed.h" -#include "EthernetInterface.h" -#include "HTTPClient.h" - -EthernetInterface eth; -HTTPClient http; -char str[512]; - -int main() -{ - eth.init(); //Use DHCP - - eth.connect(); - - //GET data - printf("\nTrying to fetch page...\n"); - int ret = http.get("https://developer.mbed.org/media/uploads/donatien/hello.txt", str, 128); - if (!ret) - { - printf("Page fetched successfully - read %d characters\n", strlen(str)); - printf("Result: %s\n", str); - } - else - { - printf("Error - ret = %d - HTTP return code = %d\n", ret, http.getHTTPResponseCode()); - } - - //POST data - HTTPMap map; - HTTPText inText(str, 512); - map.put("Hello", "World"); - map.put("test", "1234"); - printf("\nTrying to post data...\n"); - ret = http.post("http://httpbin.org/post", map, &inText); - if (!ret) - { - printf("Executed POST successfully - read %d characters\n", strlen(str)); - printf("Result: %s\n", str); - } - else - { - printf("Error - ret = %d - HTTP return code = %d\n", ret, http.getHTTPResponseCode()); - } - - //PUT data - strcpy(str, "This is a PUT test!"); - HTTPText outText(str); - //HTTPText inText(str, 512); - printf("\nTrying to put resource...\n"); - ret = http.put("http://httpbin.org/put", outText, &inText); - if (!ret) - { - printf("Executed PUT successfully - read %d characters\n", strlen(str)); - printf("Result: %s\n", str); - } - else - { - printf("Error - ret = %d - HTTP return code = %d\n", ret, http.getHTTPResponseCode()); - } - - //DELETE data - //HTTPText inText(str, 512); - printf("\nTrying to delete resource...\n"); - ret = http.del("http://httpbin.org/delete", &inText); - if (!ret) - { - printf("Executed DELETE successfully - read %d characters\n", strlen(str)); - printf("Result: %s\n", str); - } - else - { - printf("Error - ret = %d - HTTP return code = %d\n", ret, http.getHTTPResponseCode()); - } - - eth.disconnect(); - - while(1) { - } -} diff --git a/mbed/mbed-rtos-ethernet-tls/.gitignore b/mbed/mbed-rtos-ethernet-tls/.gitignore new file mode 100644 index 0000000..5402c18 --- /dev/null +++ b/mbed/mbed-rtos-ethernet-tls/.gitignore @@ -0,0 +1,3 @@ +.pioenvs +.clang_complete +.gcc-flags.json diff --git a/mbed/mbed-rtos-ethernet-tls/.travis.yml b/mbed/mbed-rtos-ethernet-tls/.travis.yml new file mode 100644 index 0000000..593d7ef --- /dev/null +++ b/mbed/mbed-rtos-ethernet-tls/.travis.yml @@ -0,0 +1,65 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < http://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < http://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < http://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to by used as a library with examples +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/mbed/mbed-rtos-ethernet-tls/README.rst b/mbed/mbed-rtos-ethernet-tls/README.rst new file mode 100644 index 0000000..4bbf253 --- /dev/null +++ b/mbed/mbed-rtos-ethernet-tls/README.rst @@ -0,0 +1,38 @@ +.. Copyright (c) 2014-present PlatformIO + 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. + +How to build PlatformIO based project +===================================== + +1. `Install PlatformIO Core `_ +2. Download `examples source code `_ +3. Extract ZIP archive +4. Run these commands: + +.. code-block:: bash + + # Change directory to example + > cd platformio-examples/mbed/mbed-rtos-ethernet-tls + + # Build project + > platformio run + + # Upload firmware + > platformio run --target upload + + # Build specific environment + > platformio run -e nucleo_f767zi + + # Upload firmware for the specific environment + > platformio run -e nucleo_f767zi --target upload + + # Clean build files + > platformio run --target clean diff --git a/mbed/mbed-rtos-ethernet-tls/lib/readme.txt b/mbed/mbed-rtos-ethernet-tls/lib/readme.txt new file mode 100644 index 0000000..4b6209e --- /dev/null +++ b/mbed/mbed-rtos-ethernet-tls/lib/readme.txt @@ -0,0 +1,38 @@ + +This directory is intended for the project specific (private) libraries. +PlatformIO will compile them to static libraries and link to executable file. + +The source code of each library should be placed in separate directory, like +"lib/private_lib/[here are source files]". + +For example, see how can be organized `Foo` and `Bar` libraries: + +|--lib +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| |--Foo +| | |- Foo.c +| | |- Foo.h +| |- readme.txt --> THIS FILE +|- platformio.ini +|--src + |- main.c + +Then in `src/main.c` you should use: + +#include +#include + +// rest H/C/CPP code + +PlatformIO will find your libraries automatically, configure preprocessor's +include paths and build them. + +See additional options for PlatformIO Library Dependency Finder `lib_*`: + +http://docs.platformio.org/page/projectconf.html#lib-install + diff --git a/mbed/mbed-http-client/platformio.ini b/mbed/mbed-rtos-ethernet-tls/platformio.ini similarity index 66% rename from mbed/mbed-http-client/platformio.ini rename to mbed/mbed-rtos-ethernet-tls/platformio.ini index e5a2e6a..89e5395 100644 --- a/mbed/mbed-http-client/platformio.ini +++ b/mbed/mbed-rtos-ethernet-tls/platformio.ini @@ -7,17 +7,15 @@ ; Please visit documentation for the other options and examples ; http://docs.platformio.org/page/projectconf.html -[platformio] -env_default = lpc1768 -# NXP LPC Platform -[env:lpc1768] -platform = nxplpc +[env:nucleo_f767zi] +platform = ststm32 framework = mbed -board = lpc1768 +board = nucleo_f767zi +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT -# ST STM32 Platform -[env:seeedArchMax] -platform = ststm32 +[env:frdm_k64f] +platform = freescalekinetis framework = mbed -board = seeedArchMax +board = frdm_k64f +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT \ No newline at end of file diff --git a/mbed/mbed-rtos-ethernet-tls/src/main.cpp b/mbed/mbed-rtos-ethernet-tls/src/main.cpp new file mode 100644 index 0000000..983dac0 --- /dev/null +++ b/mbed/mbed-rtos-ethernet-tls/src/main.cpp @@ -0,0 +1,435 @@ +/* + * Hello world example of a TLS client: fetch an HTTPS page + * + * Copyright (C) 2006-2016, 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. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +/** \file main.cpp + * \brief An example TLS Client application + * This application sends an HTTPS request to developer.mbed.org and searches for a string in + * the result. + * + * This example is implemented as a logic class (HelloHTTPS) wrapping a TCP socket. + * The logic class handles all events, leaving the main loop to just check if the process + * has finished. + */ + +/* Change to a number between 1 and 4 to debug the TLS connection */ +#define DEBUG_LEVEL 0 + +#include "mbed.h" +#include "NetworkStack.h" + +#include "EthernetInterface.h" +#include "TCPSocket.h" + +#include "mbedtls/platform.h" +#include "mbedtls/ssl.h" +#include "mbedtls/entropy.h" +#include "mbedtls/ctr_drbg.h" +#include "mbedtls/error.h" + +#if DEBUG_LEVEL > 0 +#include "mbedtls/debug.h" +#endif + +namespace { + +const char *HTTPS_SERVER_NAME = "developer.mbed.org"; +const int HTTPS_SERVER_PORT = 443; +const int RECV_BUFFER_SIZE = 600; + +const char HTTPS_PATH[] = "/media/uploads/mbed_official/hello.txt"; + +/* Test related data */ +const char *HTTPS_OK_STR = "200 OK"; +const char *HTTPS_HELLO_STR = "Hello world!"; + +/* personalization string for the drbg */ +const char *DRBG_PERS = "mbed TLS helloword client"; + +/* List of trusted root CA certificates + * currently only GlobalSign, the CA for developer.mbed.org + * + * To add more than one root, just concatenate them. + */ +const char SSL_CA_PEM[] = "-----BEGIN CERTIFICATE-----\n" + "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG\n" + "A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv\n" + "b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw\n" + "MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i\n" + "YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT\n" + "aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ\n" + "jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp\n" + "xy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp\n" + "1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG\n" + "snUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ\n" + "U26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8\n" + "9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E\n" + "BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B\n" + "AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz\n" + "yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE\n" + "38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP\n" + "AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad\n" + "DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME\n" + "HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n" + "-----END CERTIFICATE-----\n"; + +} + +/** + * \brief HelloHTTPS implements the logic for fetching a file from a webserver + * using a TCP socket and parsing the result. + */ +class HelloHTTPS { +public: + /** + * HelloHTTPS Constructor + * Initializes the TCP socket, sets up event handlers and flags. + * + * @param[in] domain The domain name to fetch from + * @param[in] port The port of the HTTPS server + */ + HelloHTTPS(const char * domain, const uint16_t port, NetworkInterface *net_iface) : + _domain(domain), _port(port) + { + + _gothello = false; + _got200 = false; + _bpos = 0; + _request_sent = 0; + _tcpsocket = new TCPSocket(net_iface); + _tcpsocket->set_blocking(false); + _buffer[RECV_BUFFER_SIZE - 1] = 0; + + mbedtls_entropy_init(&_entropy); + mbedtls_ctr_drbg_init(&_ctr_drbg); + mbedtls_x509_crt_init(&_cacert); + mbedtls_ssl_init(&_ssl); + mbedtls_ssl_config_init(&_ssl_conf); + } + /** + * HelloHTTPS Desctructor + */ + ~HelloHTTPS() { + mbedtls_entropy_free(&_entropy); + mbedtls_ctr_drbg_free(&_ctr_drbg); + mbedtls_x509_crt_free(&_cacert); + mbedtls_ssl_free(&_ssl); + mbedtls_ssl_config_free(&_ssl_conf); + _tcpsocket->close(); + delete _tcpsocket; + } + /** + * Start the test. + * + * Starts by clearing test flags, then resolves the address with DNS. + * + * @param[in] path The path of the file to fetch from the HTTPS server + * @return SOCKET_ERROR_NONE on success, or an error code on failure + */ + void startTest(const char *path) { + /* Initialize the flags */ + _got200 = false; + _gothello = false; + _disconnected = false; + _request_sent = false; + + /* + * Initialize TLS-related stuf. + */ + int ret; + if ((ret = mbedtls_ctr_drbg_seed(&_ctr_drbg, mbedtls_entropy_func, &_entropy, + (const unsigned char *) DRBG_PERS, + sizeof (DRBG_PERS))) != 0) { + print_mbedtls_error("mbedtls_crt_drbg_init", ret); + return; + } + + if ((ret = mbedtls_x509_crt_parse(&_cacert, (const unsigned char *) SSL_CA_PEM, + sizeof (SSL_CA_PEM))) != 0) { + print_mbedtls_error("mbedtls_x509_crt_parse", ret); + return; + } + + if ((ret = mbedtls_ssl_config_defaults(&_ssl_conf, + MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_TRANSPORT_STREAM, + MBEDTLS_SSL_PRESET_DEFAULT)) != 0) { + print_mbedtls_error("mbedtls_ssl_config_defaults", ret); + return; + } + + mbedtls_ssl_conf_ca_chain(&_ssl_conf, &_cacert, NULL); + mbedtls_ssl_conf_rng(&_ssl_conf, mbedtls_ctr_drbg_random, &_ctr_drbg); + + /* It is possible to disable authentication by passing + * MBEDTLS_SSL_VERIFY_NONE in the call to mbedtls_ssl_conf_authmode() + */ + mbedtls_ssl_conf_authmode(&_ssl_conf, MBEDTLS_SSL_VERIFY_REQUIRED); + +#if DEBUG_LEVEL > 0 + mbedtls_ssl_conf_verify(&_ssl_conf, my_verify, NULL); + mbedtls_ssl_conf_dbg(&_ssl_conf, my_debug, NULL); + mbedtls_debug_set_threshold(DEBUG_LEVEL); +#endif + + if ((ret = mbedtls_ssl_setup(&_ssl, &_ssl_conf)) != 0) { + print_mbedtls_error("mbedtls_ssl_setup", ret); + return; + } + + mbedtls_ssl_set_hostname(&_ssl, HTTPS_SERVER_NAME); + + mbedtls_ssl_set_bio(&_ssl, static_cast(_tcpsocket), + ssl_send, ssl_recv, NULL ); + + + /* Connect to the server */ + mbedtls_printf("Connecting with %s\r\n", _domain); + ret = _tcpsocket->connect(_domain, _port); + if (ret != NSAPI_ERROR_OK) { + mbedtls_printf("Failed to connect\r\n"); + printf("MBED: Socket Error: %d\r\n", ret); + _tcpsocket->close(); + return; + } + + /* Start the handshake, the rest will be done in onReceive() */ + mbedtls_printf("Starting the TLS handshake...\r\n"); + do { + ret = mbedtls_ssl_handshake(&_ssl); + } while (ret != 0 && (ret == MBEDTLS_ERR_SSL_WANT_READ || + ret == MBEDTLS_ERR_SSL_WANT_WRITE)); + if (ret < 0) { + print_mbedtls_error("mbedtls_ssl_handshake", ret); + _tcpsocket->close(); + return; + } + + /* Fill the request buffer */ + _bpos = snprintf(_buffer, sizeof(_buffer) - 1, + "GET %s HTTP/1.1\nHost: %s\n\n", path, HTTPS_SERVER_NAME); + + int offset = 0; + do { + ret = mbedtls_ssl_write(&_ssl, + (const unsigned char *) _buffer + offset, + _bpos - offset); + if (ret > 0) + offset += ret; + } while (offset < _bpos && (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ || + ret == MBEDTLS_ERR_SSL_WANT_WRITE)); + if (ret < 0) { + print_mbedtls_error("mbedtls_ssl_write", ret); + _tcpsocket->close(); + return; + } + + /* It also means the handshake is done, time to print info */ + printf("TLS connection to %s established\r\n", HTTPS_SERVER_NAME); + + const uint32_t buf_size = 1024; + char *buf = new char[buf_size]; + mbedtls_x509_crt_info(buf, buf_size, "\r ", + mbedtls_ssl_get_peer_cert(&_ssl)); + mbedtls_printf("Server certificate:\r\n%s\r", buf); + + uint32_t flags = mbedtls_ssl_get_verify_result(&_ssl); + if( flags != 0 ) + { + mbedtls_x509_crt_verify_info(buf, buf_size, "\r ! ", flags); + printf("Certificate verification failed:\r\n%s\r\r\n", buf); + } + else + printf("Certificate verification passed\r\n\r\n"); + + + /* Read data out of the socket */ + offset = 0; + do { + ret = mbedtls_ssl_read(&_ssl, (unsigned char *) _buffer + offset, + sizeof(_buffer) - offset - 1); + if (ret > 0) + offset += ret; + + /* Check each of the flags */ + _buffer[offset] = 0; + _got200 = _got200 || strstr(_buffer, HTTPS_OK_STR) != NULL; + _gothello = _gothello || strstr(_buffer, HTTPS_HELLO_STR) != NULL; + } while ( (!_got200 || !_gothello) && + (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ || + ret == MBEDTLS_ERR_SSL_WANT_WRITE)); + if (ret < 0) { + print_mbedtls_error("mbedtls_ssl_read", ret); + delete[] buf; + _tcpsocket->close(); + return; + } + _bpos = static_cast(offset); + + _buffer[_bpos] = 0; + + /* Close socket before status */ + _tcpsocket->close(); + + /* Print status messages */ + mbedtls_printf("HTTPS: Received %d chars from server\r\n", _bpos); + mbedtls_printf("HTTPS: Received 200 OK status ... %s\r\n", _got200 ? "[OK]" : "[FAIL]"); + mbedtls_printf("HTTPS: Received '%s' status ... %s\r\n", HTTPS_HELLO_STR, _gothello ? "[OK]" : "[FAIL]"); + mbedtls_printf("HTTPS: Received message:\r\n\r\n"); + mbedtls_printf("%s", _buffer); + + delete[] buf; + } + +protected: + /** + * Helper for pretty-printing mbed TLS error codes + */ + static void print_mbedtls_error(const char *name, int err) { + char buf[128]; + mbedtls_strerror(err, buf, sizeof (buf)); + mbedtls_printf("%s() failed: -0x%04x (%d): %s\r\n", name, -err, err, buf); + } + +#if DEBUG_LEVEL > 0 + /** + * Debug callback for mbed TLS + * Just prints on the USB serial port + */ + static void my_debug(void *ctx, int level, const char *file, int line, + const char *str) + { + const char *p, *basename; + (void) ctx; + + /* Extract basename from file */ + for(p = basename = file; *p != '\0'; p++) { + if(*p == '/' || *p == '\\') { + basename = p + 1; + } + } + + mbedtls_printf("%s:%04d: |%d| %s", basename, line, level, str); + } + + /** + * Certificate verification callback for mbed TLS + * Here we only use it to display information on each cert in the chain + */ + static int my_verify(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags) + { + const uint32_t buf_size = 1024; + char *buf = new char[buf_size]; + (void) data; + + mbedtls_printf("\nVerifying certificate at depth %d:\n", depth); + mbedtls_x509_crt_info(buf, buf_size - 1, " ", crt); + mbedtls_printf("%s", buf); + + if (*flags == 0) + mbedtls_printf("No verification issue for this certificate\n"); + else + { + mbedtls_x509_crt_verify_info(buf, buf_size, " ! ", *flags); + mbedtls_printf("%s\n", buf); + } + + delete[] buf; + return 0; + } +#endif + + /** + * Receive callback for mbed TLS + */ + static int ssl_recv(void *ctx, unsigned char *buf, size_t len) { + int recv = -1; + TCPSocket *socket = static_cast(ctx); + recv = socket->recv(buf, len); + + if(NSAPI_ERROR_WOULD_BLOCK == recv){ + return MBEDTLS_ERR_SSL_WANT_READ; + }else if(recv < 0){ + mbedtls_printf("Socket recv error %d\r\n", recv); + return -1; + }else{ + return recv; + } + } + + /** + * Send callback for mbed TLS + */ + static int ssl_send(void *ctx, const unsigned char *buf, size_t len) { + int size = -1; + TCPSocket *socket = static_cast(ctx); + size = socket->send(buf, len); + + if(NSAPI_ERROR_WOULD_BLOCK == size){ + return MBEDTLS_ERR_SSL_WANT_WRITE; + }else if(size < 0){ + mbedtls_printf("Socket send error %d\r\n", size); + return -1; + }else{ + return size; + } + } + +protected: + TCPSocket* _tcpsocket; + + const char *_domain; /**< The domain name of the HTTPS server */ + const uint16_t _port; /**< The HTTPS server port */ + char _buffer[RECV_BUFFER_SIZE]; /**< The response buffer */ + size_t _bpos; /**< The current offset in the response buffer */ + volatile bool _got200; /**< Status flag for HTTPS 200 */ + volatile bool _gothello; /**< Status flag for finding the test string */ + volatile bool _disconnected; + volatile bool _request_sent; + + mbedtls_entropy_context _entropy; + mbedtls_ctr_drbg_context _ctr_drbg; + mbedtls_x509_crt _cacert; + mbedtls_ssl_context _ssl; + mbedtls_ssl_config _ssl_conf; +}; + +/** + * The main loop of the HTTPS Hello World test + */ +int main() { + /* The default 9600 bps is too slow to print full TLS debug info and could + * cause the other party to time out. */ + + /* Inititalise with DHCP, connect, and start up the stack */ + EthernetInterface eth_iface; + eth_iface.connect(); + mbedtls_printf("Using Ethernet LWIP\r\n"); + const char *ip_addr = eth_iface.get_ip_address(); + if (ip_addr) { + mbedtls_printf("Client IP Address is %s\r\n", ip_addr); + } else { + mbedtls_printf("No Client IP Address\r\n"); + } + + HelloHTTPS *hello = new HelloHTTPS(HTTPS_SERVER_NAME, HTTPS_SERVER_PORT, ð_iface); + hello->startTest(HTTPS_PATH); + delete hello; +} \ No newline at end of file diff --git a/mbed/mbed-rtos-ethernet-tls/src/mbedtls_entropy_config.h b/mbed/mbed-rtos-ethernet-tls/src/mbedtls_entropy_config.h new file mode 100644 index 0000000..df37671 --- /dev/null +++ b/mbed/mbed-rtos-ethernet-tls/src/mbedtls_entropy_config.h @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2006-2016, 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. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#if !defined(MBEDTLS_ENTROPY_HARDWARE_ALT) && \ + !defined(MBEDTLS_ENTROPY_NV_SEED) && !defined(MBEDTLS_TEST_NULL_ENTROPY) +#error "This hardware does not have an entropy source." +#endif /* !MBEDTLS_ENTROPY_HARDWARE_ALT && !MBEDTLS_ENTROPY_NV_SEED && + * !MBEDTLS_TEST_NULL_ENTROPY */ + +#if !defined(MBEDTLS_SHA1_C) +#define MBEDTLS_SHA1_C +#endif /* !MBEDTLS_SHA1_C */ + +/* + * This value is sufficient for handling 2048 bit RSA keys. + * + * Set this value higher to enable handling larger keys, but be aware that this + * will increase the stack usage. + */ +#define MBEDTLS_MPI_MAX_SIZE 256 + +#define MBEDTLS_MPI_WINDOW_SIZE 1 \ No newline at end of file diff --git a/mbed/mbed-rtos-ethernet/.gitignore b/mbed/mbed-rtos-ethernet/.gitignore new file mode 100644 index 0000000..5402c18 --- /dev/null +++ b/mbed/mbed-rtos-ethernet/.gitignore @@ -0,0 +1,3 @@ +.pioenvs +.clang_complete +.gcc-flags.json diff --git a/mbed/mbed-rtos-ethernet/.travis.yml b/mbed/mbed-rtos-ethernet/.travis.yml new file mode 100644 index 0000000..593d7ef --- /dev/null +++ b/mbed/mbed-rtos-ethernet/.travis.yml @@ -0,0 +1,65 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < http://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < http://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < http://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to by used as a library with examples +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/mbed/mbed-rtos-ethernet/README.rst b/mbed/mbed-rtos-ethernet/README.rst new file mode 100644 index 0000000..ae21c62 --- /dev/null +++ b/mbed/mbed-rtos-ethernet/README.rst @@ -0,0 +1,38 @@ +.. Copyright (c) 2014-present PlatformIO + 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. + +How to build PlatformIO based project +===================================== + +1. `Install PlatformIO Core `_ +2. Download `examples source code `_ +3. Extract ZIP archive +4. Run these commands: + +.. code-block:: bash + + # Change directory to example + > cd platformio-examples/mbed/mbed-rtos-ethernet + + # Build project + > platformio run + + # Upload firmware + > platformio run --target upload + + # Build specific environment + > platformio run -e nucleo_f767zi + + # Upload firmware for the specific environment + > platformio run -e nucleo_f767zi --target upload + + # Clean build files + > platformio run --target clean diff --git a/mbed/mbed-rtos-ethernet/lib/NTPClient/NTPClient.cpp b/mbed/mbed-rtos-ethernet/lib/NTPClient/NTPClient.cpp new file mode 100644 index 0000000..ba4ad1b --- /dev/null +++ b/mbed/mbed-rtos-ethernet/lib/NTPClient/NTPClient.cpp @@ -0,0 +1,163 @@ +/* NTPClient.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +//Debug is disabled by default +#if 0 +//Enable debug +#define __DEBUG__ +#include +#define DBG(x, ...) std::printf("[NTPClient : DBG]"x"\r\n", ##__VA_ARGS__); +#define WARN(x, ...) std::printf("[NTPClient : WARN]"x"\r\n", ##__VA_ARGS__); +#define ERR(x, ...) std::printf("[NTPClient : ERR]"x"\r\n", ##__VA_ARGS__); + +#else +//Disable debug +#define DBG(x, ...) +#define WARN(x, ...) +#define ERR(x, ...) + +#endif + +#include "NTPClient.h" + +#include "UDPSocket.h" + +#include "mbed.h" //time() and set_time() + +#define NTP_PORT 123 +#define NTP_CLIENT_PORT 0 //Random port +#define NTP_TIMESTAMP_DELTA 2208988800ull //Diff btw a UNIX timestamp (Starting Jan, 1st 1970) and a NTP timestamp (Starting Jan, 1st 1900) + +NTPClient::NTPClient() : m_sock() +{ + + +} + +NTPResult NTPClient::setTime(const char* host, uint16_t port, uint32_t timeout) +{ +#ifdef __DEBUG__ + time_t ctTime; + ctTime = time(NULL); + DBG("Time is set to (UTC): %s", ctime(&ctTime)); +#endif + + //Create & bind socket + DBG("Binding socket"); + m_sock.bind(0); //Bind to a random port + + m_sock.set_blocking(false, timeout); //Set not blocking + + struct NTPPacket pkt; + + //Now ping the server and wait for response + DBG("Ping"); + //Prepare NTP Packet: + pkt.li = 0; //Leap Indicator : No warning + pkt.vn = 4; //Version Number : 4 + pkt.mode = 3; //Client mode + pkt.stratum = 0; //Not relevant here + pkt.poll = 0; //Not significant as well + pkt.precision = 0; //Neither this one is + + pkt.rootDelay = 0; //Or this one + pkt.rootDispersion = 0; //Or that one + pkt.refId = 0; //... + + pkt.refTm_s = 0; + pkt.origTm_s = 0; + pkt.rxTm_s = 0; + pkt.txTm_s = htonl( NTP_TIMESTAMP_DELTA + time(NULL) ); //WARN: We are in LE format, network byte order is BE + + pkt.refTm_f = pkt.origTm_f = pkt.rxTm_f = pkt.txTm_f = 0; + + Endpoint outEndpoint; + + if( outEndpoint.set_address(host, port) < 0) + { + m_sock.close(); + return NTP_DNS; + } + + //Set timeout, non-blocking and wait using select + int ret = m_sock.sendTo( outEndpoint, (char*)&pkt, sizeof(NTPPacket) ); + if (ret < 0 ) + { + ERR("Could not send packet"); + m_sock.close(); + return NTP_CONN; + } + + //Read response + Endpoint inEndpoint; + + DBG("Pong"); + do + { + ret = m_sock.receiveFrom( inEndpoint, (char*)&pkt, sizeof(NTPPacket) ); //FIXME need a DNS Resolver to actually compare the incoming address with the DNS name + if(ret < 0) + { + ERR("Could not receive packet"); + m_sock.close(); + return NTP_CONN; + } + } while( strcmp(outEndpoint.get_address(), inEndpoint.get_address()) != 0 ); + + if(ret < sizeof(NTPPacket)) //TODO: Accept chunks + { + ERR("Receive packet size does not match"); + m_sock.close(); + return NTP_PRTCL; + } + + if( pkt.stratum == 0) //Kiss of death message : Not good ! + { + ERR("Kissed to death!"); + m_sock.close(); + return NTP_PRTCL; + } + + //Correct Endianness + pkt.refTm_s = ntohl( pkt.refTm_s ); + pkt.refTm_f = ntohl( pkt.refTm_f ); + pkt.origTm_s = ntohl( pkt.origTm_s ); + pkt.origTm_f = ntohl( pkt.origTm_f ); + pkt.rxTm_s = ntohl( pkt.rxTm_s ); + pkt.rxTm_f = ntohl( pkt.rxTm_f ); + pkt.txTm_s = ntohl( pkt.txTm_s ); + pkt.txTm_f = ntohl( pkt.txTm_f ); + + //Compute offset, see RFC 4330 p.13 + uint32_t destTm_s = (NTP_TIMESTAMP_DELTA + time(NULL)); + int64_t offset = ( (int64_t)( pkt.rxTm_s - pkt.origTm_s ) + (int64_t) ( pkt.txTm_s - destTm_s ) ) / 2; //Avoid overflow + DBG("Sent @%ul", pkt.txTm_s); + DBG("Offset: %lld", offset); + //Set time accordingly + set_time( time(NULL) + offset ); + +#ifdef __DEBUG__ + ctTime = time(NULL); + DBG("Time is now (UTC): %s", ctime(&ctTime)); +#endif + + m_sock.close(); + + return NTP_OK; +} + diff --git a/mbed/mbed-rtos-ethernet/lib/NTPClient/NTPClient.h b/mbed/mbed-rtos-ethernet/lib/NTPClient/NTPClient.h new file mode 100644 index 0000000..d66cb2d --- /dev/null +++ b/mbed/mbed-rtos-ethernet/lib/NTPClient/NTPClient.h @@ -0,0 +1,102 @@ +/* NTPClient.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** \file +NTP Client header file +*/ + +#ifndef NTPCLIENT_H_ +#define NTPCLIENT_H_ + +#include + +using std::uint8_t; +using std::uint16_t; +using std::uint32_t; + +#include "UDPSocket.h" + +#define NTP_DEFAULT_PORT 123 +#define NTP_DEFAULT_TIMEOUT 4000 + +///NTP client results +enum NTPResult +{ + NTP_DNS, /// THIS FILE +|- platformio.ini +|--src + |- main.c + +Then in `src/main.c` you should use: + +#include +#include + +// rest H/C/CPP code + +PlatformIO will find your libraries automatically, configure preprocessor's +include paths and build them. + +See additional options for PlatformIO Library Dependency Finder `lib_*`: + +http://docs.platformio.org/page/projectconf.html#lib-install + diff --git a/mbed/microbit-hello-world/platformio.ini b/mbed/mbed-rtos-ethernet/platformio.ini similarity index 59% rename from mbed/microbit-hello-world/platformio.ini rename to mbed/mbed-rtos-ethernet/platformio.ini index d7ee26f..89e5395 100644 --- a/mbed/microbit-hello-world/platformio.ini +++ b/mbed/mbed-rtos-ethernet/platformio.ini @@ -7,9 +7,15 @@ ; Please visit documentation for the other options and examples ; http://docs.platformio.org/page/projectconf.html -[env:bbcmicrobit] -platform = nordicnrf51 + +[env:nucleo_f767zi] +platform = ststm32 +framework = mbed +board = nucleo_f767zi +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT + +[env:frdm_k64f] +platform = freescalekinetis framework = mbed -board = bbcmicrobit -lib_deps = - microbit@~2.0.0-rc4 +board = frdm_k64f +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT \ No newline at end of file diff --git a/mbed/mbed-rtos-ethernet/src/main.cpp b/mbed/mbed-rtos-ethernet/src/main.cpp new file mode 100644 index 0000000..908f3f2 --- /dev/null +++ b/mbed/mbed-rtos-ethernet/src/main.cpp @@ -0,0 +1,38 @@ +#include "mbed.h" +#include "EthernetInterface.h" + +// Network interface +EthernetInterface net; + +void connect_http() { + // Show the network address + const char *ip = net.get_ip_address(); + printf("IP address is: %s\n", ip ? ip : "No IP"); + + // Open a socket on the network interface, and create a TCP connection to mbed.org + TCPSocket socket; + socket.open(&net); + socket.connect("developer.mbed.org", 80); + + // Send a simple http request + char sbuffer[] = "GET / HTTP/1.1\r\nHost: developer.mbed.org\r\n\r\n"; + int scount = socket.send(sbuffer, sizeof sbuffer); + printf("sent %d [%.*s]\n", scount, strstr(sbuffer, "\r\n")-sbuffer, sbuffer); + + // Recieve a simple http response and print out the response line + char rbuffer[64]; + int rcount = socket.recv(rbuffer, sizeof rbuffer); + printf("recv %d [%.*s]\n", rcount, strstr(rbuffer, "\r\n")-rbuffer, rbuffer); + + // Close the socket to return its memory and bring down the network interface + socket.close(); +} + + +int main() { + printf("Ethernet socket example\n"); + net.connect(); + Thread t1; + t1.start(callback(connect_http)); + Thread::wait(osWaitForever); +} \ No newline at end of file diff --git a/mbed/mbed-rtos/README.rst b/mbed/mbed-rtos/README.rst index 173d5e3..76622da 100644 --- a/mbed/mbed-rtos/README.rst +++ b/mbed/mbed-rtos/README.rst @@ -10,7 +10,7 @@ limitations under the License. How to build PlatformIO based project -==================================== +===================================== 1. `Install PlatformIO Core `_ 2. Download `examples source code `_ @@ -29,10 +29,10 @@ How to build PlatformIO based project > platformio run --target upload # Build specific environment - > platformio run -e lpc1768 + > platformio run -e nrf52_dk # Upload firmware for the specific environment - > platformio run -e lpc1768 --target upload + > platformio run -e nrf52_dk --target upload # Clean build files > platformio run --target clean diff --git a/mbed/mbed-rtos/platformio.ini b/mbed/mbed-rtos/platformio.ini index 27c51db..114b5fd 100644 --- a/mbed/mbed-rtos/platformio.ini +++ b/mbed/mbed-rtos/platformio.ini @@ -15,15 +15,47 @@ env_default = lpc1768 platform = nxplpc framework = mbed board = lpc1768 +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT # Freescale FRDM Platform -[env:frdm_kl25z] +[env:frdm_k64f] platform = freescalekinetis framework = mbed -board = frdm_kl25z +board = frdm_k64f +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT + +# Maxim32 Platform +[env:maxwsnenv] +platform = maxim32 +framework = mbed +board = maxwsnenv +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT # ST STM32 Platform -[env:nucleo_f401re] +[env:mote_l152rc] platform = ststm32 framework = mbed -board = nucleo_f401re +board = mote_l152rc +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT + +# Teensy Platform +[env:teensy31] +platform = teensy +framework = mbed +board = teensy31 +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT + +# Silicon Labs EFM32 Platform +[env:efm32wg_stk3800] +platform = siliconlabsefm32 +framework = mbed +board = efm32wg_stk3800 +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT + +# WIZNet7500 Platform +[env:wizwiki_w7500eco] +platform = wiznet7500 +framework = mbed +board = wizwiki_w7500eco +build_flags = -DPIO_FRAMEWORK_MBED_RTOS_PRESENT + diff --git a/mbed/mbed-rtos/src/main.cpp b/mbed/mbed-rtos/src/main.cpp index a1aa46d..6cd1cf8 100644 --- a/mbed/mbed-rtos/src/main.cpp +++ b/mbed/mbed-rtos/src/main.cpp @@ -1,38 +1,34 @@ #include "mbed.h" #include "rtos.h" - -/* - * The stack size is defined in cmsis_os.h mainly dependent on the underlying toolchain and - * the C standard library. For GCC, ARM_STD and IAR it is defined with a size of 2048 bytes - * and for ARM_MICRO 512. Because of reduce RAM size some targets need a reduced stacksize. - */ -#if defined(TARGET_STM32L053R8) || defined(TARGET_STM32L053C8) -#define STACK_SIZE DEFAULT_STACK_SIZE/4 -#else -#define STACK_SIZE DEFAULT_STACK_SIZE -#endif - -void print_char(char c = '*') { - printf("%c", c); - fflush(stdout); + +Queue queue; + +DigitalOut myled(LED1); + +void queue_isr() { + queue.put((uint32_t*)2); + myled = !myled; } - -DigitalOut led1(LED1); -DigitalOut led2(LED2); - -void led2_thread(void const *argument) { + +void queue_thread(void const *args) { while (true) { - led2 = !led2; + queue.put((uint32_t*)1); Thread::wait(1000); - print_char(); } } - -int main() { - Thread thread(led2_thread, NULL, osPriorityNormal, STACK_SIZE); - + +int main (void) { + Thread thread(queue_thread); + + Ticker ticker; + ticker.attach(queue_isr, 1.0); + while (true) { - led1 = !led1; - Thread::wait(500); + osEvent evt = queue.get(); + if (evt.status != osEventMessage) { + printf("queue->get() returned %02x status\n\r", evt.status); + } else { + printf("queue->get() returned %d\n\r", evt.value.v); + } } -} +} \ No newline at end of file diff --git a/mbed/microbit-hello-world/.gitignore b/mbed/microbit-hello-world/.gitignore deleted file mode 100644 index 6c69f4c..0000000 --- a/mbed/microbit-hello-world/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.pioenvs -.piolibdeps diff --git a/mbed/microbit-hello-world/src/main.cpp b/mbed/microbit-hello-world/src/main.cpp deleted file mode 100755 index 88084bf..0000000 --- a/mbed/microbit-hello-world/src/main.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#define MICROBIT_DBG 1 -#include - -MicroBit uBit; - -int main() { - // Initialise the micro:bit runtime. - uBit.init(); - - // Insert your code here! - uBit.display.scroll("HELLO WORLD! :)"); - - // If main exits, there may still be other fibers running or registered event handlers etc. - // Simply release this fiber, which will mean we enter the scheduler. Worse case, we then - // sit in the idle task forever, in a power efficient sleep. - release_fiber(); - return 0; -} From 2170f4afe5f457e782477ffac32b55bb6ea2adf3 Mon Sep 17 00:00:00 2001 From: Ivan Kravets Date: Tue, 18 Jul 2017 22:28:05 +0300 Subject: [PATCH 3/3] Ignore temporary PIO directories --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 5d8988b..6c69f4c 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -atmelavr-and-arduino/engduino-magnetometer/.piolibdeps +.pioenvs +.piolibdeps