├── .mbed ├── mbed-os.lib ├── COMPONENT_ism43362.lib ├── resources └── official_armmbed_example_badge.png ├── tests ├── sockets.log └── README.md ├── .gitignore ├── CONTRIBUTING.md ├── .github ├── workflows │ └── build_example.yml └── ISSUE_TEMPLATE │ └── bug_report.md ├── include ├── wifi_helper.h └── root_ca_cert.h ├── mbed_app.json ├── CMakeLists.txt ├── README.md ├── source └── main.cpp └── LICENSE /.mbed: -------------------------------------------------------------------------------- 1 | ROOT=. 2 | -------------------------------------------------------------------------------- /mbed-os.lib: -------------------------------------------------------------------------------- 1 | https://github.com/ARMmbed/mbed-os/ 2 | -------------------------------------------------------------------------------- /COMPONENT_ism43362.lib: -------------------------------------------------------------------------------- 1 | https://github.com/ARMmbed/wifi-ism43362/ 2 | -------------------------------------------------------------------------------- /resources/official_armmbed_example_badge.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ARMmbed/mbed-os-example-sockets/HEAD/resources/official_armmbed_example_badge.png -------------------------------------------------------------------------------- /tests/sockets.log: -------------------------------------------------------------------------------- 1 | Starting socket demo 2 | Connecting to the network... 3 | IP address: (?:[0-9]{1,3}\.){3}[0-9]{1,3} 4 | Netmask: (?:[0-9]{1,3}\.){3}[0-9]{1,3} 5 | Gateway: (?:[0-9]{1,3}\.){3}[0-9]{1,3} 6 | Demo concluded successfully 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | 3 | # clion 4 | .idea/ 5 | cmake-build-*/ 6 | 7 | # exporters 8 | GettingStarted.html 9 | eclipse-extras/ 10 | 11 | # mbed build system 12 | mbed-os/ 13 | mbed_settings.py 14 | mbed_config.h 15 | *.pyc 16 | BUILD/ 17 | cmake-build-debug/ 18 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Mbed OS 2 | 3 | Mbed OS is an open-source, device software platform for the Internet of Things. Contributions are an important part of the platform, and our goal is to make it as simple as possible to become a contributor. 4 | 5 | To encourage productive collaboration, as well as robust, consistent and maintainable code, we have a set of guidelines for [contributing to Mbed OS](https://os.mbed.com/docs/mbed-os/latest/contributing/index.html). 6 | -------------------------------------------------------------------------------- /tests/README.md: -------------------------------------------------------------------------------- 1 | # Testing examples 2 | 3 | Examples are tested using tool [htrun](https://github.com/ARMmbed/mbed-os-tools/tree/master/packages/mbed-host-tests) and templated print log. 4 | 5 | To run the test, use following command after you build the example: 6 | ``` 7 | mbedhtrun -d D: -p COM4 -m K64F -f .\BUILD\K64F\GCC_ARM\sockets.bin --compare-log tests\sockets.log 8 | ``` 9 | 10 | 11 | More details about `htrun` are [here](https://github.com/ARMmbed/htrun#testing-mbed-os-examples). 12 | 13 | -------------------------------------------------------------------------------- /.github/workflows/build_example.yml: -------------------------------------------------------------------------------- 1 | name: Build example 2 | on: 3 | workflow_dispatch: 4 | schedule: 5 | - cron: '0 1 * * 6' 6 | pull_request: 7 | jobs: 8 | run-conditional-feature-compilation-test: 9 | name: Build example 10 | runs-on: ubuntu-latest 11 | container: mbedos/mbed-os-env:latest 12 | strategy: 13 | matrix: 14 | MBED_TARGET: ["K64F", "DISCO_F413ZH", "DISCO_L475VG_IOT01A"] 15 | steps: 16 | - name: Checkout 17 | uses: actions/checkout@v2 18 | 19 | - name: Deploy 20 | run: | 21 | mbed deploy 22 | 23 | - name: Build mbed-cli v1 24 | run: | 25 | mbed compile -t GCC_ARM -m ${{ matrix.MBED_TARGET }} || exit 1 26 | 27 | - name: Build cmake 28 | run: | 29 | python3 -m pip install mbed-tools --upgrade # remove after docker image is updated to contain new tools 30 | mbed-tools compile -t GCC_ARM -m ${{ matrix.MBED_TARGET }} || exit 1 31 | -------------------------------------------------------------------------------- /include/wifi_helper.h: -------------------------------------------------------------------------------- 1 | /* Sockets Example 2 | * Copyright (c) 2020 ARM Limited 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "mbed.h" 18 | 19 | static const char *get_security_string(nsapi_security_t sec) 20 | { 21 | switch (sec) { 22 | case NSAPI_SECURITY_NONE: 23 | return "None"; 24 | case NSAPI_SECURITY_WEP: 25 | return "WEP"; 26 | case NSAPI_SECURITY_WPA: 27 | return "WPA"; 28 | case NSAPI_SECURITY_WPA2: 29 | return "WPA2"; 30 | case NSAPI_SECURITY_WPA_WPA2: 31 | return "WPA/WPA2"; 32 | case NSAPI_SECURITY_UNKNOWN: 33 | default: 34 | return "Unknown"; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /mbed_app.json: -------------------------------------------------------------------------------- 1 | { 2 | "config": { 3 | "hostname": { 4 | "help": "The demo will try to connect to this web address on port 80 (or port 443 when using tls).", 5 | "value": "\"ifconfig.io\"" 6 | }, 7 | "use-tls-socket": { 8 | "value": false 9 | } 10 | }, 11 | "target_overrides": { 12 | "*": { 13 | "nsapi.default-wifi-security": "WPA_WPA2", 14 | "nsapi.default-wifi-ssid": "\"YOUR_SSID\"", 15 | "nsapi.default-wifi-password": "\"YOUR_PASSWORD\"", 16 | "platform.stdio-baud-rate": 9600, 17 | "mbed-trace.enable": false, 18 | "mbed-trace.max-level": "TRACE_LEVEL_DEBUG", 19 | "rtos.main-thread-stack-size": 8192 20 | }, 21 | "DISCO_F413ZH": { 22 | "target.components_add": ["ism43362"], 23 | "target.macros_add" : ["MBEDTLS_SHA1_C"] 24 | }, 25 | "DISCO_L475VG_IOT01A": { 26 | "target.components_add": ["ism43362"], 27 | "ism43362.provide-default": true, 28 | "target.network-default-interface-type": "WIFI", 29 | "target.macros_add" : ["MBEDTLS_SHA1_C"] 30 | }, 31 | "K64F": { 32 | "target.macros_add" : ["MBEDTLS_SHA1_C"] 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2020 ARM Limited. All rights reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | cmake_minimum_required(VERSION 3.19.0 FATAL_ERROR) 5 | 6 | set(MBED_PATH ${CMAKE_CURRENT_SOURCE_DIR}/mbed-os CACHE INTERNAL "") 7 | set(MBED_CONFIG_PATH ${CMAKE_CURRENT_BINARY_DIR} CACHE INTERNAL "") 8 | set(APP_TARGET mbed-os-example-sockets) 9 | 10 | include(${MBED_PATH}/tools/cmake/app.cmake) 11 | 12 | project(${APP_TARGET}) 13 | 14 | add_subdirectory(${MBED_PATH}) 15 | 16 | add_executable(${APP_TARGET}) 17 | 18 | mbed_configure_app_target(${APP_TARGET}) 19 | 20 | target_include_directories(${APP_TARGET} 21 | PUBLIC 22 | ${CMAKE_CURRENT_SOURCE_DIR}/include 23 | ) 24 | 25 | target_sources(${APP_TARGET} 26 | PRIVATE 27 | source/main.cpp 28 | ) 29 | 30 | target_link_libraries(${APP_TARGET} 31 | PRIVATE 32 | mbed-os 33 | mbed-netsocket 34 | mbed-mbedtls 35 | ) 36 | 37 | if("ism43362" IN_LIST MBED_TARGET_LABELS) 38 | add_subdirectory(COMPONENT_ism43362) 39 | target_link_libraries(${APP_TARGET} 40 | PRIVATE 41 | wifi-ism43362 42 | ) 43 | endif() 44 | 45 | mbed_set_post_build(${APP_TARGET}) 46 | 47 | option(VERBOSE_BUILD "Have a verbose build process") 48 | if(VERBOSE_BUILD) 49 | set(CMAKE_VERBOSE_MAKEFILE ON) 50 | endif() 51 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: 'type: bug' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 28 | 29 | ### Description of defect 30 | 31 | 35 | 36 | 37 | #### Target(s) affected by this defect ? 38 | 39 | 40 | #### Toolchain(s) (name and version) displaying this defect ? 41 | 42 | 43 | #### What version of Mbed-os are you using (tag or sha) ? 44 | 53 | 54 | 55 | #### What version(s) of tools are you using. List all that apply (E.g. mbed-cli) 56 | 57 | 58 | #### How is this defect reproduced ? 59 | -------------------------------------------------------------------------------- /include/root_ca_cert.h: -------------------------------------------------------------------------------- 1 | /* Sockets Example 2 | * Copyright (c) 2020 ARM Limited 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | static const char root_ca_cert[] = \ 18 | "-----BEGIN CERTIFICATE-----\n" 19 | "MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJ\n" 20 | "RTESMBAGA1UEChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYD\n" 21 | "VQQDExlCYWx0aW1vcmUgQ3liZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoX\n" 22 | "DTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMCSUUxEjAQBgNVBAoTCUJhbHRpbW9y\n" 23 | "ZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFsdGltb3JlIEN5YmVy\n" 24 | "VHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKMEuyKr\n" 25 | "mD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjr\n" 26 | "IZ3AQSsBUnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeK\n" 27 | "mpYcqWe4PwzV9/lSEy/CG9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSu\n" 28 | "XmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9XbIGevOF6uvUA65ehD5f/xXtabz5OTZy\n" 29 | "dc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjprl3RjM71oGDHweI12v/ye\n" 30 | "jl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoIVDaGezq1\n" 31 | "BE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3\n" 32 | "DQEBBQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT92\n" 33 | "9hkTI7gQCvlYpNRhcL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3Wgx\n" 34 | "jkzSswF07r51XgdIGn9w/xZchMB5hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0\n" 35 | "Epn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsaY71k5h+3zvDyny67G7fyUIhz\n" 36 | "ksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9HRCwBXbsdtTLS\n" 37 | "R9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp\n" 38 | "-----END CERTIFICATE-----"; 39 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![](./resources/official_armmbed_example_badge.png) 2 | # Socket Example 3 | 4 | This example shows usage of [network-socket API](https://os.mbed.com/docs/mbed-os/latest/apis/network-socket.html). 5 | 6 | The program brings up an underlying network interface and if it's Wifi also scans for access points. 7 | It creates a TCPSocket and performs an HTTP transaction targeting the website in the `mbed_app.json` config. 8 | 9 | The example can be configured to use a TLSSocket. This works only on devices that support TRNG. 10 | 11 | ## Selecting the network interface 12 | 13 | This application is able to use any network interface it finds. 14 | 15 | The interface selections is done through weak functions that are overridden by your selected target or any additional 16 | component that provides a network interface. 17 | 18 | If more than one interface is provided the target configuration `target.network-default-interface-type` 19 | selects the type provided as the default one. This is usually the Ethernet so building on Ethernet enabled boards, 20 | you do not need any further configuration. 21 | 22 | ### Configuring mbedtls 23 | 24 | By default the examples uses a TCP socket. To enable TLS edit the mbed_app.json to turn on the `use-tls-socket` option: 25 | 26 | ``` 27 | "use-tls-socket": { 28 | "value": true 29 | } 30 | ``` 31 | 32 | It might be necessary to configure the mbedtls library with appropriate macros in mbed_app.json file. Some boards 33 | (like UBLOX_EVK_ODIN_W2) will work fine without any additional configuration and some of them might require some minimal 34 | adjustment. For example K64F requires at least the following macro added: 35 | 36 | 37 | ``` 38 | "K64F": { 39 | "target.macros_add" : ["MBEDTLS_SHA1_C"] 40 | } 41 | ``` 42 | 43 | See 44 | [mbedtls configuration guidelines](https://github.com/ARMmbed/mbed-os/tree/master/connectivity/mbedtls#configuring-mbed-tls-features) 45 | for more details. 46 | 47 | Also see the API Documentation [TLSSocket](https://os.mbed.com/docs/mbed-os/latest/apis/tlssocket.html). 48 | 49 | ### WiFi 50 | 51 | If you want to use WiFi you need to provide SSID, password and security settings in `mbed_app.json`. 52 | 53 | If your board doesn't provide WiFi as the default interface because it has multiple interfaces you need to specify that 54 | you want WiFi in `mbed_app.json`. 55 | 56 | ``` 57 | { 58 | "target_overrides": { 59 | "*": { 60 | "target.network-default-interface-type": "WIFI", 61 | } 62 | } 63 | } 64 | ``` 65 | 66 | For more information about Wi-Fi APIs, please visit the 67 | [Mbed OS Wi-Fi](https://os.mbed.com/docs/mbed-os/latest/apis/wi-fi.html) 68 | documentation. 69 | 70 | ### Supported WiFi hardware 71 | 72 | * All Mbed OS boards with build-in Wi-Fi module such as: 73 | * [ST DISCO IOT board](https://os.mbed.com/platforms/ST-Discovery-L475E-IOT01A/) with integrated 74 | [ISM43362 WiFi Inventek module](https://github.com/ARMmbed/wifi-ism43362). 75 | * [ST DISCO_F413ZH board](https://os.mbed.com/platforms/ST-Discovery-F413H/) with integrated 76 | [ISM43362 WiFi Inventek module](https://github.com/ARMmbed/wifi-ism43362). 77 | * Boards with external WiFi shields such as: 78 | * [NUCLEO-F429ZI](https://os.mbed.com/platforms/ST-Nucleo-F429ZI/) with ESP8266-01 79 | 80 | ## Building and flashing the example 81 | 82 | ### Mbed OS build tools 83 | 84 | #### Mbed CLI 2 85 | 86 | Starting with version 6.5, Mbed OS uses Mbed CLI 2. It uses Ninja as a build system, and CMake to generate the build environment and manage the build process in a compiler-independent manner. If you are working with Mbed OS version prior to 6.5 then check the section [Mbed CLI 1](#mbed-cli-1). 87 | 1. [Install Mbed CLI 2](https://os.mbed.com/docs/mbed-os/latest/build-tools/install-or-upgrade.html). 88 | 1. From the command-line, import the example: `mbed-tools import mbed-os-example-sockets` 89 | 1. Change the current directory to where the project was imported. 90 | 91 | #### Mbed CLI 1 92 | 1. [Install Mbed CLI 1](https://os.mbed.com/docs/mbed-os/latest/quick-start/offline-with-mbed-cli.html). 93 | 1. From the command-line, import the example: `mbed import mbed-os-example-sockets` 94 | 1. Change the current directory to where the project was imported. 95 | 96 | ### To build the example 97 | 98 | 1. Connect a USB cable between the USB port on the board and the host computer. 99 | 1. Run the following command to build the example project and program the microcontroller flash memory: 100 | 101 | * Mbed CLI 2 102 | 103 | ```bash 104 | $ mbed-tools compile -m -t --flash --sterm 105 | ``` 106 | 107 | * Mbed CLI 1 108 | 109 | ```bash 110 | $ mbed compile -m -t --flash --sterm 111 | ``` 112 | 113 | Your PC may take a few minutes to compile your code. 114 | 115 | The binary is located at: 116 | * **Mbed CLI 2** - `./cmake_build////mbed-os-example-sockets.bin`
117 | * **Mbed CLI 1** - `./BUILD///mbed-os-example-sockets.bin` 118 | 119 | Alternatively, you can manually copy the binary to the board, which you mount on the host computer over USB. 120 | 121 | You can also open a serial terminal separately, rather than using the `--sterm` option, with the following command: 122 | 123 | * Mbed CLI 2 124 | 125 | ```bash 126 | $ mbed-tools sterm 127 | ``` 128 | 129 | * Mbed CLI 1 130 | 131 | ```bash 132 | $ mbed sterm 133 | ``` 134 | 135 | ### Expected output 136 | 137 | (Assuming you are using a wifi interface, otherwise the scanning will be skipped) 138 | 139 | ``` 140 | Starting socket demo 141 | 142 | 2 networks available: 143 | Network: Virgin Media secured: Unknown BSSID: 2A:35:D1:ba:c7:41 RSSI: -79 Ch: 6 144 | Network: VM4392164 secured: WPA2 BSSID: 18:35:D1:ba:c7:41 RSSI: -79 Ch: 6 145 | 146 | Connecting to the network... 147 | IP address: 192.168.0.27 148 | Netmask: 255.255.255.0 149 | Gateway: 192.168.0.1 150 | 151 | Resolve hostname ifconfig.io 152 | ifconfig.io address is 104.24.122.146 153 | 154 | sent 52 bytes: 155 | GET / HTTP/1.1 156 | Host: ifconfig.io 157 | Connection: close 158 | 159 | received 256 bytes: 160 | HTTP/1.1 200 OK 161 | 162 | Demo concluded successfully 163 | ``` 164 | 165 | ## License and contributions 166 | 167 | The software is provided under Apache-2.0 license. Contributions to this project are accepted under the same license. 168 | Please see [contributing.md](CONTRIBUTING.md) for more info. 169 | 170 | This project contains code from other projects. The original license text is included in those source files. 171 | They must comply with our license guide 172 | -------------------------------------------------------------------------------- /source/main.cpp: -------------------------------------------------------------------------------- 1 | /* Sockets Example 2 | * Copyright (c) 2016-2020 ARM Limited 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "mbed.h" 18 | #include "wifi_helper.h" 19 | #include "mbed-trace/mbed_trace.h" 20 | 21 | #if MBED_CONF_APP_USE_TLS_SOCKET 22 | #include "root_ca_cert.h" 23 | 24 | #ifndef DEVICE_TRNG 25 | #error "mbed-os-example-tls-socket requires a device which supports TRNG" 26 | #endif 27 | #endif // MBED_CONF_APP_USE_TLS_SOCKET 28 | 29 | class SocketDemo { 30 | static constexpr size_t MAX_NUMBER_OF_ACCESS_POINTS = 10; 31 | static constexpr size_t MAX_MESSAGE_RECEIVED_LENGTH = 100; 32 | 33 | #if MBED_CONF_APP_USE_TLS_SOCKET 34 | static constexpr size_t REMOTE_PORT = 443; // tls port 35 | #else 36 | static constexpr size_t REMOTE_PORT = 80; // standard HTTP port 37 | #endif // MBED_CONF_APP_USE_TLS_SOCKET 38 | 39 | public: 40 | SocketDemo() : _net(NetworkInterface::get_default_instance()) 41 | { 42 | } 43 | 44 | ~SocketDemo() 45 | { 46 | if (_net) { 47 | _net->disconnect(); 48 | } 49 | } 50 | 51 | void run() 52 | { 53 | if (!_net) { 54 | printf("Error! No network interface found.\r\n"); 55 | return; 56 | } 57 | 58 | /* if we're using a wifi interface run a quick scan */ 59 | if (_net->wifiInterface()) { 60 | /* the scan is not required to connect and only serves to show visible access points */ 61 | wifi_scan(); 62 | 63 | /* in this example we use credentials configured at compile time which are used by 64 | * NetworkInterface::connect() but it's possible to do this at runtime by using the 65 | * WiFiInterface::connect() which takes these parameters as arguments */ 66 | } 67 | 68 | /* connect will perform the action appropriate to the interface type to connect to the network */ 69 | 70 | printf("Connecting to the network...\r\n"); 71 | 72 | nsapi_size_or_error_t result = _net->connect(); 73 | if (result != 0) { 74 | printf("Error! _net->connect() returned: %d\r\n", result); 75 | return; 76 | } 77 | 78 | print_network_info(); 79 | 80 | /* opening the socket only allocates resources */ 81 | result = _socket.open(_net); 82 | if (result != 0) { 83 | printf("Error! _socket.open() returned: %d\r\n", result); 84 | return; 85 | } 86 | 87 | #if MBED_CONF_APP_USE_TLS_SOCKET 88 | result = _socket.set_root_ca_cert(root_ca_cert); 89 | if (result != NSAPI_ERROR_OK) { 90 | printf("Error: _socket.set_root_ca_cert() returned %d\n", result); 91 | return; 92 | } 93 | _socket.set_hostname(MBED_CONF_APP_HOSTNAME); 94 | #endif // MBED_CONF_APP_USE_TLS_SOCKET 95 | 96 | /* now we have to find where to connect */ 97 | 98 | SocketAddress address; 99 | 100 | if (!resolve_hostname(address)) { 101 | return; 102 | } 103 | 104 | address.set_port(REMOTE_PORT); 105 | 106 | /* we are connected to the network but since we're using a connection oriented 107 | * protocol we still need to open a connection on the socket */ 108 | 109 | printf("Opening connection to remote port %d\r\n", REMOTE_PORT); 110 | 111 | result = _socket.connect(address); 112 | if (result != 0) { 113 | printf("Error! _socket.connect() returned: %d\r\n", result); 114 | return; 115 | } 116 | 117 | /* exchange an HTTP request and response */ 118 | 119 | if (!send_http_request()) { 120 | return; 121 | } 122 | 123 | if (!receive_http_response()) { 124 | return; 125 | } 126 | 127 | printf("Demo concluded successfully \r\n"); 128 | } 129 | 130 | private: 131 | bool resolve_hostname(SocketAddress &address) 132 | { 133 | const char hostname[] = MBED_CONF_APP_HOSTNAME; 134 | 135 | /* get the host address */ 136 | printf("\nResolve hostname %s\r\n", hostname); 137 | nsapi_size_or_error_t result = _net->gethostbyname(hostname, &address); 138 | if (result != 0) { 139 | printf("Error! gethostbyname(%s) returned: %d\r\n", hostname, result); 140 | return false; 141 | } 142 | 143 | printf("%s address is %s\r\n", hostname, (address.get_ip_address() ? address.get_ip_address() : "None") ); 144 | 145 | return true; 146 | } 147 | 148 | bool send_http_request() 149 | { 150 | /* loop until whole request sent */ 151 | const char buffer[] = "GET / HTTP/1.1\r\n" 152 | "Host: ifconfig.io\r\n" 153 | "Connection: close\r\n" 154 | "\r\n"; 155 | 156 | nsapi_size_t bytes_to_send = strlen(buffer); 157 | nsapi_size_or_error_t bytes_sent = 0; 158 | 159 | printf("\r\nSending message: \r\n%s", buffer); 160 | 161 | while (bytes_to_send) { 162 | bytes_sent = _socket.send(buffer + bytes_sent, bytes_to_send); 163 | if (bytes_sent < 0) { 164 | printf("Error! _socket.send() returned: %d\r\n", bytes_sent); 165 | return false; 166 | } else { 167 | printf("sent %d bytes\r\n", bytes_sent); 168 | } 169 | 170 | bytes_to_send -= bytes_sent; 171 | } 172 | 173 | printf("Complete message sent\r\n"); 174 | 175 | return true; 176 | } 177 | 178 | bool receive_http_response() 179 | { 180 | char buffer[MAX_MESSAGE_RECEIVED_LENGTH]; 181 | int remaining_bytes = MAX_MESSAGE_RECEIVED_LENGTH; 182 | int received_bytes = 0; 183 | 184 | /* loop until there is nothing received or we've ran out of buffer space */ 185 | nsapi_size_or_error_t result = remaining_bytes; 186 | while (result > 0 && remaining_bytes > 0) { 187 | result = _socket.recv(buffer + received_bytes, remaining_bytes); 188 | if (result < 0) { 189 | printf("Error! _socket.recv() returned: %d\r\n", result); 190 | return false; 191 | } 192 | 193 | received_bytes += result; 194 | remaining_bytes -= result; 195 | } 196 | 197 | /* the message is likely larger but we only want the HTTP response code */ 198 | 199 | printf("received %d bytes:\r\n%.*s\r\n\r\n", received_bytes, strstr(buffer, "\n") - buffer, buffer); 200 | 201 | return true; 202 | } 203 | 204 | void wifi_scan() 205 | { 206 | WiFiInterface *wifi = _net->wifiInterface(); 207 | 208 | WiFiAccessPoint ap[MAX_NUMBER_OF_ACCESS_POINTS]; 209 | 210 | /* scan call returns number of access points found */ 211 | int result = wifi->scan(ap, MAX_NUMBER_OF_ACCESS_POINTS); 212 | 213 | if (result <= 0) { 214 | printf("WiFiInterface::scan() failed with return value: %d\r\n", result); 215 | return; 216 | } 217 | 218 | printf("%d networks available:\r\n", result); 219 | 220 | for (int i = 0; i < result; i++) { 221 | printf("Network: %s secured: %s BSSID: %hhX:%hhX:%hhX:%hhx:%hhx:%hhx RSSI: %hhd Ch: %hhd\r\n", 222 | ap[i].get_ssid(), get_security_string(ap[i].get_security()), 223 | ap[i].get_bssid()[0], ap[i].get_bssid()[1], ap[i].get_bssid()[2], 224 | ap[i].get_bssid()[3], ap[i].get_bssid()[4], ap[i].get_bssid()[5], 225 | ap[i].get_rssi(), ap[i].get_channel()); 226 | } 227 | printf("\r\n"); 228 | } 229 | 230 | void print_network_info() 231 | { 232 | /* print the network info */ 233 | SocketAddress a; 234 | _net->get_ip_address(&a); 235 | printf("IP address: %s\r\n", a.get_ip_address() ? a.get_ip_address() : "None"); 236 | _net->get_netmask(&a); 237 | printf("Netmask: %s\r\n", a.get_ip_address() ? a.get_ip_address() : "None"); 238 | _net->get_gateway(&a); 239 | printf("Gateway: %s\r\n", a.get_ip_address() ? a.get_ip_address() : "None"); 240 | } 241 | 242 | private: 243 | NetworkInterface *_net; 244 | 245 | #if MBED_CONF_APP_USE_TLS_SOCKET 246 | TLSSocket _socket; 247 | #else 248 | TCPSocket _socket; 249 | #endif // MBED_CONF_APP_USE_TLS_SOCKET 250 | }; 251 | 252 | int main() { 253 | printf("\r\nStarting socket demo\r\n\r\n"); 254 | 255 | #ifdef MBED_CONF_MBED_TRACE_ENABLE 256 | mbed_trace_init(); 257 | #endif 258 | 259 | SocketDemo *example = new SocketDemo(); 260 | MBED_ASSERT(example); 261 | example->run(); 262 | 263 | return 0; 264 | } 265 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and 10 | distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright 13 | owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities 16 | that control, are controlled by, or are under common control with that entity. 17 | For the purposes of this definition, "control" means (i) the power, direct or 18 | indirect, to cause the direction or management of such entity, whether by 19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the 20 | outstanding shares, or (iii) beneficial ownership of such entity. 21 | 22 | "You" (or "Your") shall mean an individual or Legal Entity exercising 23 | permissions granted by this License. 24 | 25 | "Source" form shall mean the preferred form for making modifications, including 26 | but not limited to software source code, documentation source, and configuration 27 | files. 28 | 29 | "Object" form shall mean any form resulting from mechanical transformation or 30 | translation of a Source form, including but not limited to compiled object code, 31 | generated documentation, and conversions to other media types. 32 | 33 | "Work" shall mean the work of authorship, whether in Source or Object form, made 34 | available under the License, as indicated by a copyright notice that is included 35 | in or attached to the work (an example is provided in the Appendix below). 36 | 37 | "Derivative Works" shall mean any work, whether in Source or Object form, that 38 | is based on (or derived from) the Work and for which the editorial revisions, 39 | annotations, elaborations, or other modifications represent, as a whole, an 40 | original work of authorship. For the purposes of this License, Derivative Works 41 | shall not include works that remain separable from, or merely link (or bind by 42 | name) to the interfaces of, the Work and Derivative Works thereof. 43 | 44 | "Contribution" shall mean any work of authorship, including the original version 45 | of the Work and any modifications or additions to that Work or Derivative Works 46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work 47 | by the copyright owner or by an individual or Legal Entity authorized to submit 48 | on behalf of the copyright owner. For the purposes of this definition, 49 | "submitted" means any form of electronic, verbal, or written communication sent 50 | to the Licensor or its representatives, including but not limited to 51 | communication on electronic mailing lists, source code control systems, and 52 | issue tracking systems that are managed by, or on behalf of, the Licensor for 53 | the purpose of discussing and improving the Work, but excluding communication 54 | that is conspicuously marked or otherwise designated in writing by the copyright 55 | owner as "Not a Contribution." 56 | 57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf 58 | of whom a Contribution has been received by Licensor and subsequently 59 | incorporated within the Work. 60 | 61 | 2. Grant of Copyright License. 62 | 63 | Subject to the terms and conditions of this License, each Contributor hereby 64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 65 | irrevocable copyright license to reproduce, prepare Derivative Works of, 66 | publicly display, publicly perform, sublicense, and distribute the Work and such 67 | Derivative Works in Source or Object form. 68 | 69 | 3. Grant of Patent License. 70 | 71 | Subject to the terms and conditions of this License, each Contributor hereby 72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 73 | irrevocable (except as stated in this section) patent license to make, have 74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where 75 | such license applies only to those patent claims licensable by such Contributor 76 | that are necessarily infringed by their Contribution(s) alone or by combination 77 | of their Contribution(s) with the Work to which such Contribution(s) was 78 | submitted. If You institute patent litigation against any entity (including a 79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a 80 | Contribution incorporated within the Work constitutes direct or contributory 81 | patent infringement, then any patent licenses granted to You under this License 82 | for that Work shall terminate as of the date such litigation is filed. 83 | 84 | 4. Redistribution. 85 | 86 | You may reproduce and distribute copies of the Work or Derivative Works thereof 87 | in any medium, with or without modifications, and in Source or Object form, 88 | provided that You meet the following conditions: 89 | 90 | You must give any other recipients of the Work or Derivative Works a copy of 91 | this License; and 92 | You must cause any modified files to carry prominent notices stating that You 93 | changed the files; and 94 | You must retain, in the Source form of any Derivative Works that You distribute, 95 | all copyright, patent, trademark, and attribution notices from the Source form 96 | of the Work, excluding those notices that do not pertain to any part of the 97 | Derivative Works; and 98 | If the Work includes a "NOTICE" text file as part of its distribution, then any 99 | Derivative Works that You distribute must include a readable copy of the 100 | attribution notices contained within such NOTICE file, excluding those notices 101 | that do not pertain to any part of the Derivative Works, in at least one of the 102 | following places: within a NOTICE text file distributed as part of the 103 | Derivative Works; within the Source form or documentation, if provided along 104 | with the Derivative Works; or, within a display generated by the Derivative 105 | Works, if and wherever such third-party notices normally appear. The contents of 106 | the NOTICE file are for informational purposes only and do not modify the 107 | License. You may add Your own attribution notices within Derivative Works that 108 | You distribute, alongside or as an addendum to the NOTICE text from the Work, 109 | provided that such additional attribution notices cannot be construed as 110 | modifying the License. 111 | You may add Your own copyright statement to Your modifications and may provide 112 | additional or different license terms and conditions for use, reproduction, or 113 | distribution of Your modifications, or for any such Derivative Works as a whole, 114 | provided Your use, reproduction, and distribution of the Work otherwise complies 115 | with the conditions stated in this License. 116 | 117 | 5. Submission of Contributions. 118 | 119 | Unless You explicitly state otherwise, any Contribution intentionally submitted 120 | for inclusion in the Work by You to the Licensor shall be under the terms and 121 | conditions of this License, without any additional terms or conditions. 122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of 123 | any separate license agreement you may have executed with Licensor regarding 124 | such Contributions. 125 | 126 | 6. Trademarks. 127 | 128 | This License does not grant permission to use the trade names, trademarks, 129 | service marks, or product names of the Licensor, except as required for 130 | reasonable and customary use in describing the origin of the Work and 131 | reproducing the content of the NOTICE file. 132 | 133 | 7. Disclaimer of Warranty. 134 | 135 | Unless required by applicable law or agreed to in writing, Licensor provides the 136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, 137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, 138 | including, without limitation, any warranties or conditions of TITLE, 139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are 140 | solely responsible for determining the appropriateness of using or 141 | redistributing the Work and assume any risks associated with Your exercise of 142 | permissions under this License. 143 | 144 | 8. Limitation of Liability. 145 | 146 | In no event and under no legal theory, whether in tort (including negligence), 147 | contract, or otherwise, unless required by applicable law (such as deliberate 148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be 149 | liable to You for damages, including any direct, indirect, special, incidental, 150 | or consequential damages of any character arising as a result of this License or 151 | out of the use or inability to use the Work (including but not limited to 152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or 153 | any and all other commercial damages or losses), even if such Contributor has 154 | been advised of the possibility of such damages. 155 | 156 | 9. Accepting Warranty or Additional Liability. 157 | 158 | While redistributing the Work or Derivative Works thereof, You may choose to 159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or 160 | other liability obligations and/or rights consistent with this License. However, 161 | in accepting such obligations, You may act only on Your own behalf and on Your 162 | sole responsibility, not on behalf of any other Contributor, and only if You 163 | agree to indemnify, defend, and hold each Contributor harmless for any liability 164 | incurred by, or claims asserted against, such Contributor by reason of your 165 | accepting any such warranty or additional liability. 166 | --------------------------------------------------------------------------------