From 69d98d4a5359ee94c77fd03b55336c7e3ba5c808 Mon Sep 17 00:00:00 2001 From: Jonathan Hui Date: Tue, 6 Feb 2018 14:14:57 -0800 Subject: [PATCH] [code-style] apply clang-format --- examples/apps/cli/main.c | 12 +- examples/apps/ncp/main.c | 19 +- examples/platforms/cc2538/alarm.c | 21 +- examples/platforms/cc2538/flash.c | 29 +- examples/platforms/cc2538/logging.c | 13 +- examples/platforms/cc2538/platform-cc2538.h | 4 +- examples/platforms/cc2538/platform.c | 2 +- examples/platforms/cc2538/radio.c | 175 ++-- examples/platforms/cc2538/random.c | 10 +- examples/platforms/cc2538/rom-utility.h | 42 +- examples/platforms/cc2538/startup-gcc.c | 176 ++-- examples/platforms/cc2538/uart.c | 35 +- examples/platforms/cc2650/alarm.c | 5 +- examples/platforms/cc2650/cc2650_startup.c | 1 - examples/platforms/cc2650/crypto/aes_alt.c | 29 +- examples/platforms/cc2650/crypto/sha256_alt.c | 2 +- examples/platforms/cc2650/cxx_helpers.c | 4 +- examples/platforms/cc2650/logging.c | 13 +- examples/platforms/cc2650/misc.c | 2 +- examples/platforms/cc2650/platform-cc2650.h | 6 +- examples/platforms/cc2650/platform.c | 14 +- examples/platforms/cc2650/radio.c | 144 ++- examples/platforms/cc2650/random.c | 22 +- examples/platforms/cc2650/uart.c | 23 +- examples/platforms/cc2652/alarm.c | 3 +- examples/platforms/cc2652/crypto/aes_alt.c | 29 +- examples/platforms/cc2652/cxx_helpers.c | 4 +- examples/platforms/cc2652/flash.c | 31 +- examples/platforms/cc2652/logging.c | 13 +- examples/platforms/cc2652/misc.c | 3 +- examples/platforms/cc2652/platform-cc2652.h | 6 +- examples/platforms/cc2652/platform.c | 9 +- examples/platforms/cc2652/radio.c | 143 ++- examples/platforms/cc2652/random.c | 24 +- examples/platforms/cc2652/uart.c | 26 +- examples/platforms/da15000/alarm.c | 14 +- examples/platforms/da15000/crypto/aes_alt.c | 31 +- examples/platforms/da15000/flash.c | 25 +- examples/platforms/da15000/logging.c | 8 +- examples/platforms/da15000/platform-da15000.h | 2 +- examples/platforms/da15000/platform.c | 35 +- examples/platforms/da15000/radio.c | 130 +-- examples/platforms/da15000/random.c | 15 +- examples/platforms/da15000/uart.c | 15 +- examples/platforms/efr32/alarm.c | 16 +- examples/platforms/efr32/flash.c | 14 +- examples/platforms/efr32/logging.c | 4 +- examples/platforms/efr32/misc.c | 8 +- examples/platforms/efr32/platform.c | 2 +- examples/platforms/efr32/radio.c | 222 ++--- examples/platforms/efr32/random.c | 13 +- examples/platforms/efr32/startup-gcc.c | 21 +- examples/platforms/efr32/uart.c | 50 +- examples/platforms/emsk/alarm.c | 9 +- examples/platforms/emsk/flash.c | 44 +- examples/platforms/emsk/logging.c | 6 +- examples/platforms/emsk/platform-emsk.h | 6 +- examples/platforms/emsk/platform.c | 4 +- examples/platforms/emsk/radio.c | 139 ++- examples/platforms/emsk/random.c | 9 +- examples/platforms/emsk/uart.c | 21 +- examples/platforms/gp712/alarm.c | 2 +- examples/platforms/gp712/flash.c | 19 +- examples/platforms/gp712/logging.c | 18 +- examples/platforms/gp712/misc.c | 10 +- examples/platforms/gp712/platform.c | 12 +- examples/platforms/gp712/radio.c | 34 +- examples/platforms/gp712/random.c | 19 +- examples/platforms/gp712/uart-posix.c | 41 +- examples/platforms/kw41z/alarm.c | 6 +- examples/platforms/kw41z/flash.c | 13 +- examples/platforms/kw41z/logging.c | 8 +- examples/platforms/kw41z/misc.c | 16 +- examples/platforms/kw41z/platform.c | 22 +- examples/platforms/kw41z/radio.c | 214 ++-- examples/platforms/kw41z/random.c | 14 +- examples/platforms/kw41z/uart.c | 19 +- examples/platforms/nrf52840/alarm.c | 51 +- examples/platforms/nrf52840/diag.c | 119 +-- examples/platforms/nrf52840/fem.c | 2 +- examples/platforms/nrf52840/flash.c | 13 +- examples/platforms/nrf52840/logging.c | 47 +- examples/platforms/nrf52840/misc.c | 12 +- examples/platforms/nrf52840/platform-config.h | 56 +- examples/platforms/nrf52840/platform-fem.h | 44 +- examples/platforms/nrf52840/platform-nrf5.h | 2 +- examples/platforms/nrf52840/platform.c | 10 +- examples/platforms/nrf52840/radio.c | 93 +- examples/platforms/nrf52840/random.c | 29 +- examples/platforms/nrf52840/temp.c | 6 +- examples/platforms/nrf52840/uart.c | 30 +- examples/platforms/nrf52840/usb-cdc-uart.c | 87 +- examples/platforms/platform.h | 4 +- examples/platforms/posix/alarm.c | 24 +- examples/platforms/posix/flash.c | 23 +- examples/platforms/posix/logging.c | 23 +- examples/platforms/posix/misc.c | 6 +- examples/platforms/posix/platform-posix.h | 16 +- examples/platforms/posix/platform.c | 18 +- examples/platforms/posix/radio.c | 203 ++-- examples/platforms/posix/random.c | 18 +- examples/platforms/posix/sim/alarm-sim.c | 12 +- examples/platforms/posix/sim/platform-sim.c | 38 +- examples/platforms/posix/sim/radio-sim.c | 217 ++--- examples/platforms/posix/uart-posix.c | 38 +- examples/platforms/samr21/alarm.c | 1 - examples/platforms/samr21/cxx_helpers.c | 4 +- examples/platforms/samr21/flash.c | 19 +- examples/platforms/samr21/misc.c | 4 +- examples/platforms/samr21/platform.c | 44 +- examples/platforms/samr21/radio.c | 81 +- examples/platforms/samr21/uart.c | 22 +- examples/platforms/utils/code_utils.h | 32 +- examples/platforms/utils/debug_uart.c | 9 +- examples/platforms/utils/flash.h | 41 +- examples/platforms/utils/settings.cpp | 113 +-- include/openthread/border_router.h | 18 +- include/openthread/channel_manager.h | 7 +- include/openthread/channel_monitor.h | 5 +- include/openthread/child_supervision.h | 5 +- include/openthread/cli.h | 11 +- include/openthread/coap.h | 174 ++-- include/openthread/commissioner.h | 61 +- include/openthread/config.h | 5 +- include/openthread/crypto.h | 34 +- include/openthread/dataset.h | 4 +- include/openthread/dataset_ftd.h | 24 +- include/openthread/dhcp6_client.h | 10 +- include/openthread/dhcp6_server.h | 4 +- include/openthread/diag.h | 4 +- include/openthread/dns.h | 29 +- include/openthread/icmp6.h | 44 +- include/openthread/instance.h | 58 +- include/openthread/ip6.h | 16 +- include/openthread/jam_detection.h | 5 +- include/openthread/joiner.h | 22 +- include/openthread/link.h | 33 +- include/openthread/link_raw.h | 16 +- include/openthread/message.h | 6 +- include/openthread/ncp.h | 16 +- include/openthread/netdata.h | 15 +- include/openthread/openthread.h | 4 +- include/openthread/platform/alarm-micro.h | 4 +- include/openthread/platform/alarm-milli.h | 4 +- include/openthread/platform/debug_uart.h | 233 +++-- include/openthread/platform/diag.h | 4 +- include/openthread/platform/logging.h | 16 +- include/openthread/platform/memory.h | 4 +- include/openthread/platform/messagepool.h | 5 +- include/openthread/platform/misc.h | 25 +- include/openthread/platform/radio.h | 63 +- include/openthread/platform/random.h | 4 +- include/openthread/platform/settings.h | 7 +- include/openthread/platform/spi-slave.h | 23 +- include/openthread/platform/toolchain.h | 62 +- include/openthread/platform/uart.h | 4 +- include/openthread/server.h | 23 +- include/openthread/tasklet.h | 4 +- include/openthread/thread.h | 39 +- include/openthread/thread_ftd.h | 17 +- include/openthread/tmf_proxy.h | 10 +- include/openthread/types.h | 634 ++++++------ include/openthread/udp.h | 16 +- src/cli/cli.cpp | 667 +++++++------ src/cli/cli.hpp | 103 +- src/cli/cli_coap.cpp | 80 +- src/cli/cli_coap.hpp | 29 +- src/cli/cli_console.cpp | 17 +- src/cli/cli_console.hpp | 11 +- src/cli/cli_dataset.cpp | 132 +-- src/cli/cli_dataset.hpp | 12 +- src/cli/cli_server.hpp | 6 +- src/cli/cli_uart.cpp | 78 +- src/cli/cli_uart.hpp | 19 +- src/cli/cli_udp_example.cpp | 60 +- src/cli/cli_udp_example.hpp | 14 +- src/core/api/border_router_api.cpp | 28 +- src/core/api/channel_manager_api.cpp | 4 +- src/core/api/channel_monitor_api.cpp | 2 +- src/core/api/child_supervision_api.cpp | 2 +- src/core/api/coap_api.cpp | 19 +- src/core/api/commissioner_api.cpp | 50 +- src/core/api/crypto_api.cpp | 30 +- src/core/api/dataset_api.cpp | 8 +- src/core/api/dataset_ftd_api.cpp | 26 +- src/core/api/dns_api.cpp | 3 +- src/core/api/icmp6_api.cpp | 11 +- src/core/api/instance_api.cpp | 1 - src/core/api/ip6_api.cpp | 18 +- src/core/api/jam_detection_api.cpp | 2 +- src/core/api/joiner_api.cpp | 13 +- src/core/api/link_api.cpp | 52 +- src/core/api/link_raw.hpp | 27 +- src/core/api/link_raw_api.cpp | 62 +- src/core/api/message_api.cpp | 30 +- src/core/api/netdata_api.cpp | 14 +- src/core/api/server_api.cpp | 26 +- src/core/api/tasklet_api.cpp | 3 +- src/core/api/thread_api.cpp | 139 +-- src/core/api/thread_ftd_api.cpp | 26 +- src/core/api/udp_api.cpp | 15 +- src/core/coap/coap.cpp | 192 ++-- src/core/coap/coap.hpp | 181 ++-- src/core/coap/coap_header.cpp | 83 +- src/core/coap/coap_header.hpp | 53 +- src/core/coap/coap_secure.cpp | 45 +- src/core/coap/coap_secure.hpp | 46 +- src/core/common/code_utils.hpp | 59 +- src/core/common/crc16.cpp | 7 +- src/core/common/crc16.hpp | 8 +- src/core/common/debug.hpp | 41 +- src/core/common/encoding.hpp | 131 ++- src/core/common/instance.cpp | 120 +-- src/core/common/instance.hpp | 52 +- src/core/common/locator.cpp | 2 +- src/core/common/locator.hpp | 27 +- src/core/common/logging.cpp | 29 +- src/core/common/logging.hpp | 395 ++++---- src/core/common/message.cpp | 82 +- src/core/common/message.hpp | 189 ++-- src/core/common/new.hpp | 7 +- src/core/common/notifier.cpp | 32 +- src/core/common/notifier.hpp | 27 +- src/core/common/owner-locator.hpp | 7 +- src/core/common/settings.hpp | 46 +- src/core/common/tasklet.cpp | 20 +- src/core/common/tasklet.hpp | 10 +- src/core/common/timer.cpp | 28 +- src/core/common/timer.hpp | 66 +- src/core/common/tlvs.cpp | 16 +- src/core/common/tlvs.hpp | 27 +- src/core/common/trickle_timer.cpp | 53 +- src/core/common/trickle_timer.hpp | 33 +- src/core/crypto/aes_ccm.cpp | 48 +- src/core/crypto/aes_ccm.hpp | 25 +- src/core/crypto/aes_ecb.cpp | 4 +- src/core/crypto/aes_ecb.hpp | 8 +- src/core/crypto/heap.cpp | 20 +- src/core/crypto/heap.hpp | 93 +- src/core/crypto/hmac_sha256.cpp | 4 +- src/core/crypto/hmac_sha256.hpp | 8 +- src/core/crypto/mbedtls.cpp | 4 +- src/core/crypto/mbedtls.hpp | 6 +- src/core/crypto/pbkdf2_cmac.cpp | 40 +- src/core/crypto/pbkdf2_cmac.h | 18 +- src/core/crypto/sha256.cpp | 4 +- src/core/crypto/sha256.hpp | 8 +- src/core/mac/mac.cpp | 287 +++--- src/core/mac/mac.hpp | 182 ++-- src/core/mac/mac_filter.cpp | 34 +- src/core/mac/mac_filter.hpp | 12 +- src/core/mac/mac_frame.cpp | 94 +- src/core/mac/mac_frame.hpp | 275 +++--- src/core/meshcop/announce_begin_client.cpp | 26 +- src/core/meshcop/announce_begin_client.hpp | 8 +- src/core/meshcop/commissioner.cpp | 274 +++--- src/core/meshcop/commissioner.hpp | 127 ++- src/core/meshcop/dataset.cpp | 102 +- src/core/meshcop/dataset.hpp | 16 +- src/core/meshcop/dataset_local.cpp | 83 +- src/core/meshcop/dataset_local.hpp | 14 +- src/core/meshcop/dataset_manager.cpp | 103 +- src/core/meshcop/dataset_manager.hpp | 64 +- src/core/meshcop/dataset_manager_ftd.cpp | 148 +-- src/core/meshcop/dtls.cpp | 98 +- src/core/meshcop/dtls.hpp | 71 +- src/core/meshcop/energy_scan_client.cpp | 67 +- src/core/meshcop/energy_scan_client.hpp | 23 +- src/core/meshcop/joiner.cpp | 171 ++-- src/core/meshcop/joiner.hpp | 63 +- src/core/meshcop/joiner_router.cpp | 148 +-- src/core/meshcop/joiner_router.hpp | 61 +- src/core/meshcop/leader.cpp | 87 +- src/core/meshcop/leader.hpp | 46 +- src/core/meshcop/meshcop.cpp | 6 +- src/core/meshcop/meshcop.hpp | 6 +- src/core/meshcop/meshcop_tlvs.cpp | 4 +- src/core/meshcop/meshcop_tlvs.hpp | 576 +++++++---- src/core/meshcop/panid_query_client.cpp | 61 +- src/core/meshcop/panid_query_client.hpp | 21 +- src/core/meshcop/timestamp.cpp | 12 +- src/core/meshcop/timestamp.hpp | 34 +- src/core/net/dhcp6.hpp | 230 +++-- src/core/net/dhcp6_client.cpp | 126 ++- src/core/net/dhcp6_client.hpp | 50 +- src/core/net/dhcp6_server.cpp | 88 +- src/core/net/dhcp6_server.hpp | 42 +- src/core/net/dns_client.cpp | 113 ++- src/core/net/dns_client.hpp | 66 +- src/core/net/dns_headers.hpp | 102 +- src/core/net/icmp6.cpp | 60 +- src/core/net/icmp6.hpp | 40 +- src/core/net/ip6.cpp | 213 ++-- src/core/net/ip6.hpp | 56 +- src/core/net/ip6_address.cpp | 54 +- src/core/net/ip6_address.hpp | 22 +- src/core/net/ip6_filter.cpp | 10 +- src/core/net/ip6_filter.hpp | 6 +- src/core/net/ip6_headers.cpp | 6 +- src/core/net/ip6_headers.hpp | 99 +- src/core/net/ip6_mpl.cpp | 52 +- src/core/net/ip6_mpl.hpp | 74 +- src/core/net/ip6_routes.cpp | 20 +- src/core/net/ip6_routes.hpp | 16 +- src/core/net/netif.cpp | 107 +- src/core/net/netif.hpp | 39 +- src/core/net/socket.hpp | 16 +- src/core/net/tcp.hpp | 8 +- src/core/net/udp6.cpp | 32 +- src/core/net/udp6.hpp | 23 +- src/core/openthread-core-config.h | 3 +- src/core/openthread-core-default-config.h | 252 ++--- src/core/thread/address_resolver.cpp | 202 ++-- src/core/thread/address_resolver.hpp | 66 +- src/core/thread/announce_begin_server.cpp | 42 +- src/core/thread/announce_begin_server.hpp | 18 +- src/core/thread/data_poll_manager.cpp | 63 +- src/core/thread/data_poll_manager.hpp | 54 +- src/core/thread/energy_scan_server.cpp | 67 +- src/core/thread/energy_scan_server.hpp | 36 +- src/core/thread/key_manager.cpp | 45 +- src/core/thread/key_manager.hpp | 30 +- src/core/thread/link_quality.cpp | 30 +- src/core/thread/link_quality.hpp | 52 +- src/core/thread/lowpan.cpp | 164 ++-- src/core/thread/lowpan.hpp | 128 ++- src/core/thread/mesh_forwarder.cpp | 296 +++--- src/core/thread/mesh_forwarder.hpp | 174 ++-- src/core/thread/mesh_forwarder_ftd.cpp | 167 ++-- src/core/thread/mesh_forwarder_mtd.cpp | 8 +- src/core/thread/mle.cpp | 710 +++++++------- src/core/thread/mle.hpp | 333 ++++--- src/core/thread/mle_constants.hpp | 40 +- src/core/thread/mle_router.cpp | 918 +++++++++--------- src/core/thread/mle_router_ftd.hpp | 180 ++-- src/core/thread/mle_router_mtd.hpp | 60 +- src/core/thread/mle_tlvs.hpp | 327 ++++--- src/core/thread/network_data.cpp | 270 +++--- src/core/thread/network_data.hpp | 60 +- src/core/thread/network_data_leader.cpp | 144 ++- src/core/thread/network_data_leader.hpp | 33 +- src/core/thread/network_data_leader_ftd.cpp | 282 +++--- src/core/thread/network_data_leader_ftd.hpp | 57 +- src/core/thread/network_data_leader_mtd.hpp | 21 +- src/core/thread/network_data_local.cpp | 73 +- src/core/thread/network_data_local.hpp | 19 +- src/core/thread/network_data_tlvs.hpp | 272 ++++-- src/core/thread/network_diagnostic.cpp | 195 ++-- src/core/thread/network_diagnostic.hpp | 40 +- src/core/thread/network_diagnostic_tlvs.hpp | 294 ++++-- src/core/thread/panid_query_server.cpp | 45 +- src/core/thread/panid_query_server.hpp | 23 +- src/core/thread/src_match_controller.cpp | 18 +- src/core/thread/src_match_controller.hpp | 6 +- src/core/thread/thread_netif.cpp | 134 +-- src/core/thread/thread_netif.hpp | 104 +- src/core/thread/thread_tlvs.hpp | 88 +- src/core/thread/thread_uri_paths.hpp | 58 +- src/core/thread/tmf_proxy.cpp | 42 +- src/core/thread/tmf_proxy.hpp | 23 +- src/core/thread/topology.cpp | 6 +- src/core/thread/topology.hpp | 99 +- src/core/utils/channel_manager.cpp | 53 +- src/core/utils/channel_manager.hpp | 25 +- src/core/utils/channel_monitor.cpp | 36 +- src/core/utils/channel_monitor.hpp | 34 +- src/core/utils/child_supervision.cpp | 28 +- src/core/utils/child_supervision.hpp | 54 +- src/core/utils/jam_detector.cpp | 50 +- src/core/utils/jam_detector.hpp | 51 +- src/core/utils/slaac_address.cpp | 32 +- src/core/utils/slaac_address.hpp | 18 +- src/core/utils/wrap_stdbool.h | 1 - src/core/utils/wrap_string.h | 19 +- tests/fuzz/fuzzer_platform.c | 11 +- tests/fuzz/ip6_send.cpp | 6 +- tests/fuzz/radio_receive_done.cpp | 8 +- tests/unit/test_aes.cpp | 112 +-- tests/unit/test_child.cpp | 28 +- tests/unit/test_heap.cpp | 11 +- tests/unit/test_hmac_sha256.cpp | 16 +- tests/unit/test_link_quality.cpp | 123 ++- tests/unit/test_lowpan.cpp | 367 +++---- tests/unit/test_lowpan.hpp | 75 +- tests/unit/test_mac_frame.cpp | 54 +- tests/unit/test_message.cpp | 26 +- tests/unit/test_message_queue.cpp | 31 +- tests/unit/test_ncp_buffer.cpp | 138 +-- tests/unit/test_network_data.cpp | 132 +-- tests/unit/test_platform.cpp | 757 ++++++++------- tests/unit/test_platform.h | 44 +- tests/unit/test_priority_queue.cpp | 71 +- tests/unit/test_pskc.cpp | 50 +- tests/unit/test_spinel_decoder.cpp | 797 +++++++-------- tests/unit/test_spinel_encoder.cpp | 520 ++++------ tests/unit/test_strlcat.c | 8 +- tests/unit/test_strlcpy.c | 8 +- tests/unit/test_timer.cpp | 499 ++++------ tests/unit/test_toolchain.cpp | 8 +- tests/unit/test_util.cpp | 12 +- tests/unit/test_util.h | 38 +- 401 files changed, 13393 insertions(+), 13112 deletions(-) mode change 100755 => 100644 examples/platforms/da15000/platform-da15000.h mode change 100755 => 100644 examples/platforms/emsk/alarm.c mode change 100755 => 100644 examples/platforms/emsk/logging.c mode change 100755 => 100644 examples/platforms/emsk/platform-emsk.h mode change 100755 => 100644 examples/platforms/emsk/platform.c mode change 100755 => 100644 examples/platforms/emsk/random.c diff --git a/examples/apps/cli/main.c b/examples/apps/cli/main.c index b787629a0..a893226d2 100644 --- a/examples/apps/cli/main.c +++ b/examples/apps/cli/main.c @@ -26,9 +26,9 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include -#include #include +#include +#include #include #include @@ -59,8 +59,8 @@ int main(int argc, char *argv[]) otInstance *sInstance; #if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES - size_t otInstanceBufferLength = 0; - uint8_t *otInstanceBuffer = NULL; + size_t otInstanceBufferLength = 0; + uint8_t *otInstanceBuffer = NULL; #endif PlatformInit(argc, argv); @@ -92,9 +92,9 @@ int main(int argc, char *argv[]) PlatformProcessDrivers(sInstance); } - // otInstanceFinalize(sInstance); + // otInstanceFinalize(sInstance); #if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES - // free(otInstanceBuffer); + // free(otInstanceBuffer); #endif return 0; diff --git a/examples/apps/ncp/main.c b/examples/apps/ncp/main.c index 0aff87682..47a4b5239 100644 --- a/examples/apps/ncp/main.c +++ b/examples/apps/ncp/main.c @@ -26,9 +26,9 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include -#include #include +#include +#include #include #include @@ -58,8 +58,8 @@ int main(int argc, char *argv[]) otInstance *sInstance; #if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES - size_t otInstanceBufferLength = 0; - uint8_t *otInstanceBuffer = NULL; + size_t otInstanceBufferLength = 0; + uint8_t *otInstanceBuffer = NULL; #endif PlatformInit(argc, argv); @@ -91,18 +91,17 @@ int main(int argc, char *argv[]) PlatformProcessDrivers(sInstance); } - // otInstanceFinalize(sInstance); + // otInstanceFinalize(sInstance); #if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES - // free(otInstanceBuffer); + // free(otInstanceBuffer); #endif return 0; } - -/* - * Provide, if required an "otPlatLog()" function - */ + /* + * Provide, if required an "otPlatLog()" function + */ #if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_APP) void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat, ...) diff --git a/examples/platforms/cc2538/alarm.c b/examples/platforms/cc2538/alarm.c index 546b1d016..1a54eb230 100644 --- a/examples/platforms/cc2538/alarm.c +++ b/examples/platforms/cc2538/alarm.c @@ -44,19 +44,19 @@ enum { - kSystemClock = 32000000, ///< MHz - kTicksPerSec = 1000, ///< Ticks per second + kSystemClock = 32000000, ///< MHz + kTicksPerSec = 1000, ///< Ticks per second }; -static uint32_t sCounter = 0; -static uint32_t sAlarmT0 = 0; -static uint32_t sAlarmDt = 0; -static bool sIsRunning = false; +static uint32_t sCounter = 0; +static uint32_t sAlarmT0 = 0; +static uint32_t sAlarmDt = 0; +static bool sIsRunning = false; void cc2538AlarmInit(void) { HWREG(NVIC_ST_RELOAD) = kSystemClock / kTicksPerSec; - HWREG(NVIC_ST_CTRL) = NVIC_ST_CTRL_CLK_SRC | NVIC_ST_CTRL_INTEN | NVIC_ST_CTRL_ENABLE; + HWREG(NVIC_ST_CTRL) = NVIC_ST_CTRL_CLK_SRC | NVIC_ST_CTRL_INTEN | NVIC_ST_CTRL_ENABLE; } uint32_t otPlatAlarmMilliGetNow(void) @@ -67,8 +67,8 @@ uint32_t otPlatAlarmMilliGetNow(void) void otPlatAlarmMilliStartAt(otInstance *aInstance, uint32_t t0, uint32_t dt) { (void)aInstance; - sAlarmT0 = t0; - sAlarmDt = dt; + sAlarmT0 = t0; + sAlarmDt = dt; sIsRunning = true; } @@ -81,7 +81,7 @@ void otPlatAlarmMilliStop(otInstance *aInstance) void cc2538AlarmProcess(otInstance *aInstance) { uint32_t expires; - bool fire = false; + bool fire = false; if (sIsRunning) { @@ -119,7 +119,6 @@ void cc2538AlarmProcess(otInstance *aInstance) } } } - } void SysTick_Handler() diff --git a/examples/platforms/cc2538/flash.c b/examples/platforms/cc2538/flash.c index 94308a388..a57fa4776 100644 --- a/examples/platforms/cc2538/flash.c +++ b/examples/platforms/cc2538/flash.c @@ -26,8 +26,8 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include #include +#include #include #include @@ -42,7 +42,7 @@ #include "utils/flash.h" #include "utils/wrap_string.h" -#define FLASH_CTRL_FCTL_BUSY 0x00000080 +#define FLASH_CTRL_FCTL_BUSY 0x00000080 #if SETTINGS_CONFIG_PAGE_SIZE != 2048 #error FLASH page size is 2048 on this chip @@ -102,16 +102,16 @@ uint32_t utilsFlashGetSize(void) otError utilsFlashErasePage(uint32_t aAddress) { - otError error = OT_ERROR_NONE; - int32_t status; + otError error = OT_ERROR_NONE; + int32_t status; uint32_t address; otEXPECT_ACTION(aAddress < utilsFlashGetSize(), error = OT_ERROR_INVALID_ARGS); address = aAddress - (aAddress & (SETTINGS_CONFIG_PAGE_SIZE - 1)); address = flashPhysAddr(address); - status = ROM_PageErase(address, SETTINGS_CONFIG_PAGE_SIZE); - error = romStatusToThread(status); + status = ROM_PageErase(address, SETTINGS_CONFIG_PAGE_SIZE); + error = romStatusToThread(status); exit: return error; @@ -119,9 +119,9 @@ exit: otError utilsFlashStatusWait(uint32_t aTimeout) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint32_t start = otPlatAlarmMilliGetNow(); - uint32_t busy = 1; + uint32_t busy = 1; while (busy && ((otPlatAlarmMilliGetNow() - start) < aTimeout)) { @@ -136,13 +136,12 @@ exit: uint32_t utilsFlashWrite(uint32_t aAddress, uint8_t *aData, uint32_t aSize) { - int32_t status; - uint32_t busy = 1; + int32_t status; + uint32_t busy = 1; uint32_t *data; - uint32_t size = 0; + uint32_t size = 0; - otEXPECT_ACTION(((aAddress + aSize) < utilsFlashGetSize()) && - (!(aAddress & 3)) && (!(aSize & 3)), aSize = 0); + otEXPECT_ACTION(((aAddress + aSize) < utilsFlashGetSize()) && (!(aAddress & 3)) && (!(aSize & 3)), aSize = 0); data = (uint32_t *)(aData); @@ -173,8 +172,8 @@ uint32_t utilsFlashRead(uint32_t aAddress, uint8_t *aData, uint32_t aSize) while (size < aSize) { - uint8_t *byte = (uint8_t *)flashPhysAddr(aAddress); - uint8_t maxIndex = 4; + uint8_t *byte = (uint8_t *)flashPhysAddr(aAddress); + uint8_t maxIndex = 4; if (size == (aSize - aSize % 4)) { diff --git a/examples/platforms/cc2538/logging.c b/examples/platforms/cc2538/logging.c index 5a282d335..0cbb7792f 100644 --- a/examples/platforms/cc2538/logging.c +++ b/examples/platforms/cc2538/logging.c @@ -27,15 +27,15 @@ */ /** -* @file logging.c -* Platform abstraction for the logging -* -*/ -#include + * @file logging.c + * Platform abstraction for the logging + * + */ #include +#include #include -#if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED) +#if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED) void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat, ...) { (void)aLogLevel; @@ -43,4 +43,3 @@ void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat (void)aFormat; } #endif - diff --git a/examples/platforms/cc2538/platform-cc2538.h b/examples/platforms/cc2538/platform-cc2538.h index fa7043bb2..2a61807cc 100644 --- a/examples/platforms/cc2538/platform-cc2538.h +++ b/examples/platforms/cc2538/platform-cc2538.h @@ -35,9 +35,9 @@ #ifndef PLATFORM_CC2538_H_ #define PLATFORM_CC2538_H_ -#include #include #include +#include #include @@ -91,4 +91,4 @@ void cc2538RandomInit(void); */ void cc2538UartProcess(void); -#endif // PLATFORM_CC2538_H_ +#endif // PLATFORM_CC2538_H_ diff --git a/examples/platforms/cc2538/platform.c b/examples/platforms/cc2538/platform.c index 8ac91740c..feaf4db9f 100644 --- a/examples/platforms/cc2538/platform.c +++ b/examples/platforms/cc2538/platform.c @@ -31,8 +31,8 @@ * @brief * This file includes the platform-specific initializers. */ -#include #include "platform-cc2538.h" +#include otInstance *sInstance; diff --git a/examples/platforms/cc2538/radio.c b/examples/platforms/cc2538/radio.c index 7500b6e7e..d7c86f0b4 100644 --- a/examples/platforms/cc2538/radio.c +++ b/examples/platforms/cc2538/radio.c @@ -44,19 +44,19 @@ enum { - IEEE802154_MIN_LENGTH = 5, - IEEE802154_MAX_LENGTH = 127, - IEEE802154_ACK_LENGTH = 5, + IEEE802154_MIN_LENGTH = 5, + IEEE802154_MAX_LENGTH = 127, + IEEE802154_ACK_LENGTH = 5, IEEE802154_FRAME_TYPE_MASK = 0x7, - IEEE802154_FRAME_TYPE_ACK = 0x2, - IEEE802154_FRAME_PENDING = 1 << 4, - IEEE802154_ACK_REQUEST = 1 << 5, - IEEE802154_DSN_OFFSET = 2, + IEEE802154_FRAME_TYPE_ACK = 0x2, + IEEE802154_FRAME_PENDING = 1 << 4, + IEEE802154_ACK_REQUEST = 1 << 5, + IEEE802154_DSN_OFFSET = 2, }; enum { - CC2538_RSSI_OFFSET = 73, + CC2538_RSSI_OFFSET = 73, CC2538_CRC_BIT_MASK = 0x80, CC2538_LQI_BIT_MASK = 0x7f, }; @@ -73,36 +73,35 @@ typedef struct TxPowerTable } TxPowerTable; // The transmit power table, the values are from SmartRF Studio 2.4.0 -static const TxPowerTable sTxPowerTable[] = -{ - { 7, 0xFF }, // - { 5, 0xED }, // - { 3, 0xD5 }, // - { 1, 0xC5 }, // - { 0, 0xB6 }, // - { -1, 0xB0 }, // - { -3, 0xA1 }, // - { -5, 0x91 }, // - { -7, 0x88 }, // - { -9, 0x72 }, // - { -11, 0x62 }, // - { -13, 0x58 }, // - { -15, 0x42 }, // - { -24, 0x00 }, // +static const TxPowerTable sTxPowerTable[] = { + {7, 0xFF}, // + {5, 0xED}, // + {3, 0xD5}, // + {1, 0xC5}, // + {0, 0xB6}, // + {-1, 0xB0}, // + {-3, 0xA1}, // + {-5, 0x91}, // + {-7, 0x88}, // + {-9, 0x72}, // + {-11, 0x62}, // + {-13, 0x58}, // + {-15, 0x42}, // + {-24, 0x00}, // }; static otRadioFrame sTransmitFrame; static otRadioFrame sReceiveFrame; -static otError sTransmitError; -static otError sReceiveError; +static otError sTransmitError; +static otError sReceiveError; static uint8_t sTransmitPsdu[IEEE802154_MAX_LENGTH]; static uint8_t sReceivePsdu[IEEE802154_MAX_LENGTH]; static uint8_t sChannel = 0; -static int8_t sTxPower = 0; +static int8_t sTxPower = 0; -static otRadioState sState = OT_RADIO_STATE_DISABLED; -static bool sIsReceiverEnabled = false; +static otRadioState sState = OT_RADIO_STATE_DISABLED; +static bool sIsReceiverEnabled = false; void enableReceiver(void) { @@ -116,7 +115,7 @@ void enableReceiver(void) // enable receiver HWREG(RFCORE_SFR_RFST) = RFCORE_SFR_RFST_INSTR_RXON; - sIsReceiverEnabled = true; + sIsReceiverEnabled = true; } } @@ -126,7 +125,8 @@ void disableReceiver(void) { otLogInfoPlat(sInstance, "Disabling receiver", NULL); - while (HWREG(RFCORE_XREG_FSMSTAT1) & RFCORE_XREG_FSMSTAT1_TX_ACTIVE); + while (HWREG(RFCORE_XREG_FSMSTAT1) & RFCORE_XREG_FSMSTAT1_TX_ACTIVE) + ; // flush rxfifo HWREG(RFCORE_SFR_RFST) = RFCORE_SFR_RFST_INSTR_FLUSHRX; @@ -157,7 +157,7 @@ void setChannel(uint8_t aChannel) otLogInfoPlat(sInstance, "Channel=%d", aChannel); HWREG(RFCORE_XREG_FREQCTRL) = 11 + (aChannel - 11) * 5; - sChannel = aChannel; + sChannel = aChannel; if (enabled) { @@ -183,7 +183,7 @@ void setTxPower(int8_t aTxPower) } HWREG(RFCORE_XREG_TXPOWER) = sTxPowerTable[i].mTxPowerReg; - sTxPower = aTxPower; + sTxPower = aTxPower; } } @@ -212,9 +212,8 @@ void otPlatRadioSetExtendedAddress(otInstance *aInstance, const otExtAddress *aA { (void)aInstance; - otLogInfoPlat(sInstance, "ExtAddr=%X%X%X%X%X%X%X%X", - aAddress->m8[7], aAddress->m8[6], aAddress->m8[5], aAddress->m8[4], - aAddress->m8[3], aAddress->m8[2], aAddress->m8[1], aAddress->m8[0]); + otLogInfoPlat(sInstance, "ExtAddr=%X%X%X%X%X%X%X%X", aAddress->m8[7], aAddress->m8[6], aAddress->m8[5], + aAddress->m8[4], aAddress->m8[3], aAddress->m8[2], aAddress->m8[1], aAddress->m8[0]); for (int i = 0; i < 8; i++) { @@ -235,9 +234,9 @@ void otPlatRadioSetShortAddress(otInstance *aInstance, uint16_t aAddress) void cc2538RadioInit(void) { sTransmitFrame.mLength = 0; - sTransmitFrame.mPsdu = sTransmitPsdu; - sReceiveFrame.mLength = 0; - sReceiveFrame.mPsdu = sReceivePsdu; + sTransmitFrame.mPsdu = sTransmitPsdu; + sReceiveFrame.mLength = 0; + sReceiveFrame.mPsdu = sReceivePsdu; // enable clock HWREG(SYS_CTRL_RCGCRFC) = SYS_CTRL_RCGCRFC_RFC0; @@ -245,11 +244,11 @@ void cc2538RadioInit(void) HWREG(SYS_CTRL_DCGCRFC) = SYS_CTRL_DCGCRFC_RFC0; // Table 23-7. - HWREG(RFCORE_XREG_AGCCTRL1) = 0x15; - HWREG(RFCORE_XREG_TXFILTCFG) = 0x09; + HWREG(RFCORE_XREG_AGCCTRL1) = 0x15; + HWREG(RFCORE_XREG_TXFILTCFG) = 0x09; HWREG(ANA_REGS_BASE + ANA_REGS_O_IVCTRL) = 0x0b; - HWREG(RFCORE_XREG_CCACTRL0) = 0xf8; + HWREG(RFCORE_XREG_CCACTRL0) = 0xf8; HWREG(RFCORE_XREG_FIFOPCTRL) = IEEE802154_MAX_LENGTH; HWREG(RFCORE_XREG_FRMCTRL0) = RFCORE_XREG_FRMCTRL0_AUTOCRC | RFCORE_XREG_FRMCTRL0_AUTOACK; @@ -258,7 +257,7 @@ void cc2538RadioInit(void) // SRCMATCH.PEND_DATAREQ_ONLY(1), RFCORE_XREG_FRMCTRL1_PENDING_OR(0) HWREG(RFCORE_XREG_TXPOWER) = sTxPowerTable[0].mTxPowerReg; - sTxPower = sTxPowerTable[0].mTxPowerVal; + sTxPower = sTxPowerTable[0].mTxPowerVal; otLogInfoPlat(sInstance, "Initialized", NULL); } @@ -299,7 +298,7 @@ otError otPlatRadioSleep(otInstance *aInstance) if (sState == OT_RADIO_STATE_SLEEP || sState == OT_RADIO_STATE_RECEIVE) { otLogDebgPlat(sInstance, "State=OT_RADIO_STATE_SLEEP", NULL); - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; sState = OT_RADIO_STATE_SLEEP; disableReceiver(); } @@ -316,7 +315,7 @@ otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) { otLogDebgPlat(sInstance, "State=OT_RADIO_STATE_RECEIVE", NULL); - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; sState = OT_RADIO_STATE_RECEIVE; setChannel(aChannel); sReceiveFrame.mChannel = aChannel; @@ -335,11 +334,12 @@ otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aFrame) { int i; - error = OT_ERROR_NONE; - sState = OT_RADIO_STATE_TRANSMIT; + error = OT_ERROR_NONE; + sState = OT_RADIO_STATE_TRANSMIT; sTransmitError = OT_ERROR_NONE; - while (HWREG(RFCORE_XREG_FSMSTAT1) & RFCORE_XREG_FSMSTAT1_TX_ACTIVE); + while (HWREG(RFCORE_XREG_FSMSTAT1) & RFCORE_XREG_FSMSTAT1_TX_ACTIVE) + ; // flush txfifo HWREG(RFCORE_SFR_RFST) = RFCORE_SFR_RFST_INSTR_FLUSHTX; @@ -356,10 +356,12 @@ otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aFrame) setChannel(aFrame->mChannel); - while ((HWREG(RFCORE_XREG_FSMSTAT1) & 1) == 0); + while ((HWREG(RFCORE_XREG_FSMSTAT1) & 1) == 0) + ; // wait for valid rssi - while ((HWREG(RFCORE_XREG_RSSISTAT) & RFCORE_XREG_RSSISTAT_RSSI_VALID) == 0); + while ((HWREG(RFCORE_XREG_RSSISTAT) & RFCORE_XREG_RSSISTAT_RSSI_VALID) == 0) + ; otEXPECT_ACTION(((HWREG(RFCORE_XREG_FSMSTAT1) & RFCORE_XREG_FSMSTAT1_CCA) && !((HWREG(RFCORE_XREG_FSMSTAT1) & RFCORE_XREG_FSMSTAT1_SFD))), @@ -370,7 +372,8 @@ otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aFrame) otPlatRadioTxStarted(aInstance, aFrame); - while (HWREG(RFCORE_XREG_FSMSTAT1) & RFCORE_XREG_FSMSTAT1_TX_ACTIVE); + while (HWREG(RFCORE_XREG_FSMSTAT1) & RFCORE_XREG_FSMSTAT1_TX_ACTIVE) + ; otLogDebgPlat(sInstance, "Transmitted %d bytes", aFrame->mLength); } @@ -423,7 +426,7 @@ void readFrame(void) { uint8_t length; uint8_t crcCorr; - int i; + int i; otEXPECT(sState == OT_RADIO_STATE_RECEIVE || sState == OT_RADIO_STATE_TRANSMIT); otEXPECT((HWREG(RFCORE_XREG_FSMSTAT1) & RFCORE_XREG_FSMSTAT1_FIFOP) != 0); @@ -435,7 +438,7 @@ void readFrame(void) #if OPENTHREAD_ENABLE_RAW_LINK_API // Timestamp sReceiveFrame.mMsec = otPlatAlarmMilliGetNow(); - sReceiveFrame.mUsec = 0; // Don't support microsecond timer for now. + sReceiveFrame.mUsec = 0; // Don't support microsecond timer for now. #endif // read psdu @@ -445,12 +448,12 @@ void readFrame(void) } sReceiveFrame.mRssi = (int8_t)HWREG(RFCORE_SFR_RFDATA) - CC2538_RSSI_OFFSET; - crcCorr = HWREG(RFCORE_SFR_RFDATA); + crcCorr = HWREG(RFCORE_SFR_RFDATA); if (crcCorr & CC2538_CRC_BIT_MASK) { sReceiveFrame.mLength = length; - sReceiveFrame.mLqi = crcCorr & CC2538_LQI_BIT_MASK; + sReceiveFrame.mLqi = crcCorr & CC2538_LQI_BIT_MASK; } else { @@ -548,8 +551,8 @@ void RFCoreErrIntHandler(void) uint32_t getSrcMatchEntriesEnableStatus(bool aShort) { - uint32_t status = 0; - uint32_t *addr = aShort ? (uint32_t *) RFCORE_XREG_SRCSHORTEN0 : (uint32_t *) RFCORE_XREG_SRCEXTEN0; + uint32_t status = 0; + uint32_t *addr = aShort ? (uint32_t *)RFCORE_XREG_SRCSHORTEN0 : (uint32_t *)RFCORE_XREG_SRCEXTEN0; for (uint8_t i = 0; i < RFCORE_XREG_SRCMATCH_ENABLE_STATUS_SIZE; i++) { @@ -561,11 +564,11 @@ uint32_t getSrcMatchEntriesEnableStatus(bool aShort) int8_t findSrcMatchShortEntry(const uint16_t aShortAddress) { - int8_t entry = -1; - uint16_t shortAddr; - uint32_t bitMask; - uint32_t *addr = NULL; - uint32_t status = getSrcMatchEntriesEnableStatus(true); + int8_t entry = -1; + uint16_t shortAddr; + uint32_t bitMask; + uint32_t *addr = NULL; + uint32_t status = getSrcMatchEntriesEnableStatus(true); for (uint8_t i = 0; i < RFCORE_XREG_SRCMATCH_SHORT_ENTRIES; i++) { @@ -593,15 +596,15 @@ int8_t findSrcMatchShortEntry(const uint16_t aShortAddress) int8_t findSrcMatchExtEntry(const otExtAddress *aExtAddress) { - int8_t entry = -1; - uint32_t bitMask; - uint32_t *addr = NULL; - uint32_t status = getSrcMatchEntriesEnableStatus(false); + int8_t entry = -1; + uint32_t bitMask; + uint32_t *addr = NULL; + uint32_t status = getSrcMatchEntriesEnableStatus(false); for (uint8_t i = 0; i < RFCORE_XREG_SRCMATCH_EXT_ENTRIES; i++) { uint8_t j = 0; - bitMask = 0x00000001 << 2 * i; + bitMask = 0x00000001 << 2 * i; if ((status & bitMask) == 0) { @@ -630,11 +633,11 @@ int8_t findSrcMatchExtEntry(const otExtAddress *aExtAddress) void setSrcMatchEntryEnableStatus(bool aShort, uint8_t aEntry, bool aEnable) { - uint8_t entry = aShort ? aEntry : (2 * aEntry); - uint8_t index = entry / 8; - uint32_t *addrEn = aShort ? (uint32_t *)RFCORE_XREG_SRCSHORTEN0 : (uint32_t *)RFCORE_XREG_SRCEXTEN0; + uint8_t entry = aShort ? aEntry : (2 * aEntry); + uint8_t index = entry / 8; + uint32_t *addrEn = aShort ? (uint32_t *)RFCORE_XREG_SRCSHORTEN0 : (uint32_t *)RFCORE_XREG_SRCEXTEN0; uint32_t *addrAutoPendEn = aShort ? (uint32_t *)RFCORE_FFSM_SRCSHORTPENDEN0 : (uint32_t *)RFCORE_FFSM_SRCEXTPENDEN0; - uint32_t bitMask = 0x00000001; + uint32_t bitMask = 0x00000001; if (aEnable) { @@ -650,10 +653,10 @@ void setSrcMatchEntryEnableStatus(bool aShort, uint8_t aEntry, bool aEnable) int8_t findSrcMatchAvailEntry(bool aShort) { - int8_t entry = -1; + int8_t entry = -1; uint32_t bitMask; uint32_t shortEnableStatus = getSrcMatchEntriesEnableStatus(true); - uint32_t extEnableStatus = getSrcMatchEntriesEnableStatus(false); + uint32_t extEnableStatus = getSrcMatchEntriesEnableStatus(false); otLogDebgPlat(sInstance, "Short enable status: 0x%x", shortEnableStatus); otLogDebgPlat(sInstance, "Ext enable status: 0x%x", extEnableStatus); @@ -693,7 +696,7 @@ int8_t findSrcMatchAvailEntry(bool aShort) break; } - extEnableStatus = extEnableStatus >> 2; + extEnableStatus = extEnableStatus >> 2; shortEnableStatus = shortEnableStatus >> 2; } } @@ -722,9 +725,9 @@ void otPlatRadioEnableSrcMatch(otInstance *aInstance, bool aEnable) otError otPlatRadioAddSrcMatchShortEntry(otInstance *aInstance, const uint16_t aShortAddress) { - otError error = OT_ERROR_NONE; - int8_t entry = findSrcMatchAvailEntry(true); - uint32_t *addr = (uint32_t *)RFCORE_FFSM_SRCADDRESS_TABLE; + otError error = OT_ERROR_NONE; + int8_t entry = findSrcMatchAvailEntry(true); + uint32_t *addr = (uint32_t *)RFCORE_FFSM_SRCADDRESS_TABLE; (void)aInstance; otLogDebgPlat(sInstance, "Add ShortAddr entry: %d", entry); @@ -746,9 +749,9 @@ exit: otError otPlatRadioAddSrcMatchExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) { - otError error = OT_ERROR_NONE; - int8_t entry = findSrcMatchAvailEntry(false); - uint32_t *addr = (uint32_t *)RFCORE_FFSM_SRCADDRESS_TABLE; + otError error = OT_ERROR_NONE; + int8_t entry = findSrcMatchAvailEntry(false); + uint32_t *addr = (uint32_t *)RFCORE_FFSM_SRCADDRESS_TABLE; (void)aInstance; otLogDebgPlat(sInstance, "Add ExtAddr entry: %d", entry); @@ -771,7 +774,7 @@ exit: otError otPlatRadioClearSrcMatchShortEntry(otInstance *aInstance, const uint16_t aShortAddress) { otError error = OT_ERROR_NONE; - int8_t entry = findSrcMatchShortEntry(aShortAddress); + int8_t entry = findSrcMatchShortEntry(aShortAddress); (void)aInstance; otLogDebgPlat(sInstance, "Clear ShortAddr entry: %d", entry); @@ -787,7 +790,7 @@ exit: otError otPlatRadioClearSrcMatchExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) { otError error = OT_ERROR_NONE; - int8_t entry = findSrcMatchExtEntry(aExtAddress); + int8_t entry = findSrcMatchExtEntry(aExtAddress); (void)aInstance; otLogDebgPlat(sInstance, "Clear ExtAddr entry: %d", entry); @@ -802,7 +805,7 @@ exit: void otPlatRadioClearSrcMatchShortEntries(otInstance *aInstance) { - uint32_t *addrEn = (uint32_t *)RFCORE_XREG_SRCSHORTEN0; + uint32_t *addrEn = (uint32_t *)RFCORE_XREG_SRCSHORTEN0; uint32_t *addrAutoPendEn = (uint32_t *)RFCORE_FFSM_SRCSHORTPENDEN0; (void)aInstance; @@ -810,14 +813,14 @@ void otPlatRadioClearSrcMatchShortEntries(otInstance *aInstance) for (uint8_t i = 0; i < RFCORE_XREG_SRCMATCH_ENABLE_STATUS_SIZE; i++) { - HWREG(addrEn++) = 0; + HWREG(addrEn++) = 0; HWREG(addrAutoPendEn++) = 0; } } void otPlatRadioClearSrcMatchExtEntries(otInstance *aInstance) { - uint32_t *addrEn = (uint32_t *)RFCORE_XREG_SRCEXTEN0; + uint32_t *addrEn = (uint32_t *)RFCORE_XREG_SRCEXTEN0; uint32_t *addrAutoPendEn = (uint32_t *)RFCORE_FFSM_SRCEXTPENDEN0; (void)aInstance; @@ -825,7 +828,7 @@ void otPlatRadioClearSrcMatchExtEntries(otInstance *aInstance) for (uint8_t i = 0; i < RFCORE_XREG_SRCMATCH_ENABLE_STATUS_SIZE; i++) { - HWREG(addrEn++) = 0; + HWREG(addrEn++) = 0; HWREG(addrAutoPendEn++) = 0; } } diff --git a/examples/platforms/cc2538/random.c b/examples/platforms/cc2538/random.c index 0f5c92fc9..be8ef2ea8 100644 --- a/examples/platforms/cc2538/random.c +++ b/examples/platforms/cc2538/random.c @@ -44,12 +44,14 @@ static void generateRandom(uint8_t *aOutput, uint16_t aOutputLength) HWREG(SOC_ADC_ADCCON1) &= ~(SOC_ADC_ADCCON1_RCTRL1 | SOC_ADC_ADCCON1_RCTRL0); HWREG(SYS_CTRL_RCGCRFC) = SYS_CTRL_RCGCRFC_RFC0; - while (HWREG(SYS_CTRL_RCGCRFC) != SYS_CTRL_RCGCRFC_RFC0); + while (HWREG(SYS_CTRL_RCGCRFC) != SYS_CTRL_RCGCRFC_RFC0) + ; HWREG(RFCORE_XREG_FRMCTRL0) = RFCORE_XREG_FRMCTRL0_INFINITY_RX; - HWREG(RFCORE_SFR_RFST) = RFCORE_SFR_RFST_INSTR_RXON; + HWREG(RFCORE_SFR_RFST) = RFCORE_SFR_RFST_INSTR_RXON; - while (!HWREG(RFCORE_XREG_RSSISTAT) & RFCORE_XREG_RSSISTAT_RSSI_VALID); + while (!HWREG(RFCORE_XREG_RSSISTAT) & RFCORE_XREG_RSSISTAT_RSSI_VALID) + ; for (uint16_t index = 0; index < aOutputLength; index++) { @@ -93,7 +95,7 @@ uint32_t otPlatRandomGet(void) otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint8_t channel = 0; otEXPECT_ACTION(aOutput, error = OT_ERROR_INVALID_ARGS); diff --git a/examples/platforms/cc2538/rom-utility.h b/examples/platforms/cc2538/rom-utility.h index 45fc67a92..d0686efde 100644 --- a/examples/platforms/cc2538/rom-utility.h +++ b/examples/platforms/cc2538/rom-utility.h @@ -31,29 +31,29 @@ #define ROM_API_TABLE_ADDR 0x00000048 -typedef uint32_t (* volatile FPTR_CRC32_T)(uint8_t * /*pData*/, uint32_t /*byteCount*/); -typedef uint32_t (* volatile FPTR_GETFLSIZE_T)(void); -typedef uint32_t (* volatile FPTR_GETCHIPID_T)(void); -typedef int32_t (* volatile FPTR_PAGEERASE_T)(uint32_t /*FlashAddr*/, uint32_t /*Size*/); -typedef int32_t (* volatile FPTR_PROGFLASH_T)(uint32_t * /*pRamData*/, uint32_t /*FlashAdr*/, uint32_t /*ByteCount*/); -typedef void (* volatile FPTR_RESETDEV_T)(void); -typedef void *(* volatile FPTR_MEMSET_T)(void * /*s*/, int32_t /*c*/, uint32_t /*n*/); -typedef void *(* volatile FPTR_MEMCPY_T)(void * /*s1*/, const void * /*s2*/, uint32_t /*n*/); -typedef int32_t (* volatile FPTR_MEMCMP_T)(const void * /*s1*/, const void * /*s2*/, uint32_t /*n*/); -typedef void *(* volatile FPTR_MEMMOVE_T)(void * /*s1*/, const void * /*s2*/, uint32_t /*n*/); +typedef uint32_t (*volatile FPTR_CRC32_T)(uint8_t * /*pData*/, uint32_t /*byteCount*/); +typedef uint32_t (*volatile FPTR_GETFLSIZE_T)(void); +typedef uint32_t (*volatile FPTR_GETCHIPID_T)(void); +typedef int32_t (*volatile FPTR_PAGEERASE_T)(uint32_t /*FlashAddr*/, uint32_t /*Size*/); +typedef int32_t (*volatile FPTR_PROGFLASH_T)(uint32_t * /*pRamData*/, uint32_t /*FlashAdr*/, uint32_t /*ByteCount*/); +typedef void (*volatile FPTR_RESETDEV_T)(void); +typedef void *(*volatile FPTR_MEMSET_T)(void * /*s*/, int32_t /*c*/, uint32_t /*n*/); +typedef void *(*volatile FPTR_MEMCPY_T)(void * /*s1*/, const void * /*s2*/, uint32_t /*n*/); +typedef int32_t (*volatile FPTR_MEMCMP_T)(const void * /*s1*/, const void * /*s2*/, uint32_t /*n*/); +typedef void *(*volatile FPTR_MEMMOVE_T)(void * /*s1*/, const void * /*s2*/, uint32_t /*n*/); typedef struct { - FPTR_CRC32_T Crc32; - FPTR_GETFLSIZE_T GetFlashSize; - FPTR_GETCHIPID_T GetChipId; - FPTR_PAGEERASE_T PageErase; - FPTR_PROGFLASH_T ProgramFlash; - FPTR_RESETDEV_T ResetDevice; - FPTR_MEMSET_T memset; - FPTR_MEMCPY_T memcpy; - FPTR_MEMCMP_T memcmp; - FPTR_MEMMOVE_T memmove; + FPTR_CRC32_T Crc32; + FPTR_GETFLSIZE_T GetFlashSize; + FPTR_GETCHIPID_T GetChipId; + FPTR_PAGEERASE_T PageErase; + FPTR_PROGFLASH_T ProgramFlash; + FPTR_RESETDEV_T ResetDevice; + FPTR_MEMSET_T memset; + FPTR_MEMCPY_T memcpy; + FPTR_MEMCMP_T memcmp; + FPTR_MEMMOVE_T memmove; } ROM_API_T; // clang-format off @@ -73,4 +73,4 @@ typedef struct // clang-format on -#endif // ROM_UTILITY_H_ +#endif // ROM_UTILITY_H_ diff --git a/examples/platforms/cc2538/startup-gcc.c b/examples/platforms/cc2538/startup-gcc.c index 3f1fc174e..6c028da11 100644 --- a/examples/platforms/cc2538/startup-gcc.c +++ b/examples/platforms/cc2538/startup-gcc.c @@ -46,13 +46,26 @@ extern uint8_t _einit_array; __extension__ typedef int __guard __attribute__((mode(__DI__))); -int __cxa_guard_acquire(__guard *g) { return !*(char *)(g); } +int __cxa_guard_acquire(__guard *g) +{ + return !*(char *)(g); +} -void __cxa_guard_release(__guard *g) { *(char *)g = 1; } +void __cxa_guard_release(__guard *g) +{ + *(char *)g = 1; +} -void __cxa_guard_abort(__guard *g) { (void)g; } +void __cxa_guard_abort(__guard *g) +{ + (void)g; +} -void __cxa_pure_virtual(void) { while (1); } +void __cxa_pure_virtual(void) +{ + while (1) + ; +} void IntDefaultHandler(void); void ResetHandler(void); @@ -65,81 +78,80 @@ extern void main(void); static uint64_t stack[512] __attribute__((section(".stack"))); -__attribute__((section(".vectors"), used)) -void (*const vectors[])(void) = -{ - (void (*)(void))((unsigned long)stack + sizeof(stack)), // Initial Stack Pointer - ResetHandler, // 1 The reset handler - ResetHandler, // 2 The NMI handler - IntDefaultHandler, // 3 The hard fault handler - IntDefaultHandler, // 4 The MPU fault handler - IntDefaultHandler, // 5 The bus fault handler - IntDefaultHandler, // 6 The usage fault handler - 0, // 7 Reserved - 0, // 8 Reserved - 0, // 9 Reserved - 0, // 10 Reserved - IntDefaultHandler, // 11 SVCall handler - IntDefaultHandler, // 12 Debug monitor handler - 0, // 13 Reserved - IntDefaultHandler, // 14 The PendSV handler - SysTick_Handler, // 15 The SysTick handler - IntDefaultHandler, // 16 GPIO Port A - IntDefaultHandler, // 17 GPIO Port B - IntDefaultHandler, // 18 GPIO Port C - IntDefaultHandler, // 19 GPIO Port D - 0, // 20 none - UART0IntHandler, // 21 UART0 Rx and Tx - IntDefaultHandler, // 22 UART1 Rx and Tx - IntDefaultHandler, // 23 SSI0 Rx and Tx - IntDefaultHandler, // 24 I2C Master and Slave - 0, // 25 Reserved - 0, // 26 Reserved - 0, // 27 Reserved - 0, // 28 Reserved - 0, // 29 Reserved - IntDefaultHandler, // 30 ADC Sequence 0 - 0, // 31 Reserved - 0, // 32 Reserved - 0, // 33 Reserved - IntDefaultHandler, // 34 Watchdog timer, timer 0 - IntDefaultHandler, // 35 Timer 0 subtimer A - IntDefaultHandler, // 36 Timer 0 subtimer B - IntDefaultHandler, // 37 Timer 1 subtimer A - IntDefaultHandler, // 38 Timer 1 subtimer B - IntDefaultHandler, // 39 Timer 2 subtimer A - IntDefaultHandler, // 40 Timer 2 subtimer B - IntDefaultHandler, // 41 Analog Comparator 0 - RFCoreRxTxIntHandler, // 42 RFCore Rx/Tx - RFCoreErrIntHandler, // 43 RFCore Error - IntDefaultHandler, // 44 IcePick - IntDefaultHandler, // 45 FLASH Control - IntDefaultHandler, // 46 AES - IntDefaultHandler, // 47 PKA - IntDefaultHandler, // 48 Sleep Timer - IntDefaultHandler, // 49 MacTimer - IntDefaultHandler, // 50 SSI1 Rx and Tx - IntDefaultHandler, // 51 Timer 3 subtimer A - IntDefaultHandler, // 52 Timer 3 subtimer B - 0, // 53 Reserved - 0, // 54 Reserved - 0, // 55 Reserved - 0, // 56 Reserved - 0, // 57 Reserved - 0, // 58 Reserved - 0, // 59 Reserved - IntDefaultHandler, // 60 USB 2538 - 0, // 61 Reserved - IntDefaultHandler, // 62 uDMA - IntDefaultHandler, // 63 uDMA Error +__attribute__((section(".vectors"), used)) void (*const vectors[])(void) = { + (void (*)(void))((unsigned long)stack + sizeof(stack)), // Initial Stack Pointer + ResetHandler, // 1 The reset handler + ResetHandler, // 2 The NMI handler + IntDefaultHandler, // 3 The hard fault handler + IntDefaultHandler, // 4 The MPU fault handler + IntDefaultHandler, // 5 The bus fault handler + IntDefaultHandler, // 6 The usage fault handler + 0, // 7 Reserved + 0, // 8 Reserved + 0, // 9 Reserved + 0, // 10 Reserved + IntDefaultHandler, // 11 SVCall handler + IntDefaultHandler, // 12 Debug monitor handler + 0, // 13 Reserved + IntDefaultHandler, // 14 The PendSV handler + SysTick_Handler, // 15 The SysTick handler + IntDefaultHandler, // 16 GPIO Port A + IntDefaultHandler, // 17 GPIO Port B + IntDefaultHandler, // 18 GPIO Port C + IntDefaultHandler, // 19 GPIO Port D + 0, // 20 none + UART0IntHandler, // 21 UART0 Rx and Tx + IntDefaultHandler, // 22 UART1 Rx and Tx + IntDefaultHandler, // 23 SSI0 Rx and Tx + IntDefaultHandler, // 24 I2C Master and Slave + 0, // 25 Reserved + 0, // 26 Reserved + 0, // 27 Reserved + 0, // 28 Reserved + 0, // 29 Reserved + IntDefaultHandler, // 30 ADC Sequence 0 + 0, // 31 Reserved + 0, // 32 Reserved + 0, // 33 Reserved + IntDefaultHandler, // 34 Watchdog timer, timer 0 + IntDefaultHandler, // 35 Timer 0 subtimer A + IntDefaultHandler, // 36 Timer 0 subtimer B + IntDefaultHandler, // 37 Timer 1 subtimer A + IntDefaultHandler, // 38 Timer 1 subtimer B + IntDefaultHandler, // 39 Timer 2 subtimer A + IntDefaultHandler, // 40 Timer 2 subtimer B + IntDefaultHandler, // 41 Analog Comparator 0 + RFCoreRxTxIntHandler, // 42 RFCore Rx/Tx + RFCoreErrIntHandler, // 43 RFCore Error + IntDefaultHandler, // 44 IcePick + IntDefaultHandler, // 45 FLASH Control + IntDefaultHandler, // 46 AES + IntDefaultHandler, // 47 PKA + IntDefaultHandler, // 48 Sleep Timer + IntDefaultHandler, // 49 MacTimer + IntDefaultHandler, // 50 SSI1 Rx and Tx + IntDefaultHandler, // 51 Timer 3 subtimer A + IntDefaultHandler, // 52 Timer 3 subtimer B + 0, // 53 Reserved + 0, // 54 Reserved + 0, // 55 Reserved + 0, // 56 Reserved + 0, // 57 Reserved + 0, // 58 Reserved + 0, // 59 Reserved + IntDefaultHandler, // 60 USB 2538 + 0, // 61 Reserved + IntDefaultHandler, // 62 uDMA + IntDefaultHandler, // 63 uDMA Error }; void IntDefaultHandler(void) { - while (1); + while (1) + ; } -// clang-format off + // clang-format off #define FLASH_CCA_BOOTLDR_CFG_DISABLE 0xEFFFFFFF ///< Disable backdoor function #define FLASH_CCA_BOOTLDR_CFG_ENABLE 0xF0FFFFFF ///< Enable backdoor function @@ -160,19 +172,12 @@ typedef struct uint8_t ui8lock[32]; } flash_cca_lock_page_t; -__attribute__((__section__(".flashcca"), used)) -const flash_cca_lock_page_t flash_cca_lock_page = -{ +__attribute__((__section__(".flashcca"), used)) const flash_cca_lock_page_t flash_cca_lock_page = { FLASH_CCA_BOOTLDR_CFG_ENABLE | (FLASH_CCA_CONF_BOOTLDR_BACKDOOR_PORT_A_PIN << FLASH_CCA_BOOTLDR_CFG_PORT_A_PIN_S), FLASH_CCA_IMAGE_VALID, - (uint32_t) &vectors, - { - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF - } -}; + (uint32_t)&vectors, + {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}; typedef void (*init_fn_t)(void); @@ -205,5 +210,6 @@ void ResetHandler(void) main(); // end here if main() returns - while (1); + while (1) + ; } diff --git a/examples/platforms/cc2538/uart.c b/examples/platforms/cc2538/uart.c index 776b40ca1..bf024bec1 100644 --- a/examples/platforms/cc2538/uart.c +++ b/examples/platforms/cc2538/uart.c @@ -32,25 +32,25 @@ * */ -#include #include +#include #include -#include #include +#include #include #include -#include #include +#include #include "platform-cc2538.h" #include "utils/code_utils.h" enum { - kPlatformClock = 32000000, - kBaudRate = 115200, + kPlatformClock = 32000000, + kBaudRate = 115200, kReceiveBufferSize = 128, }; @@ -60,7 +60,7 @@ static void processReceive(void); static void processTransmit(void); static const uint8_t *sTransmitBuffer = NULL; -static uint16_t sTransmitLength = 0; +static uint16_t sTransmitLength = 0; typedef struct RecvBuffer { @@ -109,19 +109,19 @@ otError otPlatUartEnable(void) HWREG(UART0_BASE + UART_O_CC) = 0; // tx pin - HWREG(IOC_PA1_SEL) = IOC_MUX_OUT_SEL_UART0_TXD; + HWREG(IOC_PA1_SEL) = IOC_MUX_OUT_SEL_UART0_TXD; HWREG(IOC_PA1_OVER) = IOC_OVERRIDE_OE; HWREG(GPIO_A_BASE + GPIO_O_AFSEL) |= GPIO_PIN_1; // rx pin - HWREG(IOC_PA0_SEL) = IOC_UARTRXD_UART0; + HWREG(IOC_PA0_SEL) = IOC_UARTRXD_UART0; HWREG(IOC_PA0_OVER) = IOC_OVERRIDE_DIS; HWREG(GPIO_A_BASE + GPIO_O_AFSEL) |= GPIO_PIN_0; HWREG(UART0_BASE + UART_O_CTL) = 0; // baud rate - div = (((kPlatformClock * 8) / kBaudRate) + 1) / 2; + div = (((kPlatformClock * 8) / kBaudRate) + 1) / 2; HWREG(UART0_BASE + UART_O_IBRD) = div / 64; HWREG(UART0_BASE + UART_O_FBRD) = div % 64; HWREG(UART0_BASE + UART_O_LCRH) = UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE | UART_CONFIG_PAR_NONE; @@ -186,7 +186,8 @@ void processTransmit(void) for (; sTransmitLength > 0; sTransmitLength--) { - while (HWREG(UART0_BASE + UART_O_FR) & UART_FR_TXFF); + while (HWREG(UART0_BASE + UART_O_FR) & UART_FR_TXFF) + ; HWREG(UART0_BASE + UART_O_DR) = *sTransmitBuffer++; } @@ -207,9 +208,9 @@ void cc2538UartProcess(void) void UART0IntHandler(void) { uint32_t mis; - uint8_t byte; + uint8_t byte; - mis = HWREG(UART0_BASE + UART_O_MIS); + mis = HWREG(UART0_BASE + UART_O_MIS); HWREG(UART0_BASE + UART_O_ICR) = mis; if (mis & (UART_IM_RXIM | UART_IM_RTIM)) @@ -222,7 +223,7 @@ void UART0IntHandler(void) if (sReceive.mHead != (sReceive.mTail + 1) % kReceiveBufferSize) { sReceive.mBuffer[sReceive.mTail] = byte; - sReceive.mTail = (sReceive.mTail + 1) % kReceiveBufferSize; + sReceive.mTail = (sReceive.mTail + 1) % kReceiveBufferSize; } } } @@ -260,13 +261,13 @@ int otPlatDebugUart_getc(void) void otPlatDebugUart_putchar_raw(int b) { /* wait till not busy */ - while (HWREG(UART1_BASE + UART_O_FR) & UART_FR_TXFF); + while (HWREG(UART1_BASE + UART_O_FR) & UART_FR_TXFF) + ; /* write byte */ HWREG(UART1_BASE + UART_O_DR) = ((uint32_t)(b & 0x0ff)); } - void cc2538DebugUartInit(void) { int32_t a, b; @@ -281,13 +282,13 @@ void cc2538DebugUartInit(void) // http://www.ti.com/tool/cc2538dk // PA3 => is jumper position RF1.14 // To use these, you will require a "flying-lead" UART adapter - HWREG(IOC_PA3_SEL) = IOC_MUX_OUT_SEL_UART1_TXD; + HWREG(IOC_PA3_SEL) = IOC_MUX_OUT_SEL_UART1_TXD; HWREG(IOC_PA3_OVER) = IOC_OVERRIDE_OE; HWREG(GPIO_A_BASE + GPIO_O_AFSEL) |= GPIO_PIN_3; // UART1 - rx pin we don't really use but we setup anyway // PA2 => is jumper position RF1.16 - HWREG(IOC_PA2_SEL) = IOC_UARTRXD_UART1; + HWREG(IOC_PA2_SEL) = IOC_UARTRXD_UART1; HWREG(IOC_PA2_OVER) = IOC_OVERRIDE_DIS; HWREG(GPIO_A_BASE + GPIO_O_AFSEL) |= GPIO_PIN_2; diff --git a/examples/platforms/cc2650/alarm.c b/examples/platforms/cc2650/alarm.c index f44650056..d3ce3b3f6 100644 --- a/examples/platforms/cc2650/alarm.c +++ b/examples/platforms/cc2650/alarm.c @@ -26,10 +26,10 @@ * POSSIBILITY OF SUCH DAMAGE. */ +#include #include #include #include -#include #include #include @@ -75,7 +75,7 @@ uint32_t otPlatAlarmMilliGetNow(void) void otPlatAlarmMilliStartAt(otInstance *aInstance, uint32_t aT0, uint32_t aDt) { (void)aInstance; - sTime0 = aT0; + sTime0 = aT0; sAlarmTime = aDt; sIsRunning = true; } @@ -118,4 +118,3 @@ void cc2650AlarmProcess(otInstance *aInstance) } } } - diff --git a/examples/platforms/cc2650/cc2650_startup.c b/examples/platforms/cc2650/cc2650_startup.c index d580a3869..17ac72965 100644 --- a/examples/platforms/cc2650/cc2650_startup.c +++ b/examples/platforms/cc2650/cc2650_startup.c @@ -37,4 +37,3 @@ #else #error "Unknown compiler" #endif - diff --git a/examples/platforms/cc2650/crypto/aes_alt.c b/examples/platforms/cc2650/crypto/aes_alt.c index d9994ca4d..9d88b0836 100644 --- a/examples/platforms/cc2650/crypto/aes_alt.c +++ b/examples/platforms/cc2650/crypto/aes_alt.c @@ -26,18 +26,18 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include "mbedtls/aes.h" #include "aes_alt.h" +#include "mbedtls/aes.h" #ifdef MBEDTLS_AES_ALT -#include #include #include +#include #include #define CC2650_AES_KEY_UNUSED (-1) -#define CC2650_AES_CTX_MAGIC (0x7E) +#define CC2650_AES_CTX_MAGIC (0x7E) /** * bitmap of which key stores are currently used @@ -66,11 +66,11 @@ void mbedtls_aes_init(mbedtls_aes_context *ctx) PRCMPeripheralDeepSleepEnable(PRCM_PERIPH_CRYPTO); PRCMLoadSet(); - while (!PRCMLoadGet()); - + while (!PRCMLoadGet()) + ; } - ctx->magic = CC2650_AES_CTX_MAGIC; + ctx->magic = CC2650_AES_CTX_MAGIC; ctx->key_idx = CC2650_AES_KEY_UNUSED; } @@ -98,8 +98,8 @@ void mbedtls_aes_free(mbedtls_aes_context *ctx) PRCMPeripheralDeepSleepDisable(PRCM_PERIPH_CRYPTO); PRCMLoadSet(); - while (!PRCMLoadGet()); - + while (!PRCMLoadGet()) + ; } memset((void *)ctx, 0x00, sizeof(ctx)); @@ -111,7 +111,7 @@ exit: int mbedtls_aes_setkey_enc(mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits) { unsigned char key_idx; - int retval = 0; + int retval = 0; otEXPECT_ACTION(ctx->magic == CC2650_AES_CTX_MAGIC, retval = -1); @@ -123,7 +123,8 @@ int mbedtls_aes_setkey_enc(mbedtls_aes_context *ctx, const unsigned char *key, u /* our hardware only supports 128 bit keys */ otEXPECT_ACTION(keybits == 128u, retval = MBEDTLS_ERR_AES_INVALID_KEY_LENGTH); - for (key_idx = 0; ((sUsedKeys >> key_idx) & 0x01) != 0 && key_idx < 8; key_idx++); + for (key_idx = 0; ((sUsedKeys >> key_idx) & 0x01) != 0 && key_idx < 8; key_idx++) + ; /* we have no more room for this key */ otEXPECT_ACTION(key_idx < 8, retval = -2); @@ -140,7 +141,7 @@ exit: int mbedtls_aes_setkey_dec(mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits) { unsigned char key_idx; - int retval = 0; + int retval = 0; otEXPECT_ACTION(ctx->magic == CC2650_AES_CTX_MAGIC, retval = -1); @@ -152,7 +153,8 @@ int mbedtls_aes_setkey_dec(mbedtls_aes_context *ctx, const unsigned char *key, u /* our hardware only supports 128 bit keys */ otEXPECT_ACTION(keybits == 128u, retval = MBEDTLS_ERR_AES_INVALID_KEY_LENGTH); - for (key_idx = 0; ((sUsedKeys >> key_idx) & 0x01) != 0 && key_idx < 8; key_idx++); + for (key_idx = 0; ((sUsedKeys >> key_idx) & 0x01) != 0 && key_idx < 8; key_idx++) + ; /* we have no more room for this key */ otEXPECT_ACTION(key_idx < 8, retval = -2); @@ -183,7 +185,8 @@ int mbedtls_aes_crypt_ecb(mbedtls_aes_context *ctx, int mode, const unsigned cha retval = CRYPTOAesEcb((uint32_t *)input, (uint32_t *)output, ctx->key_idx, mode == MBEDTLS_AES_ENCRYPT, false); otEXPECT(retval == AES_SUCCESS); - while ((retval = CRYPTOAesEcbStatus()) == AES_DMA_BSY); + while ((retval = CRYPTOAesEcbStatus()) == AES_DMA_BSY) + ; CRYPTOAesEcbFinish(); diff --git a/examples/platforms/cc2650/crypto/sha256_alt.c b/examples/platforms/cc2650/crypto/sha256_alt.c index 1f3e794bc..e4c56b455 100644 --- a/examples/platforms/cc2650/crypto/sha256_alt.c +++ b/examples/platforms/cc2650/crypto/sha256_alt.c @@ -106,7 +106,7 @@ void mbedtls_sha256_finish(mbedtls_sha256_context *ctx, unsigned char output[32] * Make a 64byte buffer on the stack.. * And force the compiler to think it requires this buffer. */ - char buffer[ 64 ]; + char buffer[64]; workaround_cc2650_rom = &buffer[0]; SHA256_output(ctx, (uint8_t *)output); return; diff --git a/examples/platforms/cc2650/cxx_helpers.c b/examples/platforms/cc2650/cxx_helpers.c index 05faf5ab8..d4b003662 100644 --- a/examples/platforms/cc2650/cxx_helpers.c +++ b/examples/platforms/cc2650/cxx_helpers.c @@ -49,6 +49,6 @@ void __cxa_guard_abort(__guard *g) void __cxa_pure_virtual(void) { - while (1); + while (1) + ; } - diff --git a/examples/platforms/cc2650/logging.c b/examples/platforms/cc2650/logging.c index 5a282d335..0cbb7792f 100644 --- a/examples/platforms/cc2650/logging.c +++ b/examples/platforms/cc2650/logging.c @@ -27,15 +27,15 @@ */ /** -* @file logging.c -* Platform abstraction for the logging -* -*/ -#include + * @file logging.c + * Platform abstraction for the logging + * + */ #include +#include #include -#if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED) +#if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED) void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat, ...) { (void)aLogLevel; @@ -43,4 +43,3 @@ void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat (void)aFormat; } #endif - diff --git a/examples/platforms/cc2650/misc.c b/examples/platforms/cc2650/misc.c index cf204f39a..69f5f4a44 100644 --- a/examples/platforms/cc2650/misc.c +++ b/examples/platforms/cc2650/misc.c @@ -26,9 +26,9 @@ * POSSIBILITY OF SUCH DAMAGE. */ +#include #include #include -#include /** * Function documented in platform/misc.h diff --git a/examples/platforms/cc2650/platform-cc2650.h b/examples/platforms/cc2650/platform-cc2650.h index 696d165cf..ed3a098fb 100644 --- a/examples/platforms/cc2650/platform-cc2650.h +++ b/examples/platforms/cc2650/platform-cc2650.h @@ -29,9 +29,9 @@ #ifndef PLATFORM_H_ #define PLATFORM_H_ -#include #include #include +#include #include "openthread/types.h" #ifdef __cplusplus @@ -78,7 +78,7 @@ void cc2650RandomInit(void); void cc2650UartProcess(void); #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // PLATFORM_H_ +#endif // PLATFORM_H_ diff --git a/examples/platforms/cc2650/platform.c b/examples/platforms/cc2650/platform.c index aec5bff6b..f2aa8c05b 100644 --- a/examples/platforms/cc2650/platform.c +++ b/examples/platforms/cc2650/platform.c @@ -26,9 +26,9 @@ * POSSIBILITY OF SUCH DAMAGE. */ +#include "platform-cc2650.h" #include #include -#include "platform-cc2650.h" #include "inc/hw_ccfg_simple_struct.h" extern const ccfg_t __ccfg; @@ -40,16 +40,16 @@ void *dummy_ccfg_ref = ((void *)(&(__ccfg))); */ void PlatformInit(int argc, char *argv[]) { - (void) argc; - (void) argv; + (void)argc; + (void)argv; while (dummy_ccfg_ref == NULL) { /* - * This provides a code reference to the customer configuration - * area of the flash, otherwise the data is skipped by the - * linker and not put into the final flash image. - */ + * This provides a code reference to the customer configuration + * area of the flash, otherwise the data is skipped by the + * linker and not put into the final flash image. + */ } cc2650AlarmInit(); diff --git a/examples/platforms/cc2650/radio.c b/examples/platforms/cc2650/radio.c index c8a5a9e45..62fb15413 100644 --- a/examples/platforms/cc2650/radio.c +++ b/examples/platforms/cc2650/radio.c @@ -28,30 +28,30 @@ #include +#include "cc2650_radio.h" #include #include -#include "cc2650_radio.h" #include #include #include /* to seed the CSMA-CA funciton */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include enum { - CC2650_RECEIVE_SENSITIVITY = -100, // dBm + CC2650_RECEIVE_SENSITIVITY = -100, // dBm }; /* phy state as defined by openthread */ @@ -60,8 +60,7 @@ static volatile cc2650_PhyState sState; static output_config_t const *sCurrentOutputPower = &(rgOutputPower[OUTPUT_CONFIG_COUNT - 1]); /* Overrides for IEEE 802.15.4, differential mode */ -static uint32_t sIEEEOverrides[] = -{ +static uint32_t sIEEEOverrides[] = { 0x00354038, /* Synth: Set RTRIM (POTAILRESTRIM) to 5 */ 0x4001402D, /* Synth: Correct CKVD latency setting (address) */ 0x00608402, /* Synth: Correct CKVD latency setting (value) */ @@ -129,11 +128,11 @@ static uint8_t sRxBuf0[RX_BUF_SIZE] __attribute__((aligned(4))); static uint8_t sRxBuf1[RX_BUF_SIZE] __attribute__((aligned(4))); /* The RX Data Queue */ -static dataQueue_t sRxDataQueue = { 0 }; +static dataQueue_t sRxDataQueue = {0}; /* openthread data primatives */ static otRadioFrame sTransmitFrame; -static otError sTransmitError; +static otError sTransmitError; static __attribute__((aligned(4))) uint8_t sTransmitPsdu[OT_RADIO_FRAME_MAX_SIZE]; @@ -297,7 +296,7 @@ static uint_fast8_t rfCoreClearReceiveQueue(dataQueue_t *aQueue) { /* memset skipped because sClearReceiveQueueCmd has only 2 members and padding */ sClearReceiveQueueCmd.commandNo = CMD_CLEAR_RX; - sClearReceiveQueueCmd.pQueue = aQueue; + sClearReceiveQueueCmd.pQueue = aQueue; return (RFCDoorbellSendTo((uint32_t)&sClearReceiveQueueCmd) & 0xFF); } @@ -412,7 +411,7 @@ static uint_fast8_t rfCoreModifySourceMatchEntry(uint8_t aEntryNo, cc2650_addres } sModifyReceiveSrcMatchCmd.options.entryType = aType; - sModifyReceiveSrcMatchCmd.entryNo = aEntryNo; + sModifyReceiveSrcMatchCmd.entryNo = aEntryNo; return (RFCDoorbellSendTo((uint32_t)&sModifyReceiveSrcMatchCmd) & 0xFF); } @@ -595,24 +594,24 @@ static uint_fast8_t rfCoreSendTransmitCmd(uint8_t *aPsdu, uint8_t aLen) /* reset retry count */ sTransmitRetryCount = 0; - sCsmacaBackoffCmd = cCsmacaBackoffCmd; + sCsmacaBackoffCmd = cCsmacaBackoffCmd; /* initialize the random state with a true random seed for the radio core's * psudo rng */ - sCsmacaBackoffCmd.randomState = otPlatRandomGet(); - sCsmacaBackoffCmd.pNextOp = (rfc_radioOp_t *) &sTransmitCmd; + sCsmacaBackoffCmd.randomState = otPlatRandomGet(); + sCsmacaBackoffCmd.pNextOp = (rfc_radioOp_t *)&sTransmitCmd; sTransmitCmd = cTransmitCmd; /* no need to look for an ack if the tx operation was stopped */ sTransmitCmd.payloadLen = aLen; - sTransmitCmd.pPayload = aPsdu; + sTransmitCmd.pPayload = aPsdu; if (aPsdu[0] & IEEE802154_ACK_REQUEST) { /* setup the receive ack command to follow the tx command */ sTransmitCmd.condition.rule = COND_STOP_ON_FALSE; - sTransmitCmd.pNextOp = (rfc_radioOp_t *) &sTransmitRxAckCmd; + sTransmitCmd.pNextOp = (rfc_radioOp_t *)&sTransmitRxAckCmd; - sTransmitRxAckCmd = cTransmitRxAckCmd; + sTransmitRxAckCmd = cTransmitRxAckCmd; sTransmitRxAckCmd.seqNo = aPsdu[IEEE802154_DSN_OFFSET]; } @@ -816,12 +815,14 @@ static uint_fast8_t rfCorePowerOn(void) /* Enable RF Core power domain */ PRCMPowerDomainOn(PRCM_DOMAIN_RFCORE); - while (PRCMPowerDomainStatus(PRCM_DOMAIN_RFCORE) != PRCM_DOMAIN_POWER_ON); + while (PRCMPowerDomainStatus(PRCM_DOMAIN_RFCORE) != PRCM_DOMAIN_POWER_ON) + ; PRCMDomainEnable(PRCM_DOMAIN_RFCORE); PRCMLoadSet(); - while (!PRCMLoadGet()); + while (!PRCMLoadGet()) + ; rfCoreSetupInt(); @@ -831,8 +832,8 @@ static uint_fast8_t rfCorePowerOn(void) } /* Let CPE boot */ - HWREG(RFC_PWR_NONBUF_BASE + RFC_PWR_O_PWMCLKEN) = (RFC_PWR_PWMCLKEN_RFC_M | RFC_PWR_PWMCLKEN_CPE_M | - RFC_PWR_PWMCLKEN_CPERAM_M); + HWREG(RFC_PWR_NONBUF_BASE + RFC_PWR_O_PWMCLKEN) = + (RFC_PWR_PWMCLKEN_RFC_M | RFC_PWR_PWMCLKEN_CPE_M | RFC_PWR_PWMCLKEN_CPERAM_M); /* Send ping (to verify RFCore is ready and alive) */ return rfCoreExecutePingCmd(); @@ -854,11 +855,13 @@ static void rfCorePowerOff(void) PRCMDomainDisable(PRCM_DOMAIN_RFCORE); PRCMLoadSet(); - while (!PRCMLoadGet()); + while (!PRCMLoadGet()) + ; PRCMPowerDomainOff(PRCM_DOMAIN_RFCORE); - while (PRCMPowerDomainStatus(PRCM_DOMAIN_RFCORE) != PRCM_DOMAIN_POWER_OFF); + while (PRCMPowerDomainStatus(PRCM_DOMAIN_RFCORE) != PRCM_DOMAIN_POWER_OFF) + ; if (OSCClockSourceGet(OSC_SRC_CLK_HF) != OSC_RCOSC_HF) { @@ -914,11 +917,11 @@ static uint_fast16_t rfCoreSendEnableCmd(void) /* initialize the rat start command */ sStartRatCmd = cStartRatCmd; - sStartRatCmd.pNextOp = (rfc_radioOp_t *) &sRadioSetupCmd; + sStartRatCmd.pNextOp = (rfc_radioOp_t *)&sRadioSetupCmd; sStartRatCmd.rat0 = sRatOffset; /* initialize radio setup command */ - sRadioSetupCmd = cRadioSetupCmd; + sRadioSetupCmd = cRadioSetupCmd; /* initally set the radio tx power to the max */ sRadioSetupCmd.txPower = sCurrentOutputPower->value; sRadioSetupCmd.pRegOverride = sIEEEOverrides; @@ -929,7 +932,8 @@ static uint_fast16_t rfCoreSendEnableCmd(void) otEXPECT_ACTION(CMDSTA_Done == doorbellRet, ret = doorbellRet); /* synchronously wait for the CM0 to stop executing */ - while ((HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) & IRQ_LAST_COMMAND_DONE) == 0x00); + while ((HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) & IRQ_LAST_COMMAND_DONE) == 0x00) + ; ret = sRadioSetupCmd.status; @@ -987,7 +991,7 @@ static uint_fast16_t rfCoreSendDisableCmd(void) HWREGBITW(AON_RTC_BASE + AON_RTC_O_CTL, AON_RTC_CTL_RTC_UPD_EN_BITN) = 1; /* initialize the command to power down the frequency synth */ - sFsPowerdownCmd = cFsPowerdownCmd; + sFsPowerdownCmd = cFsPowerdownCmd; sFsPowerdownCmd.pNextOp = (rfc_radioOp_t *)&sStopRatCmd; sStopRatCmd = cStopRatCmd; @@ -999,9 +1003,9 @@ static uint_fast16_t rfCoreSendDisableCmd(void) doorbellRet = (RFCDoorbellSendTo((uint32_t)&sFsPowerdownCmd) & 0xFF); otEXPECT_ACTION(CMDSTA_Done == doorbellRet, ret = doorbellRet); - /* synchronously wait for the CM0 to stop */ - while ((HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) & IRQ_LAST_COMMAND_DONE) == 0x00); + while ((HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) & IRQ_LAST_COMMAND_DONE) == 0x00) + ; ret = sStopRatCmd.status; @@ -1038,9 +1042,7 @@ void RFCCPE0IntHandler(void) { HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) = ~IRQ_LAST_COMMAND_DONE; - if (sState == cc2650_stateReceive && - sReceiveCmd.status != ACTIVE && - sReceiveCmd.status != IEEE_SUSPENDED) + if (sState == cc2650_stateReceive && sReceiveCmd.status != ACTIVE && sReceiveCmd.status != IEEE_SUSPENDED) { /* the rx command was probably aborted to change the channel */ sState = cc2650_stateSleep; @@ -1203,7 +1205,7 @@ otError otPlatRadioDisable(otInstance *aInstance) */ rfCorePowerOff(); sState = cc2650_stateDisabled; - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; } return error; @@ -1248,7 +1250,7 @@ exit: */ otError otPlatRadioSetTransmitPower(otInstance *aInstance, int8_t aPower) { - unsigned int i; + unsigned int i; output_config_t const *powerCfg = &(rgOutputPower[0]); (void)aInstance; @@ -1295,7 +1297,7 @@ otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) { /* we are already running on the right channel */ sState = cc2650_stateReceive; - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; } else { @@ -1312,7 +1314,7 @@ otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) otEXPECT_ACTION(rfCoreSendReceiveCmd() == CMDSTA_Done, error = OT_ERROR_FAILED); sState = cc2650_stateReceive; - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; } } @@ -1370,8 +1372,8 @@ otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aFrame) /* removing 2 bytes of CRC placeholder because we generate that in hardware */ otEXPECT_ACTION(rfCoreSendTransmitCmd(aFrame->mPsdu, aFrame->mLength - 2) == CMDSTA_Done, error = OT_ERROR_FAILED); - error = OT_ERROR_NONE; - sTransmitError = OT_ERROR_NONE; + error = OT_ERROR_NONE; + sTransmitError = OT_ERROR_NONE; sTxCmdChainDone = false; otPlatRadioTxStarted(aInstance, aFrame); } @@ -1429,17 +1431,15 @@ otError otPlatRadioAddSrcMatchShortEntry(otInstance *aInstance, const uint16_t a if (idx == CC2650_SRC_MATCH_NONE) { /* the entry does not exist already, add it */ - otEXPECT_ACTION((idx = rfCoreFindEmptyShortSrcMatchIdx()) != CC2650_SRC_MATCH_NONE, - error = OT_ERROR_NO_BUFS); + otEXPECT_ACTION((idx = rfCoreFindEmptyShortSrcMatchIdx()) != CC2650_SRC_MATCH_NONE, error = OT_ERROR_NO_BUFS); sSrcMatchShortData.extAddrEnt[idx].shortAddr = aShortAddress; - sSrcMatchShortData.extAddrEnt[idx].panId = sReceiveCmd.localPanID; + sSrcMatchShortData.extAddrEnt[idx].panId = sReceiveCmd.localPanID; } if (sReceiveCmd.status == ACTIVE || sReceiveCmd.status == IEEE_SUSPENDED) { /* we have a running or backgrounded rx command */ - otEXPECT_ACTION(rfCoreModifySourceMatchEntry(idx, SHORT_ADDRESS, true) == CMDSTA_Done, - error = OT_ERROR_FAILED); + otEXPECT_ACTION(rfCoreModifySourceMatchEntry(idx, SHORT_ADDRESS, true) == CMDSTA_Done, error = OT_ERROR_FAILED); } else { @@ -1499,8 +1499,7 @@ otError otPlatRadioAddSrcMatchExtEntry(otInstance *aInstance, const otExtAddress if (sReceiveCmd.status == ACTIVE || sReceiveCmd.status == IEEE_SUSPENDED) { /* we have a running or backgrounded rx command */ - otEXPECT_ACTION(rfCoreModifySourceMatchEntry(idx, EXT_ADDRESS, true) == CMDSTA_Done, - error = OT_ERROR_FAILED); + otEXPECT_ACTION(rfCoreModifySourceMatchEntry(idx, EXT_ADDRESS, true) == CMDSTA_Done, error = OT_ERROR_FAILED); } else { @@ -1527,13 +1526,12 @@ otError otPlatRadioClearSrcMatchExtEntry(otInstance *aInstance, const otExtAddre if (sReceiveCmd.status == ACTIVE || sReceiveCmd.status == IEEE_SUSPENDED) { /* we have a running or backgrounded rx command */ - otEXPECT_ACTION(rfCoreModifySourceMatchEntry(idx, EXT_ADDRESS, false) == CMDSTA_Done, - error = OT_ERROR_FAILED); + otEXPECT_ACTION(rfCoreModifySourceMatchEntry(idx, EXT_ADDRESS, false) == CMDSTA_Done, error = OT_ERROR_FAILED); } else { /* we are not running, so we must update the values ourselves */ - sSrcMatchExtData.srcPendEn[idx] = 0u; + sSrcMatchExtData.srcPendEn[idx] = 0u; sSrcMatchExtData.srcMatchEn[idx] = 0u; sSrcMatchExtData.srcPendEn[idx / 32] &= ~(1 << (idx % 32)); sSrcMatchExtData.srcMatchEn[idx / 32] &= ~(1 << (idx % 32)); @@ -1544,8 +1542,8 @@ exit: } /** -* Function documented in platform/radio.h -*/ + * Function documented in platform/radio.h + */ void otPlatRadioClearSrcMatchShortEntries(otInstance *aInstance) { (void)aInstance; @@ -1571,8 +1569,8 @@ exit: } /** -* Function documented in platform/radio.h -*/ + * Function documented in platform/radio.h + */ void otPlatRadioClearSrcMatchExtEntries(otInstance *aInstance) { (void)aInstance; @@ -1633,7 +1631,7 @@ void otPlatRadioSetPromiscuous(otInstance *aInstance, bool aEnable) */ void otPlatRadioGetIeeeEui64(otInstance *aInstance, uint8_t *aIeeeEui64) { - uint8_t *eui64; + uint8_t * eui64; unsigned int i; (void)aInstance; @@ -1762,8 +1760,10 @@ exit: return; } -static void cc2650RadioProcessTransmitDone(otInstance *aInstance, otRadioFrame *aTransmitFrame, otRadioFrame *aAckFrame, - otError aTransmitError) +static void cc2650RadioProcessTransmitDone(otInstance * aInstance, + otRadioFrame *aTransmitFrame, + otRadioFrame *aAckFrame, + otError aTransmitError) { #if OPENTHREAD_ENABLE_DIAG @@ -1795,12 +1795,12 @@ static void cc2650RadioProcessReceiveDone(otInstance *aInstance, otRadioFrame *a static void cc2650RadioProcessReceiveQueue(otInstance *aInstance) { - rfc_ieeeRxCorrCrc_t *crcCorr; + rfc_ieeeRxCorrCrc_t * crcCorr; rfc_dataEntryGeneral_t *curEntry, *startEntry; uint8_t rssi; startEntry = (rfc_dataEntryGeneral_t *)sRxDataQueue.pCurrEntry; - curEntry = startEntry; + curEntry = startEntry; /* loop through receive queue */ do @@ -1825,8 +1825,8 @@ static void cc2650RadioProcessReceiveQueue(otInstance *aInstance) { #if OPENTHREAD_ENABLE_RAW_LINK_API // TODO: Propagate CM0 timestamp - receiveFrame.mMsec = otPlatAlarmMilliGetNow(); - receiveFrame.mUsec = 0; // Don't support microsecond timer for now. + receiveFrame.mMsec = otPlatAlarmMilliGetNow(); + receiveFrame.mUsec = 0; // Don't support microsecond timer for now. #endif receiveFrame.mLength = len; @@ -1864,8 +1864,7 @@ static void cc2650RadioProcessReceiveQueue(otInstance *aInstance) } curEntry = (rfc_dataEntryGeneral_t *)(curEntry->pNextEntry); - } - while (curEntry != startEntry); + } while (curEntry != startEntry); } /** @@ -1885,8 +1884,7 @@ void cc2650RadioProcess(otInstance *aInstance) } } - if (sState == cc2650_stateReceive - || sState == cc2650_stateTransmit) + if (sState == cc2650_stateReceive || sState == cc2650_stateTransmit) { cc2650RadioProcessReceiveQueue(aInstance); } @@ -1900,7 +1898,7 @@ void cc2650RadioProcess(otInstance *aInstance) cc2650RadioProcessTransmitDone(aInstance, &sTransmitFrame, NULL, sTransmitError); } - sTransmitError = OT_ERROR_NONE; + sTransmitError = OT_ERROR_NONE; sTxCmdChainDone = false; } } diff --git a/examples/platforms/cc2650/random.c b/examples/platforms/cc2650/random.c index e31d93041..6b9dc24d7 100644 --- a/examples/platforms/cc2650/random.c +++ b/examples/platforms/cc2650/random.c @@ -26,8 +26,8 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include #include +#include #include #include @@ -55,7 +55,8 @@ void cc2650RandomInit(void) { PRCMPowerDomainOn(PRCM_DOMAIN_PERIPH); - while (PRCMPowerDomainStatus(PRCM_DOMAIN_PERIPH) != PRCM_DOMAIN_POWER_ON); + while (PRCMPowerDomainStatus(PRCM_DOMAIN_PERIPH) != PRCM_DOMAIN_POWER_ON) + ; PRCMPeripheralRunEnable(PRCM_PERIPH_TRNG); PRCMPeripheralSleepEnable(PRCM_DOMAIN_PERIPH); @@ -70,7 +71,8 @@ void cc2650RandomInit(void) */ uint32_t otPlatRandomGet(void) { - while (!(TRNGStatusGet() & TRNG_NUMBER_READY)); + while (!(TRNGStatusGet() & TRNG_NUMBER_READY)) + ; return TRNGNumberGet(TRNG_LOW_WORD); } @@ -91,7 +93,7 @@ static int TRNGPoll(unsigned char *aOutput, size_t aLen) union { uint32_t u32[2]; - uint8_t u8[8]; + uint8_t u8[8]; } buffer; while (length < aLen) @@ -99,14 +101,15 @@ static int TRNGPoll(unsigned char *aOutput, size_t aLen) if (length % 8 == 0) { /* we've run to the end of the buffer */ - while (!(TRNGStatusGet() & TRNG_NUMBER_READY)); + while (!(TRNGStatusGet() & TRNG_NUMBER_READY)) + ; /* * don't use TRNGNumberGet here because it will tell the TRNG to * refil the entropy pool, instad we do it ourself. */ - buffer.u32[0] = HWREG(TRNG_BASE + TRNG_O_OUT0); - buffer.u32[1] = HWREG(TRNG_BASE + TRNG_O_OUT1); + buffer.u32[0] = HWREG(TRNG_BASE + TRNG_O_OUT0); + buffer.u32[1] = HWREG(TRNG_BASE + TRNG_O_OUT1); HWREG(TRNG_BASE + TRNG_O_IRQFLAGCLR) = 0x1; } @@ -118,14 +121,13 @@ static int TRNGPoll(unsigned char *aOutput, size_t aLen) return 0; } - /** * Function documented in platform/random.h */ otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength) { - otError error = OT_ERROR_NONE; - size_t length = aOutputLength; + otError error = OT_ERROR_NONE; + size_t length = aOutputLength; otEXPECT_ACTION(aOutput, error = OT_ERROR_INVALID_ARGS); diff --git a/examples/platforms/cc2650/uart.c b/examples/platforms/cc2650/uart.c index 18104bfd2..bd7cd449e 100644 --- a/examples/platforms/cc2650/uart.c +++ b/examples/platforms/cc2650/uart.c @@ -28,13 +28,13 @@ #include -#include -#include #include +#include #include +#include -#include #include +#include #include /** @@ -52,9 +52,9 @@ enum static uint8_t const *sSendBuffer = NULL; static uint16_t sSendLen = 0; -static uint8_t sReceiveBuffer[CC2650_RECV_CIRC_BUFF_SIZE]; -static uint16_t sReceiveHeadIdx = 0; -static uint16_t sReceiveTailIdx = 0; +static uint8_t sReceiveBuffer[CC2650_RECV_CIRC_BUFF_SIZE]; +static uint16_t sReceiveHeadIdx = 0; +static uint16_t sReceiveTailIdx = 0; void UART0_intHandler(void); @@ -65,14 +65,16 @@ otError otPlatUartEnable(void) { PRCMPowerDomainOn(PRCM_DOMAIN_SERIAL); - while (PRCMPowerDomainStatus(PRCM_DOMAIN_SERIAL) != PRCM_DOMAIN_POWER_ON); + while (PRCMPowerDomainStatus(PRCM_DOMAIN_SERIAL) != PRCM_DOMAIN_POWER_ON) + ; PRCMPeripheralRunEnable(PRCM_PERIPH_UART0); PRCMPeripheralSleepEnable(PRCM_PERIPH_UART0); PRCMPeripheralDeepSleepEnable(PRCM_PERIPH_UART0); PRCMLoadSet(); - while (!PRCMLoadGet()); + while (!PRCMLoadGet()) + ; IOCPinTypeUart(UART0_BASE, IOID_2, IOID_3, IOID_UNUSED, IOID_UNUSED); @@ -116,7 +118,7 @@ otError otPlatUartSend(const uint8_t *aBuf, uint16_t aBufLength) otEXPECT_ACTION(sSendBuffer == NULL, error = OT_ERROR_BUSY); sSendBuffer = aBuf; - sSendLen = aBufLength; + sSendLen = aBufLength; exit: return error; @@ -160,7 +162,7 @@ static void processTransmit(void) } sSendBuffer = NULL; - sSendLen = 0; + sSendLen = 0; otPlatUartSendDone(); exit: @@ -194,4 +196,3 @@ void UART0_intHandler(void) } } } - diff --git a/examples/platforms/cc2652/alarm.c b/examples/platforms/cc2652/alarm.c index 61a64950b..dd3d1845b 100644 --- a/examples/platforms/cc2652/alarm.c +++ b/examples/platforms/cc2652/alarm.c @@ -34,9 +34,9 @@ #include +#include #include #include -#include #include @@ -128,4 +128,3 @@ void cc2652AlarmProcess(otInstance *aInstance) } } } - diff --git a/examples/platforms/cc2652/crypto/aes_alt.c b/examples/platforms/cc2652/crypto/aes_alt.c index e7abe97f2..409d43884 100644 --- a/examples/platforms/cc2652/crypto/aes_alt.c +++ b/examples/platforms/cc2652/crypto/aes_alt.c @@ -26,18 +26,18 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include "mbedtls/aes.h" #include "aes_alt.h" +#include "mbedtls/aes.h" #ifdef MBEDTLS_AES_ALT -#include #include #include +#include #include #define CC2652_AES_KEY_UNUSED (-1) -#define CC2652_AES_CTX_MAGIC (0x7E) +#define CC2652_AES_CTX_MAGIC (0x7E) /** * bitmap of which key stores are currently used @@ -69,11 +69,11 @@ void mbedtls_aes_init(mbedtls_aes_context *ctx) PRCMPeripheralDeepSleepEnable(PRCM_PERIPH_CRYPTO); PRCMLoadSet(); - while (!PRCMLoadGet()); - + while (!PRCMLoadGet()) + ; } - ctx->magic = CC2652_AES_CTX_MAGIC; + ctx->magic = CC2652_AES_CTX_MAGIC; ctx->key_idx = CC2652_AES_KEY_UNUSED; } @@ -104,8 +104,8 @@ void mbedtls_aes_free(mbedtls_aes_context *ctx) PRCMPeripheralDeepSleepDisable(PRCM_PERIPH_CRYPTO); PRCMLoadSet(); - while (!PRCMLoadGet()); - + while (!PRCMLoadGet()) + ; } memset((void *)ctx, 0x00, sizeof(ctx)); @@ -120,7 +120,7 @@ exit: int mbedtls_aes_setkey_enc(mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits) { unsigned char key_idx; - int retval = 0; + int retval = 0; otEXPECT_ACTION(ctx->magic == CC2652_AES_CTX_MAGIC, retval = -1); @@ -132,7 +132,8 @@ int mbedtls_aes_setkey_enc(mbedtls_aes_context *ctx, const unsigned char *key, u /* our hardware only supports 128 bit keys */ otEXPECT_ACTION(keybits == 128u, retval = MBEDTLS_ERR_AES_INVALID_KEY_LENGTH); - for (key_idx = 0; ((sUsedKeys >> key_idx) & 0x01) != 0 && key_idx < 8; key_idx++); + for (key_idx = 0; ((sUsedKeys >> key_idx) & 0x01) != 0 && key_idx < 8; key_idx++) + ; /* we have no more room for this key */ otEXPECT_ACTION(key_idx < 8, retval = -2); @@ -152,7 +153,7 @@ exit: int mbedtls_aes_setkey_dec(mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits) { unsigned char key_idx; - int retval = 0; + int retval = 0; otEXPECT_ACTION(ctx->magic == CC2652_AES_CTX_MAGIC, retval = -1); @@ -164,7 +165,8 @@ int mbedtls_aes_setkey_dec(mbedtls_aes_context *ctx, const unsigned char *key, u /* our hardware only supports 128 bit keys */ otEXPECT_ACTION(keybits == 128u, retval = MBEDTLS_ERR_AES_INVALID_KEY_LENGTH); - for (key_idx = 0; ((sUsedKeys >> key_idx) & 0x01) != 0 && key_idx < 8; key_idx++); + for (key_idx = 0; ((sUsedKeys >> key_idx) & 0x01) != 0 && key_idx < 8; key_idx++) + ; /* we have no more room for this key */ otEXPECT_ACTION(key_idx < 8, retval = -2); @@ -188,7 +190,8 @@ int mbedtls_aes_crypt_ecb(mbedtls_aes_context *ctx, int mode, const unsigned cha retval = CRYPTOAesEcb((uint32_t *)input, (uint32_t *)output, ctx->key_idx, mode == MBEDTLS_AES_ENCRYPT, false); otEXPECT(retval == AES_SUCCESS); - while ((retval = CRYPTOAesEcbStatus()) == AES_DMA_BSY); + while ((retval = CRYPTOAesEcbStatus()) == AES_DMA_BSY) + ; CRYPTOAesEcbFinish(); diff --git a/examples/platforms/cc2652/cxx_helpers.c b/examples/platforms/cc2652/cxx_helpers.c index 05faf5ab8..d4b003662 100644 --- a/examples/platforms/cc2652/cxx_helpers.c +++ b/examples/platforms/cc2652/cxx_helpers.c @@ -49,6 +49,6 @@ void __cxa_guard_abort(__guard *g) void __cxa_pure_virtual(void) { - while (1); + while (1) + ; } - diff --git a/examples/platforms/cc2652/flash.c b/examples/platforms/cc2652/flash.c index 2176a129f..aa95501fe 100644 --- a/examples/platforms/cc2652/flash.c +++ b/examples/platforms/cc2652/flash.c @@ -33,8 +33,8 @@ #include #include -#include #include +#include #include #include @@ -48,7 +48,7 @@ */ #ifndef SETTINGS_CONFIG_BASE_ADDRESS #error "SETTINGS_CONFIG_BASE_ADDRESS not defined in the OpenThread Core Config" -#endif /* SETTINGS_CONFIG_BASE_ADDRESS */ +#endif /* SETTINGS_CONFIG_BASE_ADDRESS */ /* * The settings configuration page size *MUST* be defined in the core config @@ -64,14 +64,14 @@ */ #ifndef SETTINGS_CONFIG_PAGE_NUM #warn "SETTINGS_CONFIG_PAGE_NUM not defined in the OpenThread Core Config" -#endif /* SETTINGS_CONFIG_PAGE_NUM */ +#endif /* SETTINGS_CONFIG_PAGE_NUM */ enum { - MIN_VDD_FLASH = 0x18, /* 1.50 volts (0.50=128/256 -> 128=0x80) */ - MAX_WRITE_INCREMENT = 8, /* maximum number of bytes to write at a time to - * avoid interrupt latency while in ROM - */ + MIN_VDD_FLASH = 0x18, /* 1.50 volts (0.50=128/256 -> 128=0x80) */ + MAX_WRITE_INCREMENT = 8, /* maximum number of bytes to write at a time to + * avoid interrupt latency while in ROM + */ }; /** @@ -84,10 +84,8 @@ enum static bool isBatMonOn(void) { uint32_t batMonCtl = HWREG(AON_BATMON_BASE + AON_BATMON_O_CTL); - return ((batMonCtl & AON_BATMON_CTL_CALC_EN_M) - == AON_BATMON_CTL_CALC_EN - && (batMonCtl & AON_BATMON_CTL_MEAS_EN_M) - == AON_BATMON_CTL_MEAS_EN); + return ((batMonCtl & AON_BATMON_CTL_CALC_EN_M) == AON_BATMON_CTL_CALC_EN && + (batMonCtl & AON_BATMON_CTL_MEAS_EN_M) == AON_BATMON_CTL_MEAS_EN); } /** @@ -138,7 +136,8 @@ static uint32_t disableFlashCache(void) { VIMSModeSet(VIMS_BASE, VIMS_MODE_DISABLED); - while (VIMSModeGet(VIMS_BASE) != VIMS_MODE_DISABLED); + while (VIMSModeGet(VIMS_BASE) != VIMS_MODE_DISABLED) + ; } return mode; @@ -151,7 +150,6 @@ static uint32_t disableFlashCache(void) */ static void restoreFlashCache(uint32_t mode) { - if (mode != VIMS_MODE_DISABLED) { VIMSModeSet(VIMS_BASE, mode); @@ -238,7 +236,7 @@ exit: otError utilsFlashStatusWait(uint32_t aTimeout) { uint32_t start = otPlatAlarmMilliGetNow(); - otError ret = OT_ERROR_BUSY; + otError ret = OT_ERROR_BUSY; while ((otPlatAlarmMilliGetNow() - start) < aTimeout) { @@ -267,10 +265,10 @@ uint32_t utilsFlashWrite(uint32_t aAddress, uint8_t *aData, uint32_t aSize) while (written < aSize) { uint32_t toWrite = aSize - written; - uint8_t *data = aData + written; + uint8_t *data = aData + written; uint32_t address = aAddress + written; uint32_t fsmRet; - bool interruptsWereDisabled; + bool interruptsWereDisabled; if (toWrite > MAX_WRITE_INCREMENT) { @@ -313,4 +311,3 @@ uint32_t utilsFlashRead(uint32_t aAddress, uint8_t *aData, uint32_t aSize) return aSize; } - diff --git a/examples/platforms/cc2652/logging.c b/examples/platforms/cc2652/logging.c index 5a282d335..0cbb7792f 100644 --- a/examples/platforms/cc2652/logging.c +++ b/examples/platforms/cc2652/logging.c @@ -27,15 +27,15 @@ */ /** -* @file logging.c -* Platform abstraction for the logging -* -*/ -#include + * @file logging.c + * Platform abstraction for the logging + * + */ #include +#include #include -#if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED) +#if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED) void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat, ...) { (void)aLogLevel; @@ -43,4 +43,3 @@ void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat (void)aFormat; } #endif - diff --git a/examples/platforms/cc2652/misc.c b/examples/platforms/cc2652/misc.c index f48423530..142aa0a17 100644 --- a/examples/platforms/cc2652/misc.c +++ b/examples/platforms/cc2652/misc.c @@ -29,8 +29,8 @@ #include #include -#include #include +#include /* * NOTE: if the system is flashed with Flash Programmer 2 or Uniflash, this @@ -91,4 +91,3 @@ void otPlatWakeHost(void) { // TODO: implement an operation to wake the host from sleep state. } - diff --git a/examples/platforms/cc2652/platform-cc2652.h b/examples/platforms/cc2652/platform-cc2652.h index 3d006a073..4a6b507c8 100644 --- a/examples/platforms/cc2652/platform-cc2652.h +++ b/examples/platforms/cc2652/platform-cc2652.h @@ -29,9 +29,9 @@ #ifndef PLATFORM_H_ #define PLATFORM_H_ -#include #include #include +#include #include "openthread/types.h" #ifdef __cplusplus @@ -83,7 +83,7 @@ void cc2652RandomInit(void); void cc2652UartProcess(void); #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // PLATFORM_H_ +#endif // PLATFORM_H_ diff --git a/examples/platforms/cc2652/platform.c b/examples/platforms/cc2652/platform.c index af06cb0ad..553ecf68a 100644 --- a/examples/platforms/cc2652/platform.c +++ b/examples/platforms/cc2652/platform.c @@ -34,13 +34,13 @@ #include +#include "platform-cc2652.h" #include #include -#include "platform-cc2652.h" -#include "inc/hw_types.h" #include "inc/hw_ccfg.h" #include "inc/hw_ccfg_simple_struct.h" +#include "inc/hw_types.h" extern const ccfg_t __ccfg; @@ -51,8 +51,8 @@ const char *dummy_ccfg_ref = ((const char *)(&(__ccfg))); */ void PlatformInit(int argc, char *argv[]) { - (void) argc; - (void) argv; + (void)argc; + (void)argv; while (dummy_ccfg_ref == NULL) { @@ -82,4 +82,3 @@ void PlatformProcessDrivers(otInstance *aInstance) cc2652RadioProcess(aInstance); cc2652AlarmProcess(aInstance); } - diff --git a/examples/platforms/cc2652/radio.c b/examples/platforms/cc2652/radio.c index 62f1e07dc..874031dbf 100644 --- a/examples/platforms/cc2652/radio.c +++ b/examples/platforms/cc2652/radio.c @@ -35,32 +35,32 @@ #include #include +#include #include +#include #include #include #include #include /* to seed the CSMA-CA funciton */ -#include -#include #include "cc2652_radio.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include enum { - CC2652_RECEIVE_SENSITIVITY = -100, // dBm + CC2652_RECEIVE_SENSITIVITY = -100, // dBm }; /* phy state as defined by openthread */ @@ -71,8 +71,7 @@ static output_config_t const *sCurrentOutputPower = &(rgOutputPower[0]); /* TODO: replace with correct overrides, pre-Alpha */ /* Overrides for IEEE 802.15.4, differential mode */ -static uint32_t sIEEEOverrides[] = -{ +static uint32_t sIEEEOverrides[] = { 0x00008403, // Use 48 MHz Crystal 0x000088C3, // Disabling dynamic DCDC settings control in RX 0x000088D3, // Disabling dynamic DCDC settings control in TX @@ -141,13 +140,13 @@ static __attribute__((aligned(4))) uint8_t sRxBuf3[RX_BUF_SIZE]; /* * The RX Data Queue used by @ref sReceiveCmd. */ -static __attribute__((aligned(4))) dataQueue_t sRxDataQueue = { 0 }; +static __attribute__((aligned(4))) dataQueue_t sRxDataQueue = {0}; /* * OpenThread data primitives */ static otRadioFrame sTransmitFrame; -static otError sTransmitError; +static otError sTransmitError; static __attribute__((aligned(4))) uint8_t sTransmitPsdu[OT_RADIO_FRAME_MAX_SIZE]; @@ -323,7 +322,7 @@ static uint_fast8_t rfCoreClearReceiveQueue(dataQueue_t *aQueue) { /* memset skipped because sClearReceiveQueueCmd has only 2 members and padding */ sClearReceiveQueueCmd.commandNo = CMD_CLEAR_RX; - sClearReceiveQueueCmd.pQueue = aQueue; + sClearReceiveQueueCmd.pQueue = aQueue; return (RFCDoorbellSendTo((uint32_t)&sClearReceiveQueueCmd) & 0xFF); } @@ -438,7 +437,7 @@ static uint_fast8_t rfCoreModifySourceMatchEntry(uint8_t aEntryNo, cc2652_addres } sModifyReceiveSrcMatchCmd.options.entryType = aType; - sModifyReceiveSrcMatchCmd.entryNo = aEntryNo; + sModifyReceiveSrcMatchCmd.entryNo = aEntryNo; return (RFCDoorbellSendTo((uint32_t)&sModifyReceiveSrcMatchCmd) & 0xFF); } @@ -621,24 +620,24 @@ static uint_fast8_t rfCoreSendTransmitCmd(uint8_t *aPsdu, uint8_t aLen) /* reset retry count */ sTransmitRetryCount = 0; - sCsmacaBackoffCmd = cCsmacaBackoffCmd; + sCsmacaBackoffCmd = cCsmacaBackoffCmd; /* initialize the random state with a true random seed for the radio core's * psudo rng */ - sCsmacaBackoffCmd.randomState = otPlatRandomGet(); - sCsmacaBackoffCmd.pNextOp = (rfc_radioOp_t *) &sTransmitCmd; + sCsmacaBackoffCmd.randomState = otPlatRandomGet(); + sCsmacaBackoffCmd.pNextOp = (rfc_radioOp_t *)&sTransmitCmd; sTransmitCmd = cTransmitCmd; /* no need to look for an ack if the tx operation was stopped */ sTransmitCmd.payloadLen = aLen; - sTransmitCmd.pPayload = aPsdu; + sTransmitCmd.pPayload = aPsdu; if (aPsdu[0] & IEEE802154_ACK_REQUEST) { /* setup the receive ack command to follow the tx command */ sTransmitCmd.condition.rule = COND_STOP_ON_FALSE; - sTransmitCmd.pNextOp = (rfc_radioOp_t *) &sTransmitRxAckCmd; + sTransmitCmd.pNextOp = (rfc_radioOp_t *)&sTransmitRxAckCmd; - sTransmitRxAckCmd = cTransmitRxAckCmd; + sTransmitRxAckCmd = cTransmitRxAckCmd; sTransmitRxAckCmd.seqNo = aPsdu[IEEE802154_DSN_OFFSET]; } @@ -812,7 +811,8 @@ static uint_fast8_t rfCorePowerOn(void) if (oscSourceSwitch) { /* Block until the high frequency clock source is ready */ - while (!OSCHfSourceReady()); + while (!OSCHfSourceReady()) + ; /* Switch the HF clock source (cc26xxware executes this from ROM) */ OSCHfSourceSwitch(); @@ -823,12 +823,14 @@ static uint_fast8_t rfCorePowerOn(void) /* Enable RF Core power domain */ PRCMPowerDomainOn(PRCM_DOMAIN_RFCORE); - while (PRCMPowerDomainStatus(PRCM_DOMAIN_RFCORE) != PRCM_DOMAIN_POWER_ON); + while (PRCMPowerDomainStatus(PRCM_DOMAIN_RFCORE) != PRCM_DOMAIN_POWER_ON) + ; PRCMDomainEnable(PRCM_DOMAIN_RFCORE); PRCMLoadSet(); - while (!PRCMLoadGet()); + while (!PRCMLoadGet()) + ; rfCoreSetupInt(); @@ -838,8 +840,8 @@ static uint_fast8_t rfCorePowerOn(void) } /* Let CPE boot */ - HWREG(RFC_PWR_NONBUF_BASE + RFC_PWR_O_PWMCLKEN) = (RFC_PWR_PWMCLKEN_RFC_M | RFC_PWR_PWMCLKEN_CPE_M | - RFC_PWR_PWMCLKEN_CPERAM_M); + HWREG(RFC_PWR_NONBUF_BASE + RFC_PWR_O_PWMCLKEN) = + (RFC_PWR_PWMCLKEN_RFC_M | RFC_PWR_PWMCLKEN_CPE_M | RFC_PWR_PWMCLKEN_CPERAM_M); /* Send ping (to verify RFCore is ready and alive) */ return rfCoreExecutePingCmd(); @@ -861,11 +863,13 @@ static void rfCorePowerOff(void) PRCMDomainDisable(PRCM_DOMAIN_RFCORE); PRCMLoadSet(); - while (!PRCMLoadGet()); + while (!PRCMLoadGet()) + ; PRCMPowerDomainOff(PRCM_DOMAIN_RFCORE); - while (PRCMPowerDomainStatus(PRCM_DOMAIN_RFCORE) != PRCM_DOMAIN_POWER_OFF); + while (PRCMPowerDomainStatus(PRCM_DOMAIN_RFCORE) != PRCM_DOMAIN_POWER_OFF) + ; if (OSCClockSourceGet(OSC_SRC_CLK_HF) != OSC_RCOSC_HF) { @@ -921,11 +925,11 @@ static uint_fast16_t rfCoreSendEnableCmd(void) /* initialize the rat start command */ sStartRatCmd = cStartRatCmd; - sStartRatCmd.pNextOp = (rfc_radioOp_t *) &sRadioSetupCmd; + sStartRatCmd.pNextOp = (rfc_radioOp_t *)&sRadioSetupCmd; sStartRatCmd.rat0 = sRatOffset; /* initialize radio setup command */ - sRadioSetupCmd = cRadioSetupCmd; + sRadioSetupCmd = cRadioSetupCmd; /* initally set the radio tx power to the max */ sRadioSetupCmd.txPower = sCurrentOutputPower->value; sRadioSetupCmd.pRegOverride = sIEEEOverrides; @@ -936,7 +940,8 @@ static uint_fast16_t rfCoreSendEnableCmd(void) otEXPECT_ACTION(CMDSTA_Done == doorbellRet, ret = doorbellRet); /* synchronously wait for the CM0 to stop executing */ - while ((HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) & IRQ_LAST_COMMAND_DONE) == 0x00); + while ((HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) & IRQ_LAST_COMMAND_DONE) == 0x00) + ; ret = sRadioSetupCmd.status; @@ -994,7 +999,7 @@ static uint_fast16_t rfCoreSendDisableCmd(void) HWREGBITW(AON_RTC_BASE + AON_RTC_O_CTL, AON_RTC_CTL_RTC_UPD_EN_BITN) = 1; /* initialize the command to power down the frequency synth */ - sFsPowerdownCmd = cFsPowerdownCmd; + sFsPowerdownCmd = cFsPowerdownCmd; sFsPowerdownCmd.pNextOp = (rfc_radioOp_t *)&sStopRatCmd; sStopRatCmd = cStopRatCmd; @@ -1006,9 +1011,9 @@ static uint_fast16_t rfCoreSendDisableCmd(void) doorbellRet = (RFCDoorbellSendTo((uint32_t)&sFsPowerdownCmd) & 0xFF); otEXPECT_ACTION(CMDSTA_Done == doorbellRet, ret = doorbellRet); - /* synchronously wait for the CM0 to stop */ - while ((HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) & IRQ_LAST_COMMAND_DONE) == 0x00); + while ((HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) & IRQ_LAST_COMMAND_DONE) == 0x00) + ; ret = sStopRatCmd.status; @@ -1045,9 +1050,7 @@ void RFCCPE0IntHandler(void) { HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) = ~IRQ_LAST_COMMAND_DONE; - if (sState == cc2652_stateReceive && - sReceiveCmd.status != ACTIVE && - sReceiveCmd.status != IEEE_SUSPENDED) + if (sState == cc2652_stateReceive && sReceiveCmd.status != ACTIVE && sReceiveCmd.status != IEEE_SUSPENDED) { /* the rx command was probably aborted to change the channel */ sState = cc2652_stateSleep; @@ -1211,7 +1214,7 @@ otError otPlatRadioDisable(otInstance *aInstance) */ rfCorePowerOff(); sState = cc2652_stateDisabled; - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; } return error; @@ -1256,7 +1259,7 @@ exit: */ otError otPlatRadioSetTransmitPower(otInstance *aInstance, int8_t aPower) { - unsigned int i; + unsigned int i; output_config_t const *powerCfg = &(rgOutputPower[0]); (void)aInstance; @@ -1304,7 +1307,7 @@ otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) { /* we are already running on the right channel */ sState = cc2652_stateReceive; - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; } else { @@ -1322,7 +1325,7 @@ otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) otEXPECT_ACTION(rfCoreSendReceiveCmd() == CMDSTA_Done, error = OT_ERROR_FAILED); sState = cc2652_stateReceive; - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; } } @@ -1380,8 +1383,8 @@ otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aFrame) /* removing 2 bytes of CRC placeholder because we generate that in hardware */ otEXPECT_ACTION(rfCoreSendTransmitCmd(aFrame->mPsdu, aFrame->mLength - 2) == CMDSTA_Done, error = OT_ERROR_FAILED); - error = OT_ERROR_NONE; - sTransmitError = OT_ERROR_NONE; + error = OT_ERROR_NONE; + sTransmitError = OT_ERROR_NONE; sTxCmdChainDone = false; otPlatRadioTxStarted(aInstance, aFrame); } @@ -1439,17 +1442,15 @@ otError otPlatRadioAddSrcMatchShortEntry(otInstance *aInstance, const uint16_t a if (idx == CC2652_SRC_MATCH_NONE) { /* the entry does not exist already, add it */ - otEXPECT_ACTION((idx = rfCoreFindEmptyShortSrcMatchIdx()) != CC2652_SRC_MATCH_NONE, - error = OT_ERROR_NO_BUFS); + otEXPECT_ACTION((idx = rfCoreFindEmptyShortSrcMatchIdx()) != CC2652_SRC_MATCH_NONE, error = OT_ERROR_NO_BUFS); sSrcMatchShortData.extAddrEnt[idx].shortAddr = aShortAddress; - sSrcMatchShortData.extAddrEnt[idx].panId = sReceiveCmd.localPanID; + sSrcMatchShortData.extAddrEnt[idx].panId = sReceiveCmd.localPanID; } if (sReceiveCmd.status == ACTIVE || sReceiveCmd.status == IEEE_SUSPENDED) { /* we have a running or backgrounded rx command */ - otEXPECT_ACTION(rfCoreModifySourceMatchEntry(idx, SHORT_ADDRESS, true) == CMDSTA_Done, - error = OT_ERROR_FAILED); + otEXPECT_ACTION(rfCoreModifySourceMatchEntry(idx, SHORT_ADDRESS, true) == CMDSTA_Done, error = OT_ERROR_FAILED); } else { @@ -1509,8 +1510,7 @@ otError otPlatRadioAddSrcMatchExtEntry(otInstance *aInstance, const otExtAddress if (sReceiveCmd.status == ACTIVE || sReceiveCmd.status == IEEE_SUSPENDED) { /* we have a running or backgrounded rx command */ - otEXPECT_ACTION(rfCoreModifySourceMatchEntry(idx, EXT_ADDRESS, true) == CMDSTA_Done, - error = OT_ERROR_FAILED); + otEXPECT_ACTION(rfCoreModifySourceMatchEntry(idx, EXT_ADDRESS, true) == CMDSTA_Done, error = OT_ERROR_FAILED); } else { @@ -1537,13 +1537,12 @@ otError otPlatRadioClearSrcMatchExtEntry(otInstance *aInstance, const otExtAddre if (sReceiveCmd.status == ACTIVE || sReceiveCmd.status == IEEE_SUSPENDED) { /* we have a running or backgrounded rx command */ - otEXPECT_ACTION(rfCoreModifySourceMatchEntry(idx, EXT_ADDRESS, false) == CMDSTA_Done, - error = OT_ERROR_FAILED); + otEXPECT_ACTION(rfCoreModifySourceMatchEntry(idx, EXT_ADDRESS, false) == CMDSTA_Done, error = OT_ERROR_FAILED); } else { /* we are not running, so we must update the values ourselves */ - sSrcMatchExtData.srcPendEn[idx] = 0u; + sSrcMatchExtData.srcPendEn[idx] = 0u; sSrcMatchExtData.srcMatchEn[idx] = 0u; sSrcMatchExtData.srcPendEn[idx / 32] &= ~(1 << (idx % 32)); sSrcMatchExtData.srcMatchEn[idx / 32] &= ~(1 << (idx % 32)); @@ -1554,8 +1553,8 @@ exit: } /** -* Function documented in platform/radio.h -*/ + * Function documented in platform/radio.h + */ void otPlatRadioClearSrcMatchShortEntries(otInstance *aInstance) { (void)aInstance; @@ -1581,8 +1580,8 @@ exit: } /** -* Function documented in platform/radio.h -*/ + * Function documented in platform/radio.h + */ void otPlatRadioClearSrcMatchExtEntries(otInstance *aInstance) { (void)aInstance; @@ -1643,7 +1642,7 @@ void otPlatRadioSetPromiscuous(otInstance *aInstance, bool aEnable) */ void otPlatRadioGetIeeeEui64(otInstance *aInstance, uint8_t *aIeeeEui64) { - uint8_t *eui64; + uint8_t * eui64; unsigned int i; (void)aInstance; @@ -1773,8 +1772,10 @@ exit: return; } -static void cc2652RadioProcessTransmitDone(otInstance *aInstance, otRadioFrame *aTransmitFrame, otRadioFrame *aAckFrame, - otError aTransmitError) +static void cc2652RadioProcessTransmitDone(otInstance * aInstance, + otRadioFrame *aTransmitFrame, + otRadioFrame *aAckFrame, + otError aTransmitError) { #if OPENTHREAD_ENABLE_DIAG @@ -1806,12 +1807,12 @@ static void cc2652RadioProcessReceiveDone(otInstance *aInstance, otRadioFrame *a static void cc2652RadioProcessReceiveQueue(otInstance *aInstance) { - rfc_ieeeRxCorrCrc_t *crcCorr; + rfc_ieeeRxCorrCrc_t * crcCorr; rfc_dataEntryGeneral_t *curEntry, *startEntry; uint8_t rssi; startEntry = (rfc_dataEntryGeneral_t *)sRxDataQueue.pCurrEntry; - curEntry = startEntry; + curEntry = startEntry; /* loop through receive queue */ do @@ -1836,8 +1837,8 @@ static void cc2652RadioProcessReceiveQueue(otInstance *aInstance) { #if OPENTHREAD_ENABLE_RAW_LINK_API // TODO: Propagate CM0 timestamp - receiveFrame.mMsec = otPlatAlarmMilliGetNow(); - receiveFrame.mUsec = 0; // Don't support microsecond timer for now. + receiveFrame.mMsec = otPlatAlarmMilliGetNow(); + receiveFrame.mUsec = 0; // Don't support microsecond timer for now. #endif receiveFrame.mLength = len; @@ -1875,8 +1876,7 @@ static void cc2652RadioProcessReceiveQueue(otInstance *aInstance) } curEntry = (rfc_dataEntryGeneral_t *)(curEntry->pNextEntry); - } - while (curEntry != startEntry); + } while (curEntry != startEntry); } /** @@ -1896,8 +1896,7 @@ void cc2652RadioProcess(otInstance *aInstance) } } - if (sState == cc2652_stateReceive - || sState == cc2652_stateTransmit) + if (sState == cc2652_stateReceive || sState == cc2652_stateTransmit) { cc2652RadioProcessReceiveQueue(aInstance); } @@ -1911,7 +1910,7 @@ void cc2652RadioProcess(otInstance *aInstance) cc2652RadioProcessTransmitDone(aInstance, &sTransmitFrame, NULL, sTransmitError); } - sTransmitError = OT_ERROR_NONE; + sTransmitError = OT_ERROR_NONE; sTxCmdChainDone = false; } } diff --git a/examples/platforms/cc2652/random.c b/examples/platforms/cc2652/random.c index 297d2c0f7..b803e2aac 100644 --- a/examples/platforms/cc2652/random.c +++ b/examples/platforms/cc2652/random.c @@ -30,9 +30,9 @@ #include -#include -#include #include +#include +#include #include #include @@ -56,7 +56,8 @@ void cc2652RandomInit(void) { PRCMPowerDomainOn(PRCM_DOMAIN_PERIPH); - while (PRCMPowerDomainStatus(PRCM_DOMAIN_PERIPH) != PRCM_DOMAIN_POWER_ON); + while (PRCMPowerDomainStatus(PRCM_DOMAIN_PERIPH) != PRCM_DOMAIN_POWER_ON) + ; PRCMPeripheralRunEnable(PRCM_PERIPH_TRNG); PRCMPeripheralSleepEnable(PRCM_DOMAIN_PERIPH); @@ -71,7 +72,8 @@ void cc2652RandomInit(void) */ uint32_t otPlatRandomGet(void) { - while (!(TRNGStatusGet() & TRNG_NUMBER_READY)); + while (!(TRNGStatusGet() & TRNG_NUMBER_READY)) + ; return TRNGNumberGet(TRNG_LOW_WORD); } @@ -92,7 +94,7 @@ static int TRNGPoll(unsigned char *aOutput, size_t aLen) union { uint32_t u32[2]; - uint8_t u8[8]; + uint8_t u8[8]; } buffer; while (length < aLen) @@ -100,14 +102,15 @@ static int TRNGPoll(unsigned char *aOutput, size_t aLen) if (length % 8 == 0) { /* we've run to the end of the buffer */ - while (!(TRNGStatusGet() & TRNG_NUMBER_READY)); + while (!(TRNGStatusGet() & TRNG_NUMBER_READY)) + ; /* * don't use TRNGNumberGet here because it will tell the TRNG to * refill the entropy pool, instead we do it ourself. */ - buffer.u32[0] = HWREG(TRNG_BASE + TRNG_O_OUT0); - buffer.u32[1] = HWREG(TRNG_BASE + TRNG_O_OUT1); + buffer.u32[0] = HWREG(TRNG_BASE + TRNG_O_OUT0); + buffer.u32[1] = HWREG(TRNG_BASE + TRNG_O_OUT1); HWREG(TRNG_BASE + TRNG_O_IRQFLAGCLR) = 0x1; } @@ -119,14 +122,13 @@ static int TRNGPoll(unsigned char *aOutput, size_t aLen) return 0; } - /** * Function documented in platform/random.h */ otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength) { - otError error = OT_ERROR_NONE; - size_t length = aOutputLength; + otError error = OT_ERROR_NONE; + size_t length = aOutputLength; otEXPECT_ACTION(aOutput, error = OT_ERROR_INVALID_ARGS); diff --git a/examples/platforms/cc2652/uart.c b/examples/platforms/cc2652/uart.c index b30165076..97877e603 100644 --- a/examples/platforms/cc2652/uart.c +++ b/examples/platforms/cc2652/uart.c @@ -32,12 +32,12 @@ * */ -#include #include +#include #include -#include #include +#include #include #include @@ -68,9 +68,9 @@ enum static uint8_t const *sSendBuffer = NULL; static uint16_t sSendLen = 0; -static uint8_t sReceiveBuffer[CC2652_RECV_CIRC_BUFF_SIZE]; -static uint16_t sReceiveHeadIdx = 0; -static uint16_t sReceiveTailIdx = 0; +static uint8_t sReceiveBuffer[CC2652_RECV_CIRC_BUFF_SIZE]; +static uint16_t sReceiveHeadIdx = 0; +static uint16_t sReceiveTailIdx = 0; void UART0_intHandler(void); @@ -87,7 +87,8 @@ static void uart_power_control(uint32_t who_base, int turnon) value = (who_base == UART0_BASE) ? PRCM_DOMAIN_SERIAL : PRCM_DOMAIN_PERIPH; PRCMPowerDomainOn(value); - while (PRCMPowerDomainStatus(value) != PRCM_DOMAIN_POWER_ON); + while (PRCMPowerDomainStatus(value) != PRCM_DOMAIN_POWER_ON) + ; value = (who_base == UART0_BASE) ? PRCM_PERIPH_UART0 : PRCM_PERIPH_UART1; PRCMPeripheralRunEnable(value); @@ -95,7 +96,8 @@ static void uart_power_control(uint32_t who_base, int turnon) PRCMPeripheralDeepSleepEnable(value); PRCMLoadSet(); - while (!PRCMLoadGet()); + while (!PRCMLoadGet()) + ; } else { @@ -114,7 +116,6 @@ static void uart_power_control(uint32_t who_base, int turnon) } } - /** * Function documented in platform/uart.h */ @@ -162,7 +163,7 @@ otError otPlatUartSend(const uint8_t *aBuf, uint16_t aBufLength) otEXPECT_ACTION(sSendBuffer == NULL, error = OT_ERROR_BUSY); sSendBuffer = aBuf; - sSendLen = aBufLength; + sSendLen = aBufLength; exit: return error; @@ -206,7 +207,7 @@ static void processTransmit(void) } sSendBuffer = NULL; - sSendLen = 0; + sSendLen = 0; otPlatUartSendDone(); exit: @@ -246,8 +247,7 @@ void UART0_intHandler(void) /* * Documented in platform-cc2652.h */ -void -cc2652DebugUartInit(void) +void cc2652DebugUartInit(void) { uart_power_control(UART1_BASE, true); /* @@ -279,7 +279,7 @@ int otPlatDebugUart_getc(void) if (otPlatDebugUart_kbhit()) { /* get & clear 0x100 bit used below as flag */ - ch = debug_uart_ungetbuf & 0x0ff; + ch = debug_uart_ungetbuf & 0x0ff; debug_uart_ungetbuf = 0; } diff --git a/examples/platforms/da15000/alarm.c b/examples/platforms/da15000/alarm.c index bdc578096..6b77c055e 100644 --- a/examples/platforms/da15000/alarm.c +++ b/examples/platforms/da15000/alarm.c @@ -27,9 +27,9 @@ */ /** -* @file alarm.c -* Platform abstraction for the alarm -*/ + * @file alarm.c + * Platform abstraction for the alarm + */ #include @@ -37,10 +37,10 @@ #include "hw_timer0.h" -static bool sIsRunning = false; -static uint32_t sAlarm = 0; +static bool sIsRunning = false; +static uint32_t sAlarm = 0; static uint32_t sCounter; -volatile bool sAlarmFired = false; +volatile bool sAlarmFired = false; static void timer0_interrupt_cb(void) { @@ -75,7 +75,7 @@ uint32_t otPlatAlarmMilliGetNow(void) void otPlatAlarmMilliStartAt(otInstance *aInstance, uint32_t t0, uint32_t dt) { (void)aInstance; - sAlarm = t0 + dt; + sAlarm = t0 + dt; sIsRunning = true; if (sCounter == 0) diff --git a/examples/platforms/da15000/crypto/aes_alt.c b/examples/platforms/da15000/crypto/aes_alt.c index caf6478b7..84e7125fb 100644 --- a/examples/platforms/da15000/crypto/aes_alt.c +++ b/examples/platforms/da15000/crypto/aes_alt.c @@ -26,21 +26,24 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include "mbedtls/aes.h" #include "aes_alt.h" +#include "mbedtls/aes.h" #ifdef MBEDTLS_AES_ALT -#include -#include -#include #include "hw_aes_hash.h" +#include +#include +#include static void mbedtls_zeroize(void *v, size_t n) { volatile unsigned char *p = (unsigned char *)v; - while (n--) { *p++ = 0; } + while (n--) + { + *p++ = 0; + } } void mbedtls_aes_init(mbedtls_aes_context *ctx) @@ -127,10 +130,7 @@ int mbedtls_aes_setkey_dec(mbedtls_aes_context *ctx, const unsigned char *key, u * * \return 0 if successful */ -int mbedtls_aes_crypt_ecb(mbedtls_aes_context *ctx, - int mode, - const unsigned char input[16], - unsigned char output[16]) +int mbedtls_aes_crypt_ecb(mbedtls_aes_context *ctx, int mode, const unsigned char input[16], unsigned char output[16]) { int retval = 0; @@ -169,15 +169,14 @@ int mbedtls_aes_self_test(int verbose) { (void)verbose; /* 128-bit Key 2b7e151628aed2a6abf7158809cf4f3c */ - const uint8_t key_128b[16] = { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, - 0x09, 0xcf, 0x4f, 0x3c - }; + const uint8_t key_128b[16] = {0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, + 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}; - int retval = 0; + int retval = 0; mbedtls_aes_context aes; - uint8_t input[16] = {0}; - uint8_t output[16] = {0}; - uint8_t decrypt[16] = {0}; + uint8_t input[16] = {0}; + uint8_t output[16] = {0}; + uint8_t decrypt[16] = {0}; strcpy((char *)input, (const char *)"hw_cryptaes_test"); diff --git a/examples/platforms/da15000/flash.c b/examples/platforms/da15000/flash.c index 1b1635218..eafa6833e 100644 --- a/examples/platforms/da15000/flash.c +++ b/examples/platforms/da15000/flash.c @@ -32,7 +32,7 @@ #define FLASH_BUFFER_SIZE 0x2000 #define FLASH_SECTOR_SIZE 0x1000 -#define FLASH_PAGE_SIZE 0x0100 +#define FLASH_PAGE_SIZE 0x0100 /* * In case that user tries to write data to flash passing as source QSPI mapped flash address @@ -72,19 +72,19 @@ otError utilsFlashStatusWait(uint32_t aTimeout) static inline bool FlashQspiAddress(const void *aBuf) { - if (((uint32_t) aBuf >= MEMORY_QSPIF_BASE) && ((uint32_t) aBuf < MEMORY_QSPIF_END)) + if (((uint32_t)aBuf >= MEMORY_QSPIF_BASE) && ((uint32_t)aBuf < MEMORY_QSPIF_END)) { return true; } - return ((uint32_t) aBuf >= MEMORY_REMAPPED_BASE) && ((uint32_t) aBuf < MEMORY_REMAPPED_END) - && (REG_GETF(CRG_TOP, SYS_CTRL_REG, REMAP_ADR0) == 2); + return ((uint32_t)aBuf >= MEMORY_REMAPPED_BASE) && ((uint32_t)aBuf < MEMORY_REMAPPED_END) && + (REG_GETF(CRG_TOP, SYS_CTRL_REG, REMAP_ADR0) == 2); } static size_t FlashWriteFromQspi(uint32_t aAddress, const uint8_t *aQspiBuf, size_t aSize) { - size_t written; - size_t offset = 0; + size_t written; + size_t offset = 0; uint8_t buf[ON_STACK_BUFFER_SIZE]; /* @@ -107,8 +107,8 @@ static size_t FlashWriteFromQspi(uint32_t aAddress, const uint8_t *aQspiBuf, siz uint32_t utilsFlashWrite(uint32_t aAddress, uint8_t *aData, uint32_t aSize) { size_t written; - size_t offset = 0; - bool buf_from_flash = FlashQspiAddress(aData); + size_t offset = 0; + bool buf_from_flash = FlashQspiAddress(aData); while (offset < aSize) { @@ -118,8 +118,7 @@ uint32_t utilsFlashWrite(uint32_t aAddress, uint8_t *aData, uint32_t aSize) */ if (buf_from_flash) { - written = FlashWriteFromQspi(aAddress + offset, aData + offset, - aSize - offset); + written = FlashWriteFromQspi(aAddress + offset, aData + offset, aSize - offset); } else { @@ -127,8 +126,7 @@ uint32_t utilsFlashWrite(uint32_t aAddress, uint8_t *aData, uint32_t aSize) * Try write everything, lower driver will reduce this value to accommodate * page boundary and and maximum write size limitation */ - written = qspi_automode_write_flash_page(aAddress + offset, aData + offset, - aSize - offset); + written = qspi_automode_write_flash_page(aAddress + offset, aData + offset, aSize - offset); } offset += written; @@ -141,5 +139,6 @@ uint32_t utilsFlashWrite(uint32_t aAddress, uint8_t *aData, uint32_t aSize) uint32_t utilsFlashRead(uint32_t aAddress, uint8_t *aData, uint32_t aSize) { - return qspi_automode_read(aAddress, aData, aSize);; + return qspi_automode_read(aAddress, aData, aSize); + ; } diff --git a/examples/platforms/da15000/logging.c b/examples/platforms/da15000/logging.c index a1dfbedff..8b042d983 100644 --- a/examples/platforms/da15000/logging.c +++ b/examples/platforms/da15000/logging.c @@ -27,10 +27,10 @@ */ /** -* @file logging.c -* Platform abstraction for the logging -* -*/ + * @file logging.c + * Platform abstraction for the logging + * + */ #include diff --git a/examples/platforms/da15000/platform-da15000.h b/examples/platforms/da15000/platform-da15000.h old mode 100755 new mode 100644 index 302d789fd..208d6952a --- a/examples/platforms/da15000/platform-da15000.h +++ b/examples/platforms/da15000/platform-da15000.h @@ -29,8 +29,8 @@ #ifndef PLATFORM_DA15000_H_ #define PLATFORM_DA15000_H_ -#include #include +#include #include /** diff --git a/examples/platforms/da15000/platform.c b/examples/platforms/da15000/platform.c index 1520819ba..e9da6890e 100644 --- a/examples/platforms/da15000/platform.c +++ b/examples/platforms/da15000/platform.c @@ -66,16 +66,16 @@ static otInstance *sInstance = NULL; */ static void ExampleProcess(otInstance *aInstance) { - static int aliveLEDcounter = 0; - otDeviceRole devRole; - static int thrValue; + static int aliveLEDcounter = 0; + otDeviceRole devRole; + static int thrValue; devRole = otThreadGetDeviceRole(aInstance); if (sBlink == false && otPlatAlarmMilliGetNow() != 0) { sMsCounterInit = otPlatAlarmMilliGetNow(); - sBlink = true; + sBlink = true; } sMsCounter = otPlatAlarmMilliGetNow() - sMsCounterInit; @@ -140,8 +140,8 @@ void PlatformInit(int argc, char *argv[]) static sys_clk_t ClkGet(void) { - sys_clk_t clk = sysclk_RC16; - uint32_t hw_clk = hw_cpm_get_sysclk(); + sys_clk_t clk = sysclk_RC16; + uint32_t hw_clk = hw_cpm_get_sysclk(); switch (hw_clk) { @@ -175,7 +175,7 @@ static sys_clk_t ClkGet(void) case SYS_CLK_IS_LP: - // fall-through + // fall-through default: ASSERT_WARNING(0); @@ -192,16 +192,17 @@ static void ClkSet(sys_clk_t clock) case sysclk_XTAL16M: if (!hw_cpm_check_xtal16m_status()) // XTAL16M disabled { - hw_cpm_enable_xtal16m(); // Enable XTAL16M + hw_cpm_enable_xtal16m(); // Enable XTAL16M } - hw_cpm_set_sysclk(SYS_CLK_IS_XTAL16M); // Set XTAL16 as sys_clk - hw_watchdog_unfreeze(); // Start watchdog + hw_cpm_set_sysclk(SYS_CLK_IS_XTAL16M); // Set XTAL16 as sys_clk + hw_watchdog_unfreeze(); // Start watchdog - while (!hw_cpm_is_xtal16m_started()); // Block until XTAL16M starts + while (!hw_cpm_is_xtal16m_started()) + ; // Block until XTAL16M starts hw_qspi_set_div(HW_QSPI_DIV_1); - hw_watchdog_freeze(); // Stop watchdog + hw_watchdog_freeze(); // Stop watchdog hw_cpm_set_hclk_div(0); hw_cpm_set_pclk_div(0); break; @@ -209,10 +210,10 @@ static void ClkSet(sys_clk_t clock) case sysclk_PLL48: if (hw_cpm_is_pll_locked() == 0) { - hw_cpm_pll_sys_on(); // Turn on PLL + hw_cpm_pll_sys_on(); // Turn on PLL } - hw_cpm_enable_pll_divider(); // Enable divider (div by 2) + hw_cpm_enable_pll_divider(); // Enable divider (div by 2) hw_qspi_set_div(HW_QSPI_DIV_1); hw_cpm_set_sysclk(SYS_CLK_IS_PLL); hw_cpm_set_hclk_div(0); @@ -222,10 +223,10 @@ static void ClkSet(sys_clk_t clock) case sysclk_PLL96: if (hw_cpm_is_pll_locked() == 0) { - hw_cpm_pll_sys_on(); // Turn on PLL + hw_cpm_pll_sys_on(); // Turn on PLL } - hw_cpm_disable_pll_divider(); // Disable divider (div by 1) + hw_cpm_disable_pll_divider(); // Disable divider (div by 1) hw_qspi_set_div(HW_QSPI_DIV_2); hw_cpm_set_sysclk(SYS_CLK_IS_PLL); hw_cpm_set_hclk_div(0); @@ -245,7 +246,7 @@ static void ClkChange(sys_clk_t lastClock, sys_clk_t newClock) } } -static void StateChangedCallback(uint32_t aFlags, void *aContext) +static void StateChangedCallback(uint32_t aFlags, void *aContext) { if ((aFlags & OT_CHANGED_COMMISSIONER_STATE) != 0) { diff --git a/examples/platforms/da15000/radio.c b/examples/platforms/da15000/radio.c index fe8e59817..1c19980ba 100644 --- a/examples/platforms/da15000/radio.c +++ b/examples/platforms/da15000/radio.c @@ -27,9 +27,9 @@ */ /** -* @file radio.cpp -* Platform abstraction for radio communication. -*/ + * @file radio.cpp + * Platform abstraction for radio communication. + */ #include #include @@ -57,51 +57,51 @@ enum { - DA15000_RECEIVE_SENSITIVITY = -100, // dBm + DA15000_RECEIVE_SENSITIVITY = -100, // dBm }; -static ftdf_dbm sRssiReal = -100; // Initialize with the worst power -static otInstance *sThreadInstance; -static otRadioState sRadioState = OT_RADIO_STATE_DISABLED; +static ftdf_dbm sRssiReal = -100; // Initialize with the worst power +static otInstance * sThreadInstance; +static otRadioState sRadioState = OT_RADIO_STATE_DISABLED; static otRadioFrame sReceiveFrame[RADIO_FRAMES_BUFFER_SIZE]; static otRadioFrame *sReceiveFrameAck; static otRadioFrame sTransmitFrame; static otError sTransmitStatus; -static bool sAckFrame = false; -static bool sDropFrame = false; -static bool sRadioPromiscuous = false; -static bool sTransmitDoneFrame = false; -static uint8_t sChannel = RADIO_DEFAULT_CHANNEL; -static uint8_t sEnableRX = 0; -static int8_t sTxPower = OPENTHREAD_CONFIG_DEFAULT_TRANSMIT_POWER; -static uint8_t sReadFrame = 0; -static uint8_t sWriteFrame = 0; -static uint32_t sSleepInitDelay = 0; +static bool sAckFrame = false; +static bool sDropFrame = false; +static bool sRadioPromiscuous = false; +static bool sTransmitDoneFrame = false; +static uint8_t sChannel = RADIO_DEFAULT_CHANNEL; +static uint8_t sEnableRX = 0; +static int8_t sTxPower = OPENTHREAD_CONFIG_DEFAULT_TRANSMIT_POWER; +static uint8_t sReadFrame = 0; +static uint8_t sWriteFrame = 0; +static uint32_t sSleepInitDelay = 0; -static uint8_t sEui64[RADIO_EUI64_TABLE_SIZE]; -static uint8_t sReceivePsdu[RADIO_FRAMES_BUFFER_SIZE][OT_RADIO_FRAME_MAX_SIZE]; -static uint8_t sTransmitPsdu[OT_RADIO_FRAME_MAX_SIZE]; +static uint8_t sEui64[RADIO_EUI64_TABLE_SIZE]; +static uint8_t sReceivePsdu[RADIO_FRAMES_BUFFER_SIZE][OT_RADIO_FRAME_MAX_SIZE]; +static uint8_t sTransmitPsdu[OT_RADIO_FRAME_MAX_SIZE]; static void da15000OtpRead(void) { - hw_otpc_init(); // Start clock. - hw_otpc_disable(); // Make sure it is in standby mode. - hw_otpc_init(); // Restart clock. + hw_otpc_init(); // Start clock. + hw_otpc_disable(); // Make sure it is in standby mode. + hw_otpc_init(); // Restart clock. hw_otpc_manual_read_on(false); __DMB(); - uint32_t *factoryTestTimeStamp = (uint32_t *) FACTORY_TEST_TIMESTAMP; - uint32_t *factoryTestId = (uint32_t *) FACTORY_TESTER_ID; + uint32_t *factoryTestTimeStamp = (uint32_t *)FACTORY_TEST_TIMESTAMP; + uint32_t *factoryTestId = (uint32_t *)FACTORY_TESTER_ID; __DMB(); - sEui64[0] = 0x80; //80-EA-CA is for Dialog Semiconductor + sEui64[0] = 0x80; // 80-EA-CA is for Dialog Semiconductor sEui64[1] = 0xEA; sEui64[2] = 0xCA; - sEui64[3] = (*factoryTestId >> 8) & 0xff; + sEui64[3] = (*factoryTestId >> 8) & 0xff; sEui64[4] = (*factoryTestTimeStamp >> 24) & 0xff; sEui64[5] = (*factoryTestTimeStamp >> 16) & 0xff; - sEui64[6] = (*factoryTestTimeStamp >> 8) & 0xff; - sEui64[7] = *factoryTestTimeStamp & 0xff; + sEui64[6] = (*factoryTestTimeStamp >> 8) & 0xff; + sEui64[7] = *factoryTestTimeStamp & 0xff; hw_otpc_manual_read_off(); hw_otpc_disable(); @@ -114,11 +114,13 @@ void da15000RadioInit(void) /* Wake up power domains */ REG_CLR_BIT(CRG_TOP, PMU_CTRL_REG, FTDF_SLEEP); - while (REG_GETF(CRG_TOP, SYS_STAT_REG, FTDF_IS_UP) == 0x0); + while (REG_GETF(CRG_TOP, SYS_STAT_REG, FTDF_IS_UP) == 0x0) + ; REG_CLR_BIT(CRG_TOP, PMU_CTRL_REG, RADIO_SLEEP); - while (REG_GETF(CRG_TOP, SYS_STAT_REG, RAD_IS_UP) == 0x0); + while (REG_GETF(CRG_TOP, SYS_STAT_REG, RAD_IS_UP) == 0x0) + ; REG_SETF(CRG_TOP, CLK_RADIO_REG, FTDF_MAC_ENABLE, 1); REG_SETF(CRG_TOP, CLK_RADIO_REG, FTDF_MAC_DIV, 0); @@ -130,8 +132,8 @@ void da15000RadioInit(void) da15000OtpRead(); - sChannel = RADIO_DEFAULT_CHANNEL; - sTransmitFrame.mPsdu = sTransmitPsdu; + sChannel = RADIO_DEFAULT_CHANNEL; + sTransmitFrame.mPsdu = sTransmitPsdu; for (ptr = 0; ptr != RADIO_FRAMES_BUFFER_SIZE; ptr++) { @@ -157,9 +159,8 @@ void otPlatRadioSetPanId(otInstance *aInstance, uint16_t aPanid) void otPlatRadioSetExtendedAddress(otInstance *aInstance, const otExtAddress *aAddress) { - otLogInfoPlat(aInstance, "Set Extended Address: %X%X%X%X%X%X%X%X", - aAddress->m8[7], aAddress->m8[6], aAddress->m8[5], aAddress->m8[4], - aAddress->m8[3], aAddress->m8[2], aAddress->m8[1], aAddress->m8[0]); + otLogInfoPlat(aInstance, "Set Extended Address: %X%X%X%X%X%X%X%X", aAddress->m8[7], aAddress->m8[6], + aAddress->m8[5], aAddress->m8[4], aAddress->m8[3], aAddress->m8[2], aAddress->m8[1], aAddress->m8[0]); ftdf_set_value(FTDF_PIB_EXTENDED_ADDRESS, aAddress->m8); } @@ -174,8 +175,8 @@ void otPlatRadioSetShortAddress(otInstance *aInstance, uint16_t aAddress) otError otPlatRadioEnable(otInstance *aInstance) { ftdf_bitmap32_t options; - otError error = OT_ERROR_NONE; - uint8_t modeCCA; + otError error = OT_ERROR_NONE; + uint8_t modeCCA; otEXPECT_ACTION(sRadioState == OT_RADIO_STATE_DISABLED, error = OT_ERROR_INVALID_STATE); @@ -189,7 +190,7 @@ otError otPlatRadioEnable(otInstance *aInstance) modeCCA = FTDF_CCA_MODE_2; ftdf_set_value(FTDF_PIB_CCA_MODE, &modeCCA); - options = FTDF_TRANSPARENT_ENABLE_FCS_GENERATION; + options = FTDF_TRANSPARENT_ENABLE_FCS_GENERATION; options |= FTDF_TRANSPARENT_WAIT_FOR_ACK; options |= FTDF_TRANSPARENT_AUTO_ACK; @@ -299,21 +300,20 @@ otError otPlatRadioAddSrcMatchShortEntry(otInstance *aInstance, const uint16_t a exit: return error; - } otError otPlatRadioAddSrcMatchExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) { - otError error = OT_ERROR_NONE; - uint8_t entry; + otError error = OT_ERROR_NONE; + uint8_t entry; ftdf_ext_address_t addr; - uint32_t addrL; - uint64_t addrH; + uint32_t addrL; + uint64_t addrH; - addrL = (aExtAddress->m8[3] << 24) | (aExtAddress->m8[2] << 16) | - (aExtAddress->m8[1] << 8) | (aExtAddress->m8[0] << 0); - addrH = (aExtAddress->m8[7] << 24) | (aExtAddress->m8[6] << 16) | - (aExtAddress->m8[5] << 8) | (aExtAddress->m8[4] << 0); + addrL = + (aExtAddress->m8[3] << 24) | (aExtAddress->m8[2] << 16) | (aExtAddress->m8[1] << 8) | (aExtAddress->m8[0] << 0); + addrH = + (aExtAddress->m8[7] << 24) | (aExtAddress->m8[6] << 16) | (aExtAddress->m8[5] << 8) | (aExtAddress->m8[4] << 0); addr = addrL | (addrH << 32); // check if address already stored @@ -349,16 +349,16 @@ exit: otError otPlatRadioClearSrcMatchExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) { - otError error = OT_ERROR_NONE; - uint8_t entry; + otError error = OT_ERROR_NONE; + uint8_t entry; ftdf_ext_address_t addr; - uint32_t addrL; - uint64_t addrH; + uint32_t addrL; + uint64_t addrH; - addrL = (aExtAddress->m8[3] << 24) | (aExtAddress->m8[2] << 16) | - (aExtAddress->m8[1] << 8) | (aExtAddress->m8[0] << 0); - addrH = (aExtAddress->m8[7] << 24) | (aExtAddress->m8[6] << 16) | - (aExtAddress->m8[5] << 8) | (aExtAddress->m8[4] << 0); + addrL = + (aExtAddress->m8[3] << 24) | (aExtAddress->m8[2] << 16) | (aExtAddress->m8[1] << 8) | (aExtAddress->m8[0] << 0); + addrH = + (aExtAddress->m8[7] << 24) | (aExtAddress->m8[6] << 16) | (aExtAddress->m8[5] << 8) | (aExtAddress->m8[4] << 0); addr = addrL | (addrH << 32); otEXPECT_ACTION(ftdf_fppr_lookup_ext_address(addr, &entry), error = OT_ERROR_NO_ADDRESS); @@ -504,7 +504,7 @@ void da15000RadioProcess(otInstance *aInstance) if (frameHeader.frame_type == FTDF_ACKNOWLEDGEMENT_FRAME) { sReceiveFrameAck = &sReceiveFrame[sReadFrame]; - sAckFrame = true; + sAckFrame = true; } otPlatRadioReceiveDone(sThreadInstance, &sReceiveFrame[sReadFrame], OT_ERROR_NONE); @@ -572,9 +572,9 @@ static void radioRssiCalc(ftdf_link_quality_t link_quality) sRssiReal = (ftdf_dbm)((0.5239 * (float)link_quality) - 114.8604); } -void ftdf_rcv_frame_transparent(ftdf_data_length_t frame_length, - ftdf_octet_t *frame, - ftdf_bitmap32_t status, +void ftdf_rcv_frame_transparent(ftdf_data_length_t frame_length, + ftdf_octet_t * frame, + ftdf_bitmap32_t status, ftdf_link_quality_t link_quality) { otEXPECT(frame_length <= OT_RADIO_FRAME_MAX_SIZE); @@ -590,12 +590,12 @@ void ftdf_rcv_frame_transparent(ftdf_data_length_t frame_length, #if OPENTHREAD_ENABLE_RAW_LINK_API // Timestamp sReceiveFrame[sWriteFrame].mMsec = otPlatAlarmMilliGetNow(); - sReceiveFrame[sWriteFrame].mUsec = 0; // Don't support microsecond timer for now. + sReceiveFrame[sWriteFrame].mUsec = 0; // Don't support microsecond timer for now. #endif - sReceiveFrame[sWriteFrame].mChannel = sChannel; - sReceiveFrame[sWriteFrame].mLength = frame_length; - sReceiveFrame[sWriteFrame].mLqi = OT_RADIO_LQI_NONE; - sReceiveFrame[sWriteFrame].mRssi = otPlatRadioGetRssi(sThreadInstance); + sReceiveFrame[sWriteFrame].mChannel = sChannel; + sReceiveFrame[sWriteFrame].mLength = frame_length; + sReceiveFrame[sWriteFrame].mLqi = OT_RADIO_LQI_NONE; + sReceiveFrame[sWriteFrame].mRssi = otPlatRadioGetRssi(sThreadInstance); memcpy(sReceiveFrame[sWriteFrame].mPsdu, frame, frame_length); sWriteFrame = (sWriteFrame + 1) % RADIO_FRAMES_BUFFER_SIZE; diff --git a/examples/platforms/da15000/random.c b/examples/platforms/da15000/random.c index b011c6112..bdf462c91 100644 --- a/examples/platforms/da15000/random.c +++ b/examples/platforms/da15000/random.c @@ -40,11 +40,11 @@ #include "hw_trng.h" #include "sdk_defs.h" -#define RANDOM_SIZE_OF_BUFFER 32 +#define RANDOM_SIZE_OF_BUFFER 32 static uint32_t sRandomNumbers[RANDOM_SIZE_OF_BUFFER]; -static uint8_t sRandomNextNumberIndex = 0; -static bool sRandomGeneratorStarted = false; +static uint8_t sRandomNextNumberIndex = 0; +static bool sRandomGeneratorStarted = false; static void RandomCallback(void) { @@ -70,7 +70,7 @@ void da15000RandomInit(void) uint32_t otPlatRandomGet(void) { uint32_t randomNumber; - bool randomGet = false; + bool randomGet = false; do { @@ -79,7 +79,7 @@ uint32_t otPlatRandomGet(void) if (sRandomNextNumberIndex < RANDOM_SIZE_OF_BUFFER) { randomNumber = sRandomNumbers[sRandomNextNumberIndex++]; - randomGet = true; + randomGet = true; if (sRandomNextNumberIndex == RANDOM_SIZE_OF_BUFFER) { @@ -89,7 +89,7 @@ uint32_t otPlatRandomGet(void) else if (hw_trng_get_fifo_level() > 0) { randomNumber = hw_trng_get_number(); - randomGet = true; + randomGet = true; } else if (!sRandomGeneratorStarted) { @@ -97,8 +97,7 @@ uint32_t otPlatRandomGet(void) } GLOBAL_INT_RESTORE(); - } - while (!randomGet); + } while (!randomGet); return randomNumber; } diff --git a/examples/platforms/da15000/uart.c b/examples/platforms/da15000/uart.c index 7e0b066bb..ae0c4a2f9 100644 --- a/examples/platforms/da15000/uart.c +++ b/examples/platforms/da15000/uart.c @@ -33,9 +33,9 @@ #include "hw_gpio.h" #include "hw_uart.h" -static bool sUartWriteDone = false; -static bool sUartReadDone = false; -static char *sInitBuf = NULL; +static bool sUartWriteDone = false; +static bool sUartReadDone = false; +static char * sInitBuf = NULL; static uint8_t sUartBuf; static void UartSignalWrite(void *p, uint16_t transferred) @@ -75,12 +75,9 @@ otError otPlatUartEnable(void) hw_uart_init_ex(HW_UART2, &uart_init); - hw_gpio_set_pin_function(HW_GPIO_PORT_1, HW_GPIO_PIN_3, - HW_GPIO_MODE_OUTPUT, HW_GPIO_FUNC_UART2_TX); - hw_gpio_set_pin_function(HW_GPIO_PORT_2, HW_GPIO_PIN_3, - HW_GPIO_MODE_OUTPUT, HW_GPIO_FUNC_UART2_RX); - hw_gpio_set_pin_function(HW_GPIO_PORT_1, HW_GPIO_PIN_5, HW_GPIO_MODE_OUTPUT, - HW_GPIO_FUNC_GPIO); + hw_gpio_set_pin_function(HW_GPIO_PORT_1, HW_GPIO_PIN_3, HW_GPIO_MODE_OUTPUT, HW_GPIO_FUNC_UART2_TX); + hw_gpio_set_pin_function(HW_GPIO_PORT_2, HW_GPIO_PIN_3, HW_GPIO_MODE_OUTPUT, HW_GPIO_FUNC_UART2_RX); + hw_gpio_set_pin_function(HW_GPIO_PORT_1, HW_GPIO_PIN_5, HW_GPIO_MODE_OUTPUT, HW_GPIO_FUNC_GPIO); hw_uart_receive(HW_UART2, &sUartBuf, 1, UartSignalRead, NULL); diff --git a/examples/platforms/efr32/alarm.c b/examples/platforms/efr32/alarm.c index 5a9e735dd..de0f838bb 100644 --- a/examples/platforms/efr32/alarm.c +++ b/examples/platforms/efr32/alarm.c @@ -44,11 +44,11 @@ #include "em_core.h" #include "rail.h" -static uint32_t sTimerHi = 0; -static uint32_t sTimerLo = 0; -static uint32_t sAlarmT0 = 0; -static uint32_t sAlarmDt = 0; -static bool sIsRunning = false; +static uint32_t sTimerHi = 0; +static uint32_t sTimerLo = 0; +static uint32_t sAlarmT0 = 0; +static uint32_t sAlarmDt = 0; +static bool sIsRunning = false; void efr32AlarmInit(void) { @@ -81,8 +81,8 @@ uint32_t otPlatAlarmMilliGetNow(void) void otPlatAlarmMilliStartAt(otInstance *aInstance, uint32_t t0, uint32_t dt) { (void)aInstance; - sAlarmT0 = t0; - sAlarmDt = dt; + sAlarmT0 = t0; + sAlarmDt = dt; sIsRunning = true; } @@ -96,7 +96,7 @@ void efr32AlarmProcess(otInstance *aInstance) { uint32_t now = otPlatAlarmMilliGetNow(); uint32_t expires; - bool fire = false; + bool fire = false; otEXPECT(sIsRunning); diff --git a/examples/platforms/efr32/flash.c b/examples/platforms/efr32/flash.c index bd5a0263a..abc88eb3f 100644 --- a/examples/platforms/efr32/flash.c +++ b/examples/platforms/efr32/flash.c @@ -94,7 +94,7 @@ otError utilsFlashErasePage(uint32_t aAddress) otError utilsFlashStatusWait(uint32_t aTimeout) { - otError error = OT_ERROR_BUSY; + otError error = OT_ERROR_BUSY; uint32_t start = otPlatAlarmMilliGetNow(); do @@ -104,8 +104,7 @@ otError utilsFlashStatusWait(uint32_t aTimeout) error = OT_ERROR_NONE; break; } - } - while (aTimeout && ((otPlatAlarmMilliGetNow() - start) < aTimeout)); + } while (aTimeout && ((otPlatAlarmMilliGetNow() - start) < aTimeout)); return error; } @@ -113,11 +112,10 @@ otError utilsFlashStatusWait(uint32_t aTimeout) uint32_t utilsFlashWrite(uint32_t aAddress, uint8_t *aData, uint32_t aSize) { uint32_t rval = aSize; - int32_t status; + int32_t status; otEXPECT_ACTION(aData, rval = 0); - otEXPECT_ACTION(((aAddress + aSize) < utilsFlashGetSize()) && - (!(aAddress & 3)) && (!(aSize & 3)), rval = 0); + otEXPECT_ACTION(((aAddress + aSize) < utilsFlashGetSize()) && (!(aAddress & 3)) && (!(aSize & 3)), rval = 0); status = MSC_WriteWord((uint32_t *)mapAddress(aAddress), aData, aSize); otEXPECT_ACTION(returnTypeConvert(status) == OT_ERROR_NONE, rval = 0); @@ -128,9 +126,9 @@ exit: uint32_t utilsFlashRead(uint32_t aAddress, uint8_t *aData, uint32_t aSize) { - uint32_t rval = aSize; + uint32_t rval = aSize; uint32_t pAddress = mapAddress(aAddress); - uint8_t *byte = aData; + uint8_t *byte = aData; otEXPECT_ACTION(aData, rval = 0); otEXPECT_ACTION((aAddress + aSize) < utilsFlashGetSize(), rval = 0); diff --git a/examples/platforms/efr32/logging.c b/examples/platforms/efr32/logging.c index cd4e8cd69..8734c2ec7 100644 --- a/examples/platforms/efr32/logging.c +++ b/examples/platforms/efr32/logging.c @@ -32,15 +32,15 @@ * */ -#include #include +#include #include #include #include "utils/code_utils.h" -#if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED) +#if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED) void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat, ...) { #if OPENTHREAD_ENABLE_CLI_LOGGING diff --git a/examples/platforms/efr32/misc.c b/examples/platforms/efr32/misc.c index bbf32473b..1a039017b 100644 --- a/examples/platforms/efr32/misc.c +++ b/examples/platforms/efr32/misc.c @@ -34,8 +34,8 @@ #include #include -#include "platform-efr32.h" #include "em_rmu.h" +#include "platform-efr32.h" static uint32_t sResetCause; @@ -79,10 +79,8 @@ otPlatResetReason otPlatGetResetReason(otInstance *aInstance) { reason = OT_PLAT_RESET_REASON_FAULT; } - else if ((sResetCause & RMU_RSTCAUSE_AVDDBOD) || - (sResetCause & RMU_RSTCAUSE_DECBOD) || - (sResetCause & RMU_RSTCAUSE_DVDDBOD) || - (sResetCause & RMU_RSTCAUSE_EM4RST)) + else if ((sResetCause & RMU_RSTCAUSE_AVDDBOD) || (sResetCause & RMU_RSTCAUSE_DECBOD) || + (sResetCause & RMU_RSTCAUSE_DVDDBOD) || (sResetCause & RMU_RSTCAUSE_EM4RST)) { reason = OT_PLAT_RESET_REASON_ASSERT; } diff --git a/examples/platforms/efr32/platform.c b/examples/platforms/efr32/platform.c index d3c452cf4..93625e627 100644 --- a/examples/platforms/efr32/platform.c +++ b/examples/platforms/efr32/platform.c @@ -42,8 +42,8 @@ #include "em_chip.h" #include "hal_common.h" -#include "platform-efr32.h" #include "openthread-core-efr32-config.h" +#include "platform-efr32.h" void halInitChipSpecific(void); diff --git a/examples/platforms/efr32/radio.c b/examples/platforms/efr32/radio.c index d008cf962..983ee0d86 100644 --- a/examples/platforms/efr32/radio.c +++ b/examples/platforms/efr32/radio.c @@ -34,55 +34,55 @@ #include -#include #include +#include #include -#include #include +#include #include "common/logging.hpp" #include "utils/code_utils.h" #include "em_core.h" #include "em_system.h" +#include "openthread-core-efr32-config.h" #include "pa_conversions_efr32.h" #include "rail.h" #include "rail_config.h" #include "rail_ieee802154.h" -#include "openthread-core-efr32-config.h" enum { - IEEE802154_MIN_LENGTH = 5, - IEEE802154_MAX_LENGTH = 127, - IEEE802154_ACK_LENGTH = 5, - IEEE802154_FRAME_TYPE_MASK = 0x7, - IEEE802154_FRAME_TYPE_ACK = 0x2, - IEEE802154_FRAME_PENDING = 1 << 4, - IEEE802154_ACK_REQUEST = 1 << 5, - IEEE802154_DSN_OFFSET = 2, + IEEE802154_MIN_LENGTH = 5, + IEEE802154_MAX_LENGTH = 127, + IEEE802154_ACK_LENGTH = 5, + IEEE802154_FRAME_TYPE_MASK = 0x7, + IEEE802154_FRAME_TYPE_ACK = 0x2, + IEEE802154_FRAME_PENDING = 1 << 4, + IEEE802154_ACK_REQUEST = 1 << 5, + IEEE802154_DSN_OFFSET = 2, }; enum { - EFR32_RECEIVE_SENSITIVITY = -100, // dBm + EFR32_RECEIVE_SENSITIVITY = -100, // dBm }; -static uint16_t sPanId = 0; -static bool sTransmitBusy = false; -static bool sPromiscuous = false; -static bool sIsSrcMatchEnabled = false; -static otRadioState sState = OT_RADIO_STATE_DISABLED; +static uint16_t sPanId = 0; +static bool sTransmitBusy = false; +static bool sPromiscuous = false; +static bool sIsSrcMatchEnabled = false; +static otRadioState sState = OT_RADIO_STATE_DISABLED; -static uint8_t sReceivePsdu[IEEE802154_MAX_LENGTH]; -static otRadioFrame sReceiveFrame; -static otError sReceiveError; +static uint8_t sReceivePsdu[IEEE802154_MAX_LENGTH]; +static otRadioFrame sReceiveFrame; +static otError sReceiveError; -static otRadioFrame sTransmitFrame; -static uint8_t sTransmitPsdu[IEEE802154_MAX_LENGTH]; -static otError sTransmitError; +static otRadioFrame sTransmitFrame; +static uint8_t sTransmitPsdu[IEEE802154_MAX_LENGTH]; +static otError sTransmitError; -typedef struct srcMatchEntry +typedef struct srcMatchEntry { uint16_t checksum; bool allocated; @@ -95,43 +95,41 @@ static uint8_t sRailTxFifo[1 + IEEE802154_MAX_LENGTH]; static void RAILCb_Generic(RAIL_Handle_t aRailHandle, RAIL_Events_t aEvents); -static RAIL_Config_t sRailConfig = -{ +static RAIL_Config_t sRailConfig = { .eventsCallback = &RAILCb_Generic, - .protocol = NULL, - .scheduler = NULL, + .protocol = NULL, + .scheduler = NULL, }; -static const RAIL_IEEE802154_Config_t sRailIeee802154Config = -{ - NULL, // addresses +static const RAIL_IEEE802154_Config_t sRailIeee802154Config = { + NULL, // addresses { // ackConfig - true, // ackConfig.enable - 894, // ackConfig.ackTimeout + true, // ackConfig.enable + 894, // ackConfig.ackTimeout { // ackConfig.rxTransitions - RAIL_RF_STATE_RX, // ackConfig.rxTransitions.success - RAIL_RF_STATE_RX, // ackConfig.rxTransitions.error + RAIL_RF_STATE_RX, // ackConfig.rxTransitions.success + RAIL_RF_STATE_RX, // ackConfig.rxTransitions.error }, { // ackConfig.txTransitions - RAIL_RF_STATE_RX, // ackConfig.txTransitions.success - RAIL_RF_STATE_RX, // ackConfig.txTransitions.error + RAIL_RF_STATE_RX, // ackConfig.txTransitions.success + RAIL_RF_STATE_RX, // ackConfig.txTransitions.error }, }, { // timings - 100, // timings.idleToRx - 192 - 10, // timings.txToRx - 100, // timings.idleToTx - 192, // timings.rxToTx - 0, // timings.rxSearchTimeout - 0, // timings.txToRxSearchTimeout + 100, // timings.idleToRx + 192 - 10, // timings.txToRx + 100, // timings.idleToTx + 192, // timings.rxToTx + 0, // timings.rxSearchTimeout + 0, // timings.txToRxSearchTimeout }, - RAIL_IEEE802154_ACCEPT_STANDARD_FRAMES, // framesMask - false, // promiscuousMode - false, // isPanCoordinator + RAIL_IEEE802154_ACCEPT_STANDARD_FRAMES, // framesMask + false, // promiscuousMode + false, // isPanCoordinator }; static RAIL_Handle_t sRailHandle = NULL; @@ -145,8 +143,7 @@ void efr32RadioInit(void) sRailHandle = RAIL_Init(&sRailConfig, NULL); assert(sRailHandle != NULL); - RAIL_DataConfig_t railDataConfig = - { + RAIL_DataConfig_t railDataConfig = { TX_PACKET_DATA, RX_PACKET_DATA, PACKET_MODE, @@ -166,24 +163,24 @@ void efr32RadioInit(void) assert(status == RAIL_STATUS_NO_ERROR); status = RAIL_ConfigEvents(sRailHandle, RAIL_EVENTS_ALL, - RAIL_EVENT_RX_ACK_TIMEOUT | // - RAIL_EVENT_TX_PACKET_SENT | // - RAIL_EVENT_RX_PACKET_RECEIVED | // - RAIL_EVENT_TX_CHANNEL_BUSY | // - RAIL_EVENT_TX_ABORTED | // - RAIL_EVENT_TX_BLOCKED | // - RAIL_EVENT_TX_UNDERFLOW | // - RAIL_EVENT_IEEE802154_DATA_REQUEST_COMMAND | // - RAIL_EVENT_CAL_NEEDED // - ); + RAIL_EVENT_RX_ACK_TIMEOUT | // + RAIL_EVENT_TX_PACKET_SENT | // + RAIL_EVENT_RX_PACKET_RECEIVED | // + RAIL_EVENT_TX_CHANNEL_BUSY | // + RAIL_EVENT_TX_ABORTED | // + RAIL_EVENT_TX_BLOCKED | // + RAIL_EVENT_TX_UNDERFLOW | // + RAIL_EVENT_IEEE802154_DATA_REQUEST_COMMAND | // + RAIL_EVENT_CAL_NEEDED // + ); assert(status == RAIL_STATUS_NO_ERROR); - RAIL_TxPowerCurvesConfig_t txPowerCurvesConfig = { curves24Hp, curvesSg, curves24Lp, piecewiseSegments }; - status = RAIL_InitTxPowerCurves(&txPowerCurvesConfig); + RAIL_TxPowerCurvesConfig_t txPowerCurvesConfig = {curves24Hp, curvesSg, curves24Lp, piecewiseSegments}; + status = RAIL_InitTxPowerCurves(&txPowerCurvesConfig); assert(status == RAIL_STATUS_NO_ERROR); - RAIL_TxPowerConfig_t txPowerConfig = { RAIL_TX_POWER_MODE_2P4_HP, 3300, 10 }; - status = RAIL_ConfigTxPower(sRailHandle, &txPowerConfig); + RAIL_TxPowerConfig_t txPowerConfig = {RAIL_TX_POWER_MODE_2P4_HP, 3300, 10}; + status = RAIL_ConfigTxPower(sRailHandle, &txPowerConfig); assert(status == RAIL_STATUS_NO_ERROR); status = RAIL_SetTxPowerDbm(sRailHandle, ((RAIL_TxPower_t)OPENTHREAD_CONFIG_DEFAULT_TRANSMIT_POWER) * 10); @@ -215,7 +212,7 @@ void otPlatRadioGetIeeeEui64(otInstance *aInstance, uint8_t *aIeeeEui64) uint8_t *eui64Ptr = NULL; (void)aInstance; - eui64 = SYSTEM_GetUnique(); + eui64 = SYSTEM_GetUnique(); eui64Ptr = (uint8_t *)&eui64; for (uint8_t i = 0; i < OT_EXT_ADDRESS_SIZE; i++) @@ -243,9 +240,8 @@ void otPlatRadioSetExtendedAddress(otInstance *aInstance, const otExtAddress *aA (void)aInstance; - otLogInfoPlat(sInstance, "ExtAddr=%X%X%X%X%X%X%X%X", - aAddress->m8[7], aAddress->m8[6], aAddress->m8[5], aAddress->m8[4], - aAddress->m8[3], aAddress->m8[2], aAddress->m8[1], aAddress->m8[0]); + otLogInfoPlat(sInstance, "ExtAddr=%X%X%X%X%X%X%X%X", aAddress->m8[7], aAddress->m8[6], aAddress->m8[5], + aAddress->m8[4], aAddress->m8[3], aAddress->m8[2], aAddress->m8[1], aAddress->m8[0]); status = RAIL_IEEE802154_SetLongAddress(sRailHandle, (uint8_t *)aAddress->m8, 0); assert(status == RAIL_STATUS_NO_ERROR); @@ -310,7 +306,7 @@ exit: otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; RAIL_Status_t status; (void)aInstance; @@ -320,7 +316,7 @@ otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) otEXPECT_ACTION(status == RAIL_STATUS_NO_ERROR, error = OT_ERROR_FAILED); otLogInfoPlat(sInstance, "State=OT_RADIO_STATE_RECEIVE", NULL); - sState = OT_RADIO_STATE_RECEIVE; + sState = OT_RADIO_STATE_RECEIVE; sReceiveFrame.mChannel = aChannel; exit: @@ -329,18 +325,18 @@ exit: otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aFrame) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; RAIL_CsmaConfig_t csmaConfig = RAIL_CSMA_CONFIG_802_15_4_2003_2p4_GHz_OQPSK_CSMA; - RAIL_TxOptions_t txOptions = RAIL_TX_OPTIONS_NONE; - RAIL_Status_t status; + RAIL_TxOptions_t txOptions = RAIL_TX_OPTIONS_NONE; + RAIL_Status_t status; (void)aInstance; otEXPECT_ACTION((sState != OT_RADIO_STATE_DISABLED) && (sState != OT_RADIO_STATE_TRANSMIT), error = OT_ERROR_INVALID_STATE); - sState = OT_RADIO_STATE_TRANSMIT; + sState = OT_RADIO_STATE_TRANSMIT; sTransmitError = OT_ERROR_NONE; - sTransmitBusy = true; + sTransmitBusy = true; RAIL_WriteTxFifo(sRailHandle, &aFrame->mLength, sizeof(aFrame->mLength), true); RAIL_WriteTxFifo(sRailHandle, aFrame->mPsdu, aFrame->mLength - 2, false); @@ -390,7 +386,7 @@ void otPlatRadioSetPromiscuous(otInstance *aInstance, bool aEnable) (void)aInstance; sPromiscuous = aEnable; - status = RAIL_IEEE802154_SetPromiscuousMode(sRailHandle, aEnable); + status = RAIL_IEEE802154_SetPromiscuousMode(sRailHandle, aEnable); assert(status == RAIL_STATUS_NO_ERROR); } @@ -426,13 +422,12 @@ int8_t findSrcMatchAvailEntry(bool aShortAddress) int8_t findSrcMatchShortEntry(const uint16_t aShortAddress) { - int8_t entry = -1; + int8_t entry = -1; uint16_t checksum = aShortAddress + sPanId; for (uint8_t i = 0; i < RADIO_CONFIG_SRC_MATCH_SHORT_ENTRY_NUM; i++) { - if (checksum == srcMatchShortEntry[i].checksum && - srcMatchShortEntry[i].allocated) + if (checksum == srcMatchShortEntry[i].checksum && srcMatchShortEntry[i].allocated) { entry = i; break; @@ -444,7 +439,7 @@ int8_t findSrcMatchShortEntry(const uint16_t aShortAddress) int8_t findSrcMatchExtEntry(const otExtAddress *aExtAddress) { - int8_t entry = -1; + int8_t entry = -1; uint16_t checksum = sPanId; checksum += (uint16_t)aExtAddress->m8[0] | (uint16_t)(aExtAddress->m8[1] << 8); @@ -454,8 +449,7 @@ int8_t findSrcMatchExtEntry(const otExtAddress *aExtAddress) for (uint8_t i = 0; i < RADIO_CONFIG_SRC_MATCH_EXT_ENTRY_NUM; i++) { - if (checksum == srcMatchExtEntry[i].checksum && - srcMatchExtEntry[i].allocated) + if (checksum == srcMatchExtEntry[i].checksum && srcMatchExtEntry[i].allocated) { entry = i; break; @@ -469,7 +463,7 @@ void addToSrcMatchShortIndirect(uint8_t entry, const uint16_t aShortAddress) { uint16_t checksum = aShortAddress + sPanId; - srcMatchShortEntry[entry].checksum = checksum; + srcMatchShortEntry[entry].checksum = checksum; srcMatchShortEntry[entry].allocated = true; } @@ -482,7 +476,7 @@ void addToSrcMatchExtIndirect(uint8_t entry, const otExtAddress *aExtAddress) checksum += (uint16_t)aExtAddress->m8[4] | (uint16_t)(aExtAddress->m8[5] << 8); checksum += (uint16_t)aExtAddress->m8[6] | (uint16_t)(aExtAddress->m8[7] << 8); - srcMatchExtEntry[entry].checksum = checksum; + srcMatchExtEntry[entry].checksum = checksum; srcMatchExtEntry[entry].allocated = true; } @@ -510,13 +504,12 @@ otError otPlatRadioAddSrcMatchShortEntry(otInstance *aInstance, const uint16_t a { (void)aInstance; otError error = OT_ERROR_NONE; - int8_t entry = -1; + int8_t entry = -1; entry = findSrcMatchAvailEntry(true); otLogDebgPlat(sInstance, "Add ShortAddr entry: %d", entry); - otEXPECT_ACTION(entry >= 0 && entry < RADIO_CONFIG_SRC_MATCH_SHORT_ENTRY_NUM, - error = OT_ERROR_NO_BUFS); + otEXPECT_ACTION(entry >= 0 && entry < RADIO_CONFIG_SRC_MATCH_SHORT_ENTRY_NUM, error = OT_ERROR_NO_BUFS); addToSrcMatchShortIndirect(entry, aShortAddress); @@ -527,14 +520,13 @@ exit: otError otPlatRadioAddSrcMatchExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) { otError error = OT_ERROR_NONE; - int8_t entry = -1; + int8_t entry = -1; (void)aInstance; entry = findSrcMatchAvailEntry(false); otLogDebgPlat(sInstance, "Add ExtAddr entry: %d", entry); - otEXPECT_ACTION(entry >= 0 && entry < RADIO_CONFIG_SRC_MATCH_EXT_ENTRY_NUM, - error = OT_ERROR_NO_BUFS); + otEXPECT_ACTION(entry >= 0 && entry < RADIO_CONFIG_SRC_MATCH_EXT_ENTRY_NUM, error = OT_ERROR_NO_BUFS); addToSrcMatchExtIndirect(entry, aExtAddress); @@ -545,14 +537,13 @@ exit: otError otPlatRadioClearSrcMatchShortEntry(otInstance *aInstance, const uint16_t aShortAddress) { otError error = OT_ERROR_NONE; - int8_t entry = -1; + int8_t entry = -1; (void)aInstance; entry = findSrcMatchShortEntry(aShortAddress); otLogDebgPlat(sInstance, "Clear ShortAddr entry: %d", entry); - otEXPECT_ACTION(entry >= 0 && entry < RADIO_CONFIG_SRC_MATCH_SHORT_ENTRY_NUM, - error = OT_ERROR_NO_ADDRESS); + otEXPECT_ACTION(entry >= 0 && entry < RADIO_CONFIG_SRC_MATCH_SHORT_ENTRY_NUM, error = OT_ERROR_NO_ADDRESS); removeFromSrcMatchShortIndirect(entry); @@ -563,14 +554,13 @@ exit: otError otPlatRadioClearSrcMatchExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) { otError error = OT_ERROR_NONE; - int8_t entry = -1; + int8_t entry = -1; (void)aInstance; entry = findSrcMatchExtEntry(aExtAddress); otLogDebgPlat(sInstance, "Clear ExtAddr entry: %d", entry); - otEXPECT_ACTION(entry >= 0 && entry < RADIO_CONFIG_SRC_MATCH_EXT_ENTRY_NUM, - error = OT_ERROR_NO_ADDRESS); + otEXPECT_ACTION(entry >= 0 && entry < RADIO_CONFIG_SRC_MATCH_EXT_ENTRY_NUM, error = OT_ERROR_NO_ADDRESS); removeFromSrcMatchExtIndirect(entry); @@ -598,19 +588,19 @@ void otPlatRadioClearSrcMatchExtEntries(otInstance *aInstance) static void checkForAck(RAIL_Handle_t aRailHandle) { - RAIL_RxPacketHandle_t packetHandle; - RAIL_RxPacketInfo_t packetInfo; + RAIL_RxPacketHandle_t packetHandle; + RAIL_RxPacketInfo_t packetInfo; RAIL_RxPacketDetails_t packetDetails; - RAIL_Status_t status; - uint8_t frame[IEEE802154_ACK_LENGTH]; - uint16_t length; + RAIL_Status_t status; + uint8_t frame[IEEE802154_ACK_LENGTH]; + uint16_t length; packetHandle = RAIL_GetRxPacketInfo(aRailHandle, RAIL_RX_PACKET_HANDLE_NEWEST, &packetInfo); assert(packetInfo.packetStatus == RAIL_RX_PACKET_READY_SUCCESS); - packetDetails.timeReceived.timePosition = RAIL_PACKET_TIME_INVALID; + packetDetails.timeReceived.timePosition = RAIL_PACKET_TIME_INVALID; packetDetails.timeReceived.totalPacketBytes = 0; - status = RAIL_GetRxPacketDetails(aRailHandle, packetHandle, &packetDetails); + status = RAIL_GetRxPacketDetails(aRailHandle, packetHandle, &packetDetails); assert(status == RAIL_STATUS_NO_ERROR); otEXPECT(packetDetails.isAck); @@ -627,8 +617,7 @@ static void checkForAck(RAIL_Handle_t aRailHandle) // read packet memcpy(frame, packetInfo.firstPortionData, packetInfo.firstPortionBytes); - memcpy(frame + packetInfo.firstPortionBytes, - packetInfo.lastPortionData, + memcpy(frame + packetInfo.firstPortionBytes, packetInfo.lastPortionData, packetInfo.packetBytes - packetInfo.firstPortionBytes); assert((frame[0] & IEEE802154_FRAME_TYPE_MASK) == IEEE802154_FRAME_TYPE_ACK); @@ -651,19 +640,19 @@ exit: static void processNextRxPacket(otInstance *aInstance, RAIL_Handle_t aRailHandle) { - RAIL_RxPacketHandle_t packetHandle = RAIL_RX_PACKET_HANDLE_INVALID; - RAIL_RxPacketInfo_t packetInfo; + RAIL_RxPacketHandle_t packetHandle = RAIL_RX_PACKET_HANDLE_INVALID; + RAIL_RxPacketInfo_t packetInfo; RAIL_RxPacketDetails_t packetDetails; - RAIL_Status_t status; - uint16_t length; + RAIL_Status_t status; + uint16_t length; packetHandle = RAIL_GetRxPacketInfo(aRailHandle, RAIL_RX_PACKET_HANDLE_OLDEST, &packetInfo); otEXPECT_ACTION(packetInfo.packetStatus == RAIL_RX_PACKET_READY_SUCCESS, packetHandle = RAIL_RX_PACKET_HANDLE_INVALID); - packetDetails.timeReceived.timePosition = RAIL_PACKET_TIME_INVALID; + packetDetails.timeReceived.timePosition = RAIL_PACKET_TIME_INVALID; packetDetails.timeReceived.totalPacketBytes = 0; - status = RAIL_GetRxPacketDetails(aRailHandle, packetHandle, &packetDetails); + status = RAIL_GetRxPacketDetails(aRailHandle, packetHandle, &packetDetails); otEXPECT(status != RAIL_STATUS_INVALID_STATE); assert(status == RAIL_STATUS_NO_ERROR); length = packetInfo.packetBytes + 1; @@ -687,13 +676,12 @@ static void processNextRxPacket(otInstance *aInstance, RAIL_Handle_t aRailHandle // read packet memcpy(sReceiveFrame.mPsdu, packetInfo.firstPortionData, packetInfo.firstPortionBytes); - memcpy(sReceiveFrame.mPsdu + packetInfo.firstPortionBytes, - packetInfo.lastPortionData, + memcpy(sReceiveFrame.mPsdu + packetInfo.firstPortionBytes, packetInfo.lastPortionData, packetInfo.packetBytes - packetInfo.firstPortionBytes); sReceiveFrame.mLength = length; - sReceiveFrame.mRssi = packetDetails.rssi; - sReceiveFrame.mLqi = packetDetails.lqi; + sReceiveFrame.mRssi = packetDetails.rssi; + sReceiveFrame.mLqi = packetDetails.lqi; // TODO: grab timestamp and handle conversion to msec/usec // sReceiveFrame.mMsec = packetDetails.packetTime; @@ -759,13 +747,13 @@ static void RAILCb_Generic(RAIL_Handle_t aRailHandle, RAIL_Events_t aEvents) if (aEvents & (RAIL_EVENT_TX_ABORTED | RAIL_EVENT_TX_BLOCKED | RAIL_EVENT_TX_UNDERFLOW)) { sTransmitError = OT_ERROR_ABORT; - sTransmitBusy = false; + sTransmitBusy = false; } if (aEvents & RAIL_EVENT_RX_ACK_TIMEOUT) { sTransmitError = OT_ERROR_NO_ACK; - sTransmitBusy = false; + sTransmitBusy = false; } if (aEvents & RAIL_EVENT_RX_PACKET_RECEIVED) @@ -784,14 +772,14 @@ static void RAILCb_Generic(RAIL_Handle_t aRailHandle, RAIL_Events_t aEvents) if ((sTransmitFrame.mPsdu[0] & IEEE802154_ACK_REQUEST) == 0) { sTransmitError = OT_ERROR_NONE; - sTransmitBusy = false; + sTransmitBusy = false; } } if (aEvents & RAIL_EVENT_TX_CHANNEL_BUSY) { sTransmitError = OT_ERROR_CHANNEL_ACCESS_FAILURE; - sTransmitBusy = false; + sTransmitBusy = false; } if (aEvents & RAIL_EVENT_CAL_NEEDED) diff --git a/examples/platforms/efr32/random.c b/examples/platforms/efr32/random.c index 7f7b33f11..3278a7366 100644 --- a/examples/platforms/efr32/random.c +++ b/examples/platforms/efr32/random.c @@ -49,7 +49,7 @@ void efr32RandomInit(void) { /* Enable ADC Clock */ CMU_ClockEnable(cmuClock_ADC0, true); - ADC_Init_TypeDef init = ADC_INIT_DEFAULT; + ADC_Init_TypeDef init = ADC_INIT_DEFAULT; ADC_InitSingle_TypeDef singleInit = ADC_INITSINGLE_DEFAULT; /* Initialize the ADC with the required values */ @@ -59,9 +59,9 @@ void efr32RandomInit(void) /* Initialize for single conversion specific to RNG */ singleInit.reference = adcRefVEntropy; - singleInit.diff = true; - singleInit.posSel = adcPosSelVSS; - singleInit.negSel = adcNegSelVSS; + singleInit.diff = true; + singleInit.posSel = adcPosSelVSS; + singleInit.negSel = adcNegSelVSS; ADC_InitSingle(ADC0, &singleInit); /* Set VINATT to maximum value and clear FIFO */ @@ -71,7 +71,7 @@ void efr32RandomInit(void) uint32_t otPlatRandomGet(void) { - uint8_t tmp = 0; + uint8_t tmp = 0; uint32_t random = 0; for (int i = 0; i < 4; i++) @@ -80,7 +80,8 @@ uint32_t otPlatRandomGet(void) { ADC_Start(ADC0, adcStartSingle); - while ((ADC0->IF & ADC_IF_SINGLE) == 0); + while ((ADC0->IF & ADC_IF_SINGLE) == 0) + ; tmp |= ((ADC_DataSingleGet(ADC0) & 0x07) << (j * 3)); } diff --git a/examples/platforms/efr32/startup-gcc.c b/examples/platforms/efr32/startup-gcc.c index 5e1664043..611d44156 100644 --- a/examples/platforms/efr32/startup-gcc.c +++ b/examples/platforms/efr32/startup-gcc.c @@ -33,10 +33,23 @@ __extension__ typedef int __guard __attribute__((mode(__DI__))); -int __cxa_guard_acquire(__guard *g) { return !*(char *)(g); } +int __cxa_guard_acquire(__guard *g) +{ + return !*(char *)(g); +} -void __cxa_guard_release(__guard *g) { *(char *)g = 1; } +void __cxa_guard_release(__guard *g) +{ + *(char *)g = 1; +} -void __cxa_guard_abort(__guard *g) { (void)g; } +void __cxa_guard_abort(__guard *g) +{ + (void)g; +} -void __cxa_pure_virtual(void) { while (1); } +void __cxa_pure_virtual(void) +{ + while (1) + ; +} diff --git a/examples/platforms/efr32/uart.c b/examples/platforms/efr32/uart.c index 3e56eb3a8..cb00e194f 100644 --- a/examples/platforms/efr32/uart.c +++ b/examples/platforms/efr32/uart.c @@ -49,35 +49,35 @@ enum kReceiveFifoSize = 128, }; -#define USART_INIT \ - { \ - USART0, /* USART port */ \ - 115200, /* Baud rate */ \ - BSP_SERIAL_APP_TX_LOC, /* USART Tx pin location number */ \ - BSP_SERIAL_APP_RX_LOC, /* USART Rx pin location number */ \ - (USART_Stopbits_TypeDef)USART_FRAME_STOPBITS_ONE, /* Stop bits */ \ - (USART_Parity_TypeDef)USART_FRAME_PARITY_NONE, /* Parity */ \ - (USART_OVS_TypeDef)USART_CTRL_OVS_X16, /* Oversampling mode*/ \ - false, /* Majority vote disable */ \ - uartdrvFlowControlHwUart, /* Flow control */ \ - BSP_SERIAL_APP_CTS_PORT, /* CTS port number */ \ - BSP_SERIAL_APP_CTS_PIN, /* CTS pin number */ \ - BSP_SERIAL_APP_RTS_PORT, /* RTS port number */ \ - BSP_SERIAL_APP_RTS_PIN, /* RTS pin number */ \ - (UARTDRV_Buffer_FifoQueue_t *)&sUartRxQueue, /* RX operation queue */ \ - (UARTDRV_Buffer_FifoQueue_t *)&sUartTxQueue, /* TX operation queue */ \ - BSP_SERIAL_APP_CTS_LOC, /* CTS location */ \ - BSP_SERIAL_APP_RTS_LOC /* RTS location */ \ +#define USART_INIT \ + { \ + USART0, /* USART port */ \ + 115200, /* Baud rate */ \ + BSP_SERIAL_APP_TX_LOC, /* USART Tx pin location number */ \ + BSP_SERIAL_APP_RX_LOC, /* USART Rx pin location number */ \ + (USART_Stopbits_TypeDef)USART_FRAME_STOPBITS_ONE, /* Stop bits */ \ + (USART_Parity_TypeDef)USART_FRAME_PARITY_NONE, /* Parity */ \ + (USART_OVS_TypeDef)USART_CTRL_OVS_X16, /* Oversampling mode*/ \ + false, /* Majority vote disable */ \ + uartdrvFlowControlHwUart, /* Flow control */ \ + BSP_SERIAL_APP_CTS_PORT, /* CTS port number */ \ + BSP_SERIAL_APP_CTS_PIN, /* CTS pin number */ \ + BSP_SERIAL_APP_RTS_PORT, /* RTS port number */ \ + BSP_SERIAL_APP_RTS_PIN, /* RTS pin number */ \ + (UARTDRV_Buffer_FifoQueue_t *)&sUartRxQueue, /* RX operation queue */ \ + (UARTDRV_Buffer_FifoQueue_t *)&sUartTxQueue, /* TX operation queue */ \ + BSP_SERIAL_APP_CTS_LOC, /* CTS location */ \ + BSP_SERIAL_APP_RTS_LOC /* RTS location */ \ } DEFINE_BUF_QUEUE(EMDRV_UARTDRV_MAX_CONCURRENT_RX_BUFS, sUartRxQueue); DEFINE_BUF_QUEUE(EMDRV_UARTDRV_MAX_CONCURRENT_TX_BUFS, sUartTxQueue); -static UARTDRV_HandleData_t sUartHandleData; -static UARTDRV_Handle_t sUartHandle = &sUartHandleData; -static uint8_t sReceiveBuffer[2]; -static const uint8_t *sTransmitBuffer = NULL; -static uint16_t sTransmitLength = 0; +static UARTDRV_HandleData_t sUartHandleData; +static UARTDRV_Handle_t sUartHandle = &sUartHandleData; +static uint8_t sReceiveBuffer[2]; +static const uint8_t * sTransmitBuffer = NULL; +static uint16_t sTransmitLength = 0; typedef struct ReceiveFifo_t { @@ -99,7 +99,7 @@ static void receiveDone(UARTDRV_Handle_t aHandle, Ecode_t aStatus, uint8_t *aDat if (sReceiveFifo.mHead != (sReceiveFifo.mTail + 1) % kReceiveFifoSize) { sReceiveFifo.mBuffer[sReceiveFifo.mTail] = aData[0]; - sReceiveFifo.mTail = (sReceiveFifo.mTail + 1) % kReceiveFifoSize; + sReceiveFifo.mTail = (sReceiveFifo.mTail + 1) % kReceiveFifoSize; } UARTDRV_Receive(aHandle, aData, 1, receiveDone); diff --git a/examples/platforms/emsk/alarm.c b/examples/platforms/emsk/alarm.c old mode 100755 new mode 100644 index 58c132ec1..a8dbeaa9f --- a/examples/platforms/emsk/alarm.c +++ b/examples/platforms/emsk/alarm.c @@ -32,14 +32,14 @@ * */ +#include "platform-emsk.h" #include #include #include "openthread/platform/alarm-milli.h" -#include "platform-emsk.h" static uint32_t sCounter = 0; static uint32_t expires; -static bool sIsRunning = false; +static bool sIsRunning = false; void emskAlarmInit(void) { @@ -54,7 +54,7 @@ uint32_t otPlatAlarmMilliGetNow(void) void otPlatAlarmMilliStartAt(otInstance *aInstance, uint32_t t0, uint32_t dt) { (void)aInstance; - expires = t0 + dt; + expires = t0 + dt; sIsRunning = true; } @@ -90,7 +90,6 @@ void emskAlarmUpdateTimeout(int32_t *aTimeout) exit: return; - } void emskAlarmProcess(otInstance *aInstance) @@ -106,7 +105,5 @@ void emskAlarmProcess(otInstance *aInstance) sIsRunning = false; otPlatAlarmMilliFired(aInstance); } - } - } diff --git a/examples/platforms/emsk/flash.c b/examples/platforms/emsk/flash.c index b789ff0a8..63917e049 100644 --- a/examples/platforms/emsk/flash.c +++ b/examples/platforms/emsk/flash.c @@ -32,11 +32,11 @@ * */ +#include "platform-emsk.h" +#include +#include #include #include "openthread/platform/alarm-milli.h" -#include -#include -#include "platform-emsk.h" /** * EMSK HAS 128 Mbit (16 MB) SPI flash memory (Winbond W25Q128BV). @@ -51,8 +51,8 @@ * Secondary bootloader: from 0x0078 0000 * Available for OpenThread: from 0x00FF D000 to 0x00FF EFFF */ -#define OPENTHREAD_FLASH_BASE 0x00ffd000 -#define OPENTHREAD_FLASH_SIZE 0x00002000 +#define OPENTHREAD_FLASH_BASE 0x00ffd000 +#define OPENTHREAD_FLASH_SIZE 0x00002000 /** * Define SETTINGS_CONFIG_BASE_ADDRESS, @@ -62,17 +62,17 @@ #ifdef SETTINGS_CONFIG_BASE_ADDRESS #undef SETTINGS_CONFIG_BASE_ADDRESS #endif // SETTINGS_CONFIG_BASE_ADDRESS -#define SETTINGS_CONFIG_BASE_ADDRESS 0x00ffe000 +#define SETTINGS_CONFIG_BASE_ADDRESS 0x00ffe000 #ifdef SETTINGS_CONFIG_PAGE_SIZE #undef SETTINGS_CONFIG_PAGE_SIZE #endif // SETTINGS_CONFIG_PAGE_SIZE -#define SETTINGS_CONFIG_PAGE_SIZE FLASH_SECTOR_SIZE +#define SETTINGS_CONFIG_PAGE_SIZE FLASH_SECTOR_SIZE #ifdef SETTINGS_CONFIG_PAGE_NUM #undef SETTINGS_CONFIG_PAGE_NUM #endif // SETTINGS_CONFIG_PAGE_NUM -#define SETTINGS_CONFIG_PAGE_NUM 1 +#define SETTINGS_CONFIG_PAGE_NUM 1 otError utilsFlashInit(void) { @@ -90,7 +90,8 @@ otError utilsFlashErasePage(uint32_t aAddress) otError error = OT_ERROR_NONE; int32_t status; - otEXPECT_ACTION((aAddress >= OPENTHREAD_FLASH_BASE) && (aAddress < (OPENTHREAD_FLASH_BASE + OPENTHREAD_FLASH_SIZE - 1)), + otEXPECT_ACTION((aAddress >= OPENTHREAD_FLASH_BASE) && + (aAddress < (OPENTHREAD_FLASH_BASE + OPENTHREAD_FLASH_SIZE - 1)), error = OT_ERROR_INVALID_ARGS); /* Use 2 sectors in the implementation, cannot erase the address over the boundry */ @@ -104,15 +105,15 @@ exit: otError utilsFlashStatusWait(uint32_t aTimeout) { - otError error = OT_ERROR_NONE; - uint32_t start = otPlatAlarmMilliGetNow(); - bool busy = true; + otError error = OT_ERROR_NONE; + uint32_t start = otPlatAlarmMilliGetNow(); + bool busy = true; uint32_t status = 0x01; while (busy && ((otPlatAlarmMilliGetNow() - start) < aTimeout)) { status = flash_read_status(); - busy = status & 0x01; + busy = status & 0x01; } otEXPECT_ACTION(!busy, error = OT_ERROR_BUSY); @@ -123,12 +124,13 @@ exit: uint32_t utilsFlashWrite(uint32_t aAddress, uint8_t *aData, uint32_t aSize) { - int32_t written_size = 0; - uint32_t size = 0; + int32_t written_size = 0; + uint32_t size = 0; otEXPECT_ACTION((aAddress >= OPENTHREAD_FLASH_BASE) && - ((aAddress + aSize) <= OPENTHREAD_FLASH_BASE + OPENTHREAD_FLASH_SIZE) && - (!(aAddress & 3)) && (!(aSize & 3)), ;); + ((aAddress + aSize) <= OPENTHREAD_FLASH_BASE + OPENTHREAD_FLASH_SIZE) && (!(aAddress & 3)) && + (!(aSize & 3)), + ;); written_size = flash_write(aAddress, aSize, aData); @@ -147,11 +149,12 @@ exit: uint32_t utilsFlashRead(uint32_t aAddress, uint8_t *aData, uint32_t aSize) { - int32_t read_size = 0; - uint32_t size = 0; + int32_t read_size = 0; + uint32_t size = 0; otEXPECT_ACTION((aAddress >= OPENTHREAD_FLASH_BASE) && - ((aAddress + aSize) <= OPENTHREAD_FLASH_BASE + OPENTHREAD_FLASH_SIZE), ;); + ((aAddress + aSize) <= OPENTHREAD_FLASH_BASE + OPENTHREAD_FLASH_SIZE), + ;); read_size = flash_read(aAddress, aSize, aData); @@ -164,7 +167,6 @@ uint32_t utilsFlashRead(uint32_t aAddress, uint8_t *aData, uint32_t aSize) size = (uint32_t)read_size; } - exit: return size; } diff --git a/examples/platforms/emsk/logging.c b/examples/platforms/emsk/logging.c old mode 100755 new mode 100644 index 2edeae529..0d4dba83f --- a/examples/platforms/emsk/logging.c +++ b/examples/platforms/emsk/logging.c @@ -32,11 +32,11 @@ * */ -#include -#include #include "openthread/platform/logging.h" +#include +#include -#if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED) +#if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED) void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat, ...) { (void)aLogLevel; diff --git a/examples/platforms/emsk/platform-emsk.h b/examples/platforms/emsk/platform-emsk.h old mode 100755 new mode 100644 index c0f2d1f33..430a0f937 --- a/examples/platforms/emsk/platform-emsk.h +++ b/examples/platforms/emsk/platform-emsk.h @@ -35,10 +35,10 @@ #ifndef PLATFORM_EMSK_H_ #define PLATFORM_EMSK_H_ -#include #include -#include #include +#include +#include #include "openthread/types.h" #include "board/board.h" @@ -87,4 +87,4 @@ void emskRandomInit(void); */ void emskUartProcess(void); -#endif // PLATFORM_EMSK_H_ +#endif // PLATFORM_EMSK_H_ diff --git a/examples/platforms/emsk/platform.c b/examples/platforms/emsk/platform.c old mode 100755 new mode 100644 index acc73fc2a..c15cb1811 --- a/examples/platforms/emsk/platform.c +++ b/examples/platforms/emsk/platform.c @@ -33,12 +33,12 @@ * */ +#include "platform-emsk.h" #include "openthread/openthread.h" #include "openthread/platform/uart.h" -#include "platform-emsk.h" #include -#define DBG(fmt, ...) printf(fmt, ##__VA_ARGS__) +#define DBG(fmt, ...) printf(fmt, ##__VA_ARGS__) void PlatformInit(int argc, char *argv[]) { diff --git a/examples/platforms/emsk/radio.c b/examples/platforms/emsk/radio.c index 0a423f1b6..6b981975f 100644 --- a/examples/platforms/emsk/radio.c +++ b/examples/platforms/emsk/radio.c @@ -31,73 +31,73 @@ * This file implements the OpenThread platform abstraction for radio communication. * */ -#include #include +#include #include "openthread/types.h" +#include "platform-emsk.h" #include #include #include -#include "platform-emsk.h" -#include "device/device_hal/inc/dev_gpio.h" #include +#include "device/device_hal/inc/dev_gpio.h" #include -#define DBG(fmt, ...) printf(fmt, ##__VA_ARGS__) +#define DBG(fmt, ...) printf(fmt, ##__VA_ARGS__) enum { - IEEE802154_MIN_LENGTH = 5, - IEEE802154_MAX_LENGTH = 127, - IEEE802154_ACK_LENGTH = 5, + IEEE802154_MIN_LENGTH = 5, + IEEE802154_MAX_LENGTH = 127, + IEEE802154_ACK_LENGTH = 5, - IEEE802154_BROADCAST = 0xffff, + IEEE802154_BROADCAST = 0xffff, - IEEE802154_FRAME_TYPE_ACK = 2 << 0, - IEEE802154_FRAME_TYPE_MACCMD = 3 << 0, - IEEE802154_FRAME_TYPE_MASK = 7 << 0, + IEEE802154_FRAME_TYPE_ACK = 2 << 0, + IEEE802154_FRAME_TYPE_MACCMD = 3 << 0, + IEEE802154_FRAME_TYPE_MASK = 7 << 0, - IEEE802154_SECURITY_ENABLED = 1 << 3, - IEEE802154_FRAME_PENDING = 1 << 4, - IEEE802154_ACK_REQUEST = 1 << 5, - IEEE802154_PANID_COMPRESSION = 1 << 6, + IEEE802154_SECURITY_ENABLED = 1 << 3, + IEEE802154_FRAME_PENDING = 1 << 4, + IEEE802154_ACK_REQUEST = 1 << 5, + IEEE802154_PANID_COMPRESSION = 1 << 6, - IEEE802154_DST_ADDR_NONE = 0 << 2, - IEEE802154_DST_ADDR_SHORT = 2 << 2, - IEEE802154_DST_ADDR_EXT = 3 << 2, - IEEE802154_DST_ADDR_MASK = 3 << 2, + IEEE802154_DST_ADDR_NONE = 0 << 2, + IEEE802154_DST_ADDR_SHORT = 2 << 2, + IEEE802154_DST_ADDR_EXT = 3 << 2, + IEEE802154_DST_ADDR_MASK = 3 << 2, - IEEE802154_SRC_ADDR_NONE = 0 << 6, - IEEE802154_SRC_ADDR_SHORT = 2 << 6, - IEEE802154_SRC_ADDR_EXT = 3 << 6, - IEEE802154_SRC_ADDR_MASK = 3 << 6, + IEEE802154_SRC_ADDR_NONE = 0 << 6, + IEEE802154_SRC_ADDR_SHORT = 2 << 6, + IEEE802154_SRC_ADDR_EXT = 3 << 6, + IEEE802154_SRC_ADDR_MASK = 3 << 6, - IEEE802154_DSN_OFFSET = 2, - IEEE802154_DSTPAN_OFFSET = 3, - IEEE802154_DSTADDR_OFFSET = 5, + IEEE802154_DSN_OFFSET = 2, + IEEE802154_DSTPAN_OFFSET = 3, + IEEE802154_DSTADDR_OFFSET = 5, - IEEE802154_SEC_LEVEL_MASK = 7 << 0, + IEEE802154_SEC_LEVEL_MASK = 7 << 0, - IEEE802154_KEY_ID_MODE_0 = 0 << 3, - IEEE802154_KEY_ID_MODE_1 = 1 << 3, - IEEE802154_KEY_ID_MODE_2 = 2 << 3, - IEEE802154_KEY_ID_MODE_3 = 3 << 3, - IEEE802154_KEY_ID_MODE_MASK = 3 << 3, + IEEE802154_KEY_ID_MODE_0 = 0 << 3, + IEEE802154_KEY_ID_MODE_1 = 1 << 3, + IEEE802154_KEY_ID_MODE_2 = 2 << 3, + IEEE802154_KEY_ID_MODE_3 = 3 << 3, + IEEE802154_KEY_ID_MODE_MASK = 3 << 3, - IEEE802154_MACCMD_DATA_REQ = 4 + IEEE802154_MACCMD_DATA_REQ = 4 }; enum { - EMSK_RECEIVE_SENSITIVITY = -100, // dBm + EMSK_RECEIVE_SENSITIVITY = -100, // dBm }; enum { MRF24J40_RSSI_OFFSET = 90, - MRF24J40_RSSI_SLOPE = 5 + MRF24J40_RSSI_SLOPE = 5 }; static void radioTransmitMessage(otInstance *aInstance); @@ -113,21 +113,21 @@ static uint8_t sTransmitPsdu[IEEE802154_MAX_LENGTH]; static uint8_t sReceivePsdu[IEEE802154_MAX_LENGTH]; static uint8_t sAckPsdu[IEEE802154_MAX_LENGTH]; -static otRadioState sState = OT_RADIO_STATE_DISABLED; -static bool sIsReceiverEnabled = false; +static otRadioState sState = OT_RADIO_STATE_DISABLED; +static bool sIsReceiverEnabled = false; -static volatile uint8_t Mrf24StatusTx = 0; -static volatile uint8_t Mrf24StatusRx = 0; +static volatile uint8_t Mrf24StatusTx = 0; +static volatile uint8_t Mrf24StatusRx = 0; static volatile uint8_t Mrf24StatusSec = 0; -static DEV_SPI_PTR pmrf_spi_ptr; +static DEV_SPI_PTR pmrf_spi_ptr; static DEV_GPIO_PTR pmrf_gpio_ptr; -static void RadioIsr(void *ptr); +static void RadioIsr(void *ptr); /* Variables for test */ -static uint32_t numInterruptRev = 0; +static uint32_t numInterruptRev = 0; static uint32_t numInterruptTrans = 0; -static uint32_t numRadioProcess = 0; +static uint32_t numRadioProcess = 0; static inline bool isSecurityEnabled(const uint8_t *frame) { @@ -267,18 +267,18 @@ void emskRadioInit(void) DEV_GPIO_BIT_ISR isr; DEV_GPIO_INT_CFG int_cfg; - int32_t ercd; + int32_t ercd; uint32_t temp; sTransmitFrame.mLength = 0; - sTransmitFrame.mPsdu = sTransmitPsdu; - sReceiveFrame.mLength = 0; - sReceiveFrame.mPsdu = sReceivePsdu; - sAckFrame.mLength = 0; - sAckFrame.mPsdu = sAckPsdu; + sTransmitFrame.mPsdu = sTransmitPsdu; + sReceiveFrame.mLength = 0; + sReceiveFrame.mPsdu = sReceivePsdu; + sAckFrame.mLength = 0; + sAckFrame.mPsdu = sAckPsdu; pmrf_spi_ptr = spi_get_dev(EMSK_PMRF_0_SPI_ID); - ercd = pmrf_spi_ptr->spi_open(DEV_MASTER_MODE, EMSK_PMRF_0_SPIFREQ); + ercd = pmrf_spi_ptr->spi_open(DEV_MASTER_MODE, EMSK_PMRF_0_SPIFREQ); if ((ercd != E_OK) && (ercd != E_OPNED)) { @@ -289,7 +289,7 @@ void emskRadioInit(void) /*MRF24J40 wakepin:output, rstpin:output, INT_PIN:input, interrupt */ pmrf_gpio_ptr = gpio_get_dev(EMSK_PMRF_0_GPIO_ID); - ercd = pmrf_gpio_ptr->gpio_open(MRF24J40_WAKE_PIN | MRF24J40_RST_PIN); + ercd = pmrf_gpio_ptr->gpio_open(MRF24J40_WAKE_PIN | MRF24J40_RST_PIN); if ((ercd != E_OK) && (ercd != E_OPNED)) { @@ -304,14 +304,14 @@ void emskRadioInit(void) pmrf_gpio_ptr->gpio_control(GPIO_CMD_DIS_BIT_INT, (void *)MRF24J40_INT_PIN); - temp = MRF24J40_INT_PIN; - int_cfg.int_bit_mask = temp; - int_cfg.int_bit_type = GPIO_INT_BITS_EDGE_TRIG(temp); + temp = MRF24J40_INT_PIN; + int_cfg.int_bit_mask = temp; + int_cfg.int_bit_type = GPIO_INT_BITS_EDGE_TRIG(temp); int_cfg.int_bit_polarity = GPIO_INT_BITS_POL_FALL_EDGE(temp); int_cfg.int_bit_debounce = GPIO_INT_BITS_DIS_DEBOUNCE(temp); pmrf_gpio_ptr->gpio_control(GPIO_CMD_SET_BIT_INT_CFG, (void *)(&int_cfg)); - isr.int_bit_ofs = MRF24J40_INT_PIN_OFS; + isr.int_bit_ofs = MRF24J40_INT_PIN_OFS; isr.int_bit_handler = RadioIsr; pmrf_gpio_ptr->gpio_control(GPIO_CMD_SET_BIT_ISR, (void *)(&isr)); @@ -321,7 +321,6 @@ void emskRadioInit(void) DBG("MRF24J40 Init Finished\r\n"); pmrf_gpio_ptr->gpio_control(GPIO_CMD_ENA_BIT_INT, (void *)MRF24J40_INT_PIN); - } bool otPlatRadioIsEnabled(otInstance *aInstance) @@ -357,7 +356,7 @@ otError otPlatRadioSleep(otInstance *aInstance) if (sState == OT_RADIO_STATE_SLEEP || sState == OT_RADIO_STATE_RECEIVE) { - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; sState = OT_RADIO_STATE_SLEEP; disableReceiver(); } @@ -372,7 +371,7 @@ otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) if (sState != OT_RADIO_STATE_DISABLED) { - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; sState = OT_RADIO_STATE_RECEIVE; setChannel(aChannel); sReceiveFrame.mChannel = aChannel; @@ -390,12 +389,11 @@ otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aFrame) if (sState == OT_RADIO_STATE_RECEIVE) { - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; sState = OT_RADIO_STATE_TRANSMIT; } return error; - } otRadioFrame *otPlatRadioGetTransmitBuffer(otInstance *aInstance) @@ -431,7 +429,6 @@ void otPlatRadioSetPromiscuous(otInstance *aInstance, bool aEnable) void readFrame(void) { - /* readBuffer * 1 bit -- 5 to 127 bits -- 1 bit -- 1bit * Frame Length -- PSDU (Header + Data Payload + FCS) -- LQI -- RSSI @@ -441,7 +438,7 @@ void readFrame(void) uint8_t readRssi = 0; uint16_t length; - int16_t i; + int16_t i; memset(readBuffer, 0, MRF24J40_RXFIFO_SIZE); @@ -466,19 +463,18 @@ void readFrame(void) #if OPENTHREAD_ENABLE_RAW_LINK_API // Timestamp sReceiveFrame.mMsec = otPlatAlarmMilliGetNow(); - sReceiveFrame.mUsec = 0; // Don't support microsecond timer for now. + sReceiveFrame.mUsec = 0; // Don't support microsecond timer for now. #endif /* Read PSDU */ memcpy(sReceiveFrame.mPsdu, readBuffer, length - 2); - sReceiveFrame.mRssi = (int8_t)(readRssi / MRF24J40_RSSI_SLOPE) - MRF24J40_RSSI_OFFSET; - sReceiveFrame.mLength = (uint8_t) length; - sReceiveFrame.mLqi = readPlqi; + sReceiveFrame.mRssi = (int8_t)(readRssi / MRF24J40_RSSI_SLOPE) - MRF24J40_RSSI_OFFSET; + sReceiveFrame.mLength = (uint8_t)length; + sReceiveFrame.mLqi = readPlqi; exit: return; - } void radioTransmitMessage(otInstance *aInstance) @@ -508,7 +504,8 @@ void radioTransmitMessage(otInstance *aInstance) else { reg &= ~(MRF24J40_TXNSECEN); - mrf24j40_write_short_ctrl_reg(MRF24J40_TXNCON, mrf24j40_read_short_ctrl_reg(MRF24J40_TXNCON) & (~MRF24J40_TXNSECEN)); + mrf24j40_write_short_ctrl_reg(MRF24J40_TXNCON, + mrf24j40_read_short_ctrl_reg(MRF24J40_TXNCON) & (~MRF24J40_TXNSECEN)); } mrf24j40_txfifo_write(MRF24J40_TXNFIFO, sTransmitFrame.mPsdu, header_len, (sTransmitFrame.mLength - 2)); @@ -518,7 +515,7 @@ void radioTransmitMessage(otInstance *aInstance) otPlatRadioTxStarted(aInstance, &sTransmitFrame); int16_t tx_timeout = 500; - Mrf24StatusTx = 0; + Mrf24StatusTx = 0; while ((tx_timeout > 0) && (Mrf24StatusTx != 1)) { @@ -566,13 +563,12 @@ void emskRadioProcess(otInstance *aInstance) else if (Mrf24StatusTx == 1) { Mrf24StatusTx = 0; - sState = OT_RADIO_STATE_RECEIVE; + sState = OT_RADIO_STATE_RECEIVE; otPlatRadioTxDone(aInstance, &sTransmitFrame, &sReceiveFrame, sTransmitError); } } sReceiveFrame.mLength = 0; - } /** @@ -618,7 +614,6 @@ static void RadioIsr(void *ptr) Mrf24StatusSec = 1; mrf24j40_sec_intcb(false); } - } /* CC2538 supports source address matching for low power consumption diff --git a/examples/platforms/emsk/random.c b/examples/platforms/emsk/random.c old mode 100755 new mode 100644 index c7ffdd788..aac1ca736 --- a/examples/platforms/emsk/random.c +++ b/examples/platforms/emsk/random.c @@ -37,9 +37,9 @@ #include -#include "openthread/platform/random.h" -#include "openthread/platform/radio.h" #include "platform-emsk.h" +#include "openthread/platform/radio.h" +#include "openthread/platform/random.h" #include @@ -60,14 +60,13 @@ void emskRandomInit(void) uint32_t otPlatRandomGet(void) { - return (uint32_t)rand(); } otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength) { - otError error = OT_ERROR_NONE; - uint8_t channel = 0; + otError error = OT_ERROR_NONE; + uint8_t channel = 0; otInstance *aInstance = NULL; otEXPECT_ACTION(aOutput && aOutputLength, error = OT_ERROR_INVALID_ARGS); diff --git a/examples/platforms/emsk/uart.c b/examples/platforms/emsk/uart.c index 501d4a8aa..e045bea53 100644 --- a/examples/platforms/emsk/uart.c +++ b/examples/platforms/emsk/uart.c @@ -34,18 +34,18 @@ #include -#include "openthread/types.h" +#include "platform-emsk.h" #include #include "openthread/platform/uart.h" -#include "platform-emsk.h" +#include "openthread/types.h" #include -#define DBG(fmt, ...) printf(fmt, ##__VA_ARGS__) +#define DBG(fmt, ...) printf(fmt, ##__VA_ARGS__) enum { - kUartId = BOARD_CONSOLE_UART_ID, - kBaudRate = BOARD_CONSOLE_UART_BAUD, + kUartId = BOARD_CONSOLE_UART_ID, + kBaudRate = BOARD_CONSOLE_UART_BAUD, kReceiveBufferSize = 128, }; @@ -53,9 +53,9 @@ static void processReceive(void); static void processTransmit(void); static const uint8_t *sTransmitBuffer = NULL; -static uint16_t sTransmitLength = 0; +static uint16_t sTransmitLength = 0; -static uint8_t sReceiveBuffer[kReceiveBufferSize]; +static uint8_t sReceiveBuffer[kReceiveBufferSize]; static uint16_t sReceiveHead = 0; static DEV_UART *consoleUart; @@ -63,7 +63,7 @@ static DEV_UART *consoleUart; otError otPlatUartEnable(void) { int32_t stateUart = 0; - otError error = OT_ERROR_DROP; + otError error = OT_ERROR_DROP; /* UART in embARC */ consoleUart = uart_get_dev(BOARD_CONSOLE_UART_ID); @@ -91,7 +91,6 @@ otError otPlatUartEnable(void) exit: return error; - } otError otPlatUartDisable(void) @@ -114,8 +113,7 @@ exit: void processReceive(void) { - - int32_t rdAvail = 0; + int32_t rdAvail = 0; uint16_t remaining; consoleUart->uart_control(UART_CMD_GET_RXAVAIL, (void *)(&rdAvail)); @@ -167,4 +165,3 @@ void emskUartProcess(void) processReceive(); processTransmit(); } - diff --git a/examples/platforms/gp712/alarm.c b/examples/platforms/gp712/alarm.c index dae725b9d..84be93fcb 100644 --- a/examples/platforms/gp712/alarm.c +++ b/examples/platforms/gp712/alarm.c @@ -36,10 +36,10 @@ #include #include +#include "alarm_qorvo.h" #include #include #include -#include "alarm_qorvo.h" void qorvoAlarmInit(void) { diff --git a/examples/platforms/gp712/flash.c b/examples/platforms/gp712/flash.c index 0d17ed3f1..5c296612e 100644 --- a/examples/platforms/gp712/flash.c +++ b/examples/platforms/gp712/flash.c @@ -45,9 +45,9 @@ static int sFlashFd; uint32_t sEraseAddress; -#define FLASH_SIZE 0x40000 +#define FLASH_SIZE 0x40000 #define FLASH_PAGE_SIZE 0x800 -#define FLASH_PAGE_NUM 128 +#define FLASH_PAGE_NUM 128 otError utilsFlashInit(void) { @@ -95,10 +95,10 @@ uint32_t utilsFlashGetSize(void) otError utilsFlashErasePage(uint32_t aAddress) { - otError error = OT_ERROR_NONE; - uint32_t address; - uint8_t dummyPage[ FLASH_SIZE ]; - ssize_t r; + otError error = OT_ERROR_NONE; + uint32_t address; + uint8_t dummyPage[FLASH_SIZE]; + ssize_t r; otEXPECT_ACTION(sFlashFd >= 0, error = OT_ERROR_FAILED); otEXPECT_ACTION(aAddress < FLASH_SIZE, error = OT_ERROR_INVALID_ARGS); @@ -110,10 +110,9 @@ otError utilsFlashErasePage(uint32_t aAddress) memset((void *)(&dummyPage[0]), 0xff, FLASH_PAGE_SIZE); // Write the page - r = pwrite(sFlashFd, &(dummyPage[0]), FLASH_PAGE_SIZE, (off_t)address); + r = pwrite(sFlashFd, &(dummyPage[0]), FLASH_PAGE_SIZE, (off_t)address); otEXPECT_ACTION((r) == ((FLASH_PAGE_SIZE)), error = OT_ERROR_FAILED); - exit: return error; } @@ -126,9 +125,9 @@ otError utilsFlashStatusWait(uint32_t aTimeout) uint32_t utilsFlashWrite(uint32_t aAddress, uint8_t *aData, uint32_t aSize) { - uint32_t ret = 0; + uint32_t ret = 0; uint32_t index = 0; - uint8_t byte; + uint8_t byte; otEXPECT(sFlashFd >= 0 && aAddress < FLASH_SIZE); diff --git a/examples/platforms/gp712/logging.c b/examples/platforms/gp712/logging.c index 01de39d7b..3ebdbef91 100644 --- a/examples/platforms/gp712/logging.c +++ b/examples/platforms/gp712/logging.c @@ -26,15 +26,15 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include -#include #include "platform_qorvo.h" +#include +#include #include #include #include -#include #include +#include #include #ifndef _WIN32 @@ -47,13 +47,13 @@ // Macro to append content to end of the log string. -#define LOG_PRINTF(...) \ - charsWritten = snprintf(&logString[offset], sizeof(logString) - offset , __VA_ARGS__); \ - otEXPECT_ACTION(charsWritten >= 0, logString[offset] = 0); \ - offset += (unsigned int)charsWritten; \ - otEXPECT_ACTION(offset < sizeof(logString), logString[sizeof(logString) -1 ] = 0) +#define LOG_PRINTF(...) \ + charsWritten = snprintf(&logString[offset], sizeof(logString) - offset, __VA_ARGS__); \ + otEXPECT_ACTION(charsWritten >= 0, logString[offset] = 0); \ + offset += (unsigned int)charsWritten; \ + otEXPECT_ACTION(offset < sizeof(logString), logString[sizeof(logString) - 1] = 0) -#if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED) +#if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED) int PlatOtLogLevelToSysLogLevel(otLogLevel aLogLevel) { diff --git a/examples/platforms/gp712/misc.c b/examples/platforms/gp712/misc.c index 42f1a2818..57ada14a6 100644 --- a/examples/platforms/gp712/misc.c +++ b/examples/platforms/gp712/misc.c @@ -28,16 +28,16 @@ #include "platform_qorvo.h" -#include #include +#include -#include -#include #include "radio_qorvo.h" #include +#include +#include -extern int gArgumentsCount; -extern char **gArguments; +extern int gArgumentsCount; +extern char **gArguments; extern void platformUartRestore(void); diff --git a/examples/platforms/gp712/platform.c b/examples/platforms/gp712/platform.c index 68315863e..3695f372c 100644 --- a/examples/platforms/gp712/platform.c +++ b/examples/platforms/gp712/platform.c @@ -49,8 +49,8 @@ void platformUartProcess(void); otInstance *localInstance = NULL; -int gArgumentsCount = 0; -char **gArguments = NULL; +int gArgumentsCount = 0; +char **gArguments = NULL; bool qorvoPlatGotoSleepCheck(void) { @@ -71,10 +71,9 @@ void PlatformInit(int argc, char *argv[]) qorvoPlatInit((qorvoPlatGotoSleepCheckCallback_t)qorvoPlatGotoSleepCheck); platformUartInit(); - //qorvoAlarmInit(); + // qorvoAlarmInit(); qorvoRandomInit(); qorvoRadioInit(); - } void PlatformProcessDrivers(otInstance *aInstance) @@ -87,7 +86,6 @@ void PlatformProcessDrivers(otInstance *aInstance) qorvoPlatMainLoop(!otTaskletsArePending(aInstance)); platformUartProcess(); - //qorvoRadioProcess(); - //qorvoAlarmProcess(); - + // qorvoRadioProcess(); + // qorvoAlarmProcess(); } diff --git a/examples/platforms/gp712/radio.c b/examples/platforms/gp712/radio.c index 99d95ce39..e36df33d3 100644 --- a/examples/platforms/gp712/radio.c +++ b/examples/platforms/gp712/radio.c @@ -36,8 +36,8 @@ #include -#include #include +#include #include "utils/code_utils.h" @@ -45,7 +45,7 @@ enum { - GP712_RECEIVE_SENSITIVITY = -100, // dBm + GP712_RECEIVE_SENSITIVITY = -100, // dBm }; enum @@ -62,15 +62,15 @@ enum enum { - QORVO_RSSI_OFFSET = 73, - QORVO_CRC_BIT_MASK = 0x80, - QORVO_LQI_BIT_MASK = 0x7f, + QORVO_RSSI_OFFSET = 73, + QORVO_CRC_BIT_MASK = 0x80, + QORVO_LQI_BIT_MASK = 0x7f, }; -extern otRadioFrame sTransmitFrame; +extern otRadioFrame sTransmitFrame; -static otRadioState sState; -static otInstance *pQorvoInstance; +static otRadioState sState; +static otInstance * pQorvoInstance; typedef struct otCachedSettings_s { @@ -79,8 +79,8 @@ typedef struct otCachedSettings_s static otCachedSettings_t otCachedSettings; -static uint8_t sScanstate = 0; -static int8_t sLastReceivedPower = 127; +static uint8_t sScanstate = 0; +static int8_t sLastReceivedPower = 127; void otPlatRadioGetIeeeEui64(otInstance *aInstance, uint8_t *aIeeeEui64) { @@ -150,7 +150,7 @@ otError otPlatRadioSleep(otInstance *aInstance) if (sState == OT_RADIO_STATE_RECEIVE) { qorvoRadioSetRxOnWhenIdle(false); - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; sState = OT_RADIO_STATE_SLEEP; } @@ -159,7 +159,7 @@ otError otPlatRadioSleep(otInstance *aInstance) otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) { - otError error = OT_ERROR_INVALID_STATE; + otError error = OT_ERROR_INVALID_STATE; pQorvoInstance = aInstance; if ((sState != OT_RADIO_STATE_DISABLED) && (sScanstate == 0)) @@ -171,12 +171,11 @@ otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) if (sState == OT_RADIO_STATE_SLEEP) { qorvoRadioSetRxOnWhenIdle(true); - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; sState = OT_RADIO_STATE_RECEIVE; } return error; - } otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aPacket) @@ -197,10 +196,10 @@ void cbQorvoRadioTransmitDone(otRadioFrame *aPacket, bool aFramePending, otError { // TODO: pass received ACK frame instead of generating one. otRadioFrame ackFrame; - uint8_t psdu[IEEE802154_ACK_LENGTH]; + uint8_t psdu[IEEE802154_ACK_LENGTH]; - ackFrame.mPsdu = psdu; - ackFrame.mLength = IEEE802154_ACK_LENGTH; + ackFrame.mPsdu = psdu; + ackFrame.mLength = IEEE802154_ACK_LENGTH; ackFrame.mPsdu[0] = IEEE802154_FRAME_TYPE_ACK; if (aFramePending) @@ -254,7 +253,6 @@ void otPlatRadioSetPromiscuous(otInstance *aInstance, bool aEnable) (void)aEnable; } - void otPlatRadioEnableSrcMatch(otInstance *aInstance, bool aEnable) { (void)aInstance; diff --git a/examples/platforms/gp712/random.c b/examples/platforms/gp712/random.c index 757be1507..550c8dc3a 100644 --- a/examples/platforms/gp712/random.c +++ b/examples/platforms/gp712/random.c @@ -35,7 +35,6 @@ #include #include - #include #include @@ -52,11 +51,11 @@ void qorvoRandomInit(void) error = otPlatRandomGetTrue((uint8_t *)&sState, sizeof(sState)); assert(error == OT_ERROR_NONE); -#else // __SANITIZE_ADDRESS__ +#else // __SANITIZE_ADDRESS__ sState = (uint32_t)time(NULL); -#endif // __SANITIZE_ADDRESS__ +#endif // __SANITIZE_ADDRESS__ } uint32_t otPlatRandomGet(void) @@ -65,10 +64,10 @@ uint32_t otPlatRandomGet(void) uint64_t tmpstate; tmpstate = (uint64_t)33614 * (uint64_t)sState; - q = tmpstate & 0xffffffff; - q = q >> 1; - p = tmpstate >> 32; - mlcg = p + q; + q = tmpstate & 0xffffffff; + q = q >> 1; + p = tmpstate >> 32; + mlcg = p + q; if (mlcg & 0x80000000) { @@ -87,7 +86,7 @@ otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength) #if __SANITIZE_ADDRESS__ == 0 - FILE *file = NULL; + FILE * file = NULL; size_t readLength; otEXPECT_ACTION(aOutput && aOutputLength, error = OT_ERROR_INVALID_ARGS); @@ -105,7 +104,7 @@ exit: fclose(file); } -#else // __SANITIZE_ADDRESS__ +#else // __SANITIZE_ADDRESS__ /* * THE IMPLEMENTATION BELOW IS NOT COMPLIANT WITH THE THREAD SPECIFICATION. @@ -124,7 +123,7 @@ exit: exit: -#endif // __SANITIZE_ADDRESS__ +#endif // __SANITIZE_ADDRESS__ return error; } diff --git a/examples/platforms/gp712/uart-posix.c b/examples/platforms/gp712/uart-posix.c index 7b991a45f..98c13b574 100644 --- a/examples/platforms/gp712/uart-posix.c +++ b/examples/platforms/gp712/uart-posix.c @@ -26,16 +26,16 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include "platform_qorvo.h" #include "alarm_qorvo.h" +#include "platform_qorvo.h" #include #include #include #include #include -#include #include +#include #include #include @@ -45,17 +45,17 @@ #ifdef OPENTHREAD_TARGET_LINUX #include -int posix_openpt(int oflag); -int grantpt(int fildes); -int unlockpt(int fd); +int posix_openpt(int oflag); +int grantpt(int fildes); +int unlockpt(int fd); char *ptsname(int fd); -#endif // OPENTHREAD_TARGET_LINUX +#endif // OPENTHREAD_TARGET_LINUX -static uint8_t s_receive_buffer[128]; +static uint8_t s_receive_buffer[128]; static const uint8_t *s_write_buffer; -static uint16_t s_write_length; -static int s_in_fd; -static int s_out_fd; +static uint16_t s_write_length; +static int s_in_fd; +static int s_out_fd; static struct termios original_stdin_termios; static struct termios original_stdout_termios; @@ -77,8 +77,8 @@ void platformDummy(void *dummyPointer) static void cbKeyPressed(uint8_t Param) { - (void) Param; - qorvoAlarmScheduleEventArg(0, platformDummy, (void *) &s_in_fd); + (void)Param; + qorvoAlarmScheduleEventArg(0, platformDummy, (void *)&s_in_fd); } void platformUartRestore(void) @@ -90,7 +90,7 @@ void platformUartRestore(void) void platformUartInit(void) { - s_in_fd = dup(STDIN_FILENO); + s_in_fd = dup(STDIN_FILENO); s_out_fd = dup(STDOUT_FILENO); dup2(STDERR_FILENO, STDOUT_FILENO); @@ -100,7 +100,7 @@ void platformUartInit(void) otError otPlatUartEnable(void) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; struct termios termios; #ifdef OPENTHREAD_TARGET_LINUX @@ -138,7 +138,7 @@ otError otPlatUartEnable(void) termios.c_cflag |= HUPCL | CREAD | CLOCAL; // "Minimum number of characters for noncanonical read" - termios.c_cc[VMIN] = 1; + termios.c_cc[VMIN] = 1; // "Timeout in deciseconds for noncanonical read" termios.c_cc[VTIME] = 0; @@ -208,12 +208,11 @@ exit: void platformUartProcess(void) { - ssize_t rval; - const int error_flags = POLLERR | POLLNVAL | POLLHUP; - struct pollfd pollfd[] = - { - { s_in_fd, POLLIN | error_flags, 0 }, - { s_out_fd, POLLOUT | error_flags, 0 }, + ssize_t rval; + const int error_flags = POLLERR | POLLNVAL | POLLHUP; + struct pollfd pollfd[] = { + {s_in_fd, POLLIN | error_flags, 0}, + {s_out_fd, POLLOUT | error_flags, 0}, }; errno = 0; diff --git a/examples/platforms/kw41z/alarm.c b/examples/platforms/kw41z/alarm.c index bbb0b9417..2b6457747 100644 --- a/examples/platforms/kw41z/alarm.c +++ b/examples/platforms/kw41z/alarm.c @@ -32,10 +32,10 @@ * */ -#include -#include "fsl_device_registers.h" #include "fsl_clock.h" +#include "fsl_device_registers.h" #include "fsl_pit.h" +#include #include "openthread/openthread.h" #include "openthread/platform/alarm-milli.h" @@ -47,7 +47,7 @@ static uint32_t sAlarmTime = 0; void kw41zAlarmInit(void) { pit_config_t config; - uint32_t count = (CLOCK_GetBusClkFreq() / 1000) - 1; + uint32_t count = (CLOCK_GetBusClkFreq() / 1000) - 1; PIT_GetDefaultConfig(&config); PIT_Init(PIT, &config); diff --git a/examples/platforms/kw41z/flash.c b/examples/platforms/kw41z/flash.c index eb050c981..9d9441043 100644 --- a/examples/platforms/kw41z/flash.c +++ b/examples/platforms/kw41z/flash.c @@ -26,12 +26,12 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include #include "fsl_device_registers.h" #include "fsl_flash.h" -#include "openthread/platform/alarm-milli.h" -#include +#include #include +#include +#include "openthread/platform/alarm-milli.h" static flash_config_t sFlashConfig; @@ -54,7 +54,7 @@ uint32_t utilsFlashGetSize(void) otError utilsFlashErasePage(uint32_t aAddress) { - otError error; + otError error; status_t status; status = FLASH_Erase(&sFlashConfig, aAddress, FSL_FEATURE_FLASH_PFLASH_BLOCK_SECTOR_SIZE, kFLASH_ApiEraseKey); @@ -77,7 +77,7 @@ otError utilsFlashErasePage(uint32_t aAddress) otError utilsFlashStatusWait(uint32_t aTimeout) { - otError error = OT_ERROR_BUSY; + otError error = OT_ERROR_BUSY; uint32_t start = otPlatAlarmMilliGetNow(); do @@ -87,8 +87,7 @@ otError utilsFlashStatusWait(uint32_t aTimeout) error = OT_ERROR_NONE; break; } - } - while (aTimeout && ((otPlatAlarmMilliGetNow() - start) < aTimeout)); + } while (aTimeout && ((otPlatAlarmMilliGetNow() - start) < aTimeout)); return error; } diff --git a/examples/platforms/kw41z/logging.c b/examples/platforms/kw41z/logging.c index 3ab8cfdce..cc8dbc32e 100644 --- a/examples/platforms/kw41z/logging.c +++ b/examples/platforms/kw41z/logging.c @@ -32,11 +32,11 @@ * */ -#include #include "fsl_device_registers.h" +#include -#include #include +#include #include "openthread/platform/logging.h" #if OPENTHREAD_ENABLE_CLI_LOGGING @@ -46,11 +46,11 @@ #include #include -#include #include +#include #endif -#if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED) +#if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED) void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat, ...) { #if OPENTHREAD_ENABLE_CLI_LOGGING diff --git a/examples/platforms/kw41z/misc.c b/examples/platforms/kw41z/misc.c index 6b5192ec1..20ada534c 100644 --- a/examples/platforms/kw41z/misc.c +++ b/examples/platforms/kw41z/misc.c @@ -26,17 +26,19 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include -#include "fsl_device_registers.h" -#include "openthread/types.h" #include "openthread/platform/misc.h" +#include "fsl_device_registers.h" +#include +#include "openthread/types.h" void otPlatReset(otInstance *aInstance) { (void)aInstance; NVIC_SystemReset(); - while (1) {} + while (1) + { + } } otPlatResetReason otPlatGetResetReason(otInstance *aInstance) @@ -60,14 +62,12 @@ otPlatResetReason otPlatGetResetReason(otInstance *aInstance) { reason = OT_PLAT_RESET_REASON_EXTERNAL; } - else if ((RCM->SRS0 & RCM_SRS0_LOC_MASK) || - (RCM->SRS1 & RCM_SRS1_SACKERR_MASK) || + else if ((RCM->SRS0 & RCM_SRS0_LOC_MASK) || (RCM->SRS1 & RCM_SRS1_SACKERR_MASK) || (RCM->SRS1 & RCM_SRS1_LOCKUP_MASK)) { reason = OT_PLAT_RESET_REASON_FAULT; } - else if ((RCM->SRS0 & RCM_SRS0_WAKEUP_MASK) || - (RCM->SRS0 & RCM_SRS0_LVD_MASK) || + else if ((RCM->SRS0 & RCM_SRS0_WAKEUP_MASK) || (RCM->SRS0 & RCM_SRS0_LVD_MASK) || (RCM->SRS1 & RCM_SRS1_MDM_AP_MASK)) { reason = OT_PLAT_RESET_REASON_ASSERT; diff --git a/examples/platforms/kw41z/platform.c b/examples/platforms/kw41z/platform.c index a34791114..75629ca62 100644 --- a/examples/platforms/kw41z/platform.c +++ b/examples/platforms/kw41z/platform.c @@ -32,21 +32,21 @@ * */ -#include -#include "fsl_device_registers.h" -#include "openthread/types.h" -#include "openthread/platform/uart.h" -#include "platform-kw41z.h" -#include "fsl_clock.h" -#include "fsl_port.h" #include "clock_config.h" +#include "fsl_clock.h" +#include "fsl_device_registers.h" +#include "fsl_port.h" +#include "platform-kw41z.h" +#include +#include "openthread/platform/uart.h" +#include "openthread/types.h" otInstance *sInstance; void PlatformInit(int argc, char *argv[]) { uint32_t temp, tempTrim; - uint8_t revId; + uint8_t revId; /* enable clock for PORTs */ CLOCK_EnableClock(kCLOCK_PortA); @@ -74,7 +74,9 @@ void PlatformInit(int argc, char *argv[]) RSIM->RF_OSC_CTRL |= RSIM_RF_OSC_CTRL_RADIO_EXT_OSC_OVRD_EN_MASK; /* wait for RF_OSC_READY */ - while ((RSIM->CONTROL & RSIM_CONTROL_RF_OSC_READY_MASK) == 0) {} + while ((RSIM->CONTROL & RSIM_CONTROL_RF_OSC_READY_MASK) == 0) + { + } if (revId == 0) { @@ -83,7 +85,7 @@ void PlatformInit(int argc, char *argv[]) XCVR_TSM_OVRD0_BB_LDO_ADCDAC_EN_OVRD_MASK; /* Force ADC DAC LDO on to prevent BGAP failure */ /* Reset LDO trim settings */ RSIM->ANA_TRIM = tempTrim; - }/* Workaround for Rev 1.0 XTAL startup and ADC analog diagnostics circuitry */ + } /* Workaround for Rev 1.0 XTAL startup and ADC analog diagnostics circuitry */ /* Init board clock */ BOARD_BootClockRUN(); diff --git a/examples/platforms/kw41z/radio.c b/examples/platforms/kw41z/radio.c index d87a0f675..7ab8d8548 100644 --- a/examples/platforms/kw41z/radio.c +++ b/examples/platforms/kw41z/radio.c @@ -32,16 +32,16 @@ * */ +#include "fsl_device_registers.h" +#include "fsl_xcvr.h" +#include "openthread-core-kw41z-config.h" #include #include -#include "fsl_device_registers.h" -#include "openthread-core-kw41z-config.h" -#include "fsl_xcvr.h" -#include -#include -#include #include +#include +#include +#include // clang-format off #define DOUBLE_BUFFERING (1) @@ -65,8 +65,7 @@ ZLL_IRQSTS_TMR4MSK_MASK ) // clang-format on -typedef enum xcvr_state_tag -{ +typedef enum xcvr_state_tag { XCVR_Idle_c, XCVR_RX_c, XCVR_TX_c, @@ -75,31 +74,30 @@ typedef enum xcvr_state_tag XCVR_CCCA_c, } xcvr_state_t; -typedef enum xcvr_cca_type_tag -{ - XCVR_ED_c, /* energy detect - CCA bit not active, not to be used for T and CCCA sequences */ - XCVR_CCA_MODE1_c, /* energy detect - CCA bit ACTIVE */ - SCVR_CCA_MODE2_c, /* 802.15.4 compliant signal detect - CCA bit ACTIVE */ - XCVR_CCA_MODE3_c /* 802.15.4 compliant signal detect and energy detect - CCA bit ACTIVE */ +typedef enum xcvr_cca_type_tag { + XCVR_ED_c, /* energy detect - CCA bit not active, not to be used for T and CCCA sequences */ + XCVR_CCA_MODE1_c, /* energy detect - CCA bit ACTIVE */ + SCVR_CCA_MODE2_c, /* 802.15.4 compliant signal detect - CCA bit ACTIVE */ + XCVR_CCA_MODE3_c /* 802.15.4 compliant signal detect and energy detect - CCA bit ACTIVE */ } xcvr_cca_type_t; -static otRadioState sState = OT_RADIO_STATE_DISABLED; -static uint16_t sPanId; -static uint8_t sExtSrcAddrBitmap[(RADIO_CONFIG_SRC_MATCH_ENTRY_NUM + 7) / 8]; -static uint8_t sChannel; -static int8_t sMaxED; -static int8_t sAutoTxPwrLevel = 0; +static otRadioState sState = OT_RADIO_STATE_DISABLED; +static uint16_t sPanId; +static uint8_t sExtSrcAddrBitmap[(RADIO_CONFIG_SRC_MATCH_ENTRY_NUM + 7) / 8]; +static uint8_t sChannel; +static int8_t sMaxED; +static int8_t sAutoTxPwrLevel = 0; /* ISR Signaling Flags */ -static bool sTxDone = false; -static bool sRxDone = false; -static bool sEdScanDone = false; -static otError sTxStatus; +static bool sTxDone = false; +static bool sRxDone = false; +static bool sEdScanDone = false; +static otError sTxStatus; -static otRadioFrame sTxFrame; -static otRadioFrame sRxFrame; +static otRadioFrame sTxFrame; +static otRadioFrame sRxFrame; #if DOUBLE_BUFFERING -static uint8_t sRxData[OT_RADIO_FRAME_MAX_SIZE]; +static uint8_t sRxData[OT_RADIO_FRAME_MAX_SIZE]; #endif /* Private functions */ @@ -146,7 +144,7 @@ void otPlatRadioGetIeeeEui64(otInstance *aInstance, uint8_t *aIeeeEui64) void otPlatRadioSetPanId(otInstance *aInstance, uint16_t aPanId) { - (void) aInstance; + (void)aInstance; sPanId = aPanId; ZLL->MACSHORTADDRS0 &= ~ZLL_MACSHORTADDRS0_MACPANID0_MASK; @@ -155,7 +153,7 @@ void otPlatRadioSetPanId(otInstance *aInstance, uint16_t aPanId) void otPlatRadioSetExtendedAddress(otInstance *aInstance, const otExtAddress *aExtAddress) { - (void) aInstance; + (void)aInstance; uint32_t addrLo; uint32_t addrHi; @@ -168,7 +166,7 @@ void otPlatRadioSetExtendedAddress(otInstance *aInstance, const otExtAddress *aE void otPlatRadioSetShortAddress(otInstance *aInstance, uint16_t aShortAddress) { - (void) aInstance; + (void)aInstance; ZLL->MACSHORTADDRS0 &= ~ZLL_MACSHORTADDRS0_MACSHORTADDRS0_MASK; ZLL->MACSHORTADDRS0 |= ZLL_MACSHORTADDRS0_MACSHORTADDRS0(aShortAddress); @@ -202,17 +200,17 @@ exit: bool otPlatRadioIsEnabled(otInstance *aInstance) { - (void) aInstance; + (void)aInstance; return sState != OT_RADIO_STATE_DISABLED; } otError otPlatRadioSleep(otInstance *aInstance) { otError status = OT_ERROR_NONE; - (void) aInstance; + (void)aInstance; - otEXPECT_ACTION(((sState != OT_RADIO_STATE_TRANSMIT) && - (sState != OT_RADIO_STATE_DISABLED)), status = OT_ERROR_INVALID_STATE); + otEXPECT_ACTION(((sState != OT_RADIO_STATE_TRANSMIT) && (sState != OT_RADIO_STATE_DISABLED)), + status = OT_ERROR_INVALID_STATE); rf_abort(); sState = OT_RADIO_STATE_SLEEP; @@ -224,10 +222,10 @@ exit: otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) { otError status = OT_ERROR_NONE; - (void) aInstance; + (void)aInstance; - otEXPECT_ACTION(((sState != OT_RADIO_STATE_TRANSMIT) && - (sState != OT_RADIO_STATE_DISABLED)), status = OT_ERROR_INVALID_STATE); + otEXPECT_ACTION(((sState != OT_RADIO_STATE_TRANSMIT) && (sState != OT_RADIO_STATE_DISABLED)), + status = OT_ERROR_INVALID_STATE); sState = OT_RADIO_STATE_RECEIVE; @@ -243,7 +241,7 @@ otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) /* Clear all IRQ flags */ ZLL->IRQSTS = ZLL->IRQSTS; /* Start the RX sequence */ - ZLL->PHY_CTRL |= XCVR_RX_c ; + ZLL->PHY_CTRL |= XCVR_RX_c; /* Unmask SEQ interrupt */ ZLL->PHY_CTRL &= ~ZLL_PHY_CTRL_SEQMSK_MASK; @@ -254,7 +252,7 @@ exit: void otPlatRadioEnableSrcMatch(otInstance *aInstance, bool aEnable) { - (void) aInstance; + (void)aInstance; if (aEnable) { @@ -268,7 +266,7 @@ void otPlatRadioEnableSrcMatch(otInstance *aInstance, bool aEnable) otError otPlatRadioAddSrcMatchShortEntry(otInstance *aInstance, const uint16_t aShortAddress) { - (void) aInstance; + (void)aInstance; uint16_t checksum = sPanId + aShortAddress; return rf_add_addr_table_entry(checksum, false); @@ -276,7 +274,7 @@ otError otPlatRadioAddSrcMatchShortEntry(otInstance *aInstance, const uint16_t a otError otPlatRadioAddSrcMatchExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) { - (void) aInstance; + (void)aInstance; uint16_t checksum = rf_get_addr_checksum((uint8_t *)aExtAddress->m8, true, sPanId); return rf_add_addr_table_entry(checksum, true); @@ -284,7 +282,7 @@ otError otPlatRadioAddSrcMatchExtEntry(otInstance *aInstance, const otExtAddress otError otPlatRadioClearSrcMatchShortEntry(otInstance *aInstance, const uint16_t aShortAddress) { - (void) aInstance; + (void)aInstance; uint16_t checksum = sPanId + aShortAddress; return rf_remove_addr_table_entry(checksum); @@ -292,7 +290,7 @@ otError otPlatRadioClearSrcMatchShortEntry(otInstance *aInstance, const uint16_t otError otPlatRadioClearSrcMatchExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) { - (void) aInstance; + (void)aInstance; uint16_t checksum = rf_get_addr_checksum((uint8_t *)aExtAddress->m8, true, sPanId); return rf_remove_addr_table_entry(checksum); @@ -300,7 +298,7 @@ otError otPlatRadioClearSrcMatchExtEntry(otInstance *aInstance, const otExtAddre void otPlatRadioClearSrcMatchShortEntries(otInstance *aInstance) { - (void) aInstance; + (void)aInstance; uint32_t i; for (i = 0; i < RADIO_CONFIG_SRC_MATCH_ENTRY_NUM; i++) @@ -315,7 +313,7 @@ void otPlatRadioClearSrcMatchShortEntries(otInstance *aInstance) void otPlatRadioClearSrcMatchExtEntries(otInstance *aInstance) { - (void) aInstance; + (void)aInstance; uint32_t i; for (i = 0; i < RADIO_CONFIG_SRC_MATCH_ENTRY_NUM; i++) @@ -336,11 +334,11 @@ otRadioFrame *otPlatRadioGetTransmitBuffer(otInstance *aInstance) otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aFrame) { - otError status = OT_ERROR_NONE; + otError status = OT_ERROR_NONE; uint32_t timeout; - otEXPECT_ACTION(((sState != OT_RADIO_STATE_TRANSMIT) && - (sState != OT_RADIO_STATE_DISABLED)), status = OT_ERROR_INVALID_STATE); + otEXPECT_ACTION(((sState != OT_RADIO_STATE_TRANSMIT) && (sState != OT_RADIO_STATE_DISABLED)), + status = OT_ERROR_INVALID_STATE); if (rf_get_state() != XCVR_Idle_c) { @@ -363,9 +361,10 @@ otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aFrame) { ZLL->PHY_CTRL |= XCVR_TR_c; /* Set ACK wait time-out */ - timeout = rf_get_timestamp(); + timeout = rf_get_timestamp(); timeout += (((XCVR_TSM->END_OF_SEQ & XCVR_TSM_END_OF_SEQ_END_OF_TX_WU_MASK) >> - XCVR_TSM_END_OF_SEQ_END_OF_TX_WU_SHIFT) >> 4); + XCVR_TSM_END_OF_SEQ_END_OF_TX_WU_SHIFT) >> + 4); timeout += IEEE802154_CCA_LEN + IEEE802154_TURNAROUND_LEN + IEEE802154_PHY_SHR_LEN + (1 + aFrame->mLength) * OT_RADIO_SYMBOLS_PER_OCTET + IEEE802154_ACK_WAIT; rf_set_timeout(timeout); @@ -376,7 +375,7 @@ otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aFrame) } sTxStatus = OT_ERROR_NONE; - sState = OT_RADIO_STATE_TRANSMIT; + sState = OT_RADIO_STATE_TRANSMIT; /* Unmask SEQ interrupt */ ZLL->PHY_CTRL &= ~ZLL_PHY_CTRL_SEQMSK_MASK; @@ -388,7 +387,7 @@ exit: int8_t otPlatRadioGetRssi(otInstance *aInstance) { - (void) aInstance; + (void)aInstance; return (ZLL->LQI_AND_RSSI & ZLL_LQI_AND_RSSI_RSSI_MASK) >> ZLL_LQI_AND_RSSI_RSSI_SHIFT; } @@ -400,20 +399,19 @@ otRadioCaps otPlatRadioGetCaps(otInstance *aInstance) bool otPlatRadioGetPromiscuous(otInstance *aInstance) { - (void) aInstance; + (void)aInstance; return (ZLL->PHY_CTRL & ZLL_PHY_CTRL_PROMISCUOUS_MASK) == ZLL_PHY_CTRL_PROMISCUOUS_MASK; } void otPlatRadioSetPromiscuous(otInstance *aInstance, bool aEnable) { - (void) aInstance; + (void)aInstance; if (aEnable) { ZLL->PHY_CTRL |= ZLL_PHY_CTRL_PROMISCUOUS_MASK; /* FRM_VER[11:8] = b1111. Any FrameVersion accepted */ - ZLL->RX_FRAME_FILTER |= (ZLL_RX_FRAME_FILTER_FRM_VER_FILTER_MASK | - ZLL_RX_FRAME_FILTER_ACK_FT_MASK | + ZLL->RX_FRAME_FILTER |= (ZLL_RX_FRAME_FILTER_FRM_VER_FILTER_MASK | ZLL_RX_FRAME_FILTER_ACK_FT_MASK | ZLL_RX_FRAME_FILTER_NS_FT_MASK); } else @@ -421,22 +419,20 @@ void otPlatRadioSetPromiscuous(otInstance *aInstance, bool aEnable) ZLL->PHY_CTRL &= ~ZLL_PHY_CTRL_PROMISCUOUS_MASK; /* FRM_VER[11:8] = b0011. Accept FrameVersion 0 and 1 packets, reject all others */ /* Beacon, Data and MAC command frame types accepted */ - ZLL->RX_FRAME_FILTER &= ~(ZLL_RX_FRAME_FILTER_FRM_VER_FILTER_MASK | - ZLL_RX_FRAME_FILTER_ACK_FT_MASK | - ZLL_RX_FRAME_FILTER_NS_FT_MASK | - ZLL_RX_FRAME_FILTER_ACTIVE_PROMISCUOUS_MASK); + ZLL->RX_FRAME_FILTER &= ~(ZLL_RX_FRAME_FILTER_FRM_VER_FILTER_MASK | ZLL_RX_FRAME_FILTER_ACK_FT_MASK | + ZLL_RX_FRAME_FILTER_NS_FT_MASK | ZLL_RX_FRAME_FILTER_ACTIVE_PROMISCUOUS_MASK); ZLL->RX_FRAME_FILTER |= ZLL_RX_FRAME_FILTER_FRM_VER_FILTER(3); } } otError otPlatRadioEnergyScan(otInstance *aInstance, uint8_t aScanChannel, uint16_t aScanDuration) { - otError status = OT_ERROR_NONE; + otError status = OT_ERROR_NONE; uint32_t timeout; - (void) aInstance; + (void)aInstance; - otEXPECT_ACTION(((sState != OT_RADIO_STATE_TRANSMIT) && - (sState != OT_RADIO_STATE_DISABLED)), status = OT_ERROR_INVALID_STATE); + otEXPECT_ACTION(((sState != OT_RADIO_STATE_TRANSMIT) && (sState != OT_RADIO_STATE_DISABLED)), + status = OT_ERROR_INVALID_STATE); if (rf_get_state() != XCVR_Idle_c) { @@ -455,7 +451,7 @@ otError otPlatRadioEnergyScan(otInstance *aInstance, uint8_t aScanChannel, uint1 /* Unmask SEQ interrupt */ ZLL->PHY_CTRL &= ~ZLL_PHY_CTRL_SEQMSK_MASK; /* Set Scan time-out */ - timeout = rf_get_timestamp(); + timeout = rf_get_timestamp(); timeout += (aScanDuration * 1000) / OT_RADIO_SYMBOL_TIME; rf_set_timeout(timeout); @@ -535,7 +531,7 @@ static void rf_set_channel(uint8_t channel) if (sChannel != channel) { ZLL->CHANNEL_NUM0 = channel; - sChannel = channel; + sChannel = channel; } } @@ -592,7 +588,7 @@ static uint16_t rf_get_addr_checksum(uint8_t *pAddr, bool ExtendedAddr, uint16_t uint16_t checksum; /* Short address */ - checksum = PanId; + checksum = PanId; checksum += *pAddr++; checksum += (uint16_t)(*pAddr++) << 8; @@ -627,9 +623,9 @@ static otError rf_add_addr_table_entry(uint16_t checksum, bool extendedAddr) otEXPECT_ACTION((index < RADIO_CONFIG_SRC_MATCH_ENTRY_NUM), status = OT_ERROR_NO_BUFS); /* Insert the checksum at the index found */ - ZLL->SAM_TABLE = ((uint32_t)index << ZLL_SAM_TABLE_SAM_INDEX_SHIFT) | - ((uint32_t)checksum << ZLL_SAM_TABLE_SAM_CHECKSUM_SHIFT) | - ZLL_SAM_TABLE_SAM_INDEX_WR_MASK | ZLL_SAM_TABLE_SAM_INDEX_EN_MASK; + ZLL->SAM_TABLE = ((uint32_t)index << ZLL_SAM_TABLE_SAM_INDEX_SHIFT) | + ((uint32_t)checksum << ZLL_SAM_TABLE_SAM_CHECKSUM_SHIFT) | ZLL_SAM_TABLE_SAM_INDEX_WR_MASK | + ZLL_SAM_TABLE_SAM_INDEX_EN_MASK; if (extendedAddr) { @@ -645,7 +641,7 @@ exit: static otError rf_remove_addr_table_entry(uint16_t checksum) { - otError status = OT_ERROR_NO_ADDRESS; + otError status = OT_ERROR_NO_ADDRESS; uint32_t i, temp; /* Search for an entry to match the provided checksum */ @@ -673,8 +669,8 @@ static otError rf_remove_addr_table_entry_index(uint8_t index) otEXPECT_ACTION(index < RADIO_CONFIG_SRC_MATCH_ENTRY_NUM, status = OT_ERROR_NO_ADDRESS); ZLL->SAM_TABLE = ((uint32_t)0xFFFF << ZLL_SAM_TABLE_SAM_CHECKSUM_SHIFT) | - ((uint32_t)index << ZLL_SAM_TABLE_SAM_INDEX_SHIFT) | - ZLL_SAM_TABLE_SAM_INDEX_INV_MASK | ZLL_SAM_TABLE_SAM_INDEX_WR_MASK; + ((uint32_t)index << ZLL_SAM_TABLE_SAM_INDEX_SHIFT) | ZLL_SAM_TABLE_SAM_INDEX_INV_MASK | + ZLL_SAM_TABLE_SAM_INDEX_WR_MASK; /* Clear bitmap */ /* Optimization: sExtSrcAddrBitmap[index / 8] &= ~(1 << (index % 8)); */ @@ -719,7 +715,7 @@ static void rf_set_timeout(uint32_t abs_timeout) /* Set time-out value */ ZLL->T3CMP = abs_timeout; /* Aknowledge and unmask TMR3 IRQ */ - irqSts = ZLL->IRQSTS & ZLL_IRQSTS_TMR_ALL_MSK_MASK; + irqSts = ZLL->IRQSTS & ZLL_IRQSTS_TMR_ALL_MSK_MASK; irqSts &= ~ZLL_IRQSTS_TMR3MSK_MASK; irqSts |= ZLL_IRQSTS_TMR3IRQ_MASK; ZLL->IRQSTS = irqSts; @@ -730,7 +726,7 @@ static void rf_set_timeout(uint32_t abs_timeout) static bool rf_process_rx_frame(void) { uint8_t temp; - bool status = true; + bool status = true; /* Get Rx length */ temp = (ZLL->IRQSTS & ZLL_IRQSTS_RX_FRAME_LENGTH_MASK) >> ZLL_IRQSTS_RX_FRAME_LENGTH_SHIFT; @@ -741,13 +737,13 @@ static bool rf_process_rx_frame(void) #if OPENTHREAD_ENABLE_RAW_LINK_API // Timestamp sRxFrame.mMsec = otPlatAlarmMilliGetNow(); - sRxFrame.mUsec = 0; // Don't support microsecond timer for now. + sRxFrame.mUsec = 0; // Don't support microsecond timer for now. #endif sRxFrame.mLength = temp; - temp = (ZLL->LQI_AND_RSSI & ZLL_LQI_AND_RSSI_LQI_VALUE_MASK) >> ZLL_LQI_AND_RSSI_LQI_VALUE_SHIFT; - sRxFrame.mLqi = rf_lqi_adjust(temp); - sRxFrame.mRssi = rf_lqi_to_rssi(sRxFrame.mLqi); + temp = (ZLL->LQI_AND_RSSI & ZLL_LQI_AND_RSSI_LQI_VALUE_MASK) >> ZLL_LQI_AND_RSSI_LQI_VALUE_SHIFT; + sRxFrame.mLqi = rf_lqi_adjust(temp); + sRxFrame.mRssi = rf_lqi_to_rssi(sRxFrame.mLqi); #if DOUBLE_BUFFERING for (temp = 0; temp < sRxFrame.mLength - 2; temp++) @@ -763,9 +759,9 @@ exit: void Radio_1_IRQHandler(void) { - xcvr_state_t state = rf_get_state(); - uint32_t irqStatus = ZLL->IRQSTS; - int8_t temp; + xcvr_state_t state = rf_get_state(); + uint32_t irqStatus = ZLL->IRQSTS; + int8_t temp; ZLL->IRQSTS = irqStatus; @@ -784,9 +780,9 @@ void Radio_1_IRQHandler(void) else if ((state == XCVR_TR_c) && !(irqStatus & ZLL_IRQSTS_RXIRQ_MASK)) { rf_abort(); - sState = OT_RADIO_STATE_RECEIVE; + sState = OT_RADIO_STATE_RECEIVE; sTxStatus = OT_ERROR_NO_ACK; - sTxDone = true; + sTxDone = true; } } @@ -808,16 +804,16 @@ void Radio_1_IRQHandler(void) { sTxStatus = OT_ERROR_CHANNEL_ACCESS_FAILURE; } - else if (!(irqStatus & ZLL_IRQSTS_RXIRQ_MASK) || - (rf_process_rx_frame() == false) || + else if (!(irqStatus & ZLL_IRQSTS_RXIRQ_MASK) || (rf_process_rx_frame() == false) || (sRxFrame.mLength != IEEE802154_ACK_LENGTH) || - ((sRxFrame.mPsdu[IEEE802154_FRM_CTL_LO_OFFSET] & IEEE802154_FRM_TYPE_MASK) != IEEE802154_FRM_TYPE_ACK) || + ((sRxFrame.mPsdu[IEEE802154_FRM_CTL_LO_OFFSET] & IEEE802154_FRM_TYPE_MASK) != + IEEE802154_FRM_TYPE_ACK) || (sRxFrame.mPsdu[IEEE802154_DSN_OFFSET] != sTxFrame.mPsdu[IEEE802154_DSN_OFFSET])) { sTxStatus = OT_ERROR_NO_ACK; } - sState = OT_RADIO_STATE_RECEIVE; + sState = OT_RADIO_STATE_RECEIVE; sTxDone = true; break; @@ -827,7 +823,7 @@ void Radio_1_IRQHandler(void) sTxStatus = OT_ERROR_CHANNEL_ACCESS_FAILURE; } - sState = OT_RADIO_STATE_RECEIVE; + sState = OT_RADIO_STATE_RECEIVE; sTxDone = true; break; @@ -842,7 +838,9 @@ void Radio_1_IRQHandler(void) if (!sEdScanDone) { /* Restart ED */ - while (ZLL->SEQ_STATE & ZLL_SEQ_STATE_SEQ_STATE_MASK) {} + while (ZLL->SEQ_STATE & ZLL_SEQ_STATE_SEQ_STATE_MASK) + { + } ZLL->IRQSTS = (ZLL->IRQSTS & ZLL_IRQSTS_TMR_ALL_MSK_MASK) | ZLL_IRQSTS_SEQIRQ_MASK; ZLL->PHY_CTRL |= XCVR_CCA_c; @@ -860,7 +858,9 @@ void Radio_1_IRQHandler(void) if ((sState == OT_RADIO_STATE_RECEIVE) && (rf_get_state() == XCVR_Idle_c)) { /* Restart RX */ - while (ZLL->SEQ_STATE & ZLL_SEQ_STATE_SEQ_STATE_MASK) {} + while (ZLL->SEQ_STATE & ZLL_SEQ_STATE_SEQ_STATE_MASK) + { + } ZLL->IRQSTS = ZLL->IRQSTS; ZLL->PHY_CTRL |= XCVR_RX_c; @@ -874,18 +874,18 @@ void kw41zRadioInit(void) /* Disable all timers, enable AUTOACK and CCA before TX, mask all interrupts */ ZLL->PHY_CTRL = ZLL_PHY_CTRL_CCATYPE(DEFAULT_CCA_MODE) | // - ZLL_PHY_CTRL_CCABFRTX_MASK | // - ZLL_PHY_CTRL_TSM_MSK_MASK | // - ZLL_PHY_CTRL_WAKE_MSK_MASK | // - ZLL_PHY_CTRL_CRC_MSK_MASK | // - ZLL_PHY_CTRL_PLL_UNLOCK_MSK_MASK | // - ZLL_PHY_CTRL_FILTERFAIL_MSK_MASK | // - ZLL_PHY_CTRL_RX_WMRK_MSK_MASK | // - ZLL_PHY_CTRL_CCAMSK_MASK | // - ZLL_PHY_CTRL_RXMSK_MASK | // - ZLL_PHY_CTRL_TXMSK_MASK | // - ZLL_PHY_CTRL_SEQMSK_MASK | // - ZLL_PHY_CTRL_AUTOACK_MASK | // + ZLL_PHY_CTRL_CCABFRTX_MASK | // + ZLL_PHY_CTRL_TSM_MSK_MASK | // + ZLL_PHY_CTRL_WAKE_MSK_MASK | // + ZLL_PHY_CTRL_CRC_MSK_MASK | // + ZLL_PHY_CTRL_PLL_UNLOCK_MSK_MASK | // + ZLL_PHY_CTRL_FILTERFAIL_MSK_MASK | // + ZLL_PHY_CTRL_RX_WMRK_MSK_MASK | // + ZLL_PHY_CTRL_CCAMSK_MASK | // + ZLL_PHY_CTRL_RXMSK_MASK | // + ZLL_PHY_CTRL_TXMSK_MASK | // + ZLL_PHY_CTRL_SEQMSK_MASK | // + ZLL_PHY_CTRL_AUTOACK_MASK | // ZLL_PHY_CTRL_TRCV_MSK_MASK; /* Clear all IRQ flags and disable all timer interrupts */ @@ -895,9 +895,9 @@ void kw41zRadioInit(void) FRM_VER[7:6] = b11. Accept FrameVersion 0 and 1 packets, reject all others */ ZLL->RX_FRAME_FILTER &= ~ZLL_RX_FRAME_FILTER_FRM_VER_FILTER_MASK; ZLL->RX_FRAME_FILTER = ZLL_RX_FRAME_FILTER_FRM_VER_FILTER(3) | // - ZLL_RX_FRAME_FILTER_CMD_FT_MASK | // - ZLL_RX_FRAME_FILTER_DATA_FT_MASK | // - ZLL_RX_FRAME_FILTER_ACK_FT_MASK | // + ZLL_RX_FRAME_FILTER_CMD_FT_MASK | // + ZLL_RX_FRAME_FILTER_DATA_FT_MASK | // + ZLL_RX_FRAME_FILTER_ACK_FT_MASK | // ZLL_RX_FRAME_FILTER_BEACON_FT_MASK; /* Set prescaller to obtain 1 symbol (16us) timebase */ @@ -922,7 +922,7 @@ void kw41zRadioInit(void) rf_set_tx_power(0); sTxFrame.mLength = 0; - sTxFrame.mPsdu = (uint8_t *)ZLL->PKT_BUFFER_TX + 1; + sTxFrame.mPsdu = (uint8_t *)ZLL->PKT_BUFFER_TX + 1; sRxFrame.mLength = 0; #if DOUBLE_BUFFERING sRxFrame.mPsdu = sRxData; diff --git a/examples/platforms/kw41z/random.c b/examples/platforms/kw41z/random.c index e2ea25932..b43d5a4dd 100644 --- a/examples/platforms/kw41z/random.c +++ b/examples/platforms/kw41z/random.c @@ -32,24 +32,24 @@ * */ -#include -#include +#include "openthread/platform/random.h" #include "fsl_device_registers.h" #include "fsl_trng.h" -#include "openthread/types.h" -#include "openthread/platform/random.h" +#include +#include #include +#include "openthread/types.h" void kw41zRandomInit(void) { trng_config_t config; - uint32_t seed; + uint32_t seed; TRNG_GetDefaultConfig(&config); config.frequencyCountLimit.minimum = 0x00000100; config.frequencyCountLimit.maximum = 0x000F0000; - config.ringOscDiv = kTRNG_RingOscDiv0; - config.entropyDelay = 1200; + config.ringOscDiv = kTRNG_RingOscDiv0; + config.entropyDelay = 1200; otEXPECT(TRNG_Init(TRNG0, &config) == kStatus_Success); diff --git a/examples/platforms/kw41z/uart.c b/examples/platforms/kw41z/uart.c index f700e941d..5043d59c6 100644 --- a/examples/platforms/kw41z/uart.c +++ b/examples/platforms/kw41z/uart.c @@ -32,18 +32,17 @@ * */ -#include #include "fsl_device_registers.h" #include #include #include -#include "openthread/types.h" #include "openthread/platform/uart.h" +#include "openthread/types.h" #include "fsl_clock.h" -#include "fsl_port.h" #include "fsl_lpuart.h" +#include "fsl_port.h" enum { @@ -62,7 +61,7 @@ static bool sTransmitDone = false; typedef struct RecvBuffer { // The data buffer - uint8_t mBuffer[kReceiveBufferSize]; + uint8_t mBuffer[kReceiveBufferSize]; // The offset of the first item written to the list. uint16_t mHead; // The offset of the next item to be written to the list. @@ -87,8 +86,8 @@ otError otPlatUartEnable(void) CLOCK_SetLpuartClock(2); LPUART_GetDefaultConfig(&config); - config.enableRx = 1; - config.enableTx = 1; + config.enableRx = 1; + config.enableTx = 1; config.baudRate_Bps = kBaudRate; LPUART_Init(LPUART0, &config, kPlatformClock); LPUART_EnableInterrupts(LPUART0, kLPUART_RxDataRegFullInterruptEnable); @@ -113,7 +112,7 @@ otError otPlatUartSend(const uint8_t *aBuf, uint16_t aBufLength) sTransmitBuffer = aBuf + 1; sTransmitLength = aBufLength - 1; - sTransmitDone = false; + sTransmitDone = false; LPUART_WriteByte(LPUART0, *aBuf); LPUART_ClearStatusFlags(LPUART0, kLPUART_TxDataRegEmptyFlag); LPUART_EnableInterrupts(LPUART0, kLPUART_TxDataRegEmptyInterruptEnable); @@ -126,7 +125,7 @@ static void processTransmit(void) { if (sTransmitBuffer && sTransmitDone) { - sTransmitDone = false; + sTransmitDone = false; sTransmitBuffer = NULL; otPlatUartSendDone(); } @@ -165,7 +164,7 @@ static void processReceive(void) void LPUART0_IRQHandler(void) { uint32_t interrupts = LPUART_GetEnabledInterrupts(LPUART0); - uint8_t rx_data; + uint8_t rx_data; /* Check if data was received */ while (LPUART_GetStatusFlags(LPUART0) & (kLPUART_RxDataRegFullFlag)) @@ -176,7 +175,7 @@ void LPUART0_IRQHandler(void) if (sReceive.mHead != (sReceive.mTail + 1) % kReceiveBufferSize) { sReceive.mBuffer[sReceive.mTail] = rx_data; - sReceive.mTail = (sReceive.mTail + 1) % kReceiveBufferSize; + sReceive.mTail = (sReceive.mTail + 1) % kReceiveBufferSize; } } diff --git a/examples/platforms/nrf52840/alarm.c b/examples/platforms/nrf52840/alarm.c index 61e066971..de2d65899 100644 --- a/examples/platforms/nrf52840/alarm.c +++ b/examples/platforms/nrf52840/alarm.c @@ -32,8 +32,8 @@ * */ -#include #include +#include #include #include @@ -67,17 +67,12 @@ #define MS_PER_OVERFLOW (512UL * MS_PER_S) ///< Time that has passed between overflow events. On full RTC speed, it occurs every 512 s. // clang-format on -typedef enum -{ - kMsTimer, - kUsTimer, - kNumTimers -} AlarmIndex; +typedef enum { kMsTimer, kUsTimer, kNumTimers } AlarmIndex; typedef struct { - volatile bool mFireAlarm; ///< Information for processing function, that alarm should fire. - uint64_t mTargetTime; ///< Alarm fire time (in millisecond for MsTimer, in microsecond for UsTimer) + volatile bool mFireAlarm; ///< Information for processing function, that alarm should fire. + uint64_t mTargetTime; ///< Alarm fire time (in millisecond for MsTimer, in microsecond for UsTimer) } AlarmData; typedef struct @@ -88,23 +83,23 @@ typedef struct nrf_rtc_int_t mCompareInt; } AlarmChannelData; -static volatile uint64_t sTimeOffset = 0; ///< Time offset to keep track of current time (in millisecond). -static AlarmData sTimerData[kNumTimers]; ///< Data of the timers. +static volatile uint64_t sTimeOffset = 0; ///< Time offset to keep track of current time (in millisecond). +static AlarmData sTimerData[kNumTimers]; ///< Data of the timers. static const AlarmChannelData sChannelData[kNumTimers] = // -{ // - [kMsTimer] = { - .mChannelNumber = 0, - .mCompareEventMask = RTC_EVTEN_COMPARE0_Msk, - .mCompareEvent = NRF_RTC_EVENT_COMPARE_0, - .mCompareInt = NRF_RTC_INT_COMPARE0_MASK, - }, - [kUsTimer] = { - .mChannelNumber = 1, - .mCompareEventMask = RTC_EVTEN_COMPARE1_Msk, - .mCompareEvent = NRF_RTC_EVENT_COMPARE_1, - .mCompareInt = NRF_RTC_INT_COMPARE1_MASK, - } -}; + { // + [kMsTimer] = + { + .mChannelNumber = 0, + .mCompareEventMask = RTC_EVTEN_COMPARE0_Msk, + .mCompareEvent = NRF_RTC_EVENT_COMPARE_0, + .mCompareInt = NRF_RTC_INT_COMPARE0_MASK, + }, + [kUsTimer] = { + .mChannelNumber = 1, + .mCompareEventMask = RTC_EVTEN_COMPARE1_Msk, + .mCompareEvent = NRF_RTC_EVENT_COMPARE_1, + .mCompareInt = NRF_RTC_INT_COMPARE1_MASK, + }}; static void HandleOverflow(void); @@ -118,7 +113,7 @@ static inline uint32_t TimeToTicks(uint64_t aTime, AlarmIndex aIndex) } else { - ticks = (uint32_t)CEIL_DIV((aTime * RTC_FREQUENCY), US_PER_S) & RTC_CC_COMPARE_Msk; + ticks = (uint32_t)CEIL_DIV((aTime * RTC_FREQUENCY), US_PER_S) & RTC_CC_COMPARE_Msk; } return ticks; @@ -244,7 +239,9 @@ void nrf5AlarmInit(void) // Setup low frequency clock. nrf_drv_clock_lfclk_request(NULL); - while (!nrf_drv_clock_lfclk_is_running()) {} + while (!nrf_drv_clock_lfclk_is_running()) + { + } // Setup RTC timer. NVIC_SetPriority(RTC_IRQN, RTC_IRQ_PRIORITY); diff --git a/examples/platforms/nrf52840/diag.c b/examples/platforms/nrf52840/diag.c index 110e53003..f74810a5a 100644 --- a/examples/platforms/nrf52840/diag.c +++ b/examples/platforms/nrf52840/diag.c @@ -26,14 +26,14 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include #include +#include +#include #include #include #include #include -#include #include "platform-nrf5.h" @@ -46,15 +46,10 @@ #include #include -#include #include +#include -typedef enum -{ - kDiagTransmitModeIdle, - kDiagTransmitModePackets, - kDiagTransmitModeCarrier -} DiagTrasmitMode; +typedef enum { kDiagTransmitModeIdle, kDiagTransmitModePackets, kDiagTransmitModeCarrier } DiagTrasmitMode; struct PlatformDiagCommand { @@ -65,25 +60,28 @@ struct PlatformDiagCommand struct PlatformDiagMessage { const char mMessageDescriptor[11]; - uint8_t mChannel; - int16_t mID; - uint32_t mCnt; + uint8_t mChannel; + int16_t mID; + uint32_t mCnt; }; /** * Diagnostics mode variables. * */ -static bool sDiagMode = false; -static bool sListen = false; -static DiagTrasmitMode sTransmitMode = kDiagTransmitModeIdle; -static uint8_t sChannel = 20; -static int8_t sTxPower = 0; -static uint32_t sTxPeriod = 1; -static int32_t sTxCount = 0; -static int32_t sTxRequestedCount = 1; -static int16_t sID = -1; -static struct PlatformDiagMessage sDiagMessage = {.mMessageDescriptor = "DiagMessage", .mChannel = 0, .mID = 0, .mCnt = 0}; +static bool sDiagMode = false; +static bool sListen = false; +static DiagTrasmitMode sTransmitMode = kDiagTransmitModeIdle; +static uint8_t sChannel = 20; +static int8_t sTxPower = 0; +static uint32_t sTxPeriod = 1; +static int32_t sTxCount = 0; +static int32_t sTxRequestedCount = 1; +static int16_t sID = -1; +static struct PlatformDiagMessage sDiagMessage = {.mMessageDescriptor = "DiagMessage", + .mChannel = 0, + .mID = 0, + .mCnt = 0}; static otError parseLong(char *argv, long *aValue) { @@ -110,7 +108,7 @@ static bool startCarrierTransmision(void) static void processListen(otInstance *aInstance, int argc, char *argv[], char *aOutput, size_t aOutputMaxLen) { - (void) aInstance; + (void)aInstance; otError error = OT_ERROR_NONE; otEXPECT_ACTION(otPlatDiagModeGet(), error = OT_ERROR_INVALID_STATE); @@ -126,7 +124,8 @@ static void processListen(otInstance *aInstance, int argc, char *argv[], char *a error = parseLong(argv[0], &value); otEXPECT(error == OT_ERROR_NONE); sListen = (bool)(value); - snprintf(aOutput, aOutputMaxLen, "set listen to %s\r\nstatus 0x%02x\r\n", sListen == true ? "yes" : "no", error); + snprintf(aOutput, aOutputMaxLen, "set listen to %s\r\nstatus 0x%02x\r\n", sListen == true ? "yes" : "no", + error); } exit: @@ -135,7 +134,7 @@ exit: static void processID(otInstance *aInstance, int argc, char *argv[], char *aOutput, size_t aOutputMaxLen) { - (void) aInstance; + (void)aInstance; otError error = OT_ERROR_NONE; @@ -160,8 +159,7 @@ exit: appendErrorResult(error, aOutput, aOutputMaxLen); } -static void processTransmit(otInstance *aInstance, int argc, char *argv[], char *aOutput, - size_t aOutputMaxLen) +static void processTransmit(otInstance *aInstance, int argc, char *argv[], char *aOutput, size_t aOutputMaxLen) { otError error = OT_ERROR_NONE; @@ -169,8 +167,8 @@ static void processTransmit(otInstance *aInstance, int argc, char *argv[], char if (argc == 0) { - snprintf(aOutput, aOutputMaxLen, "transmit will send %" PRId32 " diagnostic messages with %" PRIu32 - " ms interval\r\nstatus 0x%02x\r\n", + snprintf(aOutput, aOutputMaxLen, + "transmit will send %" PRId32 " diagnostic messages with %" PRIu32 " ms interval\r\nstatus 0x%02x\r\n", sTxRequestedCount, sTxPeriod, error); } else if (strcmp(argv[0], "stop") == 0) @@ -188,11 +186,11 @@ static void processTransmit(otInstance *aInstance, int argc, char *argv[], char otPlatAlarmMilliStop(aInstance); sTransmitMode = kDiagTransmitModePackets; - sTxCount = sTxRequestedCount; - uint32_t now = otPlatAlarmMilliGetNow(); + sTxCount = sTxRequestedCount; + uint32_t now = otPlatAlarmMilliGetNow(); otPlatAlarmMilliStartAt(aInstance, now, sTxPeriod); - snprintf(aOutput, aOutputMaxLen, "sending %" PRId32 " diagnostic messages with %" PRIu32 - " ms interval\r\nstatus 0x%02x\r\n", + snprintf(aOutput, aOutputMaxLen, + "sending %" PRId32 " diagnostic messages with %" PRIu32 " ms interval\r\nstatus 0x%02x\r\n", sTxRequestedCount, sTxPeriod, error); } else if (strcmp(argv[0], "carrier") == 0) @@ -216,8 +214,8 @@ static void processTransmit(otInstance *aInstance, int argc, char *argv[], char otEXPECT(error == OT_ERROR_NONE); otEXPECT_ACTION(value > 0, error = OT_ERROR_INVALID_ARGS); sTxPeriod = (uint32_t)(value); - snprintf(aOutput, aOutputMaxLen, "set diagnostic messages interval to %" PRIu32 " ms\r\nstatus 0x%02x\r\n", sTxPeriod, - error); + snprintf(aOutput, aOutputMaxLen, "set diagnostic messages interval to %" PRIu32 " ms\r\nstatus 0x%02x\r\n", + sTxPeriod, error); } else if (strcmp(argv[0], "count") == 0) { @@ -229,8 +227,8 @@ static void processTransmit(otInstance *aInstance, int argc, char *argv[], char otEXPECT(error == OT_ERROR_NONE); otEXPECT_ACTION((value > 0) || (value == -1), error = OT_ERROR_INVALID_ARGS); sTxRequestedCount = (uint32_t)(value); - snprintf(aOutput, aOutputMaxLen, "set diagnostic messages count to %" PRId32 "\r\nstatus 0x%02x\r\n", sTxRequestedCount, - error); + snprintf(aOutput, aOutputMaxLen, "set diagnostic messages count to %" PRId32 "\r\nstatus 0x%02x\r\n", + sTxRequestedCount, error); } else { @@ -241,12 +239,11 @@ exit: appendErrorResult(error, aOutput, aOutputMaxLen); } -static void processGpio(otInstance *aInstance, int argc, char *argv[], - char *aOutput, size_t aOutputMaxLen) +static void processGpio(otInstance *aInstance, int argc, char *argv[], char *aOutput, size_t aOutputMaxLen) { OT_UNUSED_VARIABLE(aInstance); - long pinnum; + long pinnum; otError error = OT_ERROR_NONE; otEXPECT_ACTION(otPlatDiagModeGet(), error = OT_ERROR_INVALID_STATE); @@ -260,8 +257,7 @@ static void processGpio(otInstance *aInstance, int argc, char *argv[], value = nrf_gpio_pin_read(pinnum); - snprintf(aOutput, aOutputMaxLen, "gpio %d = %d\r\n", - (uint8_t)pinnum, (uint8_t)value); + snprintf(aOutput, aOutputMaxLen, "gpio %d = %d\r\n", (uint8_t)pinnum, (uint8_t)value); } else if (strcmp(argv[0], "set") == 0) { @@ -301,8 +297,7 @@ static void processGpio(otInstance *aInstance, int argc, char *argv[], nrf_gpio_cfg_input(pinnum, NRF_GPIO_PIN_NOPULL); - snprintf(aOutput, aOutputMaxLen, "gpio %d: in no pull\r\n", - (uint8_t)pinnum); + snprintf(aOutput, aOutputMaxLen, "gpio %d: in no pull\r\n", (uint8_t)pinnum); } else { @@ -313,7 +308,6 @@ exit: appendErrorResult(error, aOutput, aOutputMaxLen); } - static void processTemp(otInstance *aInstance, int argc, char *argv[], char *aOutput, size_t aOutputMaxLen) { OT_UNUSED_VARIABLE(aInstance); @@ -337,7 +331,7 @@ exit: static void processCcaThreshold(otInstance *aInstance, int argc, char *argv[], char *aOutput, size_t aOutputMaxLen) { - (void) aInstance; + (void)aInstance; otError error = OT_ERROR_NONE; nrf_drv_radio802154_cca_cfg_t ccaConfig; @@ -362,22 +356,20 @@ static void processCcaThreshold(otInstance *aInstance, int argc, char *argv[], c ccaConfig.ed_threshold = (uint8_t)value; nrf_drv_radio802154_cca_cfg_set(&ccaConfig); - snprintf(aOutput, aOutputMaxLen, "set cca threshold to %u\r\nstatus 0x%02x\r\n", - ccaConfig.ed_threshold, error); + snprintf(aOutput, aOutputMaxLen, "set cca threshold to %u\r\nstatus 0x%02x\r\n", ccaConfig.ed_threshold, error); } exit: appendErrorResult(error, aOutput, aOutputMaxLen); } -const struct PlatformDiagCommand sCommands[] = -{ - { "ccathreshold", &processCcaThreshold }, - { "gpio", &processGpio }, - { "id", &processID }, - { "listen", &processListen }, - { "temp", &processTemp }, - { "transmit", &processTransmit }, +const struct PlatformDiagCommand sCommands[] = { + {"ccathreshold", &processCcaThreshold}, + {"gpio", &processGpio}, + {"id", &processID}, + {"listen", &processListen}, + {"temp", &processTemp}, + {"transmit", &processTransmit}, }; void otPlatDiagProcess(otInstance *aInstance, int argc, char *argv[], char *aOutput, size_t aOutputMaxLen) @@ -432,7 +424,7 @@ void otPlatDiagTxPowerSet(int8_t aTxPower) void otPlatDiagRadioReceived(otInstance *aInstance, otRadioFrame *aFrame, otError aError) { - (void) aInstance; + (void)aInstance; if (sListen && (aError == OT_ERROR_NONE)) { @@ -451,13 +443,7 @@ void otPlatDiagRadioReceived(otInstance *aInstance, otRadioFrame *aFrame, otErro "\"RemoteID\":%" PRId16 "," "\"RSSI\":%d" "}}\r\n", - aFrame->mChannel, - message->mChannel, - message->mCnt, - sID, - message->mID, - aFrame->mRssi - ); + aFrame->mChannel, message->mChannel, message->mCnt, sID, message->mID, aFrame->mRssi); } } } @@ -465,18 +451,17 @@ void otPlatDiagRadioReceived(otInstance *aInstance, otRadioFrame *aFrame, otErro void otPlatDiagAlarmCallback(otInstance *aInstance) { - if (sTransmitMode == kDiagTransmitModePackets) { if ((sTxCount > 0) || (sTxCount == -1)) { otRadioFrame *sTxPacket = otPlatRadioGetTransmitBuffer(aInstance); - sTxPacket->mLength = sizeof(struct PlatformDiagMessage); + sTxPacket->mLength = sizeof(struct PlatformDiagMessage); sTxPacket->mChannel = sChannel; sDiagMessage.mChannel = sTxPacket->mChannel; - sDiagMessage.mID = sID; + sDiagMessage.mID = sID; memcpy(sTxPacket->mPsdu, &sDiagMessage, sizeof(struct PlatformDiagMessage)); otPlatRadioTransmit(aInstance, sTxPacket); diff --git a/examples/platforms/nrf52840/fem.c b/examples/platforms/nrf52840/fem.c index 578d400cd..34ed19083 100644 --- a/examples/platforms/nrf52840/fem.c +++ b/examples/platforms/nrf52840/fem.c @@ -32,8 +32,8 @@ * */ -#include #include +#include #include #include diff --git a/examples/platforms/nrf52840/flash.c b/examples/platforms/nrf52840/flash.c index 79fa88010..504f6cc4e 100644 --- a/examples/platforms/nrf52840/flash.c +++ b/examples/platforms/nrf52840/flash.c @@ -26,22 +26,22 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include #include +#include +#include #include #include -#include +#include +#include #include #include -#include -#include #include "platform-nrf5.h" #define FLASH_PAGE_ADDR_MASK 0xFFFFF000 -#define FLASH_PAGE_SIZE 4096 +#define FLASH_PAGE_SIZE 4096 static uint32_t sFlashDataStart; static uint32_t sFlashDataEnd; @@ -124,8 +124,7 @@ otError utilsFlashStatusWait(uint32_t aTimeout) error = OT_ERROR_NONE; break; } - } - while (otPlatAlarmMilliGetNow() - startTime < aTimeout); + } while (otPlatAlarmMilliGetNow() - startTime < aTimeout); } return error; diff --git a/examples/platforms/nrf52840/logging.c b/examples/platforms/nrf52840/logging.c index 4c56f31c2..00eab1353 100644 --- a/examples/platforms/nrf52840/logging.c +++ b/examples/platforms/nrf52840/logging.c @@ -32,15 +32,15 @@ * */ -#include #include +#include #include #include -#include -#include #include +#include +#include #include "platform-nrf5.h" @@ -53,19 +53,19 @@ #if (LOG_RTT_COLOR_ENABLE == 1) #define RTT_COLOR_CODE_DEFAULT "\x1B[0m" -#define RTT_COLOR_CODE_RED "\x1B[1;31m" -#define RTT_COLOR_CODE_GREEN "\x1B[1;32m" -#define RTT_COLOR_CODE_YELLOW "\x1B[1;33m" -#define RTT_COLOR_CODE_CYAN "\x1B[1;36m" +#define RTT_COLOR_CODE_RED "\x1B[1;31m" +#define RTT_COLOR_CODE_GREEN "\x1B[1;32m" +#define RTT_COLOR_CODE_YELLOW "\x1B[1;33m" +#define RTT_COLOR_CODE_CYAN "\x1B[1;36m" #else // LOG_RTT_COLOR_ENABLE == 1 #define RTT_COLOR_CODE_DEFAULT "" -#define RTT_COLOR_CODE_RED "" -#define RTT_COLOR_CODE_GREEN "" -#define RTT_COLOR_CODE_YELLOW "" -#define RTT_COLOR_CODE_CYAN "" +#define RTT_COLOR_CODE_RED "" +#define RTT_COLOR_CODE_GREEN "" +#define RTT_COLOR_CODE_YELLOW "" +#define RTT_COLOR_CODE_CYAN "" #endif // LOG_RTT_COLOR_ENABLE == 1 -static bool sLogInitialized = false; +static bool sLogInitialized = false; static uint8_t sLogBuffer[LOG_RTT_BUFFER_SIZE]; /** @@ -105,8 +105,7 @@ static inline const char *levelToString(otLogLevel aLogLevel) */ static inline uint16_t logTimestamp(char *aLogString, uint16_t aMaxSize) { - return snprintf(aLogString, aMaxSize, "%s[%010ld]", RTT_COLOR_CODE_CYAN, - otPlatAlarmMilliGetNow()); + return snprintf(aLogString, aMaxSize, "%s[%010ld]", RTT_COLOR_CODE_CYAN, otPlatAlarmMilliGetNow()); } #endif @@ -119,17 +118,14 @@ static inline uint16_t logTimestamp(char *aLogString, uint16_t aMaxSize) * * @returns Number of bytes successfully written to the log buffer. */ -static inline uint16_t logLevel(char *aLogString, uint16_t aMaxSize, - otLogLevel aLogLevel) +static inline uint16_t logLevel(char *aLogString, uint16_t aMaxSize, otLogLevel aLogLevel) { return snprintf(aLogString, aMaxSize, "%s ", levelToString(aLogLevel)); } void nrf5LogInit() { - int res = SEGGER_RTT_ConfigUpBuffer(LOG_RTT_BUFFER_INDEX, - LOG_RTT_BUFFER_NAME, sLogBuffer, - LOG_RTT_BUFFER_SIZE, + int res = SEGGER_RTT_ConfigUpBuffer(LOG_RTT_BUFFER_INDEX, LOG_RTT_BUFFER_NAME, sLogBuffer, LOG_RTT_BUFFER_SIZE, SEGGER_RTT_MODE_NO_BLOCK_TRIM); otEXPECT(res >= 0); @@ -144,13 +140,12 @@ void nrf5LogDeinit() sLogInitialized = false; } -void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, - const char *aFormat, ...) +void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat, ...) { - (void) aLogRegion; + (void)aLogRegion; uint16_t length = 0; - char logString[LOG_PARSE_BUFFER_SIZE + 1]; + char logString[LOG_PARSE_BUFFER_SIZE + 1]; otEXPECT(sLogInitialized == true); @@ -159,14 +154,12 @@ void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, #endif // Add level information. - length += logLevel(&logString[length], (LOG_PARSE_BUFFER_SIZE - length), - aLogLevel); + length += logLevel(&logString[length], (LOG_PARSE_BUFFER_SIZE - length), aLogLevel); // Parse user string. va_list paramList; va_start(paramList, aFormat); - length += vsnprintf(&logString[length], (LOG_PARSE_BUFFER_SIZE - length), - aFormat, paramList); + length += vsnprintf(&logString[length], (LOG_PARSE_BUFFER_SIZE - length), aFormat, paramList); if (length > LOG_PARSE_BUFFER_SIZE) { diff --git a/examples/platforms/nrf52840/misc.c b/examples/platforms/nrf52840/misc.c index 77d776fc5..b223676ff 100644 --- a/examples/platforms/nrf52840/misc.c +++ b/examples/platforms/nrf52840/misc.c @@ -26,8 +26,8 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include #include +#include #include #include @@ -56,9 +56,9 @@ void nrf5MiscInit(void) sd_power_reset_reason_get(&sResetReason); sd_power_reset_reason_clr(0xFFFFFFFF); #else - sResetReason = NRF_POWER->RESETREAS; + sResetReason = NRF_POWER->RESETREAS; NRF_POWER->RESETREAS = 0xFFFFFFFF; -#endif // SOFTDEVICE_PRESENT +#endif // SOFTDEVICE_PRESENT } void nrf5MiscDeinit(void) @@ -94,10 +94,8 @@ otPlatResetReason otPlatGetResetReason(otInstance *aInstance) { reason = OT_PLAT_RESET_REASON_FAULT; } - else if ((sResetReason & POWER_RESETREAS_OFF_Msk) || - (sResetReason & POWER_RESETREAS_LPCOMP_Msk) || - (sResetReason & POWER_RESETREAS_DIF_Msk) || - (sResetReason & POWER_RESETREAS_NFC_Msk) || + else if ((sResetReason & POWER_RESETREAS_OFF_Msk) || (sResetReason & POWER_RESETREAS_LPCOMP_Msk) || + (sResetReason & POWER_RESETREAS_DIF_Msk) || (sResetReason & POWER_RESETREAS_NFC_Msk) || (sResetReason & POWER_RESETREAS_VBUS_Msk)) { reason = OT_PLAT_RESET_REASON_OTHER; diff --git a/examples/platforms/nrf52840/platform-config.h b/examples/platforms/nrf52840/platform-config.h index 46d886213..155861863 100644 --- a/examples/platforms/nrf52840/platform-config.h +++ b/examples/platforms/nrf52840/platform-config.h @@ -55,7 +55,7 @@ * */ #ifndef UART_INSTANCE -#define UART_INSTANCE NRF_UART0 +#define UART_INSTANCE NRF_UART0 #endif /** @@ -69,7 +69,7 @@ * */ #ifndef UART_PARITY -#define UART_PARITY NRF_UART_PARITY_EXCLUDED +#define UART_PARITY NRF_UART_PARITY_EXCLUDED #endif /** @@ -83,7 +83,7 @@ * */ #ifndef UART_HWFC -#define UART_HWFC NRF_UART_HWFC_ENABLED +#define UART_HWFC NRF_UART_HWFC_ENABLED #endif /** @@ -111,7 +111,7 @@ * */ #ifndef UART_BAUDRATE -#define UART_BAUDRATE NRF_UART_BAUDRATE_115200 +#define UART_BAUDRATE NRF_UART_BAUDRATE_115200 #endif /** @@ -121,7 +121,7 @@ * */ #ifndef UART_IRQN -#define UART_IRQN UARTE0_UART0_IRQn +#define UART_IRQN UARTE0_UART0_IRQn #endif /** @@ -131,7 +131,7 @@ * */ #ifndef UART_IRQ_PRIORITY -#define UART_IRQ_PRIORITY 6 +#define UART_IRQ_PRIORITY 6 #endif /** @@ -141,7 +141,7 @@ * */ #ifndef UART_RX_BUFFER_SIZE -#define UART_RX_BUFFER_SIZE 256 +#define UART_RX_BUFFER_SIZE 256 #endif /** @@ -151,7 +151,7 @@ * */ #ifndef UART_PIN_TX -#define UART_PIN_TX 6 +#define UART_PIN_TX 6 #endif /** @@ -161,7 +161,7 @@ * */ #ifndef UART_PIN_RX -#define UART_PIN_RX 8 +#define UART_PIN_RX 8 #endif /** @@ -171,7 +171,7 @@ * */ #ifndef UART_PIN_CTS -#define UART_PIN_CTS 7 +#define UART_PIN_CTS 7 #endif /** @@ -181,7 +181,7 @@ * */ #ifndef UART_PIN_RTS -#define UART_PIN_RTS 5 +#define UART_PIN_RTS 5 #endif /******************************************************************************* @@ -195,7 +195,7 @@ * */ #ifndef RTC_INSTANCE -#define RTC_INSTANCE NRF_RTC2 +#define RTC_INSTANCE NRF_RTC2 #endif /** @@ -205,7 +205,7 @@ * */ #ifndef RTC_IRQ_HANDLER -#define RTC_IRQ_HANDLER RTC2_IRQHandler +#define RTC_IRQ_HANDLER RTC2_IRQHandler #endif /** @@ -215,7 +215,7 @@ * */ #ifndef RTC_IRQN -#define RTC_IRQN RTC2_IRQn +#define RTC_IRQN RTC2_IRQn #endif /** @@ -225,7 +225,7 @@ * */ #ifndef RTC_IRQ_PRIORITY -#define RTC_IRQ_PRIORITY 6 +#define RTC_IRQ_PRIORITY 6 #endif /******************************************************************************* @@ -239,7 +239,7 @@ * */ #ifndef RNG_BUFFER_SIZE -#define RNG_BUFFER_SIZE 64 +#define RNG_BUFFER_SIZE 64 #endif /** @@ -249,7 +249,7 @@ * */ #ifndef RNG_IRQ_PRIORITY -#define RNG_IRQ_PRIORITY 6 +#define RNG_IRQ_PRIORITY 6 #endif /******************************************************************************* @@ -263,7 +263,7 @@ * */ #ifndef LOG_RTT_BUFFER_INDEX -#define LOG_RTT_BUFFER_INDEX 0 +#define LOG_RTT_BUFFER_INDEX 0 #endif /** @@ -273,7 +273,7 @@ * */ #ifndef LOG_RTT_BUFFER_NAME -#define LOG_RTT_BUFFER_NAME "Terminal" +#define LOG_RTT_BUFFER_NAME "Terminal" #endif /** @@ -283,7 +283,7 @@ * */ #ifndef LOG_RTT_BUFFER_SIZE -#define LOG_RTT_BUFFER_SIZE 256 +#define LOG_RTT_BUFFER_SIZE 256 #endif /** @@ -293,7 +293,7 @@ * */ #ifndef LOG_RTT_COLOR_ENABLE -#define LOG_RTT_COLOR_ENABLE 1 +#define LOG_RTT_COLOR_ENABLE 1 #endif /** @@ -304,7 +304,7 @@ * */ #ifndef LOG_PARSE_BUFFER_SIZE -#define LOG_PARSE_BUFFER_SIZE 128 +#define LOG_PARSE_BUFFER_SIZE 128 #endif /** @@ -314,7 +314,7 @@ * */ #ifndef LOG_TIMESTAMP_ENABLE -#define LOG_TIMESTAMP_ENABLE 1 +#define LOG_TIMESTAMP_ENABLE 1 #endif /** @@ -324,7 +324,7 @@ * */ #ifndef USB_INITIAL_DELAY_MS -#define USB_INITIAL_DELAY_MS 600 +#define USB_INITIAL_DELAY_MS 600 #endif /** @@ -344,7 +344,7 @@ * Use USB CDC driver for serial communication. */ #ifndef USB_CDC_AS_SERIAL_TRANSPORT -#define USB_CDC_AS_SERIAL_TRANSPORT 0 +#define USB_CDC_AS_SERIAL_TRANSPORT 0 #endif /******************************************************************************* @@ -358,7 +358,7 @@ * */ #ifndef NRF_DRV_RADIO802154_PENDING_SHORT_ADDRESSES -#define NRF_DRV_RADIO802154_PENDING_SHORT_ADDRESSES OPENTHREAD_CONFIG_MAX_CHILDREN +#define NRF_DRV_RADIO802154_PENDING_SHORT_ADDRESSES OPENTHREAD_CONFIG_MAX_CHILDREN #endif /** @@ -368,7 +368,7 @@ * */ #ifndef NRF_DRV_RADIO802154_PENDING_EXTENDED_ADDRESSES -#define NRF_DRV_RADIO802154_PENDING_EXTENDED_ADDRESSES OPENTHREAD_CONFIG_MAX_CHILDREN +#define NRF_DRV_RADIO802154_PENDING_EXTENDED_ADDRESSES OPENTHREAD_CONFIG_MAX_CHILDREN #endif -#endif // PLATFORM_CONFIG_H_ +#endif // PLATFORM_CONFIG_H_ diff --git a/examples/platforms/nrf52840/platform-fem.h b/examples/platforms/nrf52840/platform-fem.h index 7d54a4b64..c4ead70e1 100644 --- a/examples/platforms/nrf52840/platform-fem.h +++ b/examples/platforms/nrf52840/platform-fem.h @@ -49,23 +49,25 @@ // clang-format on -#define PLATFORM_FEM_DEFAULT_CONFIG \ - ((PlatformFemConfigParams) { \ - .mPaCfg = { \ - .mEnable = 1, \ - .mActiveHigh = 1, \ - .mGpioPin = PLATFORM_FEM_DEFAULT_PA_PIN, \ - }, \ - .mLnaCfg = { \ - .mEnable = 1, \ - .mActiveHigh = 1, \ - .mGpioPin = PLATFORM_FEM_DEFAULT_LNA_PIN, \ - }, \ - .mPpiChIdClr = PLATFORM_FEM_DEFAULT_CLR_PPI_CHANNEL, \ - .mPpiChIdSet = PLATFORM_FEM_DEFAULT_SET_PPI_CHANNEL, \ - .mTimerPpiGrp = PLATFORM_FEM_DEFAULT_TIMER_MATCH_PPI_GROUP, \ - .mRadioPpiGrp = PLATFORM_FEM_DEFAULT_RADIO_DISABLED_PPI_GROUP, \ - .mGpioteChId = PLATFORM_FEM_DEFAULT_GPIOTE_CHANNEL, \ +#define PLATFORM_FEM_DEFAULT_CONFIG \ + ((PlatformFemConfigParams){ \ + .mPaCfg = \ + { \ + .mEnable = 1, \ + .mActiveHigh = 1, \ + .mGpioPin = PLATFORM_FEM_DEFAULT_PA_PIN, \ + }, \ + .mLnaCfg = \ + { \ + .mEnable = 1, \ + .mActiveHigh = 1, \ + .mGpioPin = PLATFORM_FEM_DEFAULT_LNA_PIN, \ + }, \ + .mPpiChIdClr = PLATFORM_FEM_DEFAULT_CLR_PPI_CHANNEL, \ + .mPpiChIdSet = PLATFORM_FEM_DEFAULT_SET_PPI_CHANNEL, \ + .mTimerPpiGrp = PLATFORM_FEM_DEFAULT_TIMER_MATCH_PPI_GROUP, \ + .mRadioPpiGrp = PLATFORM_FEM_DEFAULT_RADIO_DISABLED_PPI_GROUP, \ + .mGpioteChId = PLATFORM_FEM_DEFAULT_GPIOTE_CHANNEL, \ }) /** @@ -73,9 +75,9 @@ */ typedef struct { - uint8_t mEnable : 1; /**< Enable toggling for this amplifier */ - uint8_t mActiveHigh : 1; /**< Set the pin to be active high */ - uint8_t mGpioPin : 6; /**< The GPIO pin to toggle for this amplifier */ + uint8_t mEnable : 1; /**< Enable toggling for this amplifier */ + uint8_t mActiveHigh : 1; /**< Set the pin to be active high */ + uint8_t mGpioPin : 6; /**< The GPIO pin to toggle for this amplifier */ } PlatformFemConfigPaLna; /** @@ -107,4 +109,4 @@ typedef struct */ void PlatformFemSetConfigParams(const PlatformFemConfigParams *aConfig); -#endif // PLATFORM_FEM_H_ +#endif // PLATFORM_FEM_H_ diff --git a/examples/platforms/nrf52840/platform-nrf5.h b/examples/platforms/nrf52840/platform-nrf5.h index 98c20ccf7..0403ef0cd 100644 --- a/examples/platforms/nrf52840/platform-nrf5.h +++ b/examples/platforms/nrf52840/platform-nrf5.h @@ -201,4 +201,4 @@ otError nrf5SdErrorToOtError(uint32_t aSdError); void nrf5SdSocFlashProcess(uint32_t aEvtId); #endif // SOFTDEVICE_PRESENT -#endif // PLATFORM_NRF5_H_ +#endif // PLATFORM_NRF5_H_ diff --git a/examples/platforms/nrf52840/platform.c b/examples/platforms/nrf52840/platform.c index 931fe1cd9..6b1063d3c 100644 --- a/examples/platforms/nrf52840/platform.c +++ b/examples/platforms/nrf52840/platform.c @@ -32,18 +32,22 @@ * */ -#include #include +#include #include +#include "platform-nrf5.h" #include #include -#include "platform-nrf5.h" #include -void __cxa_pure_virtual(void) { while (1); } +void __cxa_pure_virtual(void) +{ + while (1) + ; +} void PlatformInit(int argc, char *argv[]) { diff --git a/examples/platforms/nrf52840/radio.c b/examples/platforms/nrf52840/radio.c index 178088e0b..5d9ae1217 100644 --- a/examples/platforms/nrf52840/radio.c +++ b/examples/platforms/nrf52840/radio.c @@ -32,9 +32,8 @@ * */ -#include -#include #include +#include #include #include @@ -48,8 +47,8 @@ #include #include -#include "platform.h" #include "platform-nrf5.h" +#include "platform.h" #include #include @@ -69,7 +68,7 @@ enum { - NRF52840_RECEIVE_SENSITIVITY = -100, // dBm + NRF52840_RECEIVE_SENSITIVITY = -100, // dBm }; static bool sDisabled; @@ -81,14 +80,13 @@ static uint8_t sTransmitPsdu[OT_RADIO_FRAME_MAX_SIZE + 1]; static otRadioFrame sAckFrame; -static int8_t sDefaultTxPower; +static int8_t sDefaultTxPower; -static uint32_t sEnergyDetectionTime; -static uint8_t sEnergyDetectionChannel; -static int8_t sEnergyDetected; +static uint32_t sEnergyDetectionTime; +static uint8_t sEnergyDetectionChannel; +static int8_t sEnergyDetected; -typedef enum -{ +typedef enum { kPendingEventSleep, // Requested to enter Sleep state. kPendingEventTransmit, // Frame is queued for transmission. kPendingEventFrameTransmitted, // Transmitted frame and received ACK (if requested). @@ -119,7 +117,7 @@ static void dataInit(void) static void convertShortAddress(uint8_t *aTo, uint16_t aFrom) { - aTo[0] = (uint8_t) aFrom; + aTo[0] = (uint8_t)aFrom; aTo[1] = (uint8_t)(aFrom >> 8); } @@ -137,8 +135,7 @@ static void setPendingEvent(RadioPendingEvents aEvent) { pendingEvents = __LDREXW((unsigned long volatile *)&sPendingEvents); pendingEvents |= bitToSet; - } - while (__STREXW(pendingEvents, (unsigned long volatile *)&sPendingEvents)); + } while (__STREXW(pendingEvents, (unsigned long volatile *)&sPendingEvents)); PlatformEventSignalPending(); } @@ -152,8 +149,7 @@ static void resetPendingEvent(RadioPendingEvents aEvent) { pendingEvents = __LDREXW((unsigned long volatile *)&sPendingEvents); pendingEvents &= bitsToRemain; - } - while (__STREXW(pendingEvents, (unsigned long volatile *)&sPendingEvents)); + } while (__STREXW(pendingEvents, (unsigned long volatile *)&sPendingEvents)); } static inline void clearPendingEvents(void) @@ -172,23 +168,22 @@ static inline void clearPendingEvents(void) { pendingEvents = __LDREXW((unsigned long volatile *)&sPendingEvents); pendingEvents &= bitsToRemain; - } - while (__STREXW(pendingEvents, (unsigned long volatile *)&sPendingEvents)); + } while (__STREXW(pendingEvents, (unsigned long volatile *)&sPendingEvents)); } void otPlatRadioGetIeeeEui64(otInstance *aInstance, uint8_t *aIeeeEui64) { - (void) aInstance; + (void)aInstance; uint64_t factoryAddress = (uint64_t)NRF_FICR->DEVICEID[0] << 32; - factoryAddress |= NRF_FICR->DEVICEID[1]; + factoryAddress |= NRF_FICR->DEVICEID[1]; memcpy(aIeeeEui64, &factoryAddress, sizeof(factoryAddress)); } void otPlatRadioSetPanId(otInstance *aInstance, uint16_t aPanId) { - (void) aInstance; + (void)aInstance; uint8_t address[SHORT_ADDRESS_SIZE]; convertShortAddress(address, aPanId); @@ -198,14 +193,14 @@ void otPlatRadioSetPanId(otInstance *aInstance, uint16_t aPanId) void otPlatRadioSetExtendedAddress(otInstance *aInstance, const otExtAddress *aExtAddress) { - (void) aInstance; + (void)aInstance; nrf_drv_radio802154_extended_address_set(aExtAddress->m8); } void otPlatRadioSetShortAddress(otInstance *aInstance, uint16_t aShortAddress) { - (void) aInstance; + (void)aInstance; uint8_t address[SHORT_ADDRESS_SIZE]; convertShortAddress(address, aShortAddress); @@ -226,7 +221,7 @@ void nrf5RadioDeinit(void) otRadioState otPlatRadioGetState(otInstance *aInstance) { - (void) aInstance; + (void)aInstance; if (sDisabled) { @@ -254,14 +249,14 @@ otRadioState otPlatRadioGetState(otInstance *aInstance) otError otPlatRadioEnable(otInstance *aInstance) { - (void) aInstance; + (void)aInstance; otError error; if (sDisabled) { sDisabled = false; - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; } else { @@ -273,14 +268,14 @@ otError otPlatRadioEnable(otInstance *aInstance) otError otPlatRadioDisable(otInstance *aInstance) { - (void) aInstance; + (void)aInstance; otError error; if (!sDisabled) { sDisabled = true; - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; } else { @@ -292,14 +287,14 @@ otError otPlatRadioDisable(otInstance *aInstance) bool otPlatRadioIsEnabled(otInstance *aInstance) { - (void) aInstance; + (void)aInstance; return !sDisabled; } otError otPlatRadioSleep(otInstance *aInstance) { - (void) aInstance; + (void)aInstance; if (nrf_drv_radio802154_sleep()) { @@ -316,7 +311,7 @@ otError otPlatRadioSleep(otInstance *aInstance) otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) { - (void) aInstance; + (void)aInstance; nrf_drv_radio802154_channel_set(aChannel); nrf_drv_radio802154_tx_power_set(sDefaultTxPower); @@ -328,7 +323,7 @@ otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aFrame) { - (void) aInstance; + (void)aInstance; aFrame->mPsdu[-1] = aFrame->mLength; @@ -350,49 +345,49 @@ otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aFrame) otRadioFrame *otPlatRadioGetTransmitBuffer(otInstance *aInstance) { - (void) aInstance; + (void)aInstance; return &sTransmitFrame; } int8_t otPlatRadioGetRssi(otInstance *aInstance) { - (void) aInstance; + (void)aInstance; return nrf_drv_radio802154_rssi_last_get(); } otRadioCaps otPlatRadioGetCaps(otInstance *aInstance) { - (void) aInstance; + (void)aInstance; return OT_RADIO_CAPS_ENERGY_SCAN; } bool otPlatRadioGetPromiscuous(otInstance *aInstance) { - (void) aInstance; + (void)aInstance; return nrf_drv_radio802154_promiscuous_get(); } void otPlatRadioSetPromiscuous(otInstance *aInstance, bool aEnable) { - (void) aInstance; + (void)aInstance; nrf_drv_radio802154_promiscuous_set(aEnable); } void otPlatRadioEnableSrcMatch(otInstance *aInstance, bool aEnable) { - (void) aInstance; + (void)aInstance; nrf_drv_radio802154_auto_pending_bit_set(aEnable); } otError otPlatRadioAddSrcMatchShortEntry(otInstance *aInstance, const uint16_t aShortAddress) { - (void) aInstance; + (void)aInstance; otError error; @@ -413,7 +408,7 @@ otError otPlatRadioAddSrcMatchShortEntry(otInstance *aInstance, const uint16_t a otError otPlatRadioAddSrcMatchExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) { - (void) aInstance; + (void)aInstance; otError error; @@ -431,7 +426,7 @@ otError otPlatRadioAddSrcMatchExtEntry(otInstance *aInstance, const otExtAddress otError otPlatRadioClearSrcMatchShortEntry(otInstance *aInstance, const uint16_t aShortAddress) { - (void) aInstance; + (void)aInstance; otError error; @@ -452,7 +447,7 @@ otError otPlatRadioClearSrcMatchShortEntry(otInstance *aInstance, const uint16_t otError otPlatRadioClearSrcMatchExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) { - (void) aInstance; + (void)aInstance; otError error; @@ -470,23 +465,23 @@ otError otPlatRadioClearSrcMatchExtEntry(otInstance *aInstance, const otExtAddre void otPlatRadioClearSrcMatchShortEntries(otInstance *aInstance) { - (void) aInstance; + (void)aInstance; nrf_drv_radio802154_pending_bit_for_addr_reset(false); } void otPlatRadioClearSrcMatchExtEntries(otInstance *aInstance) { - (void) aInstance; + (void)aInstance; nrf_drv_radio802154_pending_bit_for_addr_reset(true); } otError otPlatRadioEnergyScan(otInstance *aInstance, uint8_t aScanChannel, uint16_t aScanDuration) { - (void) aInstance; + (void)aInstance; - sEnergyDetectionTime = (uint32_t) aScanDuration * 1000UL; + sEnergyDetectionTime = (uint32_t)aScanDuration * 1000UL; sEnergyDetectionChannel = aScanChannel; clearPendingEvents(); @@ -550,7 +545,7 @@ void nrf5RadioProcess(otInstance *aInstance) otPlatRadioReceiveDone(aInstance, &sReceivedFrames[i], OT_ERROR_NONE); } - uint8_t *bufferAddress = &sReceivedFrames[i].mPsdu[-1]; + uint8_t *bufferAddress = &sReceivedFrames[i].mPsdu[-1]; sReceivedFrames[i].mPsdu = NULL; nrf_drv_radio802154_buffer_free_raw(bufferAddress); } @@ -691,9 +686,9 @@ void nrf_drv_radio802154_received_raw(uint8_t *p_data, int8_t power, int8_t lqi) receivedFrame->mLqi = lqi; receivedFrame->mChannel = nrf_drv_radio802154_channel_get(); #if OPENTHREAD_ENABLE_RAW_LINK_API - uint64_t timestamp = nrf5AlarmGetCurrentTime(); - receivedFrame->mMsec = timestamp / US_PER_MS; - receivedFrame->mUsec = timestamp - receivedFrame->mMsec * US_PER_MS; + uint64_t timestamp = nrf5AlarmGetCurrentTime(); + receivedFrame->mMsec = timestamp / US_PER_MS; + receivedFrame->mUsec = timestamp - receivedFrame->mMsec * US_PER_MS; #endif PlatformEventSignalPending(); diff --git a/examples/platforms/nrf52840/random.c b/examples/platforms/nrf52840/random.c index 322f4ca2a..329a78664 100644 --- a/examples/platforms/nrf52840/random.c +++ b/examples/platforms/nrf52840/random.c @@ -32,15 +32,15 @@ * */ -#include #include +#include #include #include #include -#include #include +#include #include "platform-nrf5.h" @@ -49,7 +49,7 @@ #else #include -static uint8_t sBuffer[RNG_BUFFER_SIZE]; +static uint8_t sBuffer[RNG_BUFFER_SIZE]; static volatile uint32_t sReadPosition; static volatile uint32_t sWritePosition; @@ -125,8 +125,7 @@ static void generatorStop(void) void RNG_IRQHandler(void) { - if (nrf_rng_event_get(NRF_RNG_EVENT_VALRDY) && - nrf_rng_int_get(NRF_RNG_INT_VALRDY_MASK)) + if (nrf_rng_event_get(NRF_RNG_EVENT_VALRDY) && nrf_rng_int_get(NRF_RNG_INT_VALRDY_MASK)) { nrf_rng_event_clear(NRF_RNG_EVENT_VALRDY); @@ -151,12 +150,11 @@ void nrf5RandomInit(void) { // Wait for the first randomized 4 bytes, to randomize software generator seed. retval = sd_rand_application_vector_get((uint8_t *)&seed, sizeof(seed)); - } - while (retval != NRF_SUCCESS && seed == 0); + } while (retval != NRF_SUCCESS && seed == 0); -#else // SOFTDEVICE_PRESENT +#else // SOFTDEVICE_PRESENT memset(sBuffer, 0, sizeof(sBuffer)); - sReadPosition = 0; + sReadPosition = 0; sWritePosition = 0; NVIC_SetPriority(RNG_IRQn, RNG_IRQ_PRIORITY); @@ -168,7 +166,8 @@ void nrf5RandomInit(void) generatorStart(); // Wait for the first randomized 4 bytes, to randomize software generator seed. - while (!bufferIsUint32Ready()) ; + while (!bufferIsUint32Ready()) + ; seed = bufferGetUint32(); #endif // SOFTDEVICE_PRESENT @@ -194,7 +193,7 @@ uint32_t otPlatRandomGet(void) otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint8_t copyLength; uint16_t index = 0; @@ -204,7 +203,7 @@ otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength) { #if SOFTDEVICE_PRESENT sd_rand_application_bytes_available_get(©Length); -#else // SOFTDEVICE_PRESENT +#else // SOFTDEVICE_PRESENT copyLength = (uint8_t)bufferCount(); #endif // SOFTDEVICE_PRESENT @@ -215,11 +214,10 @@ otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength) if (copyLength > 0) { - #if SOFTDEVICE_PRESENT uint32_t retval = sd_rand_application_vector_get(aOutput + index, copyLength); otEXPECT_ACTION(retval == NRF_SUCCESS, error = OT_ERROR_FAILED); -#else // SOFTDEVICE_PRESENT +#else // SOFTDEVICE_PRESENT for (uint32_t i = 0; i < copyLength; i++) { @@ -231,8 +229,7 @@ otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength) index += copyLength; } - } - while (index < aOutputLength); + } while (index < aOutputLength); exit: return error; diff --git a/examples/platforms/nrf52840/temp.c b/examples/platforms/nrf52840/temp.c index c9c1715ce..bba02e1f6 100644 --- a/examples/platforms/nrf52840/temp.c +++ b/examples/platforms/nrf52840/temp.c @@ -30,8 +30,8 @@ #include #include -#include #include +#include #include "platform-nrf5.h" @@ -43,7 +43,7 @@ __STATIC_INLINE void dataReadyEventClear(void) { NRF_TEMP->EVENTS_DATARDY = 0; - volatile uint32_t dummy = NRF_TEMP->EVENTS_DATARDY; + volatile uint32_t dummy = NRF_TEMP->EVENTS_DATARDY; (void)dummy; } #endif @@ -66,7 +66,7 @@ int32_t nrf5TempGet(void) { #if SOFTDEVICE_PRESENT int32_t temperature; - (void) sd_temp_get(&temperature); + (void)sd_temp_get(&temperature); #else NRF_TEMP->TASKS_START = 1; diff --git a/examples/platforms/nrf52840/uart.c b/examples/platforms/nrf52840/uart.c index b8c556ba2..ca0b3750e 100644 --- a/examples/platforms/nrf52840/uart.c +++ b/examples/platforms/nrf52840/uart.c @@ -32,23 +32,23 @@ * */ -#include #include +#include #include #include +#include #include #include #include -#include #include "platform.h" -#include -#include -#include #include "platform-nrf5.h" +#include +#include +#include #if (USB_CDC_AS_SERIAL_TRANSPORT == 0) @@ -58,13 +58,13 @@ bool sUartEnabled = false; * UART TX buffer variables. */ static const uint8_t *sTransmitBuffer = NULL; -static uint16_t sTransmitLength = 0; -static bool sTransmitDone = 0; +static uint16_t sTransmitLength = 0; +static bool sTransmitDone = 0; /** * UART RX ring buffer variables. */ -static uint8_t sReceiveBuffer[UART_RX_BUFFER_SIZE]; +static uint8_t sReceiveBuffer[UART_RX_BUFFER_SIZE]; static uint16_t sReceiveHead = 0; static uint16_t sReceiveTail = 0; @@ -105,16 +105,14 @@ static void processReceive(void) // bytes from the end of the buffer. if (head < sReceiveTail) { - otPlatUartReceived(&sReceiveBuffer[sReceiveTail], - (UART_RX_BUFFER_SIZE - sReceiveTail)); + otPlatUartReceived(&sReceiveBuffer[sReceiveTail], (UART_RX_BUFFER_SIZE - sReceiveTail)); sReceiveTail = 0; } // Notify about received bytes. if (head > sReceiveTail) { - otPlatUartReceived(&sReceiveBuffer[sReceiveTail], - (head - sReceiveTail)); + otPlatUartReceived(&sReceiveBuffer[sReceiveTail], (head - sReceiveTail)); sReceiveTail = head; } @@ -134,7 +132,7 @@ static void processTransmit(void) // Clear Transmition transaction and notify application. sTransmitBuffer = NULL; sTransmitLength = 0; - sTransmitDone = false; + sTransmitDone = false; otPlatUartSendDone(); } @@ -206,7 +204,9 @@ otError otPlatUartEnable(void) // Start HFCLK nrf_drv_clock_hfclk_request(NULL); - while (!nrf_drv_clock_hfclk_is_running()) {} + while (!nrf_drv_clock_hfclk_is_running()) + { + } // Enable UART instance, and start RX on it. nrf_uart_enable(UART_INSTANCE); @@ -289,7 +289,7 @@ void UARTE0_UART0_IRQHandler(void) if (!isRxBufferFull()) { sReceiveBuffer[sReceiveHead] = byte; - sReceiveHead = (sReceiveHead + 1) % UART_RX_BUFFER_SIZE; + sReceiveHead = (sReceiveHead + 1) % UART_RX_BUFFER_SIZE; PlatformEventSignalPending(); } } diff --git a/examples/platforms/nrf52840/usb-cdc-uart.c b/examples/platforms/nrf52840/usb-cdc-uart.c index 14a016fd0..7fad3914d 100644 --- a/examples/platforms/nrf52840/usb-cdc-uart.c +++ b/examples/platforms/nrf52840/usb-cdc-uart.c @@ -36,20 +36,20 @@ #pragma GCC diagnostic ignored "-Wpedantic" #endif -#include #include +#include +#include #include #include -#include -#include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include +#include #include "platform-nrf5.h" @@ -60,40 +60,28 @@ #if (USB_CDC_AS_SERIAL_TRANSPORT == 1) -static void cdcAcmUserEventHandler(app_usbd_class_inst_t const *aInstance, - app_usbd_cdc_acm_user_event_t aEvent); +static void cdcAcmUserEventHandler(app_usbd_class_inst_t const *aInstance, app_usbd_cdc_acm_user_event_t aEvent); -#define CDC_ACM_COMM_INTERFACE 0 -#define CDC_ACM_COMM_EPIN NRF_DRV_USBD_EPIN2 +#define CDC_ACM_COMM_INTERFACE 0 +#define CDC_ACM_COMM_EPIN NRF_DRV_USBD_EPIN2 -#define CDC_ACM_DATA_INTERFACE 1 -#define CDC_ACM_DATA_EPIN NRF_DRV_USBD_EPIN1 -#define CDC_ACM_DATA_EPOUT NRF_DRV_USBD_EPOUT1 +#define CDC_ACM_DATA_INTERFACE 1 +#define CDC_ACM_DATA_EPIN NRF_DRV_USBD_EPIN1 +#define CDC_ACM_DATA_EPOUT NRF_DRV_USBD_EPOUT1 #define SERIAL_NUMBER_STRING_SIZE 16 -#define CDC_ACM_INTERFACES_CONFIG() \ - APP_USBD_CDC_ACM_CONFIG(CDC_ACM_COMM_INTERFACE, \ - CDC_ACM_COMM_EPIN, \ - CDC_ACM_DATA_INTERFACE, \ - CDC_ACM_DATA_EPIN, \ +#define CDC_ACM_INTERFACES_CONFIG() \ + APP_USBD_CDC_ACM_CONFIG(CDC_ACM_COMM_INTERFACE, CDC_ACM_COMM_EPIN, CDC_ACM_DATA_INTERFACE, CDC_ACM_DATA_EPIN, \ CDC_ACM_DATA_EPOUT) +static const uint8_t sCdcAcmClassDescriptors[] = {APP_USBD_CDC_ACM_DEFAULT_DESC(CDC_ACM_COMM_INTERFACE, + CDC_ACM_COMM_EPIN, + CDC_ACM_DATA_INTERFACE, + CDC_ACM_DATA_EPIN, + CDC_ACM_DATA_EPOUT)}; -static const uint8_t sCdcAcmClassDescriptors[] = -{ - APP_USBD_CDC_ACM_DEFAULT_DESC( - CDC_ACM_COMM_INTERFACE, - CDC_ACM_COMM_EPIN, - CDC_ACM_DATA_INTERFACE, - CDC_ACM_DATA_EPIN, - CDC_ACM_DATA_EPOUT) -}; - -APP_USBD_CDC_ACM_GLOBAL_DEF(sAppCdcAcm, - CDC_ACM_INTERFACES_CONFIG(), - cdcAcmUserEventHandler, - sCdcAcmClassDescriptors); +APP_USBD_CDC_ACM_GLOBAL_DEF(sAppCdcAcm, CDC_ACM_INTERFACES_CONFIG(), cdcAcmUserEventHandler, sCdcAcmClassDescriptors); // Rx buffer length must by multiple of NRF_DRV_USBD_EPSIZE. static char sRxBuffer[NRF_DRV_USBD_EPSIZE * ((UART_RX_BUFFER_SIZE + NRF_DRV_USBD_EPSIZE - 1) / NRF_DRV_USBD_EPSIZE)]; @@ -133,8 +121,7 @@ static void serialNumberStringCreate(void) } } -static void cdcAcmUserEventHandler(app_usbd_class_inst_t const *aCdcAcmInstance, - app_usbd_cdc_acm_user_event_t aEvent) +static void cdcAcmUserEventHandler(app_usbd_class_inst_t const *aCdcAcmInstance, app_usbd_cdc_acm_user_event_t aEvent) { app_usbd_cdc_acm_t const *cdcAcmClass = app_usbd_cdc_acm_class_get(aCdcAcmInstance); @@ -293,15 +280,15 @@ static void processTransmit(void) if (app_usbd_cdc_acm_write(&sAppCdcAcm, sUsbState.mTxBuffer, sUsbState.mTxSize) == NRF_SUCCESS) { sUsbState.mTransferInProgress = true; - sUsbState.mTxBuffer = NULL; - sUsbState.mTxSize = 0; + sUsbState.mTxBuffer = NULL; + sUsbState.mTxSize = 0; } } else if (sUsbState.mTransferDone) { otPlatLog(OT_LOG_LEVEL_DEBG, OT_LOG_REGION_PLATFORM, "otPlatUartSendDone"); - sUsbState.mTransferDone = false; + sUsbState.mTransferDone = false; sUsbState.mTransferInProgress = false; otPlatUartSendDone(); @@ -310,15 +297,9 @@ static void processTransmit(void) void nrf5UartInit(void) { - static const nrf_drv_power_usbevt_config_t powerConfig = - { - .handler = powerUsbEventHandler - }; + static const nrf_drv_power_usbevt_config_t powerConfig = {.handler = powerUsbEventHandler}; - static const app_usbd_config_t usbdConfig = - { - .ev_state_proc = usbdUserEventHandler - }; + static const app_usbd_config_t usbdConfig = {.ev_state_proc = usbdUserEventHandler}; memset((void *)&sUsbState, 0, sizeof(sUsbState)); @@ -331,7 +312,7 @@ void nrf5UartInit(void) assert(ret == NRF_SUCCESS); app_usbd_class_inst_t const *cdcAcmInstance = app_usbd_cdc_acm_class_inst_get(&sAppCdcAcm); - ret = app_usbd_class_append(cdcAcmInstance); + ret = app_usbd_class_append(cdcAcmInstance); assert(ret == NRF_SUCCESS); ret = nrf_drv_power_usbevt_init(&powerConfig); @@ -344,7 +325,9 @@ void nrf5UartDeinit(void) { app_usbd_stop(); - while (app_usbd_event_queue_process()) { } + while (app_usbd_event_queue_process()) + { + } } else if (nrf_drv_usbd_is_enabled()) { @@ -361,7 +344,9 @@ void nrf5UartDeinit(void) void nrf5UartProcess(void) { - while (app_usbd_event_queue_process()) { } + while (app_usbd_event_queue_process()) + { + } processConnection(); processReceive(); @@ -393,7 +378,7 @@ otError otPlatUartSend(const uint8_t *aBuf, uint16_t aBufLength) { // If port is closed, queue the message until it can be sent. sUsbState.mTxBuffer = aBuf; - sUsbState.mTxSize = aBufLength; + sUsbState.mTxSize = aBufLength; } else { diff --git a/examples/platforms/platform.h b/examples/platforms/platform.h index c5e2e9052..6a955009f 100644 --- a/examples/platforms/platform.h +++ b/examples/platforms/platform.h @@ -68,7 +68,7 @@ void PlatformProcessDrivers(otInstance *aInstance); extern void PlatformEventSignalPending(void); #ifdef __cplusplus -} // end of extern "C" +} // end of extern "C" #endif -#endif // PLATFORM_H_ +#endif // PLATFORM_H_ diff --git a/examples/platforms/posix/alarm.c b/examples/platforms/posix/alarm.c index 8f00609c4..65a28d37e 100644 --- a/examples/platforms/posix/alarm.c +++ b/examples/platforms/posix/alarm.c @@ -38,17 +38,17 @@ #include #include -#define MS_PER_S 1000 +#define MS_PER_S 1000 #define US_PER_MS 1000 -#define US_PER_S 1000000 +#define US_PER_S 1000000 -#define DEFAULT_TIMEOUT 10 // seconds +#define DEFAULT_TIMEOUT 10 // seconds -static bool sIsMsRunning = false; -static uint32_t sMsAlarm = 0; +static bool sIsMsRunning = false; +static uint32_t sMsAlarm = 0; -static bool sIsUsRunning = false; -static uint32_t sUsAlarm = 0; +static bool sIsUsRunning = false; +static uint32_t sUsAlarm = 0; static struct timeval sStart; @@ -70,7 +70,7 @@ uint32_t otPlatAlarmMilliGetNow(void) void otPlatAlarmMilliStartAt(otInstance *aInstance, uint32_t aT0, uint32_t aDt) { (void)aInstance; - sMsAlarm = aT0 + aDt; + sMsAlarm = aT0 + aDt; sIsMsRunning = true; } @@ -93,7 +93,7 @@ uint32_t otPlatAlarmMicroGetNow(void) void otPlatAlarmMicroStartAt(otInstance *aInstance, uint32_t aT0, uint32_t aDt) { (void)aInstance; - sUsAlarm = aT0 + aDt; + sUsAlarm = aT0 + aDt; sIsUsRunning = true; } @@ -125,17 +125,17 @@ void platformAlarmUpdateTimeout(struct timeval *aTimeout) if (usRemaining <= 0 || msRemaining <= 0) { - aTimeout->tv_sec = 0; + aTimeout->tv_sec = 0; aTimeout->tv_usec = 0; } else if (msRemaining * US_PER_MS < usRemaining) { - aTimeout->tv_sec = msRemaining / MS_PER_S; + aTimeout->tv_sec = msRemaining / MS_PER_S; aTimeout->tv_usec = (msRemaining % MS_PER_S) * US_PER_MS; } else { - aTimeout->tv_sec = usRemaining / US_PER_S; + aTimeout->tv_sec = usRemaining / US_PER_S; aTimeout->tv_usec = usRemaining % US_PER_S; } } diff --git a/examples/platforms/posix/flash.c b/examples/platforms/posix/flash.c index 6bd191ec6..db24275ee 100644 --- a/examples/platforms/posix/flash.c +++ b/examples/platforms/posix/flash.c @@ -41,21 +41,21 @@ #include "utils/flash.h" static int sFlashFd = -1; -uint32_t sEraseAddress; +uint32_t sEraseAddress; enum { - FLASH_SIZE = 0x40000, + FLASH_SIZE = 0x40000, FLASH_PAGE_SIZE = 0x800, - FLASH_PAGE_NUM = 128, + FLASH_PAGE_NUM = 128, }; otError utilsFlashInit(void) { - otError error = OT_ERROR_NONE; - char fileName[20]; + otError error = OT_ERROR_NONE; + char fileName[20]; struct stat st; - bool create = false; + bool create = false; const char *offset = getenv("PORT_OFFSET"); memset(&st, 0, sizeof(st)); @@ -102,9 +102,9 @@ uint32_t utilsFlashGetSize(void) otError utilsFlashErasePage(uint32_t aAddress) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint32_t address; - uint8_t dummyPage[ FLASH_SIZE ]; + uint8_t dummyPage[FLASH_SIZE]; otEXPECT_ACTION(sFlashFd >= 0, error = OT_ERROR_FAILED); otEXPECT_ACTION(aAddress < FLASH_SIZE, error = OT_ERROR_INVALID_ARGS); @@ -117,10 +117,9 @@ otError utilsFlashErasePage(uint32_t aAddress) // Write the page ssize_t r; - r = pwrite(sFlashFd, &(dummyPage[0]), FLASH_PAGE_SIZE, (off_t)address); + r = pwrite(sFlashFd, &(dummyPage[0]), FLASH_PAGE_SIZE, (off_t)address); otEXPECT_ACTION(((int)r) == ((int)(FLASH_PAGE_SIZE)), error = OT_ERROR_FAILED); - exit: return error; } @@ -133,9 +132,9 @@ otError utilsFlashStatusWait(uint32_t aTimeout) uint32_t utilsFlashWrite(uint32_t aAddress, uint8_t *aData, uint32_t aSize) { - uint32_t ret = 0; + uint32_t ret = 0; uint32_t index = 0; - uint8_t byte; + uint8_t byte; otEXPECT(sFlashFd >= 0 && aAddress < FLASH_SIZE); diff --git a/examples/platforms/posix/logging.c b/examples/platforms/posix/logging.c index 8fbb13cbe..dad702e99 100644 --- a/examples/platforms/posix/logging.c +++ b/examples/platforms/posix/logging.c @@ -26,15 +26,15 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include -#include #include "platform-posix.h" +#include +#include #include #include #include -#include #include +#include #include #ifndef _WIN32 @@ -47,20 +47,19 @@ // Macro to append content to end of the log string. -#define LOG_PRINTF(...) \ - charsWritten = snprintf(&logString[offset], sizeof(logString) - offset , __VA_ARGS__); \ - otEXPECT_ACTION(charsWritten >= 0, logString[offset] = 0); \ - offset += (unsigned int)charsWritten; \ - otEXPECT_ACTION(offset < sizeof(logString), logString[sizeof(logString) -1 ] = 0) - +#define LOG_PRINTF(...) \ + charsWritten = snprintf(&logString[offset], sizeof(logString) - offset, __VA_ARGS__); \ + otEXPECT_ACTION(charsWritten >= 0, logString[offset] = 0); \ + offset += (unsigned int)charsWritten; \ + otEXPECT_ACTION(offset < sizeof(logString), logString[sizeof(logString) - 1] = 0) #if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED) void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat, ...) { - char logString[512]; + char logString[512]; unsigned int offset; - int charsWritten; - va_list args; + int charsWritten; + va_list args; offset = 0; diff --git a/examples/platforms/posix/misc.c b/examples/platforms/posix/misc.c index 929df0728..c076e95ac 100644 --- a/examples/platforms/posix/misc.c +++ b/examples/platforms/posix/misc.c @@ -38,8 +38,8 @@ #include "platform.h" #ifndef _WIN32 -extern int gArgumentsCount; -extern char **gArguments; +extern int gArgumentsCount; +extern char **gArguments; #endif void otPlatReset(otInstance *aInstance) @@ -63,7 +63,7 @@ void otPlatReset(otInstance *aInstance) perror("reset failed"); exit(EXIT_FAILURE); #else - // This function does nothing on the Windows platform. +// This function does nothing on the Windows platform. #endif // _WIN32 (void)aInstance; } diff --git a/examples/platforms/posix/platform-posix.h b/examples/platforms/posix/platform-posix.h index 0d227f958..9753a334e 100644 --- a/examples/platforms/posix/platform-posix.h +++ b/examples/platforms/posix/platform-posix.h @@ -35,18 +35,18 @@ #ifndef PLATFORM_POSIX_H_ #define PLATFORM_POSIX_H_ -#include #include +#include #include -#include #include +#include #include #include #if _WIN32 -#include #include +#include #include #define POLL WSAPoll #define ssize_t int @@ -56,13 +56,13 @@ __forceinline int gettimeofday(struct timeval *tv, struct timezone *tz) { (void)tz; - tv->tv_sec = _time32(NULL); + tv->tv_sec = _time32(NULL); tv->tv_usec = 0; return 0; } __forceinline void timersub(struct timeval *a, struct timeval *b, struct timeval *res) { - res->tv_sec = (long)_difftime32(a->tv_sec, b->tv_sec); + res->tv_sec = (long)_difftime32(a->tv_sec, b->tv_sec); res->tv_usec = 0; } #else @@ -93,9 +93,9 @@ OT_TOOL_PACKED_BEGIN struct Event { uint64_t mDelay; - uint8_t mEvent; + uint8_t mEvent; uint16_t mDataLength; - uint8_t mData[OT_EVENT_DATA_MAX_SIZE]; + uint8_t mData[OT_EVENT_DATA_MAX_SIZE]; } OT_TOOL_PACKED_END; /** @@ -224,4 +224,4 @@ void platformUartProcess(void); */ void platformUartRestore(void); -#endif // PLATFORM_POSIX_H_ +#endif // PLATFORM_POSIX_H_ diff --git a/examples/platforms/posix/platform.c b/examples/platforms/posix/platform.c index 7272aa485..72f3a9cde 100644 --- a/examples/platforms/posix/platform.c +++ b/examples/platforms/posix/platform.c @@ -52,12 +52,12 @@ #include #include -uint32_t NODE_ID = 1; +uint32_t NODE_ID = 1; uint32_t WELLKNOWN_NODE_ID = 34; #ifndef _WIN32 -int gArgumentsCount = 0; -char **gArguments = NULL; +int gArgumentsCount = 0; +char **gArguments = NULL; #endif void PlatformInit(int argc, char *argv[]) @@ -74,7 +74,7 @@ void PlatformInit(int argc, char *argv[]) setlogmask(setlogmask(0) & LOG_UPTO(LOG_NOTICE)); gArgumentsCount = argc; - gArguments = argv; + gArguments = argv; #endif NODE_ID = (uint32_t)strtol(argv[1], &endptr, 0); @@ -97,12 +97,12 @@ void PlatformDeinit(void) void PlatformProcessDrivers(otInstance *aInstance) { - fd_set read_fds; - fd_set write_fds; - fd_set error_fds; - int max_fd = -1; + fd_set read_fds; + fd_set write_fds; + fd_set error_fds; + int max_fd = -1; struct timeval timeout; - int rval; + int rval; FD_ZERO(&read_fds); FD_ZERO(&write_fds); diff --git a/examples/platforms/posix/radio.c b/examples/platforms/posix/radio.c index bc0976a81..b57af7e36 100644 --- a/examples/platforms/posix/radio.c +++ b/examples/platforms/posix/radio.c @@ -38,49 +38,49 @@ enum { - IEEE802154_MIN_LENGTH = 5, - IEEE802154_MAX_LENGTH = 127, - IEEE802154_ACK_LENGTH = 5, + IEEE802154_MIN_LENGTH = 5, + IEEE802154_MAX_LENGTH = 127, + IEEE802154_ACK_LENGTH = 5, - IEEE802154_BROADCAST = 0xffff, + IEEE802154_BROADCAST = 0xffff, - IEEE802154_FRAME_TYPE_ACK = 2 << 0, - IEEE802154_FRAME_TYPE_MACCMD = 3 << 0, - IEEE802154_FRAME_TYPE_MASK = 7 << 0, + IEEE802154_FRAME_TYPE_ACK = 2 << 0, + IEEE802154_FRAME_TYPE_MACCMD = 3 << 0, + IEEE802154_FRAME_TYPE_MASK = 7 << 0, - IEEE802154_SECURITY_ENABLED = 1 << 3, - IEEE802154_FRAME_PENDING = 1 << 4, - IEEE802154_ACK_REQUEST = 1 << 5, - IEEE802154_PANID_COMPRESSION = 1 << 6, + IEEE802154_SECURITY_ENABLED = 1 << 3, + IEEE802154_FRAME_PENDING = 1 << 4, + IEEE802154_ACK_REQUEST = 1 << 5, + IEEE802154_PANID_COMPRESSION = 1 << 6, - IEEE802154_DST_ADDR_NONE = 0 << 2, - IEEE802154_DST_ADDR_SHORT = 2 << 2, - IEEE802154_DST_ADDR_EXT = 3 << 2, - IEEE802154_DST_ADDR_MASK = 3 << 2, + IEEE802154_DST_ADDR_NONE = 0 << 2, + IEEE802154_DST_ADDR_SHORT = 2 << 2, + IEEE802154_DST_ADDR_EXT = 3 << 2, + IEEE802154_DST_ADDR_MASK = 3 << 2, - IEEE802154_SRC_ADDR_NONE = 0 << 6, - IEEE802154_SRC_ADDR_SHORT = 2 << 6, - IEEE802154_SRC_ADDR_EXT = 3 << 6, - IEEE802154_SRC_ADDR_MASK = 3 << 6, + IEEE802154_SRC_ADDR_NONE = 0 << 6, + IEEE802154_SRC_ADDR_SHORT = 2 << 6, + IEEE802154_SRC_ADDR_EXT = 3 << 6, + IEEE802154_SRC_ADDR_MASK = 3 << 6, - IEEE802154_DSN_OFFSET = 2, - IEEE802154_DSTPAN_OFFSET = 3, - IEEE802154_DSTADDR_OFFSET = 5, + IEEE802154_DSN_OFFSET = 2, + IEEE802154_DSTPAN_OFFSET = 3, + IEEE802154_DSTADDR_OFFSET = 5, - IEEE802154_SEC_LEVEL_MASK = 7 << 0, + IEEE802154_SEC_LEVEL_MASK = 7 << 0, - IEEE802154_KEY_ID_MODE_0 = 0 << 3, - IEEE802154_KEY_ID_MODE_1 = 1 << 3, - IEEE802154_KEY_ID_MODE_2 = 2 << 3, - IEEE802154_KEY_ID_MODE_3 = 3 << 3, - IEEE802154_KEY_ID_MODE_MASK = 3 << 3, + IEEE802154_KEY_ID_MODE_0 = 0 << 3, + IEEE802154_KEY_ID_MODE_1 = 1 << 3, + IEEE802154_KEY_ID_MODE_2 = 2 << 3, + IEEE802154_KEY_ID_MODE_3 = 3 << 3, + IEEE802154_KEY_ID_MODE_MASK = 3 << 3, - IEEE802154_MACCMD_DATA_REQ = 4, + IEEE802154_MACCMD_DATA_REQ = 4, }; enum { - POSIX_RECEIVE_SENSITIVITY = -100, // dBm + POSIX_RECEIVE_SENSITIVITY = -100, // dBm POSIX_MAX_SRC_MATCH_ENTRIES = OPENTHREAD_CONFIG_MAX_CHILDREN, }; @@ -96,27 +96,27 @@ static void radioSendMessage(otInstance *aInstance); static void radioSendAck(void); static void radioProcessFrame(otInstance *aInstance); -static otRadioState sState = OT_RADIO_STATE_DISABLED; +static otRadioState sState = OT_RADIO_STATE_DISABLED; static struct RadioMessage sReceiveMessage; static struct RadioMessage sTransmitMessage; static struct RadioMessage sAckMessage; -static otRadioFrame sReceiveFrame; -static otRadioFrame sTransmitFrame; -static otRadioFrame sAckFrame; +static otRadioFrame sReceiveFrame; +static otRadioFrame sTransmitFrame; +static otRadioFrame sAckFrame; -static uint8_t sExtendedAddress[OT_EXT_ADDRESS_SIZE]; +static uint8_t sExtendedAddress[OT_EXT_ADDRESS_SIZE]; static uint16_t sShortAddress; static uint16_t sPanid; static uint16_t sPortOffset = 0; -static int sSockFd; -static bool sPromiscuous = false; -static bool sAckWait = false; +static int sSockFd; +static bool sPromiscuous = false; +static bool sAckWait = false; -static uint8_t sShortAddressMatchTableCount = 0; -static uint8_t sExtAddressMatchTableCount = 0; -static uint16_t sShortAddressMatchTable[POSIX_MAX_SRC_MATCH_ENTRIES]; +static uint8_t sShortAddressMatchTableCount = 0; +static uint8_t sExtAddressMatchTableCount = 0; +static uint16_t sShortAddressMatchTable[POSIX_MAX_SRC_MATCH_ENTRIES]; static otExtAddress sExtAddressMatchTable[POSIX_MAX_SRC_MATCH_ENTRIES]; -static bool sSrcMatchEnabled = false; +static bool sSrcMatchEnabled = false; static bool findShortAddress(uint16_t aShortAddress) { @@ -176,9 +176,9 @@ static inline bool isPanIdCompressed(const uint8_t *frame) static inline bool isDataRequestAndHasFramePending(const uint8_t *frame) { const uint8_t *cur = frame; - uint8_t securityControl; - bool isDataRequest = false; - bool hasFramePending = false; + uint8_t securityControl; + bool isDataRequest = false; + bool hasFramePending = false; // FCF + DSN cur += 2 + 1; @@ -302,41 +302,26 @@ static uint16_t crc16_citt(uint16_t aFcs, uint8_t aByte) // CRC-16/CCITT, CRC-16/CCITT-TRUE, CRC-CCITT // width=16 poly=0x1021 init=0x0000 refin=true refout=true xorout=0x0000 check=0x2189 name="KERMIT" // http://reveng.sourceforge.net/crc-catalogue/16.htm#crc.cat.kermit - static const uint16_t sFcsTable[256] = - { - 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, - 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, - 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, - 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, - 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, - 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, - 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, - 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974, - 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb, - 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, - 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a, - 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, - 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, - 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, - 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, - 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70, - 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, - 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff, - 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, - 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, - 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, - 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, - 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134, - 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, - 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, - 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb, - 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, - 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, - 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, - 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9, - 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, - 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78 - }; + static const uint16_t sFcsTable[256] = { + 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, + 0xe97e, 0xf8f7, 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, 0x9cc9, 0x8d40, 0xbfdb, 0xae52, + 0xdaed, 0xcb64, 0xf9ff, 0xe876, 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, 0xad4a, 0xbcc3, + 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, + 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974, 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, + 0x2732, 0x36bb, 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, 0x5285, 0x430c, 0x7197, 0x601e, + 0x14a1, 0x0528, 0x37b3, 0x263a, 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, 0x6306, 0x728f, + 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, + 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, + 0x9af9, 0x8b70, 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, 0x0840, 0x19c9, 0x2b52, 0x3adb, + 0x4e64, 0x5fed, 0x6d76, 0x7cff, 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, 0x18c1, 0x0948, + 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, + 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, + 0xd0bd, 0xc134, 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, 0xc60c, 0xd785, 0xe51e, 0xf497, + 0x8028, 0x91a1, 0xa33a, 0xb2b3, 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb, 0xd68d, 0xc704, + 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, + 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, + 0x0e70, 0x1ff9, 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, 0x7bc7, 0x6a4e, 0x58d5, 0x495c, + 0x3de3, 0x2c6a, 0x1ef1, 0x0f78}; return (aFcs >> 8) ^ sFcsTable[(aFcs ^ aByte) & 0xff]; } @@ -384,7 +369,7 @@ void otPlatRadioSetPromiscuous(otInstance *aInstance, bool aEnable) void platformRadioInit(void) { struct sockaddr_in sockaddr; - char *offset; + char * offset; memset(&sockaddr, 0, sizeof(sockaddr)); sockaddr.sin_family = AF_INET; @@ -430,9 +415,9 @@ void platformRadioInit(void) exit(EXIT_FAILURE); } - sReceiveFrame.mPsdu = sReceiveMessage.mPsdu; + sReceiveFrame.mPsdu = sReceiveMessage.mPsdu; sTransmitFrame.mPsdu = sTransmitMessage.mPsdu; - sAckFrame.mPsdu = sAckMessage.mPsdu; + sAckFrame.mPsdu = sAckMessage.mPsdu; } void platformRadioDeinit(void) @@ -473,7 +458,7 @@ otError otPlatRadioSleep(otInstance *aInstance) if (sState == OT_RADIO_STATE_SLEEP || sState == OT_RADIO_STATE_RECEIVE) { - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; sState = OT_RADIO_STATE_SLEEP; } @@ -487,9 +472,9 @@ otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) if (sState != OT_RADIO_STATE_DISABLED) { - error = OT_ERROR_NONE; - sState = OT_RADIO_STATE_RECEIVE; - sAckWait = false; + error = OT_ERROR_NONE; + sState = OT_RADIO_STATE_RECEIVE; + sAckWait = false; sReceiveFrame.mChannel = aChannel; } @@ -504,7 +489,7 @@ otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aRadio) if (sState == OT_RADIO_STATE_RECEIVE) { - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; sState = OT_RADIO_STATE_TRANSMIT; } @@ -548,17 +533,15 @@ void radioReceive(otInstance *aInstance) #if OPENTHREAD_ENABLE_RAW_LINK_API // Timestamp sReceiveFrame.mMsec = otPlatAlarmMilliGetNow(); - sReceiveFrame.mUsec = 0; // Don't support microsecond timer for now. + sReceiveFrame.mUsec = 0; // Don't support microsecond timer for now. #endif sReceiveFrame.mLength = (uint8_t)(rval - 1); - if (sAckWait && - sTransmitFrame.mChannel == sReceiveMessage.mChannel && - isFrameTypeAck(sReceiveFrame.mPsdu) && + if (sAckWait && sTransmitFrame.mChannel == sReceiveMessage.mChannel && isFrameTypeAck(sReceiveFrame.mPsdu) && getDsn(sReceiveFrame.mPsdu) == getDsn(sTransmitFrame.mPsdu)) { - sState = OT_RADIO_STATE_RECEIVE; + sState = OT_RADIO_STATE_RECEIVE; sAckWait = false; otPlatRadioTxDone(aInstance, &sTransmitFrame, &sReceiveFrame, OT_ERROR_NONE); @@ -622,8 +605,8 @@ void platformRadioUpdateFdSet(fd_set *aReadFdSet, fd_set *aWriteFdSet, int *aMax void platformRadioProcess(otInstance *aInstance) { - const int flags = POLLIN | POLLRDNORM | POLLERR | POLLNVAL | POLLHUP; - struct pollfd pollfd = { sSockFd, flags, 0 }; + const int flags = POLLIN | POLLRDNORM | POLLERR | POLLNVAL | POLLHUP; + struct pollfd pollfd = {sSockFd, flags, 0}; if (POLL(&pollfd, 1, 0) > 0 && (pollfd.revents & flags) != 0) { @@ -638,10 +621,10 @@ void platformRadioProcess(otInstance *aInstance) void radioTransmit(struct RadioMessage *aMessage, const struct otRadioFrame *aFrame) { - uint32_t i; + uint32_t i; struct sockaddr_in sockaddr; - uint16_t crc = 0; + uint16_t crc = 0; uint16_t crc_offset = aFrame->mLength - sizeof(uint16_t); for (i = 0; i < crc_offset; i++) @@ -649,7 +632,7 @@ void radioTransmit(struct RadioMessage *aMessage, const struct otRadioFrame *aFr crc = crc16_citt(crc, aMessage->mPsdu[i]); } - aMessage->mPsdu[crc_offset] = crc & 0xff; + aMessage->mPsdu[crc_offset] = crc & 0xff; aMessage->mPsdu[crc_offset + 1] = crc >> 8; memset(&sockaddr, 0, sizeof(sockaddr)); @@ -666,8 +649,8 @@ void radioTransmit(struct RadioMessage *aMessage, const struct otRadioFrame *aFr } sockaddr.sin_port = htons(9000 + sPortOffset + i); - rval = sendto(sSockFd, (const char *)aMessage, 1 + aFrame->mLength, - 0, (struct sockaddr *)&sockaddr, sizeof(sockaddr)); + rval = sendto(sSockFd, (const char *)aMessage, 1 + aFrame->mLength, 0, (struct sockaddr *)&sockaddr, + sizeof(sockaddr)); if (rval < 0) { @@ -679,7 +662,7 @@ void radioTransmit(struct RadioMessage *aMessage, const struct otRadioFrame *aFr void radioSendAck(void) { - sAckFrame.mLength = IEEE802154_ACK_LENGTH; + sAckFrame.mLength = IEEE802154_ACK_LENGTH; sAckMessage.mPsdu[0] = IEEE802154_FRAME_TYPE_ACK; if (isDataRequestAndHasFramePending(sReceiveFrame.mPsdu)) @@ -697,10 +680,10 @@ void radioSendAck(void) void radioProcessFrame(otInstance *aInstance) { - otError error = OT_ERROR_NONE; - otPanId dstpan; + otError error = OT_ERROR_NONE; + otPanId dstpan; otShortAddress short_address; - otExtAddress ext_address; + otExtAddress ext_address; otEXPECT_ACTION(sPromiscuous == false, error = OT_ERROR_NONE); @@ -710,10 +693,10 @@ void radioProcessFrame(otInstance *aInstance) break; case IEEE802154_DST_ADDR_SHORT: - dstpan = getDstPan(sReceiveFrame.mPsdu); + dstpan = getDstPan(sReceiveFrame.mPsdu); short_address = getShortAddress(sReceiveFrame.mPsdu); otEXPECT_ACTION((dstpan == IEEE802154_BROADCAST || dstpan == sPanid) && - (short_address == IEEE802154_BROADCAST || short_address == sShortAddress), + (short_address == IEEE802154_BROADCAST || short_address == sShortAddress), error = OT_ERROR_ABORT); break; @@ -721,7 +704,7 @@ void radioProcessFrame(otInstance *aInstance) dstpan = getDstPan(sReceiveFrame.mPsdu); getExtAddress(sReceiveFrame.mPsdu, &ext_address); otEXPECT_ACTION((dstpan == IEEE802154_BROADCAST || dstpan == sPanid) && - memcmp(&ext_address, sExtendedAddress, sizeof(ext_address)) == 0, + memcmp(&ext_address, sExtendedAddress, sizeof(ext_address)) == 0, error = OT_ERROR_ABORT); break; @@ -731,7 +714,7 @@ void radioProcessFrame(otInstance *aInstance) } sReceiveFrame.mRssi = -20; - sReceiveFrame.mLqi = OT_RADIO_LQI_NONE; + sReceiveFrame.mLqi = OT_RADIO_LQI_NONE; // generate acknowledgment if (isAckRequested(sReceiveFrame.mPsdu)) @@ -808,7 +791,7 @@ otError otPlatRadioClearSrcMatchShortEntry(otInstance *aInstance, const uint16_t if (sShortAddressMatchTable[i] == aShortAddress) { sShortAddressMatchTable[i] = sShortAddressMatchTable[--sShortAddressMatchTableCount]; - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; goto exit; } } @@ -829,7 +812,7 @@ otError otPlatRadioClearSrcMatchExtEntry(otInstance *aInstance, const otExtAddre if (!memcmp(&sExtAddressMatchTable[i], aExtAddress, sizeof(otExtAddress))) { sExtAddressMatchTable[i] = sExtAddressMatchTable[--sExtAddressMatchTableCount]; - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; goto exit; } } diff --git a/examples/platforms/posix/random.c b/examples/platforms/posix/random.c index fb120e7b9..7b405e851 100644 --- a/examples/platforms/posix/random.c +++ b/examples/platforms/posix/random.c @@ -53,12 +53,12 @@ void platformRandomInit(void) error = otPlatRandomGetTrue((uint8_t *)&sState, sizeof(sState)); assert(error == OT_ERROR_NONE); -#else // __SANITIZE_ADDRESS__ +#else // __SANITIZE_ADDRESS__ // Multiplying NODE_ID assures that no two nodes gets the same seed within an hour. sState = (uint32_t)time(NULL) + (3600 * NODE_ID); -#endif // __SANITIZE_ADDRESS__ +#endif // __SANITIZE_ADDRESS__ } uint32_t otPlatRandomGet(void) @@ -67,10 +67,10 @@ uint32_t otPlatRandomGet(void) uint64_t tmpstate; tmpstate = (uint64_t)33614 * (uint64_t)sState; - q = tmpstate & 0xffffffff; - q = q >> 1; - p = tmpstate >> 32; - mlcg = p + q; + q = tmpstate & 0xffffffff; + q = q >> 1; + p = tmpstate >> 32; + mlcg = p + q; if (mlcg & 0x80000000) { @@ -89,7 +89,7 @@ otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength) #if __SANITIZE_ADDRESS__ == 0 - FILE *file = NULL; + FILE * file = NULL; size_t readLength; otEXPECT_ACTION(aOutput && aOutputLength, error = OT_ERROR_INVALID_ARGS); @@ -107,7 +107,7 @@ exit: fclose(file); } -#else // __SANITIZE_ADDRESS__ +#else // __SANITIZE_ADDRESS__ /* * THE IMPLEMENTATION BELOW IS NOT COMPLIANT WITH THE THREAD SPECIFICATION. @@ -126,7 +126,7 @@ exit: exit: -#endif // __SANITIZE_ADDRESS__ +#endif // __SANITIZE_ADDRESS__ return error; } diff --git a/examples/platforms/posix/sim/alarm-sim.c b/examples/platforms/posix/sim/alarm-sim.c index d27c61ec0..415826f07 100644 --- a/examples/platforms/posix/sim/alarm-sim.c +++ b/examples/platforms/posix/sim/alarm-sim.c @@ -42,11 +42,11 @@ static uint64_t sNow = 0; // microseconds -static bool sIsMsRunning = false; -static uint32_t sMsAlarm = 0; +static bool sIsMsRunning = false; +static uint32_t sMsAlarm = 0; -static bool sIsUsRunning = false; -static uint32_t sUsAlarm = 0; +static bool sIsUsRunning = false; +static uint32_t sUsAlarm = 0; void platformAlarmInit(void) { @@ -71,7 +71,7 @@ uint32_t otPlatAlarmMilliGetNow(void) void otPlatAlarmMilliStartAt(otInstance *aInstance, uint32_t aT0, uint32_t aDt) { (void)aInstance; - sMsAlarm = aT0 + aDt; + sMsAlarm = aT0 + aDt; sIsMsRunning = true; } @@ -89,7 +89,7 @@ uint32_t otPlatAlarmMicroGetNow(void) void otPlatAlarmMicroStartAt(otInstance *aInstance, uint32_t aT0, uint32_t aDt) { (void)aInstance; - sUsAlarm = aT0 + aDt; + sUsAlarm = aT0 + aDt; sIsUsRunning = true; } diff --git a/examples/platforms/posix/sim/platform-sim.c b/examples/platforms/posix/sim/platform-sim.c index 780fea2b7..049062db2 100644 --- a/examples/platforms/posix/sim/platform-sim.c +++ b/examples/platforms/posix/sim/platform-sim.c @@ -49,19 +49,19 @@ #include #include -uint32_t NODE_ID = 1; +uint32_t NODE_ID = 1; uint32_t WELLKNOWN_NODE_ID = 34; -int gArgumentsCount = 0; -char **gArguments = NULL; +int gArgumentsCount = 0; +char **gArguments = NULL; -int sSockFd; +int sSockFd; uint16_t sPortOffset; static void receiveEvent(otInstance *aInstance) { struct Event event; - ssize_t rval = recvfrom(sSockFd, (char *)&event, sizeof(event), 0, NULL, NULL); + ssize_t rval = recvfrom(sSockFd, (char *)&event, sizeof(event), 0, NULL, NULL); if (rval < 0 || (uint16_t)rval < offsetof(struct Event, mData)) { @@ -84,9 +84,9 @@ static void receiveEvent(otInstance *aInstance) static bool processEvent(otInstance *aInstance) { - const int flags = POLLIN | POLLRDNORM | POLLERR | POLLNVAL | POLLHUP; - struct pollfd pollfd = { sSockFd, flags, 0 }; - bool rval = false; + const int flags = POLLIN | POLLRDNORM | POLLERR | POLLNVAL | POLLHUP; + struct pollfd pollfd = {sSockFd, flags, 0}; + bool rval = false; if (POLL(&pollfd, 1, 0) > 0 && (pollfd.revents & flags) != 0) { @@ -100,13 +100,13 @@ static bool processEvent(otInstance *aInstance) static void platformSendSleepEvent(void) { struct sockaddr_in sockaddr; - struct Event event; - ssize_t rval; + struct Event event; + ssize_t rval; assert(platformAlarmGetNext() > 0); - event.mDelay = (uint64_t)platformAlarmGetNext(); - event.mEvent = OT_SIM_EVENT_ALARM_FIRED; + event.mDelay = (uint64_t)platformAlarmGetNext(); + event.mEvent = OT_SIM_EVENT_ALARM_FIRED; event.mDataLength = 0; memset(&sockaddr, 0, sizeof(sockaddr)); @@ -114,8 +114,8 @@ static void platformSendSleepEvent(void) inet_pton(AF_INET, "127.0.0.1", &sockaddr.sin_addr); sockaddr.sin_port = htons(9000 + sPortOffset); - rval = sendto(sSockFd, (const char *)&event, offsetof(struct Event, mData), - 0, (struct sockaddr *)&sockaddr, sizeof(sockaddr)); + rval = sendto(sSockFd, (const char *)&event, offsetof(struct Event, mData), 0, (struct sockaddr *)&sockaddr, + sizeof(sockaddr)); if (rval < 0) { @@ -127,7 +127,7 @@ static void platformSendSleepEvent(void) static void socket_init(void) { struct sockaddr_in sockaddr; - char *offset; + char * offset; memset(&sockaddr, 0, sizeof(sockaddr)); sockaddr.sin_family = AF_INET; @@ -148,7 +148,7 @@ static void socket_init(void) sPortOffset *= WELLKNOWN_NODE_ID; } - sockaddr.sin_port = htons(9000 + sPortOffset + NODE_ID); + sockaddr.sin_port = htons(9000 + sPortOffset + NODE_ID); sockaddr.sin_addr.s_addr = INADDR_ANY; sSockFd = (int)socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); @@ -179,7 +179,7 @@ void PlatformInit(int argc, char *argv[]) setlogmask(setlogmask(0) & LOG_UPTO(LOG_NOTICE)); gArgumentsCount = argc; - gArguments = argv; + gArguments = argv; NODE_ID = (uint32_t)strtol(argv[1], &endptr, 0); @@ -206,8 +206,8 @@ void PlatformProcessDrivers(otInstance *aInstance) fd_set read_fds; fd_set write_fds; fd_set error_fds; - int max_fd = -1; - int rval; + int max_fd = -1; + int rval; FD_ZERO(&read_fds); FD_ZERO(&write_fds); diff --git a/examples/platforms/posix/sim/radio-sim.c b/examples/platforms/posix/sim/radio-sim.c index f8b8ed3e1..f2138a869 100644 --- a/examples/platforms/posix/sim/radio-sim.c +++ b/examples/platforms/posix/sim/radio-sim.c @@ -38,53 +38,53 @@ enum { - IEEE802154_MIN_LENGTH = 5, - IEEE802154_MAX_LENGTH = 127, - IEEE802154_ACK_LENGTH = 5, + IEEE802154_MIN_LENGTH = 5, + IEEE802154_MAX_LENGTH = 127, + IEEE802154_ACK_LENGTH = 5, - IEEE802154_BROADCAST = 0xffff, + IEEE802154_BROADCAST = 0xffff, - IEEE802154_FRAME_TYPE_ACK = 2 << 0, - IEEE802154_FRAME_TYPE_MACCMD = 3 << 0, - IEEE802154_FRAME_TYPE_MASK = 7 << 0, + IEEE802154_FRAME_TYPE_ACK = 2 << 0, + IEEE802154_FRAME_TYPE_MACCMD = 3 << 0, + IEEE802154_FRAME_TYPE_MASK = 7 << 0, - IEEE802154_SECURITY_ENABLED = 1 << 3, - IEEE802154_FRAME_PENDING = 1 << 4, - IEEE802154_ACK_REQUEST = 1 << 5, - IEEE802154_PANID_COMPRESSION = 1 << 6, + IEEE802154_SECURITY_ENABLED = 1 << 3, + IEEE802154_FRAME_PENDING = 1 << 4, + IEEE802154_ACK_REQUEST = 1 << 5, + IEEE802154_PANID_COMPRESSION = 1 << 6, - IEEE802154_DST_ADDR_NONE = 0 << 2, - IEEE802154_DST_ADDR_SHORT = 2 << 2, - IEEE802154_DST_ADDR_EXT = 3 << 2, - IEEE802154_DST_ADDR_MASK = 3 << 2, + IEEE802154_DST_ADDR_NONE = 0 << 2, + IEEE802154_DST_ADDR_SHORT = 2 << 2, + IEEE802154_DST_ADDR_EXT = 3 << 2, + IEEE802154_DST_ADDR_MASK = 3 << 2, - IEEE802154_SRC_ADDR_NONE = 0 << 6, - IEEE802154_SRC_ADDR_SHORT = 2 << 6, - IEEE802154_SRC_ADDR_EXT = 3 << 6, - IEEE802154_SRC_ADDR_MASK = 3 << 6, + IEEE802154_SRC_ADDR_NONE = 0 << 6, + IEEE802154_SRC_ADDR_SHORT = 2 << 6, + IEEE802154_SRC_ADDR_EXT = 3 << 6, + IEEE802154_SRC_ADDR_MASK = 3 << 6, - IEEE802154_DSN_OFFSET = 2, - IEEE802154_DSTPAN_OFFSET = 3, - IEEE802154_DSTADDR_OFFSET = 5, + IEEE802154_DSN_OFFSET = 2, + IEEE802154_DSTPAN_OFFSET = 3, + IEEE802154_DSTADDR_OFFSET = 5, - IEEE802154_SEC_LEVEL_MASK = 7 << 0, + IEEE802154_SEC_LEVEL_MASK = 7 << 0, - IEEE802154_KEY_ID_MODE_0 = 0 << 3, - IEEE802154_KEY_ID_MODE_1 = 1 << 3, - IEEE802154_KEY_ID_MODE_2 = 2 << 3, - IEEE802154_KEY_ID_MODE_3 = 3 << 3, - IEEE802154_KEY_ID_MODE_MASK = 3 << 3, + IEEE802154_KEY_ID_MODE_0 = 0 << 3, + IEEE802154_KEY_ID_MODE_1 = 1 << 3, + IEEE802154_KEY_ID_MODE_2 = 2 << 3, + IEEE802154_KEY_ID_MODE_3 = 3 << 3, + IEEE802154_KEY_ID_MODE_MASK = 3 << 3, - IEEE802154_MACCMD_DATA_REQ = 4, + IEEE802154_MACCMD_DATA_REQ = 4, }; enum { - POSIX_RECEIVE_SENSITIVITY = -100, // dBm + POSIX_RECEIVE_SENSITIVITY = -100, // dBm POSIX_MAX_SRC_MATCH_ENTRIES = OPENTHREAD_CONFIG_MAX_CHILDREN, }; -extern int sSockFd; +extern int sSockFd; extern uint16_t sPortOffset; OT_TOOL_PACKED_BEGIN @@ -99,25 +99,25 @@ static void radioSendMessage(otInstance *aInstance); static void radioSendAck(void); static void radioProcessFrame(otInstance *aInstance); -static otRadioState sState = OT_RADIO_STATE_DISABLED; +static otRadioState sState = OT_RADIO_STATE_DISABLED; static struct RadioMessage sReceiveMessage; static struct RadioMessage sTransmitMessage; static struct RadioMessage sAckMessage; -static otRadioFrame sReceiveFrame; -static otRadioFrame sTransmitFrame; -static otRadioFrame sAckFrame; +static otRadioFrame sReceiveFrame; +static otRadioFrame sTransmitFrame; +static otRadioFrame sAckFrame; -static uint8_t sExtendedAddress[OT_EXT_ADDRESS_SIZE]; +static uint8_t sExtendedAddress[OT_EXT_ADDRESS_SIZE]; static uint16_t sShortAddress; static uint16_t sPanid; -static bool sPromiscuous = false; -static bool sAckWait = false; +static bool sPromiscuous = false; +static bool sAckWait = false; -static uint8_t sShortAddressMatchTableCount = 0; -static uint8_t sExtAddressMatchTableCount = 0; -static uint16_t sShortAddressMatchTable[POSIX_MAX_SRC_MATCH_ENTRIES]; +static uint8_t sShortAddressMatchTableCount = 0; +static uint8_t sExtAddressMatchTableCount = 0; +static uint16_t sShortAddressMatchTable[POSIX_MAX_SRC_MATCH_ENTRIES]; static otExtAddress sExtAddressMatchTable[POSIX_MAX_SRC_MATCH_ENTRIES]; -static bool sSrcMatchEnabled = false; +static bool sSrcMatchEnabled = false; static bool findShortAddress(uint16_t aShortAddress) { @@ -177,9 +177,9 @@ static inline bool isPanIdCompressed(const uint8_t *frame) static inline bool isDataRequestAndHasFramePending(const uint8_t *frame) { const uint8_t *cur = frame; - uint8_t securityControl; - bool isDataRequest = false; - bool hasFramePending = false; + uint8_t securityControl; + bool isDataRequest = false; + bool hasFramePending = false; // FCF + DSN cur += 2 + 1; @@ -303,41 +303,26 @@ static uint16_t crc16_citt(uint16_t aFcs, uint8_t aByte) // CRC-16/CCITT, CRC-16/CCITT-TRUE, CRC-CCITT // width=16 poly=0x1021 init=0x0000 refin=true refout=true xorout=0x0000 check=0x2189 name="KERMIT" // http://reveng.sourceforge.net/crc-catalogue/16.htm#crc.cat.kermit - static const uint16_t sFcsTable[256] = - { - 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, - 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, - 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, - 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, - 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, - 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, - 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, - 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974, - 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb, - 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, - 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a, - 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, - 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, - 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, - 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, - 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70, - 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, - 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff, - 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, - 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, - 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, - 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, - 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134, - 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, - 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, - 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb, - 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, - 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, - 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, - 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9, - 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, - 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78 - }; + static const uint16_t sFcsTable[256] = { + 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, + 0xe97e, 0xf8f7, 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, 0x9cc9, 0x8d40, 0xbfdb, 0xae52, + 0xdaed, 0xcb64, 0xf9ff, 0xe876, 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, 0xad4a, 0xbcc3, + 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, + 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974, 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, + 0x2732, 0x36bb, 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, 0x5285, 0x430c, 0x7197, 0x601e, + 0x14a1, 0x0528, 0x37b3, 0x263a, 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, 0x6306, 0x728f, + 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, + 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, + 0x9af9, 0x8b70, 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, 0x0840, 0x19c9, 0x2b52, 0x3adb, + 0x4e64, 0x5fed, 0x6d76, 0x7cff, 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, 0x18c1, 0x0948, + 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, + 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, + 0xd0bd, 0xc134, 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, 0xc60c, 0xd785, 0xe51e, 0xf497, + 0x8028, 0x91a1, 0xa33a, 0xb2b3, 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb, 0xd68d, 0xc704, + 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, + 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, + 0x0e70, 0x1ff9, 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, 0x7bc7, 0x6a4e, 0x58d5, 0x495c, + 0x3de3, 0x2c6a, 0x1ef1, 0x0f78}; return (aFcs >> 8) ^ sFcsTable[(aFcs ^ aByte) & 0xff]; } @@ -384,9 +369,9 @@ void otPlatRadioSetPromiscuous(otInstance *aInstance, bool aEnable) void platformRadioInit(void) { - sReceiveFrame.mPsdu = sReceiveMessage.mPsdu; + sReceiveFrame.mPsdu = sReceiveMessage.mPsdu; sTransmitFrame.mPsdu = sTransmitMessage.mPsdu; - sAckFrame.mPsdu = sAckMessage.mPsdu; + sAckFrame.mPsdu = sAckMessage.mPsdu; } bool otPlatRadioIsEnabled(otInstance *aInstance) @@ -422,7 +407,7 @@ otError otPlatRadioSleep(otInstance *aInstance) if (sState == OT_RADIO_STATE_SLEEP || sState == OT_RADIO_STATE_RECEIVE) { - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; sState = OT_RADIO_STATE_SLEEP; } @@ -436,9 +421,9 @@ otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) if (sState != OT_RADIO_STATE_DISABLED) { - error = OT_ERROR_NONE; - sState = OT_RADIO_STATE_RECEIVE; - sAckWait = false; + error = OT_ERROR_NONE; + sState = OT_RADIO_STATE_RECEIVE; + sAckWait = false; sReceiveFrame.mChannel = aChannel; } @@ -453,7 +438,7 @@ otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aRadio) if (sState == OT_RADIO_STATE_RECEIVE) { - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; sState = OT_RADIO_STATE_TRANSMIT; } @@ -493,20 +478,17 @@ void platformRadioReceive(otInstance *aInstance, uint8_t *aBuf, uint16_t aBufLen #if OPENTHREAD_ENABLE_RAW_LINK_API // Timestamp sReceiveFrame.mMsec = otPlatAlarmMilliGetNow(); - sReceiveFrame.mUsec = 0; // Don't support microsecond timer for now. + sReceiveFrame.mUsec = 0; // Don't support microsecond timer for now. #endif sReceiveFrame.mLength = (uint8_t)(aBufLength - 1); - if (sState == OT_RADIO_STATE_TRANSMIT && - sAckWait && - !isAckRequested(sTransmitFrame.mPsdu) && - sTransmitFrame.mChannel == sReceiveMessage.mChannel && - !isFrameTypeAck(sTransmitFrame.mPsdu) && + if (sState == OT_RADIO_STATE_TRANSMIT && sAckWait && !isAckRequested(sTransmitFrame.mPsdu) && + sTransmitFrame.mChannel == sReceiveMessage.mChannel && !isFrameTypeAck(sTransmitFrame.mPsdu) && sTransmitFrame.mLength == sReceiveFrame.mLength && memcmp(sTransmitFrame.mPsdu, sReceiveFrame.mPsdu, sTransmitFrame.mLength) == 0) { - sState = OT_RADIO_STATE_RECEIVE; + sState = OT_RADIO_STATE_RECEIVE; sAckWait = false; #if OPENTHREAD_ENABLE_DIAG @@ -521,14 +503,11 @@ void platformRadioReceive(otInstance *aInstance, uint8_t *aBuf, uint16_t aBufLen otPlatRadioTxDone(aInstance, &sTransmitFrame, NULL, OT_ERROR_NONE); } } - else if (sState == OT_RADIO_STATE_TRANSMIT && - sAckWait && - isAckRequested(sTransmitFrame.mPsdu) && - sTransmitFrame.mChannel == sReceiveMessage.mChannel && - isFrameTypeAck(sReceiveFrame.mPsdu) && + else if (sState == OT_RADIO_STATE_TRANSMIT && sAckWait && isAckRequested(sTransmitFrame.mPsdu) && + sTransmitFrame.mChannel == sReceiveMessage.mChannel && isFrameTypeAck(sReceiveFrame.mPsdu) && getDsn(sReceiveFrame.mPsdu) == getDsn(sTransmitFrame.mPsdu)) { - sState = OT_RADIO_STATE_RECEIVE; + sState = OT_RADIO_STATE_RECEIVE; sAckWait = false; #if OPENTHREAD_ENABLE_DIAG @@ -571,10 +550,10 @@ void platformRadioProcess(otInstance *aInstance) void radioTransmit(struct RadioMessage *aMessage, const struct otRadioFrame *aFrame) { struct sockaddr_in sockaddr; - struct Event event; - ssize_t rval; + struct Event event; + ssize_t rval; - uint16_t crc = 0; + uint16_t crc = 0; uint16_t crc_offset = aFrame->mLength - sizeof(uint16_t); for (uint32_t i = 0; i < crc_offset; i++) @@ -582,12 +561,12 @@ void radioTransmit(struct RadioMessage *aMessage, const struct otRadioFrame *aFr crc = crc16_citt(crc, aMessage->mPsdu[i]); } - aMessage->mPsdu[crc_offset] = crc & 0xff; + aMessage->mPsdu[crc_offset] = crc & 0xff; aMessage->mPsdu[crc_offset + 1] = crc >> 8; - event.mDelay = 1; // 1us for now - event.mEvent = OT_SIM_EVENT_RADIO_RECEIVED; - event.mDataLength = 1 + aFrame->mLength; // include channel in first byte + event.mDelay = 1; // 1us for now + event.mEvent = OT_SIM_EVENT_RADIO_RECEIVED; + event.mDataLength = 1 + aFrame->mLength; // include channel in first byte memcpy(event.mData, aMessage, event.mDataLength); memset(&sockaddr, 0, sizeof(sockaddr)); @@ -595,8 +574,8 @@ void radioTransmit(struct RadioMessage *aMessage, const struct otRadioFrame *aFr inet_pton(AF_INET, "127.0.0.1", &sockaddr.sin_addr); sockaddr.sin_port = htons(9000 + sPortOffset); - rval = sendto(sSockFd, (const char *)&event, offsetof(struct Event, mData) + event.mDataLength, - 0, (struct sockaddr *)&sockaddr, sizeof(sockaddr)); + rval = sendto(sSockFd, (const char *)&event, offsetof(struct Event, mData) + event.mDataLength, 0, + (struct sockaddr *)&sockaddr, sizeof(sockaddr)); if (rval < 0) { @@ -607,7 +586,7 @@ void radioTransmit(struct RadioMessage *aMessage, const struct otRadioFrame *aFr void radioSendAck(void) { - sAckFrame.mLength = IEEE802154_ACK_LENGTH; + sAckFrame.mLength = IEEE802154_ACK_LENGTH; sAckMessage.mPsdu[0] = IEEE802154_FRAME_TYPE_ACK; if (isDataRequestAndHasFramePending(sReceiveFrame.mPsdu)) @@ -625,10 +604,10 @@ void radioSendAck(void) void radioProcessFrame(otInstance *aInstance) { - otError error = OT_ERROR_NONE; - otPanId dstpan; + otError error = OT_ERROR_NONE; + otPanId dstpan; otShortAddress short_address; - otExtAddress ext_address; + otExtAddress ext_address; otEXPECT_ACTION(sPromiscuous == false, error = OT_ERROR_NONE); @@ -638,10 +617,10 @@ void radioProcessFrame(otInstance *aInstance) break; case IEEE802154_DST_ADDR_SHORT: - dstpan = getDstPan(sReceiveFrame.mPsdu); + dstpan = getDstPan(sReceiveFrame.mPsdu); short_address = getShortAddress(sReceiveFrame.mPsdu); otEXPECT_ACTION((dstpan == IEEE802154_BROADCAST || dstpan == sPanid) && - (short_address == IEEE802154_BROADCAST || short_address == sShortAddress), + (short_address == IEEE802154_BROADCAST || short_address == sShortAddress), error = OT_ERROR_ABORT); break; @@ -649,7 +628,7 @@ void radioProcessFrame(otInstance *aInstance) dstpan = getDstPan(sReceiveFrame.mPsdu); getExtAddress(sReceiveFrame.mPsdu, &ext_address); otEXPECT_ACTION((dstpan == IEEE802154_BROADCAST || dstpan == sPanid) && - memcmp(&ext_address, sExtendedAddress, sizeof(ext_address)) == 0, + memcmp(&ext_address, sExtendedAddress, sizeof(ext_address)) == 0, error = OT_ERROR_ABORT); break; @@ -659,7 +638,7 @@ void radioProcessFrame(otInstance *aInstance) } sReceiveFrame.mRssi = -20; - sReceiveFrame.mLqi = OT_RADIO_LQI_NONE; + sReceiveFrame.mLqi = OT_RADIO_LQI_NONE; // generate acknowledgment if (isAckRequested(sReceiveFrame.mPsdu)) @@ -736,7 +715,7 @@ otError otPlatRadioClearSrcMatchShortEntry(otInstance *aInstance, const uint16_t if (sShortAddressMatchTable[i] == aShortAddress) { sShortAddressMatchTable[i] = sShortAddressMatchTable[--sShortAddressMatchTableCount]; - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; goto exit; } } @@ -757,7 +736,7 @@ otError otPlatRadioClearSrcMatchExtEntry(otInstance *aInstance, const otExtAddre if (!memcmp(&sExtAddressMatchTable[i], aExtAddress, sizeof(otExtAddress))) { sExtAddressMatchTable[i] = sExtAddressMatchTable[--sExtAddressMatchTableCount]; - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; goto exit; } } diff --git a/examples/platforms/posix/uart-posix.c b/examples/platforms/posix/uart-posix.c index b4364902e..4ce0a545b 100644 --- a/examples/platforms/posix/uart-posix.c +++ b/examples/platforms/posix/uart-posix.c @@ -33,8 +33,8 @@ #include #include #include -#include #include +#include #include #include @@ -45,17 +45,17 @@ #ifdef OPENTHREAD_TARGET_LINUX #include -int posix_openpt(int oflag); -int grantpt(int fildes); -int unlockpt(int fd); +int posix_openpt(int oflag); +int grantpt(int fildes); +int unlockpt(int fd); char *ptsname(int fd); -#endif // OPENTHREAD_TARGET_LINUX +#endif // OPENTHREAD_TARGET_LINUX -static uint8_t s_receive_buffer[128]; +static uint8_t s_receive_buffer[128]; static const uint8_t *s_write_buffer; -static uint16_t s_write_length; -static int s_in_fd; -static int s_out_fd; +static uint16_t s_write_length; +static int s_in_fd; +static int s_out_fd; static struct termios original_stdin_termios; static struct termios original_stdout_termios; @@ -79,7 +79,7 @@ void platformUartRestore(void) otError otPlatUartEnable(void) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; struct termios termios; #ifdef OPENTHREAD_TARGET_LINUX @@ -88,7 +88,7 @@ otError otPlatUartEnable(void) prctl(PR_SET_PDEATHSIG, SIGHUP); #endif - s_in_fd = dup(STDIN_FILENO); + s_in_fd = dup(STDIN_FILENO); s_out_fd = dup(STDOUT_FILENO); dup2(STDERR_FILENO, STDOUT_FILENO); @@ -121,7 +121,7 @@ otError otPlatUartEnable(void) termios.c_cflag |= HUPCL | CREAD | CLOCAL; // "Minimum number of characters for noncanonical read" - termios.c_cc[VMIN] = 1; + termios.c_cc[VMIN] = 1; // "Timeout in deciseconds for noncanonical read" termios.c_cc[VTIME] = 0; @@ -221,12 +221,11 @@ void platformUartUpdateFdSet(fd_set *aReadFdSet, fd_set *aWriteFdSet, fd_set *aE void platformUartProcess(void) { - ssize_t rval; - const int error_flags = POLLERR | POLLNVAL | POLLHUP; - struct pollfd pollfd[] = - { - { s_in_fd, POLLIN | error_flags, 0 }, - { s_out_fd, POLLOUT | error_flags, 0 }, + ssize_t rval; + const int error_flags = POLLERR | POLLNVAL | POLLHUP; + struct pollfd pollfd[] = { + {s_in_fd, POLLIN | error_flags, 0}, + {s_out_fd, POLLOUT | error_flags, 0}, }; errno = 0; @@ -287,7 +286,7 @@ void platformUartProcess(void) } } -#if OPENTHREAD_CONFIG_ENABLE_DEBUG_UART && (OPENTHREAD_CONFIG_LOG_OUTPUT==OPENTHREAD_CONFIG_LOG_OUTPUT_DEBUG_UART) +#if OPENTHREAD_CONFIG_ENABLE_DEBUG_UART && (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_DEBUG_UART) static FILE *posix_logfile; @@ -331,4 +330,3 @@ int otPlatDebugUart_getc(void) } #endif - diff --git a/examples/platforms/samr21/alarm.c b/examples/platforms/samr21/alarm.c index 193e7207c..87d60cedb 100644 --- a/examples/platforms/samr21/alarm.c +++ b/examples/platforms/samr21/alarm.c @@ -60,7 +60,6 @@ uint32_t otPlatAlarmMilliGetNow(void) return sTime; } - void SysTick_Handler(void) { sTime++; diff --git a/examples/platforms/samr21/cxx_helpers.c b/examples/platforms/samr21/cxx_helpers.c index 05faf5ab8..d4b003662 100644 --- a/examples/platforms/samr21/cxx_helpers.c +++ b/examples/platforms/samr21/cxx_helpers.c @@ -49,6 +49,6 @@ void __cxa_guard_abort(__guard *g) void __cxa_pure_virtual(void) { - while (1); + while (1) + ; } - diff --git a/examples/platforms/samr21/flash.c b/examples/platforms/samr21/flash.c index c44a7f43c..35765f78b 100644 --- a/examples/platforms/samr21/flash.c +++ b/examples/platforms/samr21/flash.c @@ -40,7 +40,7 @@ otError utilsFlashInit(void) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; struct nvm_config configNvm; nvm_get_config_defaults(&configNvm); @@ -49,7 +49,8 @@ otError utilsFlashInit(void) enum status_code status; - while ((status = nvm_set_config(&configNvm)) == STATUS_BUSY); + while ((status = nvm_set_config(&configNvm)) == STATUS_BUSY) + ; if (status != STATUS_OK) { @@ -78,7 +79,7 @@ otError utilsFlashErasePage(uint32_t aAddress) otError utilsFlashStatusWait(uint32_t aTimeout) { - otError error = OT_ERROR_BUSY; + otError error = OT_ERROR_BUSY; uint32_t start = otPlatAlarmMilliGetNow(); do @@ -88,8 +89,7 @@ otError utilsFlashStatusWait(uint32_t aTimeout) error = OT_ERROR_NONE; break; } - } - while (aTimeout && ((otPlatAlarmMilliGetNow() - start) < aTimeout)); + } while (aTimeout && ((otPlatAlarmMilliGetNow() - start) < aTimeout)); return error; } @@ -100,8 +100,7 @@ uint32_t utilsFlashWrite(uint32_t aAddress, uint8_t *aData, uint32_t aSize) otEXPECT_ACTION(aData, rval = 0); otEXPECT_ACTION(aAddress >= SETTINGS_CONFIG_BASE_ADDRESS, rval = 0); - otEXPECT_ACTION((aAddress - SETTINGS_CONFIG_BASE_ADDRESS + aSize) <= - utilsFlashGetSize(), rval = 0); + otEXPECT_ACTION((aAddress - SETTINGS_CONFIG_BASE_ADDRESS + aSize) <= utilsFlashGetSize(), rval = 0); otEXPECT_ACTION(((aAddress & 3) == 0) && ((aSize & 3) == 0), rval = 0); for (uint32_t i = 0; i < (aSize / sizeof(uint32_t)); i++) @@ -116,8 +115,7 @@ uint32_t utilsFlashWrite(uint32_t aAddress, uint8_t *aData, uint32_t aSize) { enum status_code status; - status = nvm_execute_command(NVM_COMMAND_WRITE_PAGE, - aAddress & (~(NVMCTRL_PAGE_SIZE - 1)), 0); + status = nvm_execute_command(NVM_COMMAND_WRITE_PAGE, aAddress & (~(NVMCTRL_PAGE_SIZE - 1)), 0); otEXPECT_ACTION(status == STATUS_OK, rval = 0); } @@ -132,8 +130,7 @@ uint32_t utilsFlashRead(uint32_t aAddress, uint8_t *aData, uint32_t aSize) otEXPECT_ACTION(aData, rval = 0); otEXPECT_ACTION(aAddress >= SETTINGS_CONFIG_BASE_ADDRESS, rval = 0); - otEXPECT_ACTION((aAddress - SETTINGS_CONFIG_BASE_ADDRESS + aSize) <= - utilsFlashGetSize(), rval = 0); + otEXPECT_ACTION((aAddress - SETTINGS_CONFIG_BASE_ADDRESS + aSize) <= utilsFlashGetSize(), rval = 0); while (aSize--) { diff --git a/examples/platforms/samr21/misc.c b/examples/platforms/samr21/misc.c index acddba472..3986c087b 100644 --- a/examples/platforms/samr21/misc.c +++ b/examples/platforms/samr21/misc.c @@ -41,7 +41,9 @@ void otPlatReset(otInstance *aInstance) system_reset(); - while (1) {} + while (1) + { + } } otPlatResetReason otPlatGetResetReason(otInstance *aInstance) diff --git a/examples/platforms/samr21/platform.c b/examples/platforms/samr21/platform.c index e189a0aa2..c9d143df7 100644 --- a/examples/platforms/samr21/platform.c +++ b/examples/platforms/samr21/platform.c @@ -50,11 +50,11 @@ samr21UserRow *sUserRow = (samr21UserRow *)SAMR21_USER_ROW; #ifdef CONF_KIT_DATA_EXIST -#define EDBG_ADDRESS 0x28 +#define EDBG_ADDRESS 0x28 -#define EDBG_KIT_DATA_TOKEN 0xD2; +#define EDBG_KIT_DATA_TOKEN 0xD2; -#define KIT_DATA_MAX_RETRY 1000 +#define KIT_DATA_MAX_RETRY 1000 static uint8_t sIeeeEui64[OT_EXT_ADDRESS_SIZE]; @@ -67,8 +67,8 @@ static void configureI2cMaster() i2c_master_get_config_defaults(&configI2c); /* Change pins */ - configI2c.pinmux_pad0 = EDBG_I2C_SERCOM_PINMUX_PAD0; - configI2c.pinmux_pad1 = EDBG_I2C_SERCOM_PINMUX_PAD1; + configI2c.pinmux_pad0 = EDBG_I2C_SERCOM_PINMUX_PAD0; + configI2c.pinmux_pad1 = EDBG_I2C_SERCOM_PINMUX_PAD1; /* Initialize and enable device with config */ i2c_master_init(&sI2cMasterInstance, EDBG_I2C_MODULE, &configI2c); @@ -78,8 +78,8 @@ static void configureI2cMaster() static void getKitData() { - uint8_t requestToken = EDBG_KIT_DATA_TOKEN; - uint32_t timeout; + uint8_t requestToken = EDBG_KIT_DATA_TOKEN; + uint32_t timeout; struct i2c_master_packet masterPacket; /** Send the request token */ @@ -92,21 +92,19 @@ static void getKitData() timeout = 0; - while (i2c_master_write_packet_wait_no_stop(&sI2cMasterInstance, &masterPacket) != - STATUS_OK) + while (i2c_master_write_packet_wait_no_stop(&sI2cMasterInstance, &masterPacket) != STATUS_OK) { /* Increment timeout counter and check if timed out. */ otEXPECT(timeout++ < KIT_DATA_MAX_RETRY); } /** Get the extension boards info */ - masterPacket.data_length = OT_EXT_ADDRESS_SIZE; - masterPacket.data = sIeeeEui64; + masterPacket.data_length = OT_EXT_ADDRESS_SIZE; + masterPacket.data = sIeeeEui64; timeout = 0; - while (i2c_master_read_packet_wait(&sI2cMasterInstance, &masterPacket) != - STATUS_OK) + while (i2c_master_read_packet_wait(&sI2cMasterInstance, &masterPacket) != STATUS_OK) { /* Increment timeout counter and check if timed out. */ otEXPECT(timeout++ < KIT_DATA_MAX_RETRY); @@ -126,19 +124,19 @@ void boardInit(void) struct port_config pin_conf; port_get_config_defaults(&pin_conf); - pin_conf.direction = PORT_PIN_DIR_OUTPUT; - port_pin_set_config(AT86RFX_SPI_SCK, &pin_conf); + pin_conf.direction = PORT_PIN_DIR_OUTPUT; + port_pin_set_config(AT86RFX_SPI_SCK, &pin_conf); port_pin_set_config(AT86RFX_SPI_MOSI, &pin_conf); - port_pin_set_config(AT86RFX_SPI_CS, &pin_conf); - port_pin_set_config(AT86RFX_RST_PIN, &pin_conf); - port_pin_set_config(AT86RFX_SLP_PIN, &pin_conf); - port_pin_set_output_level(AT86RFX_SPI_SCK, true); + port_pin_set_config(AT86RFX_SPI_CS, &pin_conf); + port_pin_set_config(AT86RFX_RST_PIN, &pin_conf); + port_pin_set_config(AT86RFX_SLP_PIN, &pin_conf); + port_pin_set_output_level(AT86RFX_SPI_SCK, true); port_pin_set_output_level(AT86RFX_SPI_MOSI, true); - port_pin_set_output_level(AT86RFX_SPI_CS, true); - port_pin_set_output_level(AT86RFX_RST_PIN, true); - port_pin_set_output_level(AT86RFX_SLP_PIN, true); + port_pin_set_output_level(AT86RFX_SPI_CS, true); + port_pin_set_output_level(AT86RFX_RST_PIN, true); + port_pin_set_output_level(AT86RFX_SLP_PIN, true); - pin_conf.direction = PORT_PIN_DIR_INPUT; + pin_conf.direction = PORT_PIN_DIR_INPUT; port_pin_set_config(AT86RFX_SPI_MISO, &pin_conf); } diff --git a/examples/platforms/samr21/radio.c b/examples/platforms/samr21/radio.c index d71fd7d53..fc870d2e2 100644 --- a/examples/platforms/samr21/radio.c +++ b/examples/platforms/samr21/radio.c @@ -46,13 +46,13 @@ enum { - IEEE802154_ACK_LENGTH = 5, - IEEE802154_FCS_SIZE = 2 + IEEE802154_ACK_LENGTH = 5, + IEEE802154_FCS_SIZE = 2 }; enum { - SAMR21_RECEIVE_SENSITIVITY = -99 // dBm + SAMR21_RECEIVE_SENSITIVITY = -99 // dBm }; static otRadioFrame sTransmitFrame; @@ -60,40 +60,22 @@ static uint8_t sTransmitPsdu[OT_RADIO_FRAME_MAX_SIZE]; static otRadioFrame sReceiveFrame; -static bool sSleep = false; -static bool sRxEnable = false; -static bool sTxDone = false; -static bool sRxDone = false; -static otError sTxStatus = OT_ERROR_NONE; -static int8_t sPower = OPENTHREAD_CONFIG_DEFAULT_TRANSMIT_POWER; -static otRadioState sState = OT_RADIO_STATE_DISABLED; -static bool sPromiscuous = false; -static uint8_t sChannel = 0xFF; +static bool sSleep = false; +static bool sRxEnable = false; +static bool sTxDone = false; +static bool sRxDone = false; +static otError sTxStatus = OT_ERROR_NONE; +static int8_t sPower = OPENTHREAD_CONFIG_DEFAULT_TRANSMIT_POWER; +static otRadioState sState = OT_RADIO_STATE_DISABLED; +static bool sPromiscuous = false; +static uint8_t sChannel = 0xFF; -static int8_t sMaxRssi; -static uint32_t sScanStartTime; -static uint16_t sScanDuration; -static bool sStartScan = false; +static int8_t sMaxRssi; +static uint32_t sScanStartTime; +static uint16_t sScanDuration; +static bool sStartScan = false; -static int8_t sTxPowerTable[] = -{ - 4, - 4, - 3, - 3, - 3, - 2, - 1, - 0, - -1, - -2, - -3, - -4, - -6, - -8, - -12, - -17 -}; +static int8_t sTxPowerTable[] = {4, 4, 3, 3, 3, 2, 1, 0, -1, -2, -3, -4, -6, -8, -12, -17}; /******************************************************************************* * Static @@ -106,7 +88,7 @@ static void radioSleep() PHY_SetRxState(false); PHY_Sleep(); - sSleep = true; + sSleep = true; sRxEnable = false; } } @@ -235,7 +217,7 @@ static void handleRx(void) #if OPENTHREAD_ENABLE_RAW_LINK_API // Timestamp sReceiveFrame.mMsec = otPlatAlarmMilliGetNow(); - sReceiveFrame.mUsec = 0; // Don't support microsecond timer for now. + sReceiveFrame.mUsec = 0; // Don't support microsecond timer for now. #endif #if OPENTHREAD_ENABLE_DIAG @@ -251,8 +233,7 @@ static void handleRx(void) // otherwise only signal MAC layer for non-ACK frame if (sPromiscuous || sReceiveFrame.mLength > IEEE802154_ACK_LENGTH) { - otLogDebgPlat(sInstance, "Radio receive done, rssi: %d", - sReceiveFrame.mRssi); + otLogDebgPlat(sInstance, "Radio receive done, rssi: %d", sReceiveFrame.mRssi); otPlatRadioReceiveDone(sInstance, &sReceiveFrame, OT_ERROR_NONE); } @@ -275,8 +256,7 @@ static void handleTx(void) else #endif { - otLogDebgPlat(sInstance, "Radio transmit done, status: %d", - sTxStatus); + otLogDebgPlat(sInstance, "Radio transmit done, status: %d", sTxStatus); otPlatRadioTxDone(sInstance, &sTransmitFrame, NULL, sTxStatus); } @@ -289,9 +269,9 @@ static void handleTx(void) void PHY_DataInd(PHY_DataInd_t *ind) { - sReceiveFrame.mPsdu = ind->data; + sReceiveFrame.mPsdu = ind->data; sReceiveFrame.mLength = ind->size + IEEE802154_FCS_SIZE; - sReceiveFrame.mRssi = ind->rssi; + sReceiveFrame.mRssi = ind->rssi; sRxDone = true; } @@ -469,9 +449,7 @@ otError otPlatRadioSleep(otInstance *aInstance) otError error = OT_ERROR_NONE; - otEXPECT_ACTION(sState == OT_RADIO_STATE_SLEEP || - sState == OT_RADIO_STATE_RECEIVE, - error = OT_ERROR_INVALID_STATE); + otEXPECT_ACTION(sState == OT_RADIO_STATE_SLEEP || sState == OT_RADIO_STATE_RECEIVE, error = OT_ERROR_INVALID_STATE); radioSleep(); @@ -490,8 +468,7 @@ otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) otError error = OT_ERROR_NONE; - otEXPECT_ACTION(sState != OT_RADIO_STATE_DISABLED, - error = OT_ERROR_INVALID_STATE); + otEXPECT_ACTION(sState != OT_RADIO_STATE_DISABLED, error = OT_ERROR_INVALID_STATE); setChannel(aChannel); @@ -512,8 +489,7 @@ otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aFrame) otError error = OT_ERROR_NONE; - otEXPECT_ACTION(sState == OT_RADIO_STATE_RECEIVE, - error = OT_ERROR_INVALID_STATE); + otEXPECT_ACTION(sState == OT_RADIO_STATE_RECEIVE, error = OT_ERROR_INVALID_STATE); uint8_t frame[OT_RADIO_FRAME_MAX_SIZE + 1]; @@ -547,8 +523,7 @@ int8_t otPlatRadioGetRssi(otInstance *aInstance) otRadioCaps otPlatRadioGetCaps(otInstance *aInstance) { - return OT_RADIO_CAPS_ENERGY_SCAN | OT_RADIO_CAPS_TRANSMIT_RETRIES | - OT_RADIO_CAPS_ACK_TIMEOUT; + return OT_RADIO_CAPS_ENERGY_SCAN | OT_RADIO_CAPS_TRANSMIT_RETRIES | OT_RADIO_CAPS_ACK_TIMEOUT; } bool otPlatRadioGetPromiscuous(otInstance *aInstance) @@ -606,7 +581,7 @@ otError otPlatRadioEnergyScan(otInstance *aInstance, uint8_t aScanChannel, uint1 (void)aInstance; sScanStartTime = otPlatAlarmMilliGetNow(); - sScanDuration = aScanDuration; + sScanDuration = aScanDuration; sMaxRssi = PHY_EdReq(); diff --git a/examples/platforms/samr21/uart.c b/examples/platforms/samr21/uart.c index 9f0552a86..3c7da8547 100644 --- a/examples/platforms/samr21/uart.c +++ b/examples/platforms/samr21/uart.c @@ -45,7 +45,7 @@ enum typedef struct RecvBuffer { // The data buffer - uint8_t mBuffer[kReceiveBufferSize]; + uint8_t mBuffer[kReceiveBufferSize]; // The offset of the first item written to the list. uint16_t mHead; // The offset of the next item to be written to the list. @@ -65,8 +65,7 @@ static void usartReadCallback(struct usart_module *const usartModule) sReceive.mTail = (sReceive.mTail + 1) % kReceiveBufferSize; } - usart_read_job(&sUsartInstance, - (uint16_t *)&sReceive.mBuffer[sReceive.mTail]); + usart_read_job(&sUsartInstance, (uint16_t *)&sReceive.mBuffer[sReceive.mTail]); } static void usartWriteCallback(struct usart_module *const usartModule) @@ -126,24 +125,21 @@ otError otPlatUartEnable(void) configUsart.pinmux_pad2 = UART_SERCOM_PINMUX_PAD2; configUsart.pinmux_pad3 = UART_SERCOM_PINMUX_PAD3; - while (usart_init(&sUsartInstance, UART_SERCOM_MODULE, &configUsart) - != STATUS_OK); + while (usart_init(&sUsartInstance, UART_SERCOM_MODULE, &configUsart) != STATUS_OK) + ; usart_enable(&sUsartInstance); sReceive.mHead = 0; sReceive.mTail = 0; - usart_register_callback(&sUsartInstance, usartWriteCallback, - USART_CALLBACK_BUFFER_TRANSMITTED); - usart_register_callback(&sUsartInstance, usartReadCallback, - USART_CALLBACK_BUFFER_RECEIVED); + usart_register_callback(&sUsartInstance, usartWriteCallback, USART_CALLBACK_BUFFER_TRANSMITTED); + usart_register_callback(&sUsartInstance, usartReadCallback, USART_CALLBACK_BUFFER_RECEIVED); usart_enable_callback(&sUsartInstance, USART_CALLBACK_BUFFER_TRANSMITTED); usart_enable_callback(&sUsartInstance, USART_CALLBACK_BUFFER_RECEIVED); - usart_read_job(&sUsartInstance, - (uint16_t *)&sReceive.mBuffer[sReceive.mTail]); + usart_read_job(&sUsartInstance, (uint16_t *)&sReceive.mBuffer[sReceive.mTail]); return OT_ERROR_NONE; } @@ -159,12 +155,10 @@ otError otPlatUartSend(const uint8_t *aBuf, uint16_t aBufLength) { otError error = OT_ERROR_NONE; - if (usart_write_buffer_job(&sUsartInstance, (uint8_t *)aBuf, - aBufLength) != STATUS_OK) + if (usart_write_buffer_job(&sUsartInstance, (uint8_t *)aBuf, aBufLength) != STATUS_OK) { error = OT_ERROR_FAILED; } return error; } - diff --git a/examples/platforms/utils/code_utils.h b/examples/platforms/utils/code_utils.h index 1c5e8c5b9..30a9e0168 100644 --- a/examples/platforms/utils/code_utils.h +++ b/examples/platforms/utils/code_utils.h @@ -42,13 +42,13 @@ * @param[in] aCondition A Boolean expression to be evaluated. * */ -#define otEXPECT(aCondition) \ - do \ - { \ - if (!(aCondition)) \ - { \ - goto exit; \ - } \ +#define otEXPECT(aCondition) \ + do \ + { \ + if (!(aCondition)) \ + { \ + goto exit; \ + } \ } while (0) /** @@ -61,14 +61,14 @@ * assertion fails. * */ -#define otEXPECT_ACTION(aCondition, aAction) \ - do \ - { \ - if (!(aCondition)) \ - { \ - aAction; \ - goto exit; \ - } \ +#define otEXPECT_ACTION(aCondition, aAction) \ + do \ + { \ + if (!(aCondition)) \ + { \ + aAction; \ + goto exit; \ + } \ } while (0) -#endif // CODE_UTILS_H +#endif // CODE_UTILS_H diff --git a/examples/platforms/utils/debug_uart.c b/examples/platforms/utils/debug_uart.c index 89c465a6d..40d0ea214 100644 --- a/examples/platforms/utils/debug_uart.c +++ b/examples/platforms/utils/debug_uart.c @@ -25,15 +25,15 @@ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ -#include #include -#include #include +#include +#include #include -#include #include #include +#include /* * Implementation note: @@ -102,7 +102,6 @@ void otPlatDebugUart_putchar(int c) otPlatDebugUart_putchar_raw(c); } - /* provide WEAK stubs for platforms that do not implement all functions */ OT_TOOL_WEAK void otPlatDebugUart_putchar_raw(int c) @@ -133,7 +132,7 @@ otError otPlatDebugUart_logfile(const char *filename) /* this should not be a WEAK function */ void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat, ...) { - va_list ap; + va_list ap; uint32_t now; OT_UNUSED_VARIABLE(aLogLevel); diff --git a/examples/platforms/utils/flash.h b/examples/platforms/utils/flash.h index 0da743548..8ffc29e49 100644 --- a/examples/platforms/utils/flash.h +++ b/examples/platforms/utils/flash.h @@ -63,9 +63,9 @@ uint32_t utilsFlashGetSize(void); * Erase one flash page that include the input address. * This is a non-blocking function. It can work with utilsFlashStatusWait to check when erase is done. * - * The flash address starts from 0, and this function maps the input address to the physical address of flash for erasing. - * 0 is always mapped to the beginning of one flash page. - * The input address should never be mapped to the firmware space or any other protected flash space. + * The flash address starts from 0, and this function maps the input address to the physical address of flash for + * erasing. 0 is always mapped to the beginning of one flash page. The input address should never be mapped to the + * firmware space or any other protected flash space. * * @param[in] aAddress The start address of the flash to erase. * @@ -76,23 +76,24 @@ uint32_t utilsFlashGetSize(void); otError utilsFlashErasePage(uint32_t aAddress); /** - * Check whether flash is ready or busy. - * - * @param[in] aTimeout The interval in milliseconds waiting for the flash operation to be done and become ready again. - * zero indicates that it is a polling function, and returns current status of flash immediately. - * non-zero indicates that it is blocking there until the operation is done and become ready, or timeout expires. - * - * @retval OT_ERROR_NONE Flash is ready for any operation. - * @retval OT_ERROR_BUSY Flash is busy. - */ + * Check whether flash is ready or busy. + * + * @param[in] aTimeout The interval in milliseconds waiting for the flash operation to be done and become ready again. + * zero indicates that it is a polling function, and returns current status of flash immediately. + * non-zero indicates that it is blocking there until the operation is done and become ready, or + * timeout expires. + * + * @retval OT_ERROR_NONE Flash is ready for any operation. + * @retval OT_ERROR_BUSY Flash is busy. + */ otError utilsFlashStatusWait(uint32_t aTimeout); /** * Write flash. The write operation only clears bits, but never set bits. * - * The flash address starts from 0, and this function maps the input address to the physical address of flash for writing. - * 0 is always mapped to the beginning of one flash page. - * The input address should never be mapped to the firmware space or any other protected flash space. + * The flash address starts from 0, and this function maps the input address to the physical address of flash for + * writing. 0 is always mapped to the beginning of one flash page. The input address should never be mapped to the + * firmware space or any other protected flash space. * * @param[in] aAddress The start address of the flash to write. * @param[in] aData The pointer of the data to write. @@ -107,9 +108,9 @@ uint32_t utilsFlashWrite(uint32_t aAddress, uint8_t *aData, uint32_t aSize); /** * Read flash. * - * The flash address starts from 0, and this function maps the input address to the physical address of flash for reading. - * 0 is always mapped to the beginning of one flash page. - * The input address should never be mapped to the firmware space or any other protected flash space. + * The flash address starts from 0, and this function maps the input address to the physical address of flash for + * reading. 0 is always mapped to the beginning of one flash page. The input address should never be mapped to the + * firmware space or any other protected flash space. * * @param[in] aAddress The start address of the flash to read. * @param[Out] aData The pointer of buffer for reading. @@ -122,7 +123,7 @@ uint32_t utilsFlashWrite(uint32_t aAddress, uint8_t *aData, uint32_t aSize); uint32_t utilsFlashRead(uint32_t aAddress, uint8_t *aData, uint32_t aSize); #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // UTILS_FLASH_H +#endif // UTILS_FLASH_H diff --git a/examples/platforms/utils/settings.cpp b/examples/platforms/utils/settings.cpp index 1a1c22557..c7648abe5 100644 --- a/examples/platforms/utils/settings.cpp +++ b/examples/platforms/utils/settings.cpp @@ -32,15 +32,15 @@ * */ -#include -#include -#include "utils/wrap_string.h" #include +#include +#include +#include "utils/wrap_string.h" #include -#include "openthread/types.h" #include "openthread/platform/settings.h" +#include "openthread/types.h" #include @@ -52,19 +52,19 @@ extern "C" { enum { - kBlockAddBeginFlag = 0x1, + kBlockAddBeginFlag = 0x1, kBlockAddCompleteFlag = 0x02, - kBlockDeleteFlag = 0x04, - kBlockIndex0Flag = 0x08, + kBlockDeleteFlag = 0x04, + kBlockIndex0Flag = 0x08, }; enum { - kSettingsFlagSize = 4, + kSettingsFlagSize = 4, kSettingsBlockDataSize = 255, kSettingsInSwap = 0xbe5cc5ef, - kSettingsInUse = 0xbe5cc5ee, + kSettingsInUse = 0xbe5cc5ee, kSettingsNotUse = 0xbe5cc5ec, }; @@ -77,7 +77,6 @@ struct settingsBlock uint16_t reserved; } OT_TOOL_PACKED_END; - /** * @def SETTINGS_CONFIG_BASE_ADDRESS * @@ -85,8 +84,8 @@ struct settingsBlock * */ #ifndef SETTINGS_CONFIG_BASE_ADDRESS -#define SETTINGS_CONFIG_BASE_ADDRESS 0x39000 -#endif // SETTINGS_CONFIG_BASE_ADDRESS +#define SETTINGS_CONFIG_BASE_ADDRESS 0x39000 +#endif // SETTINGS_CONFIG_BASE_ADDRESS /** * @def SETTINGS_CONFIG_PAGE_SIZE @@ -95,8 +94,8 @@ struct settingsBlock * */ #ifndef SETTINGS_CONFIG_PAGE_SIZE -#define SETTINGS_CONFIG_PAGE_SIZE 0x800 -#endif // SETTINGS_CONFIG_PAGE_SIZE +#define SETTINGS_CONFIG_PAGE_SIZE 0x800 +#endif // SETTINGS_CONFIG_PAGE_SIZE /** * @def SETTINGS_CONFIG_PAGE_NUM @@ -105,8 +104,8 @@ struct settingsBlock * */ #ifndef SETTINGS_CONFIG_PAGE_NUM -#define SETTINGS_CONFIG_PAGE_NUM 2 -#endif // SETTINGS_CONFIG_PAGE_NUM +#define SETTINGS_CONFIG_PAGE_NUM 2 +#endif // SETTINGS_CONFIG_PAGE_NUM static uint32_t sSettingsBaseAddress; static uint32_t sSettingsUsedSize; @@ -123,10 +122,9 @@ static void setSettingsFlag(uint32_t aBase, uint32_t aFlag) static void initSettings(uint32_t aBase, uint32_t aFlag) { - uint32_t address = aBase; - uint32_t settingsSize = SETTINGS_CONFIG_PAGE_NUM > 1 ? - SETTINGS_CONFIG_PAGE_SIZE * SETTINGS_CONFIG_PAGE_NUM / 2 : - SETTINGS_CONFIG_PAGE_SIZE; + uint32_t address = aBase; + uint32_t settingsSize = SETTINGS_CONFIG_PAGE_NUM > 1 ? SETTINGS_CONFIG_PAGE_SIZE * SETTINGS_CONFIG_PAGE_NUM / 2 + : SETTINGS_CONFIG_PAGE_SIZE; while (address < (aBase + settingsSize)) { @@ -140,20 +138,18 @@ static void initSettings(uint32_t aBase, uint32_t aFlag) static uint32_t swapSettingsBlock(otInstance *aInstance) { - uint32_t oldBase = sSettingsBaseAddress; - uint32_t swapAddress = oldBase; - uint32_t usedSize = sSettingsUsedSize; - uint8_t pageNum = SETTINGS_CONFIG_PAGE_NUM; - uint32_t settingsSize = pageNum > 1 ? SETTINGS_CONFIG_PAGE_SIZE * pageNum / 2 : - SETTINGS_CONFIG_PAGE_SIZE; + uint32_t oldBase = sSettingsBaseAddress; + uint32_t swapAddress = oldBase; + uint32_t usedSize = sSettingsUsedSize; + uint8_t pageNum = SETTINGS_CONFIG_PAGE_NUM; + uint32_t settingsSize = pageNum > 1 ? SETTINGS_CONFIG_PAGE_SIZE * pageNum / 2 : SETTINGS_CONFIG_PAGE_SIZE; (void)aInstance; otEXPECT(pageNum > 1); - sSettingsBaseAddress = (swapAddress == SETTINGS_CONFIG_BASE_ADDRESS) ? - (swapAddress + settingsSize) : - SETTINGS_CONFIG_BASE_ADDRESS; + sSettingsBaseAddress = + (swapAddress == SETTINGS_CONFIG_BASE_ADDRESS) ? (swapAddress + settingsSize) : SETTINGS_CONFIG_BASE_ADDRESS; initSettings(sSettingsBaseAddress, static_cast(kSettingsInSwap)); sSettingsUsedSize = kSettingsFlagSize; @@ -165,9 +161,9 @@ static uint32_t swapSettingsBlock(otInstance *aInstance) struct addSettingsBlock { struct settingsBlock block; - uint8_t data[kSettingsBlockDataSize]; + uint8_t data[kSettingsBlockDataSize]; } OT_TOOL_PACKED_END addBlock; - bool valid = true; + bool valid = true; utilsFlashRead(swapAddress, reinterpret_cast(&addBlock.block), sizeof(struct settingsBlock)); swapAddress += sizeof(struct settingsBlock); @@ -195,8 +191,7 @@ static uint32_t swapSettingsBlock(otInstance *aInstance) if (valid) { utilsFlashRead(swapAddress, addBlock.data, getAlignLength(addBlock.block.length)); - utilsFlashWrite(sSettingsBaseAddress + sSettingsUsedSize, - reinterpret_cast(&addBlock), + utilsFlashWrite(sSettingsBaseAddress + sSettingsUsedSize, reinterpret_cast(&addBlock), getAlignLength(addBlock.block.length) + sizeof(struct settingsBlock)); sSettingsUsedSize += (sizeof(struct settingsBlock) + getAlignLength(addBlock.block.length)); } @@ -216,22 +211,24 @@ exit: return settingsSize - sSettingsUsedSize; } -static otError addSetting(otInstance *aInstance, uint16_t aKey, bool aIndex0, const uint8_t *aValue, - uint16_t aValueLength) +static otError addSetting(otInstance * aInstance, + uint16_t aKey, + bool aIndex0, + const uint8_t *aValue, + uint16_t aValueLength) { otError error = OT_ERROR_NONE; OT_TOOL_PACKED_BEGIN struct addSettingsBlock { struct settingsBlock block; - uint8_t data[kSettingsBlockDataSize]; + uint8_t data[kSettingsBlockDataSize]; } OT_TOOL_PACKED_END addBlock; - uint32_t settingsSize = SETTINGS_CONFIG_PAGE_NUM > 1 ? - SETTINGS_CONFIG_PAGE_SIZE * SETTINGS_CONFIG_PAGE_NUM / 2 : - SETTINGS_CONFIG_PAGE_SIZE; + uint32_t settingsSize = SETTINGS_CONFIG_PAGE_NUM > 1 ? SETTINGS_CONFIG_PAGE_SIZE * SETTINGS_CONFIG_PAGE_NUM / 2 + : SETTINGS_CONFIG_PAGE_SIZE; addBlock.block.flag = 0xff; - addBlock.block.key = aKey; + addBlock.block.key = aKey; if (aIndex0) { @@ -241,15 +238,14 @@ static otError addSetting(otInstance *aInstance, uint16_t aKey, bool aIndex0, co addBlock.block.flag &= (~kBlockAddBeginFlag); addBlock.block.length = aValueLength; - if ((sSettingsUsedSize + getAlignLength(addBlock.block.length) + sizeof(struct settingsBlock)) >= - settingsSize) + if ((sSettingsUsedSize + getAlignLength(addBlock.block.length) + sizeof(struct settingsBlock)) >= settingsSize) { - otEXPECT_ACTION(swapSettingsBlock(aInstance) >= (getAlignLength(addBlock.block.length) + sizeof(struct settingsBlock)), + otEXPECT_ACTION(swapSettingsBlock(aInstance) >= + (getAlignLength(addBlock.block.length) + sizeof(struct settingsBlock)), error = OT_ERROR_NO_BUFS); } - utilsFlashWrite(sSettingsBaseAddress + sSettingsUsedSize, - reinterpret_cast(&addBlock.block), + utilsFlashWrite(sSettingsBaseAddress + sSettingsUsedSize, reinterpret_cast(&addBlock.block), sizeof(struct settingsBlock)); memset(addBlock.data, 0xff, kSettingsBlockDataSize); @@ -259,8 +255,7 @@ static otError addSetting(otInstance *aInstance, uint16_t aKey, bool aIndex0, co reinterpret_cast(addBlock.data), getAlignLength(addBlock.block.length)); addBlock.block.flag &= (~kBlockAddCompleteFlag); - utilsFlashWrite(sSettingsBaseAddress + sSettingsUsedSize, - reinterpret_cast(&addBlock.block), + utilsFlashWrite(sSettingsBaseAddress + sSettingsUsedSize, reinterpret_cast(&addBlock.block), sizeof(struct settingsBlock)); sSettingsUsedSize += (sizeof(struct settingsBlock) + getAlignLength(addBlock.block.length)); @@ -271,10 +266,9 @@ exit: // settings API void otPlatSettingsInit(otInstance *aInstance) { - uint8_t index; - uint32_t settingsSize = SETTINGS_CONFIG_PAGE_NUM > 1 ? - SETTINGS_CONFIG_PAGE_SIZE * SETTINGS_CONFIG_PAGE_NUM / 2 : - SETTINGS_CONFIG_PAGE_SIZE; + uint8_t index; + uint32_t settingsSize = SETTINGS_CONFIG_PAGE_NUM > 1 ? SETTINGS_CONFIG_PAGE_SIZE * SETTINGS_CONFIG_PAGE_NUM / 2 + : SETTINGS_CONFIG_PAGE_SIZE; (void)aInstance; @@ -306,8 +300,7 @@ void otPlatSettingsInit(otInstance *aInstance) { struct settingsBlock block; - utilsFlashRead(sSettingsBaseAddress + sSettingsUsedSize, - reinterpret_cast(&block), sizeof(block)); + utilsFlashRead(sSettingsBaseAddress + sSettingsUsedSize, reinterpret_cast(&block), sizeof(block)); if (!(block.flag & kBlockAddBeginFlag)) { @@ -340,10 +333,10 @@ otError otPlatSettingsAbandonChange(otInstance *aInstance) otError otPlatSettingsGet(otInstance *aInstance, uint16_t aKey, int aIndex, uint8_t *aValue, uint16_t *aValueLength) { - otError error = OT_ERROR_NOT_FOUND; - uint32_t address = sSettingsBaseAddress + kSettingsFlagSize; + otError error = OT_ERROR_NOT_FOUND; + uint32_t address = sSettingsBaseAddress + kSettingsFlagSize; uint16_t valueLength = 0; - int index = 0; + int index = 0; (void)aInstance; @@ -379,7 +372,7 @@ otError otPlatSettingsGet(otInstance *aInstance, uint16_t aKey, int aIndex, uint } valueLength = block.length; - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; } index++; @@ -405,7 +398,7 @@ otError otPlatSettingsSet(otInstance *aInstance, uint16_t aKey, const uint8_t *a otError otPlatSettingsAdd(otInstance *aInstance, uint16_t aKey, const uint8_t *aValue, uint16_t aValueLength) { uint16_t length; - bool index0; + bool index0; index0 = (otPlatSettingsGet(aInstance, aKey, 0, NULL, &length) == OT_ERROR_NOT_FOUND ? true : false); return addSetting(aInstance, aKey, index0, aValue, aValueLength); @@ -413,9 +406,9 @@ otError otPlatSettingsAdd(otInstance *aInstance, uint16_t aKey, const uint8_t *a otError otPlatSettingsDelete(otInstance *aInstance, uint16_t aKey, int aIndex) { - otError error = OT_ERROR_NOT_FOUND; + otError error = OT_ERROR_NOT_FOUND; uint32_t address = sSettingsBaseAddress + kSettingsFlagSize; - int index = 0; + int index = 0; (void)aInstance; diff --git a/include/openthread/border_router.h b/include/openthread/border_router.h index c41f2b120..87e335377 100644 --- a/include/openthread/border_router.h +++ b/include/openthread/border_router.h @@ -60,8 +60,10 @@ extern "C" { * @param[inout] aDataLength On entry, size of the data buffer pointed to by @p aData. * On exit, number of copied bytes. */ -OTAPI otError OTCALL otBorderRouterGetNetData(otInstance *aInstance, bool aStable, uint8_t *aData, - uint8_t *aDataLength); +OTAPI otError OTCALL otBorderRouterGetNetData(otInstance *aInstance, + bool aStable, + uint8_t * aData, + uint8_t * aDataLength); /** * Add a border router configuration to the local network data. @@ -104,8 +106,9 @@ OTAPI otError OTCALL otBorderRouterRemoveOnMeshPrefix(otInstance *aInstance, con * @retval OT_ERROR_NOT_FOUND No subsequent On Mesh prefix exists in the Thread Network Data. * */ -OTAPI otError OTCALL otBorderRouterGetNextOnMeshPrefix(otInstance *aInstance, otNetworkDataIterator *aIterator, - otBorderRouterConfig *aConfig); +OTAPI otError OTCALL otBorderRouterGetNextOnMeshPrefix(otInstance * aInstance, + otNetworkDataIterator *aIterator, + otBorderRouterConfig * aConfig); /** * Add an external route configuration to the local network data. @@ -148,7 +151,8 @@ OTAPI otError OTCALL otBorderRouterRemoveRoute(otInstance *aInstance, const otIp * @retval OT_ERROR_NOT_FOUND No subsequent external route entry exists in the Thread Network Data. * */ -otError otBorderRouterGetNextRoute(otInstance *aInstance, otNetworkDataIterator *aIterator, +otError otBorderRouterGetNextRoute(otInstance * aInstance, + otNetworkDataIterator *aIterator, otExternalRouteConfig *aConfig); /** @@ -171,7 +175,7 @@ OTAPI otError OTCALL otBorderRouterRegister(otInstance *aInstance); */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_BORDER_ROUTER_H_ +#endif // OPENTHREAD_BORDER_ROUTER_H_ diff --git a/include/openthread/channel_manager.h b/include/openthread/channel_manager.h index 2cef557b4..247fd4e84 100644 --- a/include/openthread/channel_manager.h +++ b/include/openthread/channel_manager.h @@ -35,7 +35,6 @@ #ifndef OPENTHREAD_CHANNEL_MANAGER_H_ #define OPENTHREAD_CHANNEL_MANAGER_H_ - #include "openthread/types.h" #ifdef __cplusplus @@ -122,7 +121,7 @@ uint32_t otChannelManagerGetSupportedChannels(otInstance *aInstance); * @param[in] aChannelMask A channel mask. * */ -void otChannelManagerSetSupportedChannels(otInstance *aInstance, uint32_t aChannelMask); +void otChannelManagerSetSupportedChannels(otInstance *aInstance, uint32_t aChannelMask); /** * @} @@ -130,7 +129,7 @@ void otChannelManagerSetSupportedChannels(otInstance *aInstance, uint32_t aChan */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_CHANNEL_MANAGER_H_ +#endif // OPENTHREAD_CHANNEL_MANAGER_H_ diff --git a/include/openthread/channel_monitor.h b/include/openthread/channel_monitor.h index 312af533c..84263cc33 100644 --- a/include/openthread/channel_monitor.h +++ b/include/openthread/channel_monitor.h @@ -35,7 +35,6 @@ #ifndef OPENTHREAD_CHANNEL_MONITOR_H_ #define OPENTHREAD_CHANNEL_MONITOR_H_ - #include "openthread/types.h" #ifdef __cplusplus @@ -133,7 +132,7 @@ uint16_t otChannelMonitorGetChannelQuality(otInstance *aInstance, uint8_t aChann */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_CHANNEL_MONITOR_H_ +#endif // OPENTHREAD_CHANNEL_MONITOR_H_ diff --git a/include/openthread/child_supervision.h b/include/openthread/child_supervision.h index 9163c9675..fb6a5d294 100644 --- a/include/openthread/child_supervision.h +++ b/include/openthread/child_supervision.h @@ -35,7 +35,6 @@ #ifndef OPENTHREAD_CHILD_SUPERVISION_H_ #define OPENTHREAD_CHILD_SUPERVISION_H_ - #include "openthread/types.h" #ifdef __cplusplus @@ -106,7 +105,7 @@ void otChildSupervisionSetCheckTimeout(otInstance *aInstance, uint16_t aTimeout) */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_CHILD_SUPERVISION_H_ +#endif // OPENTHREAD_CHILD_SUPERVISION_H_ diff --git a/include/openthread/cli.h b/include/openthread/cli.h index e2b6f8b36..7edece9be 100644 --- a/include/openthread/cli.h +++ b/include/openthread/cli.h @@ -35,8 +35,8 @@ #ifndef CLI_H_ #define CLI_H_ -#include #include +#include #include #ifdef __cplusplus @@ -49,8 +49,8 @@ extern "C" { */ typedef struct otCliCommand { - const char *mName; ///< A pointer to the command string. - void (*mCommand)(int argc, char *argv[]); ///< A function pointer to process the command. + const char *mName; ///< A pointer to the command string. + void (*mCommand)(int argc, char *argv[]); ///< A function pointer to process the command. } otCliCommand; /** @@ -73,8 +73,7 @@ typedef struct otCliCommand * @returns Number of bytes processed by the callback. * */ -typedef int (*otCliConsoleOutputCallback)(const char *aBuf, - uint16_t aBufLength, void *aContext); +typedef int (*otCliConsoleOutputCallback)(const char *aBuf, uint16_t aBufLength, void *aContext); /** * Initialize the CLI CONSOLE module. @@ -150,7 +149,7 @@ void otCliPlatLogv(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFo */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif #endif diff --git a/include/openthread/coap.h b/include/openthread/coap.h index ab9f44e55..040460b8c 100644 --- a/include/openthread/coap.h +++ b/include/openthread/coap.h @@ -57,44 +57,42 @@ extern "C" { * */ -#define OT_DEFAULT_COAP_PORT 5683 ///< Default CoAP port, as specified in RFC 7252 +#define OT_DEFAULT_COAP_PORT 5683 ///< Default CoAP port, as specified in RFC 7252 /** * CoAP Type values. * */ -typedef enum otCoapType -{ - OT_COAP_TYPE_CONFIRMABLE = 0x00, ///< Confirmable - OT_COAP_TYPE_NON_CONFIRMABLE = 0x10, ///< Non-confirmable - OT_COAP_TYPE_ACKNOWLEDGMENT = 0x20, ///< Acknowledgment - OT_COAP_TYPE_RESET = 0x30, ///< Reset +typedef enum otCoapType { + OT_COAP_TYPE_CONFIRMABLE = 0x00, ///< Confirmable + OT_COAP_TYPE_NON_CONFIRMABLE = 0x10, ///< Non-confirmable + OT_COAP_TYPE_ACKNOWLEDGMENT = 0x20, ///< Acknowledgment + OT_COAP_TYPE_RESET = 0x30, ///< Reset } otCoapType; /** * Helper macro to define CoAP Code values. * */ -#define OT_COAP_CODE(c, d) ((((c) & 0x7) << 5) | ((d) & 0x1f)) +#define OT_COAP_CODE(c, d) ((((c)&0x7) << 5) | ((d)&0x1f)) /** * CoAP Code values. * */ -typedef enum otCoapCode -{ - OT_COAP_CODE_EMPTY = OT_COAP_CODE(0, 0), ///< Empty message code - OT_COAP_CODE_GET = OT_COAP_CODE(0, 1), ///< Get - OT_COAP_CODE_POST = OT_COAP_CODE(0, 2), ///< Post - OT_COAP_CODE_PUT = OT_COAP_CODE(0, 3), ///< Put - OT_COAP_CODE_DELETE = OT_COAP_CODE(0, 4), ///< Delete +typedef enum otCoapCode { + OT_COAP_CODE_EMPTY = OT_COAP_CODE(0, 0), ///< Empty message code + OT_COAP_CODE_GET = OT_COAP_CODE(0, 1), ///< Get + OT_COAP_CODE_POST = OT_COAP_CODE(0, 2), ///< Post + OT_COAP_CODE_PUT = OT_COAP_CODE(0, 3), ///< Put + OT_COAP_CODE_DELETE = OT_COAP_CODE(0, 4), ///< Delete - OT_COAP_CODE_RESPONSE_MIN = OT_COAP_CODE(2, 0), ///< 2.00 - OT_COAP_CODE_CREATED = OT_COAP_CODE(2, 1), ///< Created - OT_COAP_CODE_DELETED = OT_COAP_CODE(2, 2), ///< Deleted - OT_COAP_CODE_VALID = OT_COAP_CODE(2, 3), ///< Valid - OT_COAP_CODE_CHANGED = OT_COAP_CODE(2, 4), ///< Changed - OT_COAP_CODE_CONTENT = OT_COAP_CODE(2, 5), ///< Content + OT_COAP_CODE_RESPONSE_MIN = OT_COAP_CODE(2, 0), ///< 2.00 + OT_COAP_CODE_CREATED = OT_COAP_CODE(2, 1), ///< Created + OT_COAP_CODE_DELETED = OT_COAP_CODE(2, 2), ///< Deleted + OT_COAP_CODE_VALID = OT_COAP_CODE(2, 3), ///< Valid + OT_COAP_CODE_CHANGED = OT_COAP_CODE(2, 4), ///< Changed + OT_COAP_CODE_CONTENT = OT_COAP_CODE(2, 5), ///< Content OT_COAP_CODE_BAD_REQUEST = OT_COAP_CODE(4, 0), ///< Bad Request OT_COAP_CODE_UNAUTHORIZED = OT_COAP_CODE(4, 1), ///< Unauthorized @@ -107,35 +105,34 @@ typedef enum otCoapCode OT_COAP_CODE_REQUEST_TOO_LARGE = OT_COAP_CODE(4, 13), ///< Request Entity Too Large OT_COAP_CODE_UNSUPPORTED_FORMAT = OT_COAP_CODE(4, 15), ///< Unsupported Content-Format - OT_COAP_CODE_INTERNAL_ERROR = OT_COAP_CODE(5, 0), ///< Internal Server Error - OT_COAP_CODE_NOT_IMPLEMENTED = OT_COAP_CODE(5, 1), ///< Not Implemented - OT_COAP_CODE_BAD_GATEWAY = OT_COAP_CODE(5, 2), ///< Bad Gateway - OT_COAP_CODE_SERVICE_UNAVAILABLE = OT_COAP_CODE(5, 3), ///< Service Unavailable - OT_COAP_CODE_GATEWAY_TIMEOUT = OT_COAP_CODE(5, 4), ///< Gateway Timeout - OT_COAP_CODE_PROXY_NOT_SUPPORTED = OT_COAP_CODE(5, 5), ///< Proxying Not Supported + OT_COAP_CODE_INTERNAL_ERROR = OT_COAP_CODE(5, 0), ///< Internal Server Error + OT_COAP_CODE_NOT_IMPLEMENTED = OT_COAP_CODE(5, 1), ///< Not Implemented + OT_COAP_CODE_BAD_GATEWAY = OT_COAP_CODE(5, 2), ///< Bad Gateway + OT_COAP_CODE_SERVICE_UNAVAILABLE = OT_COAP_CODE(5, 3), ///< Service Unavailable + OT_COAP_CODE_GATEWAY_TIMEOUT = OT_COAP_CODE(5, 4), ///< Gateway Timeout + OT_COAP_CODE_PROXY_NOT_SUPPORTED = OT_COAP_CODE(5, 5), ///< Proxying Not Supported } otCoapCode; /** * CoAP Option Numbers */ -typedef enum otCoapOptionType -{ - OT_COAP_OPTION_IF_MATCH = 1, ///< If-Match - OT_COAP_OPTION_URI_HOST = 3, ///< Uri-Host - OT_COAP_OPTION_E_TAG = 4, ///< ETag - OT_COAP_OPTION_IF_NONE_MATCH = 5, ///< If-None-Match - OT_COAP_OPTION_OBSERVE = 6, ///< Observe - OT_COAP_OPTION_URI_PORT = 7, ///< Uri-Port - OT_COAP_OPTION_LOCATION_PATH = 8, ///< Location-Path - OT_COAP_OPTION_URI_PATH = 11, ///< Uri-Path - OT_COAP_OPTION_CONTENT_FORMAT = 12, ///< Content-Format - OT_COAP_OPTION_MAX_AGE = 14, ///< Max-Age - OT_COAP_OPTION_URI_QUERY = 15, ///< Uri-Query - OT_COAP_OPTION_ACCEPT = 17, ///< Accept - OT_COAP_OPTION_LOCATION_QUERY = 20, ///< Location-Query - OT_COAP_OPTION_PROXY_URI = 35, ///< Proxy-Uri - OT_COAP_OPTION_PROXY_SCHEME = 39, ///< Proxy-Scheme - OT_COAP_OPTION_SIZE1 = 60, ///< Size1 +typedef enum otCoapOptionType { + OT_COAP_OPTION_IF_MATCH = 1, ///< If-Match + OT_COAP_OPTION_URI_HOST = 3, ///< Uri-Host + OT_COAP_OPTION_E_TAG = 4, ///< ETag + OT_COAP_OPTION_IF_NONE_MATCH = 5, ///< If-None-Match + OT_COAP_OPTION_OBSERVE = 6, ///< Observe + OT_COAP_OPTION_URI_PORT = 7, ///< Uri-Port + OT_COAP_OPTION_LOCATION_PATH = 8, ///< Location-Path + OT_COAP_OPTION_URI_PATH = 11, ///< Uri-Path + OT_COAP_OPTION_CONTENT_FORMAT = 12, ///< Content-Format + OT_COAP_OPTION_MAX_AGE = 14, ///< Max-Age + OT_COAP_OPTION_URI_QUERY = 15, ///< Uri-Query + OT_COAP_OPTION_ACCEPT = 17, ///< Accept + OT_COAP_OPTION_LOCATION_QUERY = 20, ///< Location-Query + OT_COAP_OPTION_PROXY_URI = 35, ///< Proxy-Uri + OT_COAP_OPTION_PROXY_SCHEME = 39, ///< Proxy-Scheme + OT_COAP_OPTION_SIZE1 = 60, ///< Size1 } otCoapOptionType; /** @@ -144,26 +141,25 @@ typedef enum otCoapOptionType */ typedef struct otCoapOption { - uint16_t mNumber; ///< Option Number - uint16_t mLength; ///< Option Length - const uint8_t *mValue; ///< A pointer to the Option Value + uint16_t mNumber; ///< Option Number + uint16_t mLength; ///< Option Length + const uint8_t *mValue; ///< A pointer to the Option Value } otCoapOption; /** * CoAP Content Format codes. The full list is documented at * https://tools.ietf.org/html/rfc7252#page-92 */ -typedef enum otCoapOptionContentFormat -{ - OT_COAP_OPTION_CONTENT_FORMAT_TEXT_PLAIN = 0, ///< text/plain - OT_COAP_OPTION_CONTENT_FORMAT_LINK_FORMAT = 40, ///< application/link-format - OT_COAP_OPTION_CONTENT_FORMAT_XML = 41, ///< application/xml - OT_COAP_OPTION_CONTENT_FORMAT_OCTET_STREAM = 42, ///< application/octet-stream - OT_COAP_OPTION_CONTENT_FORMAT_EXI = 47, ///< application/exi - OT_COAP_OPTION_CONTENT_FORMAT_JSON = 50, ///< application/json +typedef enum otCoapOptionContentFormat { + OT_COAP_OPTION_CONTENT_FORMAT_TEXT_PLAIN = 0, ///< text/plain + OT_COAP_OPTION_CONTENT_FORMAT_LINK_FORMAT = 40, ///< application/link-format + OT_COAP_OPTION_CONTENT_FORMAT_XML = 41, ///< application/xml + OT_COAP_OPTION_CONTENT_FORMAT_OCTET_STREAM = 42, ///< application/octet-stream + OT_COAP_OPTION_CONTENT_FORMAT_EXI = 47, ///< application/exi + OT_COAP_OPTION_CONTENT_FORMAT_JSON = 50, ///< application/json } otCoapOptionContentFormat; -#define OT_COAP_HEADER_MAX_LENGTH 128 ///< Max CoAP header length (bytes) +#define OT_COAP_HEADER_MAX_LENGTH 128 ///< Max CoAP header length (bytes) /** * This structure represents a CoAP header. @@ -175,17 +171,17 @@ typedef struct otCoapHeader { struct { - uint8_t mVersionTypeToken; ///< The CoAP Version, Type, and Token Length - uint8_t mCode; ///< The CoAP Code - uint16_t mMessageId; ///< The CoAP Message ID - } mFields; ///< Structure representing a CoAP base header - uint8_t mBytes[OT_COAP_HEADER_MAX_LENGTH]; ///< The raw byte encoding for the CoAP header - } mHeader; ///< The CoAP header encoding - uint8_t mHeaderLength; ///< The CoAP header length (bytes) - uint16_t mOptionLast; ///< The last CoAP Option Number value - uint16_t mFirstOptionOffset; ///< The byte offset for the first CoAP Option - uint16_t mNextOptionOffset; ///< The byte offset for the next CoAP Option - otCoapOption mOption; ///< A structure representing the current CoAP Option. + uint8_t mVersionTypeToken; ///< The CoAP Version, Type, and Token Length + uint8_t mCode; ///< The CoAP Code + uint16_t mMessageId; ///< The CoAP Message ID + } mFields; ///< Structure representing a CoAP base header + uint8_t mBytes[OT_COAP_HEADER_MAX_LENGTH]; ///< The raw byte encoding for the CoAP header + } mHeader; ///< The CoAP header encoding + uint8_t mHeaderLength; ///< The CoAP header length (bytes) + uint16_t mOptionLast; ///< The last CoAP Option Number value + uint16_t mFirstOptionOffset; ///< The byte offset for the first CoAP Option + uint16_t mNextOptionOffset; ///< The byte offset for the next CoAP Option + otCoapOption mOption; ///< A structure representing the current CoAP Option. } otCoapHeader; /** @@ -202,8 +198,11 @@ typedef struct otCoapHeader * @retval OT_ERROR_RESPONSE_TIMEOUT No response or acknowledgment received during timeout period. * */ -typedef void (*otCoapResponseHandler)(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError aResult); +typedef void (*otCoapResponseHandler)(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aResult); /** * This function pointer is called when a CoAP request with a given Uri-Path is received. @@ -214,7 +213,9 @@ typedef void (*otCoapResponseHandler)(void *aContext, otCoapHeader *aHeader, otM * @param[in] aMessageInfo A pointer to the message info for @p aMessage. * */ -typedef void (*otCoapRequestHandler)(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +typedef void (*otCoapRequestHandler)(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); /** @@ -223,10 +224,10 @@ typedef void (*otCoapRequestHandler)(void *aContext, otCoapHeader *aHeader, otMe */ typedef struct otCoapResource { - const char *mUriPath; ///< The URI Path string - otCoapRequestHandler mHandler; ///< The callback for handling a received request - void *mContext; ///< Application-specific context - struct otCoapResource *mNext; ///< The next CoAP resource in the list + const char * mUriPath; ///< The URI Path string + otCoapRequestHandler mHandler; ///< The callback for handling a received request + void * mContext; ///< Application-specific context + struct otCoapResource *mNext; ///< The next CoAP resource in the list } otCoapResource; /** @@ -396,13 +397,13 @@ otCoapType otCoapHeaderGetType(const otCoapHeader *aHeader); otCoapCode otCoapHeaderGetCode(const otCoapHeader *aHeader); /** -* This function returns the Message ID value. -* -* @param[in] aHeader A pointer to the CoAP header. -* -* @returns The Message ID value. -* -*/ + * This function returns the Message ID value. + * + * @param[in] aHeader A pointer to the CoAP header. + * + * @returns The Message ID value. + * + */ uint16_t otCoapHeaderGetMessageId(const otCoapHeader *aHeader); /** @@ -472,8 +473,11 @@ otMessage *otCoapNewMessage(otInstance *aInstance, const otCoapHeader *aHeader); * @retval OT_ERROR_NO_BUFS Failed to allocate retransmission data. * */ -otError otCoapSendRequest(otInstance *aInstance, otMessage *aMessage, const otMessageInfo *aMessageInfo, - otCoapResponseHandler aHandler, void *aContext); +otError otCoapSendRequest(otInstance * aInstance, + otMessage * aMessage, + const otMessageInfo * aMessageInfo, + otCoapResponseHandler aHandler, + void * aContext); /** * This function starts the CoAP server. @@ -545,7 +549,7 @@ otError otCoapSendResponse(otInstance *aInstance, otMessage *aMessage, const otM */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif #endif /* OPENTHREAD_COAP_H_ */ diff --git a/include/openthread/commissioner.h b/include/openthread/commissioner.h index 3df7e423f..1a92c3073 100644 --- a/include/openthread/commissioner.h +++ b/include/openthread/commissioner.h @@ -56,8 +56,7 @@ extern "C" { * This enumeration defines the Commissioner State. * */ -typedef enum otCommissionerState -{ +typedef enum otCommissionerState { OT_COMMISSIONER_STATE_DISABLED = 0, ///< Commissioner role is disabled. OT_COMMISSIONER_STATE_PETITION = 1, ///< Currently petitioning to become a Commissioner. OT_COMMISSIONER_STATE_ACTIVE = 2, ///< Commissioner role is active. @@ -99,8 +98,10 @@ OTAPI otError OTCALL otCommissionerStop(otInstance *aInstance); * @note Only use this after successfully starting the Commissioner role with otCommissionerStart(). * */ -OTAPI otError OTCALL otCommissionerAddJoiner(otInstance *aInstance, const otExtAddress *aEui64, - const char *aPSKd, uint32_t aTimeout); +OTAPI otError OTCALL otCommissionerAddJoiner(otInstance * aInstance, + const otExtAddress *aEui64, + const char * aPSKd, + uint32_t aTimeout); /** * This function removes a Joiner entry. @@ -146,8 +147,10 @@ OTAPI otError OTCALL otCommissionerSetProvisioningUrl(otInstance *aInstance, con * @note Only use this after successfully starting the Commissioner role with otCommissionerStart(). * */ -OTAPI otError OTCALL otCommissionerAnnounceBegin(otInstance *aInstance, uint32_t aChannelMask, uint8_t aCount, - uint16_t aPeriod, +OTAPI otError OTCALL otCommissionerAnnounceBegin(otInstance * aInstance, + uint32_t aChannelMask, + uint8_t aCount, + uint16_t aPeriod, const otIp6Address *aAddress); /** @@ -159,8 +162,10 @@ OTAPI otError OTCALL otCommissionerAnnounceBegin(otInstance *aInstance, uint32_t * @param[in] aContext A pointer to application-specific context. * */ -typedef void (OTCALL *otCommissionerEnergyReportCallback)(uint32_t aChannelMask, const uint8_t *aEnergyList, - uint8_t aEnergyListLength, void *aContext); +typedef void(OTCALL *otCommissionerEnergyReportCallback)(uint32_t aChannelMask, + const uint8_t *aEnergyList, + uint8_t aEnergyListLength, + void * aContext); /** * This function sends an Energy Scan Query message. @@ -181,9 +186,14 @@ typedef void (OTCALL *otCommissionerEnergyReportCallback)(uint32_t aChannelMask, * @note Only use this after successfully starting the Commissioner role with otCommissionerStart(). * */ -OTAPI otError OTCALL otCommissionerEnergyScan(otInstance *aInstance, uint32_t aChannelMask, uint8_t aCount, - uint16_t aPeriod, uint16_t aScanDuration, const otIp6Address *aAddress, - otCommissionerEnergyReportCallback aCallback, void *aContext); +OTAPI otError OTCALL otCommissionerEnergyScan(otInstance * aInstance, + uint32_t aChannelMask, + uint8_t aCount, + uint16_t aPeriod, + uint16_t aScanDuration, + const otIp6Address * aAddress, + otCommissionerEnergyReportCallback aCallback, + void * aContext); /** * This function pointer is called when the Commissioner receives a PAN ID Conflict message. @@ -193,7 +203,7 @@ OTAPI otError OTCALL otCommissionerEnergyScan(otInstance *aInstance, uint32_t aC * @param[in] aContext A pointer to application-specific context. * */ -typedef void (OTCALL *otCommissionerPanIdConflictCallback)(uint16_t aPanId, uint32_t aChannelMask, void *aContext); +typedef void(OTCALL *otCommissionerPanIdConflictCallback)(uint16_t aPanId, uint32_t aChannelMask, void *aContext); /** * This function sends a PAN ID Query message. @@ -212,9 +222,12 @@ typedef void (OTCALL *otCommissionerPanIdConflictCallback)(uint16_t aPanId, uint * @note Only use this after successfully starting the Commissioner role with otCommissionerStart(). * */ -OTAPI otError OTCALL otCommissionerPanIdQuery(otInstance *aInstance, uint16_t aPanId, uint32_t aChannelMask, - const otIp6Address *aAddress, - otCommissionerPanIdConflictCallback aCallback, void *aContext); +OTAPI otError OTCALL otCommissionerPanIdQuery(otInstance * aInstance, + uint16_t aPanId, + uint32_t aChannelMask, + const otIp6Address * aAddress, + otCommissionerPanIdConflictCallback aCallback, + void * aContext); /** * This function sends MGMT_COMMISSIONER_GET. @@ -241,8 +254,10 @@ OTAPI otError OTCALL otCommissionerSendMgmtGet(otInstance *aInstance, const uint * @retval OT_ERROR_NO_BUFS Insufficient buffer space to send. * */ -OTAPI otError OTCALL otCommissionerSendMgmtSet(otInstance *aInstance, const otCommissioningDataset *aDataset, - const uint8_t *aTlvs, uint8_t aLength); +OTAPI otError OTCALL otCommissionerSendMgmtSet(otInstance * aInstance, + const otCommissioningDataset *aDataset, + const uint8_t * aTlvs, + uint8_t aLength); /** * This function returns the Commissioner Session ID. @@ -281,9 +296,11 @@ OTAPI otCommissionerState OTCALL otCommissionerGetState(otInstance *aInstance); * @retval OT_ERROR_INVALID_ARGS If any of the input arguments is invalid. * */ -OTAPI otError OTCALL otCommissionerGeneratePSKc(otInstance *aInstance, const char *aPassPhrase, - const char *aNetworkName, const uint8_t *aExtPanId, - uint8_t *aPSKc); +OTAPI otError OTCALL otCommissionerGeneratePSKc(otInstance * aInstance, + const char * aPassPhrase, + const char * aNetworkName, + const uint8_t *aExtPanId, + uint8_t * aPSKc); /** * @} @@ -291,7 +308,7 @@ OTAPI otError OTCALL otCommissionerGeneratePSKc(otInstance *aInstance, const cha */ #ifdef __cplusplus -} // end of extern "C" +} // end of extern "C" #endif -#endif // OPENTHREAD_COMMISSIONER_H_ +#endif // OPENTHREAD_COMMISSIONER_H_ diff --git a/include/openthread/config.h b/include/openthread/config.h index 1267e6407..2a5fd26b6 100644 --- a/include/openthread/config.h +++ b/include/openthread/config.h @@ -47,7 +47,4 @@ #include OPENTHREAD_CONFIG_FILE -#endif //OPENTHREAD_CONFIG_H_ - - - +#endif // OPENTHREAD_CONFIG_H_ diff --git a/include/openthread/crypto.h b/include/openthread/crypto.h index d80a45af8..1690a0e02 100644 --- a/include/openthread/crypto.h +++ b/include/openthread/crypto.h @@ -52,7 +52,7 @@ extern "C" { * */ -#define OT_CRYPTO_HMAC_SHA_HASH_SIZE 32 ///< Length of HMAC SHA (in bytes). +#define OT_CRYPTO_HMAC_SHA_HASH_SIZE 32 ///< Length of HMAC SHA (in bytes). /** * This function performs HMAC computation. @@ -64,10 +64,11 @@ extern "C" { * @param[out] aHash A pointer to the output hash buffer. * */ -void otCryptoHmacSha256( - const uint8_t *aKey, uint16_t aKeyLength, - const uint8_t *aBuf, uint16_t aBufLength, - uint8_t *aHash); +void otCryptoHmacSha256(const uint8_t *aKey, + uint16_t aKeyLength, + const uint8_t *aBuf, + uint16_t aBufLength, + uint8_t * aHash); /** * This method performs AES CCM computation. @@ -89,13 +90,18 @@ void otCryptoHmacSha256( * @param[out] aTag A pointer to the tag. * */ -void otCryptoAesCcm( - const uint8_t *aKey, uint16_t aKeyLength, - uint8_t aTagLength, - const void *aNonce, uint8_t aNonceLength, - const void *aHeader, uint32_t aHeaderLength, - void *aPlainText, void *aCipherText, uint32_t aLength, bool aEncrypt, - void *aTag); +void otCryptoAesCcm(const uint8_t *aKey, + uint16_t aKeyLength, + uint8_t aTagLength, + const void * aNonce, + uint8_t aNonceLength, + const void * aHeader, + uint32_t aHeaderLength, + void * aPlainText, + void * aCipherText, + uint32_t aLength, + bool aEncrypt, + void * aTag); /** * @} @@ -103,7 +109,7 @@ void otCryptoAesCcm( */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_CRYPTO_H_ +#endif // OPENTHREAD_CRYPTO_H_ diff --git a/include/openthread/dataset.h b/include/openthread/dataset.h index 12cb08986..31c23d4ec 100644 --- a/include/openthread/dataset.h +++ b/include/openthread/dataset.h @@ -88,7 +88,7 @@ OTAPI otError OTCALL otDatasetGetPending(otInstance *aInstance, otOperationalDat */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_DATASET_H_ +#endif // OPENTHREAD_DATASET_H_ diff --git a/include/openthread/dataset_ftd.h b/include/openthread/dataset_ftd.h index 6c9a45d6d..d5b35c432 100644 --- a/include/openthread/dataset_ftd.h +++ b/include/openthread/dataset_ftd.h @@ -86,7 +86,9 @@ OTAPI otError OTCALL otDatasetSetPending(otInstance *aInstance, const otOperatio * @retval OT_ERROR_NO_BUFS Insufficient buffer space to send. * */ -OTAPI otError OTCALL otDatasetSendMgmtActiveGet(otInstance *aInstance, const uint8_t *aTlvTypes, uint8_t aLength, +OTAPI otError OTCALL otDatasetSendMgmtActiveGet(otInstance * aInstance, + const uint8_t * aTlvTypes, + uint8_t aLength, const otIp6Address *aAddress); /** @@ -101,8 +103,10 @@ OTAPI otError OTCALL otDatasetSendMgmtActiveGet(otInstance *aInstance, const uin * @retval OT_ERROR_NO_BUFS Insufficient buffer space to send. * */ -OTAPI otError OTCALL otDatasetSendMgmtActiveSet(otInstance *aInstance, const otOperationalDataset *aDataset, - const uint8_t *aTlvs, uint8_t aLength); +OTAPI otError OTCALL otDatasetSendMgmtActiveSet(otInstance * aInstance, + const otOperationalDataset *aDataset, + const uint8_t * aTlvs, + uint8_t aLength); /** * This function sends MGMT_PENDING_GET. @@ -116,7 +120,9 @@ OTAPI otError OTCALL otDatasetSendMgmtActiveSet(otInstance *aInstance, const otO * @retval OT_ERROR_NO_BUFS Insufficient buffer space to send. * */ -OTAPI otError OTCALL otDatasetSendMgmtPendingGet(otInstance *aInstance, const uint8_t *aTlvTypes, uint8_t aLength, +OTAPI otError OTCALL otDatasetSendMgmtPendingGet(otInstance * aInstance, + const uint8_t * aTlvTypes, + uint8_t aLength, const otIp6Address *aAddress); /** @@ -131,8 +137,10 @@ OTAPI otError OTCALL otDatasetSendMgmtPendingGet(otInstance *aInstance, const ui * @retval OT_ERROR_NO_BUFS Insufficient buffer space to send. * */ -OTAPI otError OTCALL otDatasetSendMgmtPendingSet(otInstance *aInstance, const otOperationalDataset *aDataset, - const uint8_t *aTlvs, uint8_t aLength); +OTAPI otError OTCALL otDatasetSendMgmtPendingSet(otInstance * aInstance, + const otOperationalDataset *aDataset, + const uint8_t * aTlvs, + uint8_t aLength); /** * Get minimal delay timer. @@ -162,7 +170,7 @@ OTAPI otError OTCALL otDatasetSetDelayTimerMinimal(otInstance *aInstance, uint32 */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_DATASET_FTD_H_ +#endif // OPENTHREAD_DATASET_FTD_H_ diff --git a/include/openthread/dhcp6_client.h b/include/openthread/dhcp6_client.h index ebdfa8f24..78c9a55f4 100644 --- a/include/openthread/dhcp6_client.h +++ b/include/openthread/dhcp6_client.h @@ -54,9 +54,9 @@ extern "C" { */ typedef struct otDhcpAddress { - otNetifAddress mAddress; ///< The network interface address. - uint32_t mPreferredLifetime; ///< The preferred lifetime. - uint32_t mValidLifetime; ///< The valid lifetime. + otNetifAddress mAddress; ///< The network interface address. + uint32_t mPreferredLifetime; ///< The preferred lifetime. + uint32_t mValidLifetime; ///< The valid lifetime. } otDhcpAddress; /** @@ -76,7 +76,7 @@ void otDhcp6ClientUpdate(otInstance *aInstance, otDhcpAddress *aAddresses, uint3 */ #ifdef __cplusplus -} // end of extern "C" +} // end of extern "C" #endif -#endif // OPENTHREAD_DHCP6_CLIENT_H_ +#endif // OPENTHREAD_DHCP6_CLIENT_H_ diff --git a/include/openthread/dhcp6_server.h b/include/openthread/dhcp6_server.h index 429fefcd2..3cba3683d 100644 --- a/include/openthread/dhcp6_server.h +++ b/include/openthread/dhcp6_server.h @@ -62,7 +62,7 @@ void otDhcp6ServerUpdate(otInstance *aInstance); */ #ifdef __cplusplus -} // end of extern "C" +} // end of extern "C" #endif -#endif // OPENTHREAD_DHCP6_SERVER_H_ +#endif // OPENTHREAD_DHCP6_SERVER_H_ diff --git a/include/openthread/diag.h b/include/openthread/diag.h index 9e67e57f6..e43040376 100644 --- a/include/openthread/diag.h +++ b/include/openthread/diag.h @@ -94,7 +94,7 @@ bool otDiagIsEnabled(void); */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_DIAG_H_ +#endif // OPENTHREAD_DIAG_H_ diff --git a/include/openthread/dns.h b/include/openthread/dns.h index 5abcff74c..e3f78bbe0 100644 --- a/include/openthread/dns.h +++ b/include/openthread/dns.h @@ -52,10 +52,10 @@ extern "C" { * */ -#define OT_DNS_MAX_HOSTNAME_LENGTH 62 ///< Maximum allowed hostname length (maximum label size - 1 for compression). +#define OT_DNS_MAX_HOSTNAME_LENGTH 62 ///< Maximum allowed hostname length (maximum label size - 1 for compression). -#define OT_DNS_DEFAULT_DNS_SERVER_IP "2001:4860:4860::8888" ///< Defines default DNS Server address - Google DNS. -#define OT_DNS_DEFAULT_DNS_SERVER_PORT 53 ///< Defines default DNS Server port. +#define OT_DNS_DEFAULT_DNS_SERVER_IP "2001:4860:4860::8888" ///< Defines default DNS Server address - Google DNS. +#define OT_DNS_DEFAULT_DNS_SERVER_PORT 53 ///< Defines default DNS Server port. /** * This structure implements DNS Query parameters. @@ -63,9 +63,9 @@ extern "C" { */ typedef struct otDnsQuery { - const char *mHostname; ///< Identifies hostname to be found. It shall not change during resolving. - const otMessageInfo *mMessageInfo; ///< A reference to the message info related with DNS Server. - bool mNoRecursion; ///< If cleared, it directs name server to pursue the query recursively. + const char * mHostname; ///< Identifies hostname to be found. It shall not change during resolving. + const otMessageInfo *mMessageInfo; ///< A reference to the message info related with DNS Server. + bool mNoRecursion; ///< If cleared, it directs name server to pursue the query recursively. } otDnsQuery; /** @@ -85,8 +85,11 @@ typedef struct otDnsQuery * @retval OT_ERROR_FAILED A response was received but status code is different than success. * */ -typedef void (*otDnsResponseHandler)(void *aContext, const char *aHostname, otIp6Address *aAddress, - uint32_t aTtl, otError aResult); +typedef void (*otDnsResponseHandler)(void * aContext, + const char * aHostname, + otIp6Address *aAddress, + uint32_t aTtl, + otError aResult); /** * This function sends a DNS query for AAAA (IPv6) record. @@ -99,8 +102,10 @@ typedef void (*otDnsResponseHandler)(void *aContext, const char *aHostname, otIp * @param[in] aContext A pointer to arbitrary context information. * */ -otError otDnsClientQuery(otInstance *aInstance, const otDnsQuery *aQuery, otDnsResponseHandler aHandler, - void *aContext); +otError otDnsClientQuery(otInstance * aInstance, + const otDnsQuery * aQuery, + otDnsResponseHandler aHandler, + void * aContext); /** * @} @@ -108,7 +113,7 @@ otError otDnsClientQuery(otInstance *aInstance, const otDnsQuery *aQuery, otDnsR */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_DNS_H_ +#endif // OPENTHREAD_DNS_H_ diff --git a/include/openthread/icmp6.h b/include/openthread/icmp6.h index 2d26d4ed0..fefd3a168 100644 --- a/include/openthread/icmp6.h +++ b/include/openthread/icmp6.h @@ -56,23 +56,21 @@ extern "C" { * ICMPv6 Message Types * */ -typedef enum otIcmp6Type -{ - OT_ICMP6_TYPE_DST_UNREACH = 1, ///< Destination Unreachable - OT_ICMP6_TYPE_ECHO_REQUEST = 128, ///< Echo Request - OT_ICMP6_TYPE_ECHO_REPLY = 129, ///< Echo Reply +typedef enum otIcmp6Type { + OT_ICMP6_TYPE_DST_UNREACH = 1, ///< Destination Unreachable + OT_ICMP6_TYPE_ECHO_REQUEST = 128, ///< Echo Request + OT_ICMP6_TYPE_ECHO_REPLY = 129, ///< Echo Reply } otIcmp6Type; /** * ICMPv6 Message Codes * */ -typedef enum otIcmp6Code -{ - OT_ICMP6_CODE_DST_UNREACH_NO_ROUTE = 0, ///< Destination Unreachable No Route +typedef enum otIcmp6Code { + OT_ICMP6_CODE_DST_UNREACH_NO_ROUTE = 0, ///< Destination Unreachable No Route } otIcmp6Code; -#define OT_ICMP6_HEADER_DATA_SIZE 4 ///< Size of an message specific data of ICMPv6 Header. +#define OT_ICMP6_HEADER_DATA_SIZE 4 ///< Size of an message specific data of ICMPv6 Header. /** * @struct otIcmp6Header @@ -83,15 +81,15 @@ typedef enum otIcmp6Code OT_TOOL_PACKED_BEGIN struct otIcmp6Header { - uint8_t mType; ///< Type - uint8_t mCode; ///< Code - uint16_t mChecksum; ///< Checksum + uint8_t mType; ///< Type + uint8_t mCode; ///< Code + uint16_t mChecksum; ///< Checksum union OT_TOOL_PACKED_FIELD { uint8_t m8[OT_ICMP6_HEADER_DATA_SIZE / sizeof(uint8_t)]; uint16_t m16[OT_ICMP6_HEADER_DATA_SIZE / sizeof(uint16_t)]; uint32_t m32[OT_ICMP6_HEADER_DATA_SIZE / sizeof(uint32_t)]; - } mData; ///< Message-specific data + } mData; ///< Message-specific data } OT_TOOL_PACKED_END; /** @@ -109,7 +107,9 @@ typedef struct otIcmp6Header otIcmp6Header; * @param[in] aIcmpHeader A pointer to the received ICMPv6 header. * */ -typedef void (*otIcmp6ReceiveCallback)(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo, +typedef void (*otIcmp6ReceiveCallback)(void * aContext, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, const otIcmp6Header *aIcmpHeader); /** @@ -118,9 +118,9 @@ typedef void (*otIcmp6ReceiveCallback)(void *aContext, otMessage *aMessage, cons */ typedef struct otIcmp6Handler { - otIcmp6ReceiveCallback mReceiveCallback; ///< The ICMPv6 received callback - void *mContext; ///< A pointer to arbitrary context information. - struct otIcmp6Handler *mNext; ///< A pointer to the next handler in the list. + otIcmp6ReceiveCallback mReceiveCallback; ///< The ICMPv6 received callback + void * mContext; ///< A pointer to arbitrary context information. + struct otIcmp6Handler *mNext; ///< A pointer to the next handler in the list. } otIcmp6Handler; /** @@ -166,8 +166,10 @@ otError otIcmp6RegisterHandler(otInstance *aInstance, otIcmp6Handler *aHandler); * May be zero. * */ -otError otIcmp6SendEchoRequest(otInstance *aInstance, otMessage *aMessage, const otMessageInfo *aMessageInfo, - uint16_t aIdentifier); +otError otIcmp6SendEchoRequest(otInstance * aInstance, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + uint16_t aIdentifier); /** * @} @@ -175,7 +177,7 @@ otError otIcmp6SendEchoRequest(otInstance *aInstance, otMessage *aMessage, const */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_ICMP6_H_ +#endif // OPENTHREAD_ICMP6_H_ diff --git a/include/openthread/instance.h b/include/openthread/instance.h index cea69da86..6c2eaf853 100644 --- a/include/openthread/instance.h +++ b/include/openthread/instance.h @@ -92,7 +92,7 @@ OTAPI void OTCALL otFreeMemory(const void *aMem); * @param[in] aContext A pointer to application-specific context. * */ -typedef void (OTCALL *otDeviceAvailabilityChangedCallback)(bool aAdded, const GUID *aDeviceGuid, void *aContext); +typedef void(OTCALL *otDeviceAvailabilityChangedCallback)(bool aAdded, const GUID *aDeviceGuid, void *aContext); /** * This function registers a callback to indicate OpenThread devices come and go. @@ -102,9 +102,9 @@ typedef void (OTCALL *otDeviceAvailabilityChangedCallback)(bool aAdded, const GU * @param[in] aContextContext A pointer to application-specific context. * */ -OTAPI void OTCALL otSetDeviceAvailabilityChangedCallback(otApiInstance *aApiInstance, +OTAPI void OTCALL otSetDeviceAvailabilityChangedCallback(otApiInstance * aApiInstance, otDeviceAvailabilityChangedCallback aCallback, - void *aCallbackContext); + void * aCallbackContext); /** * This function querys the list of OpenThread device contexts on the system. @@ -224,29 +224,29 @@ void otInstanceFinalize(otInstance *aInstance); */ enum { - OT_CHANGED_IP6_ADDRESS_ADDED = 1 << 0, ///< IPv6 address was added - OT_CHANGED_IP6_ADDRESS_REMOVED = 1 << 1, ///< IPv6 address was removed - OT_CHANGED_THREAD_ROLE = 1 << 2, ///< Role (disabled, detached, child, router, leader) changed - OT_CHANGED_THREAD_LL_ADDR = 1 << 3, ///< The link-local address changed - OT_CHANGED_THREAD_ML_ADDR = 1 << 4, ///< The mesh-local address changed - OT_CHANGED_THREAD_RLOC_ADDED = 1 << 5, ///< RLOC was added - OT_CHANGED_THREAD_RLOC_REMOVED = 1 << 6, ///< RLOC was removed - OT_CHANGED_THREAD_PARTITION_ID = 1 << 7, ///< Partition ID changed - OT_CHANGED_THREAD_KEY_SEQUENCE_COUNTER = 1 << 8, ///< Thread Key Sequence changed - OT_CHANGED_THREAD_NETDATA = 1 << 9, ///< Thread Network Data changed - OT_CHANGED_THREAD_CHILD_ADDED = 1 << 10, ///< Child was added - OT_CHANGED_THREAD_CHILD_REMOVED = 1 << 11, ///< Child was removed - OT_CHANGED_IP6_MULTICAST_SUBSRCRIBED = 1 << 12, ///< Subscribed to a IPv6 multicast address - OT_CHANGED_IP6_MULTICAST_UNSUBSRCRIBED = 1 << 13, ///< Unsubscribed from a IPv6 multicast address - OT_CHANGED_COMMISSIONER_STATE = 1 << 14, ///< Commissioner state changed - OT_CHANGED_JOINER_STATE = 1 << 15, ///< Joiner state changed - OT_CHANGED_THREAD_CHANNEL = 1 << 16, ///< Thread network channel changed - OT_CHANGED_THREAD_PANID = 1 << 17, ///< Thread network PAN Id changed - OT_CHANGED_THREAD_NETWORK_NAME = 1 << 18, ///< Thread network name changed - OT_CHANGED_THREAD_EXT_PANID = 1 << 19, ///< Thread network extended PAN ID changed - OT_CHANGED_MASTER_KEY = 1 << 20, ///< Master key changed - OT_CHANGED_PSKC = 1 << 21, ///< PSKc changed - OT_CHANGED_SECURITY_POLICY = 1 << 22, ///< Security Policy changed + OT_CHANGED_IP6_ADDRESS_ADDED = 1 << 0, ///< IPv6 address was added + OT_CHANGED_IP6_ADDRESS_REMOVED = 1 << 1, ///< IPv6 address was removed + OT_CHANGED_THREAD_ROLE = 1 << 2, ///< Role (disabled, detached, child, router, leader) changed + OT_CHANGED_THREAD_LL_ADDR = 1 << 3, ///< The link-local address changed + OT_CHANGED_THREAD_ML_ADDR = 1 << 4, ///< The mesh-local address changed + OT_CHANGED_THREAD_RLOC_ADDED = 1 << 5, ///< RLOC was added + OT_CHANGED_THREAD_RLOC_REMOVED = 1 << 6, ///< RLOC was removed + OT_CHANGED_THREAD_PARTITION_ID = 1 << 7, ///< Partition ID changed + OT_CHANGED_THREAD_KEY_SEQUENCE_COUNTER = 1 << 8, ///< Thread Key Sequence changed + OT_CHANGED_THREAD_NETDATA = 1 << 9, ///< Thread Network Data changed + OT_CHANGED_THREAD_CHILD_ADDED = 1 << 10, ///< Child was added + OT_CHANGED_THREAD_CHILD_REMOVED = 1 << 11, ///< Child was removed + OT_CHANGED_IP6_MULTICAST_SUBSRCRIBED = 1 << 12, ///< Subscribed to a IPv6 multicast address + OT_CHANGED_IP6_MULTICAST_UNSUBSRCRIBED = 1 << 13, ///< Unsubscribed from a IPv6 multicast address + OT_CHANGED_COMMISSIONER_STATE = 1 << 14, ///< Commissioner state changed + OT_CHANGED_JOINER_STATE = 1 << 15, ///< Joiner state changed + OT_CHANGED_THREAD_CHANNEL = 1 << 16, ///< Thread network channel changed + OT_CHANGED_THREAD_PANID = 1 << 17, ///< Thread network PAN Id changed + OT_CHANGED_THREAD_NETWORK_NAME = 1 << 18, ///< Thread network name changed + OT_CHANGED_THREAD_EXT_PANID = 1 << 19, ///< Thread network extended PAN ID changed + OT_CHANGED_MASTER_KEY = 1 << 20, ///< Master key changed + OT_CHANGED_PSKC = 1 << 21, ///< PSKc changed + OT_CHANGED_SECURITY_POLICY = 1 << 22, ///< Security Policy changed }; /** @@ -256,7 +256,7 @@ enum * @param[in] aContext A pointer to application-specific context. * */ -typedef void (OTCALL *otStateChangedCallback)(uint32_t aFlags, void *aContext); +typedef void(OTCALL *otStateChangedCallback)(uint32_t aFlags, void *aContext); /** * This function registers a callback to indicate when certain configuration or state changes within OpenThread. @@ -340,7 +340,7 @@ otError otSetDynamicLogLevel(otInstance *aInstance, otLogLevel aLogLevel); */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_INSTANCE_H_ +#endif // OPENTHREAD_INSTANCE_H_ diff --git a/include/openthread/ip6.h b/include/openthread/ip6.h index fd576e0c7..6ccc69d61 100644 --- a/include/openthread/ip6.h +++ b/include/openthread/ip6.h @@ -125,7 +125,8 @@ OTAPI const otNetifAddress *OTCALL otIp6GetUnicastAddresses(otInstance *aInstanc * @retval OT_ERROR_NONE Successfully subscribed to the Network Interface Multicast Address. * @retval OT_ERROR_ALREADY The multicast address is already subscribed. * @retval OT_ERROR_INVALID_ARGS The IP Address indicated by @p aAddress is invalid address. - * @retval OT_ERROR_NO_BUFS The Network Interface is already storing the maximum allowed external multicast addresses. + * @retval OT_ERROR_NO_BUFS The Network Interface is already storing the maximum allowed external multicast + * addresses. * */ otError otIp6SubscribeMulticastAddress(otInstance *aInstance, const otIp6Address *aAddress); @@ -181,7 +182,7 @@ void otIp6SetMulticastPromiscuousEnabled(otInstance *aInstance, bool aEnabled); * @retval OT_ERROR_IP6_ADDRESS_CREATION_FAILURE Creation of valid IID for given IPv6 address failed. * */ -typedef otError(*otIp6SlaacIidCreate)(otInstance *aInstance, otNetifAddress *aAddress, void *aContext); +typedef otError (*otIp6SlaacIidCreate)(otInstance *aInstance, otNetifAddress *aAddress, void *aContext); /** * Update all automatically created IPv6 addresses for prefixes from current Network Data with SLAAC procedure. @@ -193,8 +194,11 @@ typedef otError(*otIp6SlaacIidCreate)(otInstance *aInstance, otNetifAddress *aAd * @param[in] aContext A pointer to data passed to aIidCreate function. * */ -void otIp6SlaacUpdate(otInstance *aInstance, otNetifAddress *aAddresses, uint32_t aNumAddresses, - otIp6SlaacIidCreate aIidCreate, void *aContext); +void otIp6SlaacUpdate(otInstance * aInstance, + otNetifAddress * aAddresses, + uint32_t aNumAddresses, + otIp6SlaacIidCreate aIidCreate, + void * aContext); /** * Create random IID for given IPv6 address. @@ -394,7 +398,7 @@ bool otIp6IsAddressUnspecified(const otIp6Address *aAddress); */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_IP6_H_ +#endif // OPENTHREAD_IP6_H_ diff --git a/include/openthread/jam_detection.h b/include/openthread/jam_detection.h index fdb16d1fe..96c7f7f74 100644 --- a/include/openthread/jam_detection.h +++ b/include/openthread/jam_detection.h @@ -41,7 +41,6 @@ extern "C" { #endif - /** * @addtogroup api-jam-detection * @@ -194,7 +193,7 @@ uint64_t otJamDetectionGetHistoryBitmap(otInstance *aInstance); */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_JAM_DETECTION_H_ +#endif // OPENTHREAD_JAM_DETECTION_H_ diff --git a/include/openthread/joiner.h b/include/openthread/joiner.h index 7c9a477bd..af31e7d39 100644 --- a/include/openthread/joiner.h +++ b/include/openthread/joiner.h @@ -56,8 +56,7 @@ extern "C" { * This enumeration defines the Joiner State. * */ -typedef enum otJoinerState -{ +typedef enum otJoinerState { OT_JOINER_STATE_IDLE = 0, OT_JOINER_STATE_DISCOVER = 1, OT_JOINER_STATE_CONNECT = 2, @@ -76,7 +75,7 @@ typedef enum otJoinerState * @param[in] aContext A pointer to application-specific context. * */ -typedef void (OTCALL *otJoinerCallback)(otError aError, void *aContext); +typedef void(OTCALL *otJoinerCallback)(otError aError, void *aContext); /** * This function enables the Thread Joiner role. @@ -96,10 +95,15 @@ typedef void (OTCALL *otJoinerCallback)(otError aError, void *aContext); * @retval OT_ERROR_DISABLED_FEATURE The Joiner feature is not enabled in this build. * */ -OTAPI otError OTCALL otJoinerStart(otInstance *aInstance, const char *aPSKd, const char *aProvisioningUrl, - const char *aVendorName, const char *aVendorModel, - const char *aVendorSwVersion, const char *aVendorData, - otJoinerCallback aCallback, void *aContext); +OTAPI otError OTCALL otJoinerStart(otInstance * aInstance, + const char * aPSKd, + const char * aProvisioningUrl, + const char * aVendorName, + const char * aVendorModel, + const char * aVendorSwVersion, + const char * aVendorData, + otJoinerCallback aCallback, + void * aContext); /** * This function disables the Thread Joiner role. @@ -148,7 +152,7 @@ OTAPI otError OTCALL otJoinerGetId(otInstance *aInstance, otExtAddress *aJoinerI */ #ifdef __cplusplus -} // end of extern "C" +} // end of extern "C" #endif -#endif // OPENTHREAD_JOINER_H_ +#endif // OPENTHREAD_JOINER_H_ diff --git a/include/openthread/link.h b/include/openthread/link.h index d68da5348..a8799ddc7 100644 --- a/include/openthread/link.h +++ b/include/openthread/link.h @@ -60,7 +60,7 @@ extern "C" { * @param[in] aContext A pointer to application-specific context. * */ -typedef void (OTCALL *otHandleActiveScanResult)(otActiveScanResult *aResult, void *aContext); +typedef void(OTCALL *otHandleActiveScanResult)(otActiveScanResult *aResult, void *aContext); /** * This function starts an IEEE 802.15.4 Active Scan @@ -75,8 +75,11 @@ typedef void (OTCALL *otHandleActiveScanResult)(otActiveScanResult *aResult, voi * @retval OT_ERROR_BUSY Already performing an Active Scan. * */ -OTAPI otError OTCALL otLinkActiveScan(otInstance *aInstance, uint32_t aScanChannels, uint16_t aScanDuration, - otHandleActiveScanResult aCallback, void *aCallbackContext); +OTAPI otError OTCALL otLinkActiveScan(otInstance * aInstance, + uint32_t aScanChannels, + uint16_t aScanDuration, + otHandleActiveScanResult aCallback, + void * aCallbackContext); /** * This function indicates whether or not an IEEE 802.15.4 Active Scan is currently in progress. @@ -95,7 +98,7 @@ OTAPI bool OTCALL otLinkIsActiveScanInProgress(otInstance *aInstance); * @param[in] aContext A pointer to application-specific context. * */ -typedef void (OTCALL *otHandleEnergyScanResult)(otEnergyScanResult *aResult, void *aContext); +typedef void(OTCALL *otHandleEnergyScanResult)(otEnergyScanResult *aResult, void *aContext); /** * This function starts an IEEE 802.15.4 Energy Scan @@ -110,8 +113,11 @@ typedef void (OTCALL *otHandleEnergyScanResult)(otEnergyScanResult *aResult, voi * @retval OT_ERROR_BUSY Could not start the energy scan. * */ -OTAPI otError OTCALL otLinkEnergyScan(otInstance *aInstance, uint32_t aScanChannels, uint16_t aScanDuration, - otHandleEnergyScanResult aCallback, void *aCallbackContext); +OTAPI otError OTCALL otLinkEnergyScan(otInstance * aInstance, + uint32_t aScanChannels, + uint16_t aScanDuration, + otHandleEnergyScanResult aCallback, + void * aCallbackContext); /** * This function indicates whether or not an IEEE 802.15.4 Energy Scan is currently in progress. @@ -416,8 +422,9 @@ OTAPI void OTCALL otLinkFilterClearAddresses(otInstance *aInstance); * @sa otLinkFilterGetNextRssIn * */ -OTAPI otError OTCALL otLinkFilterGetNextAddress(otInstance *aInstance, - otMacFilterIterator *aIterator, otMacFilterEntry *aEntry); +OTAPI otError OTCALL otLinkFilterGetNextAddress(otInstance * aInstance, + otMacFilterIterator *aIterator, + otMacFilterEntry * aEntry); /** * This method sets the received signal strength (in dBm) for the messages from the Extended Address. @@ -512,8 +519,9 @@ OTAPI void OTCALL otLinkFilterClearRssIn(otInstance *aInstance); * @sa otLinkFilterClearRssIn * */ -OTAPI otError OTCALL otLinkFilterGetNextRssIn(otInstance *aInstance, - otMacFilterIterator *aIterator, otMacFilterEntry *aEntry); +OTAPI otError OTCALL otLinkFilterGetNextRssIn(otInstance * aInstance, + otMacFilterIterator *aIterator, + otMacFilterEntry * aEntry); /** * This method converts received signal strength to link quality. @@ -597,7 +605,6 @@ bool otLinkIsPromiscuous(otInstance *aInstance); */ otError otLinkSetPromiscuous(otInstance *aInstance, bool aPromiscuous); - /** * This function returns the current CCA (Clear Channel Assessment) failure rate. * @@ -615,7 +622,7 @@ uint16_t otLinkGetCcaFailureRate(otInstance *aInstance); */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_LINK_H_ +#endif // OPENTHREAD_LINK_H_ diff --git a/include/openthread/link_raw.h b/include/openthread/link_raw.h index 03464fc67..495d4fb8c 100644 --- a/include/openthread/link_raw.h +++ b/include/openthread/link_raw.h @@ -156,7 +156,7 @@ otError otLinkRawSleep(otInstance *aInstance); * OT_ERROR_ABORT when reception was aborted and a frame was not received. * */ -typedef void (OTCALL *otLinkRawReceiveDone)(otInstance *aInstance, otRadioFrame *aFrame, otError aError); +typedef void(OTCALL *otLinkRawReceiveDone)(otInstance *aInstance, otRadioFrame *aFrame, otError aError); /** * Transitioning the radio from Sleep to Receive. @@ -199,8 +199,10 @@ otRadioFrame *otLinkRawGetTransmitBuffer(otInstance *aInstance); * OT_ERROR_ABORT when transmission was aborted for other reasons. * */ -typedef void (*otLinkRawTransmitDone)(otInstance *aInstance, otRadioFrame *aFrame, - otRadioFrame *aAckFrame, otError aError); +typedef void (*otLinkRawTransmitDone)(otInstance * aInstance, + otRadioFrame *aFrame, + otRadioFrame *aAckFrame, + otError aError); /** * This method begins the transmit sequence on the radio. @@ -264,7 +266,9 @@ typedef void (*otLinkRawEnergyScanDone)(otInstance *aInstance, int8_t aEnergySca * @retval OT_ERROR_INVALID_STATE If the raw link-layer isn't enabled. * */ -otError otLinkRawEnergyScan(otInstance *aInstance, uint8_t aScanChannel, uint16_t aScanDuration, +otError otLinkRawEnergyScan(otInstance * aInstance, + uint8_t aScanChannel, + uint16_t aScanDuration, otLinkRawEnergyScanDone aCallback); /** @@ -359,7 +363,7 @@ otError otLinkRawSrcMatchClearExtEntries(otInstance *aInstance); */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // LINK_RAW_H_ +#endif // LINK_RAW_H_ diff --git a/include/openthread/message.h b/include/openthread/message.h index f6f31402d..e0374b057 100644 --- a/include/openthread/message.h +++ b/include/openthread/message.h @@ -234,7 +234,7 @@ int otMessageWrite(otMessage *aMessage, uint16_t aOffset, const void *aBuf, uint */ typedef struct { - void *mData; ///< Opaque data used by the implementation. + void *mData; ///< Opaque data used by the implementation. } otMessageQueue; /** @@ -322,7 +322,7 @@ OTAPI void OTCALL otMessageGetBufferInfo(otInstance *aInstance, otBufferInfo *aB */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_MESSAGE_H_ +#endif // OPENTHREAD_MESSAGE_H_ diff --git a/include/openthread/ncp.h b/include/openthread/ncp.h index 154af679a..90a80f8d9 100644 --- a/include/openthread/ncp.h +++ b/include/openthread/ncp.h @@ -35,8 +35,8 @@ #ifndef NCP_H_ #define NCP_H_ -#include #include +#include #ifdef __cplusplus extern "C" { @@ -81,7 +81,7 @@ void otNcpInit(otInstance *aInstance); * @retval OT_ERROR_BUSY There are not enough resources to complete this * request. This is usually a temporary condition. * @retval OT_ERROR_INVALID_ARGS The given aStreamId was invalid. -*/ + */ otError otNcpStreamWrite(int aStreamId, const uint8_t *aDataPtr, int aDataLen); //----------------------------------------------------------------------------------------- @@ -120,7 +120,7 @@ otError otNcpRegisterPeekPokeDelagates(otNcpDelegateAllowPeekPoke aAllowPeekDele //----------------------------------------------------------------------------------------- // Legacy network APIs -#define OT_NCP_LEGACY_ULA_PREFIX_LENGTH 8 ///< Legacy ULA size (in bytes) +#define OT_NCP_LEGACY_ULA_PREFIX_LENGTH 8 ///< Legacy ULA size (in bytes) /** * Defines handler (function pointer) type for starting legacy network @@ -165,10 +165,10 @@ typedef void (*otNcpHandlerSetLegacyUlaPrefix)(const uint8_t *aUlaPrefix); */ typedef struct otNcpLegacyHandlers { - otNcpHandlerStartLegacy mStartLegacy; ///< Start handler - otNcpHandlerStopLegacy mStopLegacy; ///< Stop handler - otNcpHandlerJoinLegacyNode mJoinLegacyNode; ///< Join handler - otNcpHandlerSetLegacyUlaPrefix mSetLegacyUlaPrefix; ///< Set ULA handler + otNcpHandlerStartLegacy mStartLegacy; ///< Start handler + otNcpHandlerStopLegacy mStopLegacy; ///< Stop handler + otNcpHandlerJoinLegacyNode mJoinLegacyNode; ///< Join handler + otNcpHandlerSetLegacyUlaPrefix mSetLegacyUlaPrefix; ///< Set ULA handler } otNcpLegacyHandlers; /** @@ -218,7 +218,7 @@ void otNcpPlatLogv(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFo */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif #endif diff --git a/include/openthread/netdata.h b/include/openthread/netdata.h index 630d49edc..d45ccd6d0 100644 --- a/include/openthread/netdata.h +++ b/include/openthread/netdata.h @@ -57,8 +57,7 @@ extern "C" { * @param[inout] aDataLength On entry, size of the data buffer pointed to by @p aData. * On exit, number of copied bytes. */ -OTAPI otError OTCALL otNetDataGet(otInstance *aInstance, bool aStable, uint8_t *aData, - uint8_t *aDataLength); +OTAPI otError OTCALL otNetDataGet(otInstance *aInstance, bool aStable, uint8_t *aData, uint8_t *aDataLength); /** * This function gets the next On Mesh Prefix in the partition's Network Data. @@ -72,8 +71,9 @@ OTAPI otError OTCALL otNetDataGet(otInstance *aInstance, bool aStable, uint8_t * * @retval OT_ERROR_NOT_FOUND No subsequent On Mesh prefix exists in the Thread Network Data. * */ -OTAPI otError OTCALL otNetDataGetNextOnMeshPrefix(otInstance *aInstance, otNetworkDataIterator *aIterator, - otBorderRouterConfig *aConfig); +OTAPI otError OTCALL otNetDataGetNextOnMeshPrefix(otInstance * aInstance, + otNetworkDataIterator *aIterator, + otBorderRouterConfig * aConfig); /** * This function gets the next external route in the partition's Network Data. @@ -87,8 +87,7 @@ OTAPI otError OTCALL otNetDataGetNextOnMeshPrefix(otInstance *aInstance, otNetwo * @retval OT_ERROR_NOT_FOUND No subsequent external route entry exists in the Thread Network Data. * */ -otError otNetDataGetNextRoute(otInstance *aInstance, otNetworkDataIterator *aIterator, - otExternalRouteConfig *aConfig); +otError otNetDataGetNextRoute(otInstance *aInstance, otNetworkDataIterator *aIterator, otExternalRouteConfig *aConfig); /** * Get the Network Data Version. @@ -114,7 +113,7 @@ OTAPI uint8_t OTCALL otNetDataGetStableVersion(otInstance *aInstance); */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_NETDATA_H_ +#endif // OPENTHREAD_NETDATA_H_ diff --git a/include/openthread/openthread.h b/include/openthread/openthread.h index 28cf35a31..ed0e2d729 100644 --- a/include/openthread/openthread.h +++ b/include/openthread/openthread.h @@ -169,7 +169,7 @@ OTAPI const char *OTCALL otGetVersionString(void); OTAPI const char *OTCALL otThreadErrorToString(otError aError); #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_H_ +#endif // OPENTHREAD_H_ diff --git a/include/openthread/platform/alarm-micro.h b/include/openthread/platform/alarm-micro.h index ff7ca670d..113b5f729 100644 --- a/include/openthread/platform/alarm-micro.h +++ b/include/openthread/platform/alarm-micro.h @@ -89,7 +89,7 @@ extern void otPlatAlarmMicroFired(otInstance *aInstance); */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // ALARM_MICRO_H_ +#endif // ALARM_MICRO_H_ diff --git a/include/openthread/platform/alarm-milli.h b/include/openthread/platform/alarm-milli.h index ae49609cb..ed078ba8e 100644 --- a/include/openthread/platform/alarm-milli.h +++ b/include/openthread/platform/alarm-milli.h @@ -96,7 +96,7 @@ extern void otPlatDiagAlarmFired(otInstance *aInstance); */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // ALARM_MILLI_H_ +#endif // ALARM_MILLI_H_ diff --git a/include/openthread/platform/debug_uart.h b/include/openthread/platform/debug_uart.h index ba28d2865..52c13a1b0 100644 --- a/include/openthread/platform/debug_uart.h +++ b/include/openthread/platform/debug_uart.h @@ -59,137 +59,136 @@ extern "C" { #endif - /** - * @addtogroup internal-debug-api - * - * @{ - */ +/** + * @addtogroup internal-debug-api + * + * @{ + */ - /** - * Standard printf() to the debug uart with no log decoration. - * - * @param[in] fmt printf formatter text - * - * This is a debug convenience function that is not intended to be - * used in anything other then "debug scenarios" by a developer. - * - * lf -> cr/lf mapping is automatically handled via otPlatDebugUart_putchar() - * - * @sa otPlatDebugUart_vprintf() for limitations - * - * This is a WEAK symbol that can easily be overridden as needed. - */ - void otPlatDebugUart_printf(const char *fmt, ...); +/** + * Standard printf() to the debug uart with no log decoration. + * + * @param[in] fmt printf formatter text + * + * This is a debug convenience function that is not intended to be + * used in anything other then "debug scenarios" by a developer. + * + * lf -> cr/lf mapping is automatically handled via otPlatDebugUart_putchar() + * + * @sa otPlatDebugUart_vprintf() for limitations + * + * This is a WEAK symbol that can easily be overridden as needed. + */ +void otPlatDebugUart_printf(const char *fmt, ...); - /** - * Standard vprintf() to the debug uart, with no log decoration. - * - * @param[in] fmt printf formatter text - * @param[in] ap va_list value for print parameters. - * - * Implementation limitation: this formats the text into - * a purposely small text buffer on the stack, thus long - * messages may be truncated. - * - * This is a WEAK symbol that can easily be overridden as needed. - * - * For example, some platforms might override this via a non-WEAK - * symbol because the platform provides a UART_vprintf() like - * function that can handle an arbitrary length output. - */ - void otPlatDebugUart_vprintf(const char *fmt, va_list ap); +/** + * Standard vprintf() to the debug uart, with no log decoration. + * + * @param[in] fmt printf formatter text + * @param[in] ap va_list value for print parameters. + * + * Implementation limitation: this formats the text into + * a purposely small text buffer on the stack, thus long + * messages may be truncated. + * + * This is a WEAK symbol that can easily be overridden as needed. + * + * For example, some platforms might override this via a non-WEAK + * symbol because the platform provides a UART_vprintf() like + * function that can handle an arbitrary length output. + */ +void otPlatDebugUart_vprintf(const char *fmt, va_list ap); - /** - * Platform specific write single byte to Debug Uart - * This should not perform CR/LF mapping. - * - * This function MUST be implemented by the platform - * - * @param[in] the_byte what to transmit - */ - void otPlatDebugUart_putchar_raw(int the_byte); +/** + * Platform specific write single byte to Debug Uart + * This should not perform CR/LF mapping. + * + * This function MUST be implemented by the platform + * + * @param[in] the_byte what to transmit + */ +void otPlatDebugUart_putchar_raw(int the_byte); - /** - * Poll/test debug uart if a key has been pressed. - * It would be common to a stub function that returns 0. - * - * This function MUST be implemented by the platform - * - * @retval zero - nothing ready - * @retval nonzero - otPlatDebugUart_getc() will succeed. - */ - int otPlatDebugUart_kbhit(void); +/** + * Poll/test debug uart if a key has been pressed. + * It would be common to a stub function that returns 0. + * + * This function MUST be implemented by the platform + * + * @retval zero - nothing ready + * @retval nonzero - otPlatDebugUart_getc() will succeed. + */ +int otPlatDebugUart_kbhit(void); - /** - * Poll/Read a byte from the debug uart - * - * This function MUST be implemented by the platform - * - * @retval (negative) no data available, @sa otPlatDebugUart_kbhit() - * @retval (0x00..0x0ff) data byte value - * - */ - int otPlatDebugUart_getc(void); +/** + * Poll/Read a byte from the debug uart + * + * This function MUST be implemented by the platform + * + * @retval (negative) no data available, @sa otPlatDebugUart_kbhit() + * @retval (0x00..0x0ff) data byte value + * + */ +int otPlatDebugUart_getc(void); - /** - * Write byte to the uart, expand cr/lf as need. - * - * A WEAK default implementation is provided - * that can be overridden as needed. - * - * @param[in] the_byte the byte to transmit - */ - void otPlatDebugUart_putchar(int the_byte); +/** + * Write byte to the uart, expand cr/lf as need. + * + * A WEAK default implementation is provided + * that can be overridden as needed. + * + * @param[in] the_byte the byte to transmit + */ +void otPlatDebugUart_putchar(int the_byte); - /** - * identical to "man 3 puts" - terminates with lf - * Which is then mapped to cr/lf as required - * - * A WEAK default implementation is provided - * that can be overridden as needed. - * - * @param[in] s the string to print with a lf at the end - */ - void otPlatDebugUart_puts(const char *s); +/** + * identical to "man 3 puts" - terminates with lf + * Which is then mapped to cr/lf as required + * + * A WEAK default implementation is provided + * that can be overridden as needed. + * + * @param[in] s the string to print with a lf at the end + */ +void otPlatDebugUart_puts(const char *s); - /** - * Write N bytes to the UART, mapping cr/lf - * - * @param[in] pBytes pointer to bytes to transmit. - * @param[in] nBytes how many bytes to transmit. - */ - void otPlatDebugUart_write_bytes(const uint8_t *pBytes, int nBytes); +/** + * Write N bytes to the UART, mapping cr/lf + * + * @param[in] pBytes pointer to bytes to transmit. + * @param[in] nBytes how many bytes to transmit. + */ +void otPlatDebugUart_write_bytes(const uint8_t *pBytes, int nBytes); - /** - * puts() without a terminal newline. - * see: "man 3 puts", without a adding a terminal lf - * - * @param[in] s the string to print without a lf at the end - * - * Note, the terminal "lf" mapped to cr/lf via - * the function otPlatDebugUart_putchar() - */ - void otPlatDebugUart_puts_no_nl(const char *s); +/** + * puts() without a terminal newline. + * see: "man 3 puts", without a adding a terminal lf + * + * @param[in] s the string to print without a lf at the end + * + * Note, the terminal "lf" mapped to cr/lf via + * the function otPlatDebugUart_putchar() + */ +void otPlatDebugUart_puts_no_nl(const char *s); - /** - * Some platforms (posix) can log to a file. - * - * @returns OT_ERROR_NONE - * @returns OT_ERROR_FAILED - * - * Platforms that desire this MUST provide an implementation. - * - */ - otError otPlatDebugUart_logfile(const char *filename); +/** + * Some platforms (posix) can log to a file. + * + * @returns OT_ERROR_NONE + * @returns OT_ERROR_FAILED + * + * Platforms that desire this MUST provide an implementation. + * + */ +otError otPlatDebugUart_logfile(const char *filename); - /** - * @} - * - */ +/** + * @} + * + */ #if __cplusplus } // extern "C" #endif #endif // OPENTHREAD_PLATFORM_DEBUG_UART_H - diff --git a/include/openthread/platform/diag.h b/include/openthread/platform/diag.h index dd4b3c917..15cd0156a 100644 --- a/include/openthread/platform/diag.h +++ b/include/openthread/platform/diag.h @@ -36,8 +36,8 @@ #ifndef DIAG_H_ #define DIAG_H_ -#include #include +#include #include #include @@ -124,7 +124,7 @@ void otPlatDiagAlarmCallback(otInstance *aInstance); */ #ifdef __cplusplus -} // end of extern "C" +} // end of extern "C" #endif #endif diff --git a/include/openthread/platform/logging.h b/include/openthread/platform/logging.h index a78b40119..c1ac81913 100644 --- a/include/openthread/platform/logging.h +++ b/include/openthread/platform/logging.h @@ -35,8 +35,8 @@ #ifndef LOGGING_H_ #define LOGGING_H_ -#include #include +#include #include @@ -61,11 +61,11 @@ extern "C" { * embedded code can remove code at compile time via if/else/endif */ -#define OT_LOG_LEVEL_NONE 0 ///< None -#define OT_LOG_LEVEL_CRIT 1 ///< Critical -#define OT_LOG_LEVEL_WARN 2 ///< Warning -#define OT_LOG_LEVEL_INFO 3 ///< Info -#define OT_LOG_LEVEL_DEBG 4 ///< Debug +#define OT_LOG_LEVEL_NONE 0 ///< None +#define OT_LOG_LEVEL_CRIT 1 ///< Critical +#define OT_LOG_LEVEL_WARN 2 ///< Warning +#define OT_LOG_LEVEL_INFO 3 ///< Info +#define OT_LOG_LEVEL_DEBG 4 ///< Debug /* note: The enum otLogRegion is found in 'openthread/types.h' */ @@ -97,7 +97,7 @@ void otPlatLogv(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aForma */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // DEBUG_H_ +#endif // DEBUG_H_ diff --git a/include/openthread/platform/memory.h b/include/openthread/platform/memory.h index bbada59ec..4b6ac6c1f 100644 --- a/include/openthread/platform/memory.h +++ b/include/openthread/platform/memory.h @@ -86,7 +86,7 @@ void otPlatFree(void *aPtr); */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // DEBUG_H_ +#endif // DEBUG_H_ diff --git a/include/openthread/platform/messagepool.h b/include/openthread/platform/messagepool.h index b9a7eaed8..c2924b5e9 100644 --- a/include/openthread/platform/messagepool.h +++ b/include/openthread/platform/messagepool.h @@ -94,7 +94,7 @@ void otPlatMessagePoolFree(otInstance *aInstance, otMessage *aBuffer); uint16_t otPlatMessagePoolNumFreeBuffers(otInstance *aInstance); #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif /** @@ -102,5 +102,4 @@ uint16_t otPlatMessagePoolNumFreeBuffers(otInstance *aInstance); * */ - -#endif // MESSAGEPOOL_H_ +#endif // MESSAGEPOOL_H_ diff --git a/include/openthread/platform/misc.h b/include/openthread/platform/misc.h index 0115c0ec7..f85120338 100644 --- a/include/openthread/platform/misc.h +++ b/include/openthread/platform/misc.h @@ -67,17 +67,16 @@ void otPlatReset(otInstance *aInstance); * These are in the same order as the Spinel reset reason codes. * */ -typedef enum -{ - OT_PLAT_RESET_REASON_POWER_ON = 0, - OT_PLAT_RESET_REASON_EXTERNAL = 1, - OT_PLAT_RESET_REASON_SOFTWARE = 2, - OT_PLAT_RESET_REASON_FAULT = 3, - OT_PLAT_RESET_REASON_CRASH = 4, - OT_PLAT_RESET_REASON_ASSERT = 5, - OT_PLAT_RESET_REASON_OTHER = 6, - OT_PLAT_RESET_REASON_UNKNOWN = 7, - OT_PLAT_RESET_REASON_WATCHDOG = 8, +typedef enum { + OT_PLAT_RESET_REASON_POWER_ON = 0, + OT_PLAT_RESET_REASON_EXTERNAL = 1, + OT_PLAT_RESET_REASON_SOFTWARE = 2, + OT_PLAT_RESET_REASON_FAULT = 3, + OT_PLAT_RESET_REASON_CRASH = 4, + OT_PLAT_RESET_REASON_ASSERT = 5, + OT_PLAT_RESET_REASON_OTHER = 6, + OT_PLAT_RESET_REASON_UNKNOWN = 7, + OT_PLAT_RESET_REASON_WATCHDOG = 8, OT_PLAT_RESET_REASON_COUNT, } otPlatResetReason; @@ -112,7 +111,7 @@ void otPlatWakeHost(void); */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OT_PLATFORM_MISC_H +#endif // OT_PLATFORM_MISC_H diff --git a/include/openthread/platform/radio.h b/include/openthread/platform/radio.h index 5cecaf7f6..798d92010 100644 --- a/include/openthread/platform/radio.h +++ b/include/openthread/platform/radio.h @@ -66,31 +66,30 @@ extern "C" { enum { - OT_RADIO_FRAME_MAX_SIZE = 127, ///< aMaxPHYPacketSize (IEEE 802.15.4-2006) - OT_RADIO_CHANNEL_MIN = 11, ///< 2.4 GHz IEEE 802.15.4-2006 - OT_RADIO_CHANNEL_MAX = 26, ///< 2.4 GHz IEEE 802.15.4-2006 - OT_RADIO_SUPPORTED_CHANNELS = 0xffff << OT_RADIO_CHANNEL_MIN, ///< 2.4 GHz IEEE 802.15.4-2006 - OT_RADIO_SYMBOLS_PER_OCTET = 2, ///< 2.4 GHz IEEE 802.15.4-2006 - OT_RADIO_BIT_RATE = 250000, ///< 2.4 GHz IEEE 802.15.4 (kilobits per second) + OT_RADIO_FRAME_MAX_SIZE = 127, ///< aMaxPHYPacketSize (IEEE 802.15.4-2006) + OT_RADIO_CHANNEL_MIN = 11, ///< 2.4 GHz IEEE 802.15.4-2006 + OT_RADIO_CHANNEL_MAX = 26, ///< 2.4 GHz IEEE 802.15.4-2006 + OT_RADIO_SUPPORTED_CHANNELS = 0xffff << OT_RADIO_CHANNEL_MIN, ///< 2.4 GHz IEEE 802.15.4-2006 + OT_RADIO_SYMBOLS_PER_OCTET = 2, ///< 2.4 GHz IEEE 802.15.4-2006 + OT_RADIO_BIT_RATE = 250000, ///< 2.4 GHz IEEE 802.15.4 (kilobits per second) - OT_RADIO_BITS_PER_OCTET = 8, ///< Number of bits per octet - OT_RADIO_SYMBOL_TIME = ((OT_RADIO_BITS_PER_OCTET / OT_RADIO_SYMBOLS_PER_OCTET) * 1000000) / OT_RADIO_BIT_RATE, + OT_RADIO_BITS_PER_OCTET = 8, ///< Number of bits per octet + OT_RADIO_SYMBOL_TIME = ((OT_RADIO_BITS_PER_OCTET / OT_RADIO_SYMBOLS_PER_OCTET) * 1000000) / OT_RADIO_BIT_RATE, - OT_RADIO_LQI_NONE = 0, ///< LQI measurement not supported - OT_RADIO_RSSI_INVALID = 127, ///< Invalid or unknown RSSI value + OT_RADIO_LQI_NONE = 0, ///< LQI measurement not supported + OT_RADIO_RSSI_INVALID = 127, ///< Invalid or unknown RSSI value }; /** * This enum represents radio capabilities. * */ -typedef enum otRadioCaps -{ - OT_RADIO_CAPS_NONE = 0, ///< None - OT_RADIO_CAPS_ACK_TIMEOUT = 1, ///< Radio supports AckTime event - OT_RADIO_CAPS_ENERGY_SCAN = 2, ///< Radio supports Energy Scans - OT_RADIO_CAPS_TRANSMIT_RETRIES = 4, ///< Radio supports transmission retry logic with collision avoidance (CSMA). - OT_RADIO_CAPS_CSMA_BACKOFF = 8, ///< Radio supports CSMA backoff for frame transmission (but no retry). +typedef enum otRadioCaps { + OT_RADIO_CAPS_NONE = 0, ///< None + OT_RADIO_CAPS_ACK_TIMEOUT = 1, ///< Radio supports AckTime event + OT_RADIO_CAPS_ENERGY_SCAN = 2, ///< Radio supports Energy Scans + OT_RADIO_CAPS_TRANSMIT_RETRIES = 4, ///< Radio supports transmission retry logic with collision avoidance (CSMA). + OT_RADIO_CAPS_CSMA_BACKOFF = 8, ///< Radio supports CSMA backoff for frame transmission (but no retry). } otRadioCaps; /** @@ -98,16 +97,16 @@ typedef enum otRadioCaps */ typedef struct otRadioFrame { - uint8_t *mPsdu; ///< The PSDU. - uint8_t mLength; ///< Length of the PSDU. - uint8_t mChannel; ///< Channel used to transmit/receive the frame. - int8_t mRssi ; ///< Received signal strength indicator in dBm for received frames. - uint8_t mLqi; ///< Link Quality Indicator for received frames. - uint8_t mMaxTxAttempts; ///< Max number of transmit attempts for an outbound frame. - bool mSecurityValid: 1; ///< Security Enabled flag is set and frame passes security checks. - bool mDidTX: 1; ///< Set to true if this frame sent from the radio. Ignored by radio driver. - bool mIsARetx: 1; ///< Set to true if this frame is a retransmission. Should be ignored by radio driver. - bool mIsCcaEnabled: 1; ///< Set to true if CCA must be enabled for this packet. False otherwise. + uint8_t *mPsdu; ///< The PSDU. + uint8_t mLength; ///< Length of the PSDU. + uint8_t mChannel; ///< Channel used to transmit/receive the frame. + int8_t mRssi; ///< Received signal strength indicator in dBm for received frames. + uint8_t mLqi; ///< Link Quality Indicator for received frames. + uint8_t mMaxTxAttempts; ///< Max number of transmit attempts for an outbound frame. + bool mSecurityValid : 1; ///< Security Enabled flag is set and frame passes security checks. + bool mDidTX : 1; ///< Set to true if this frame sent from the radio. Ignored by radio driver. + bool mIsARetx : 1; ///< Set to true if this frame is a retransmission. Should be ignored by radio driver. + bool mIsCcaEnabled : 1; ///< Set to true if CCA must be enabled for this packet. False otherwise. /** * The timestamp when the frame was received (milliseconds). @@ -128,8 +127,7 @@ typedef struct otRadioFrame * This structure represents the state of a radio. * Initially, a radio is in the Disabled state. */ -typedef enum otRadioState -{ +typedef enum otRadioState { OT_RADIO_STATE_DISABLED = 0, OT_RADIO_STATE_SLEEP = 1, OT_RADIO_STATE_RECEIVE = 2, @@ -429,8 +427,7 @@ extern void otPlatRadioTxStarted(otInstance *aInstance, otRadioFrame *aFrame); * aborted for other reasons. * */ -extern void otPlatRadioTxDone(otInstance *aInstance, otRadioFrame *aFrame, otRadioFrame *aAckFrame, - otError aError); +extern void otPlatRadioTxDone(otInstance *aInstance, otRadioFrame *aFrame, otRadioFrame *aAckFrame, otError aError); /** * Get the most recent RSSI measurement. @@ -558,7 +555,7 @@ int8_t otPlatRadioGetReceiveSensitivity(otInstance *aInstance); */ #ifdef __cplusplus -} // end of extern "C" +} // end of extern "C" #endif -#endif // RADIO_H_ +#endif // RADIO_H_ diff --git a/include/openthread/platform/random.h b/include/openthread/platform/random.h index 6c40e325e..666681ba9 100644 --- a/include/openthread/platform/random.h +++ b/include/openthread/platform/random.h @@ -84,7 +84,7 @@ otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength); */ #ifdef __cplusplus -} // end of extern "C" +} // end of extern "C" #endif -#endif // RANDOM_H_ +#endif // RANDOM_H_ diff --git a/include/openthread/platform/settings.h b/include/openthread/platform/settings.h index 265284ab7..fdf48d800 100644 --- a/include/openthread/platform/settings.h +++ b/include/openthread/platform/settings.h @@ -172,8 +172,7 @@ otError otPlatSettingsAbandonChange(otInstance *aInstance); * @retval OT_ERROR_NOT_IMPLEMENTED * This function is not implemented on this platform. */ -otError otPlatSettingsGet(otInstance *aInstance, uint16_t aKey, int aIndex, uint8_t *aValue, - uint16_t *aValueLength); +otError otPlatSettingsGet(otInstance *aInstance, uint16_t aKey, int aIndex, uint8_t *aValue, uint16_t *aValueLength); /// Sets or replaces the value of a setting /** This function sets or replaces the value of a setting @@ -276,7 +275,7 @@ void otPlatSettingsWipe(otInstance *aInstance); */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OT_PLATFORM_SETTINGS_H +#endif // OT_PLATFORM_SETTINGS_H diff --git a/include/openthread/platform/spi-slave.h b/include/openthread/platform/spi-slave.h index 829ed2709..58aa5b2fa 100644 --- a/include/openthread/platform/spi-slave.h +++ b/include/openthread/platform/spi-slave.h @@ -78,11 +78,13 @@ extern "C" { * @returns TRUE if after this call returns the platform should invoke the process callback `aProcessCallback`, * FALSE if there is nothing to process and no need to invoke the process callback. */ -typedef bool (*otPlatSpiSlaveTransactionCompleteCallback)(void *aContext, uint8_t *aOutputBuf, uint16_t aOutputBufLen, - uint8_t *aInputBuf, uint16_t aInputBufLen, +typedef bool (*otPlatSpiSlaveTransactionCompleteCallback)(void * aContext, + uint8_t *aOutputBuf, + uint16_t aOutputBufLen, + uint8_t *aInputBuf, + uint16_t aInputBufLen, uint16_t aTransactionLength); - /** * Invoked after a transaction complete callback is called and returns `TRUE` to do any further processing required. * Unlike `otPlatSpiSlaveTransactionCompleteCallback` which can be called from any OS context (e.g., ISR), this @@ -93,7 +95,6 @@ typedef bool (*otPlatSpiSlaveTransactionCompleteCallback)(void *aContext, uint8_ */ typedef void (*otPlatSpiSlaveTransactionProcessCallback)(void *aContext); - /** * Initialize the SPI slave interface. @@ -112,7 +113,8 @@ typedef void (*otPlatSpiSlaveTransactionProcessCallback)(void *aContext); * */ otError otPlatSpiSlaveEnable(otPlatSpiSlaveTransactionCompleteCallback aCompleteCallback, - otPlatSpiSlaveTransactionProcessCallback aProcessCallback, void *aContext); + otPlatSpiSlaveTransactionProcessCallback aProcessCallback, + void * aContext); /** * Shutdown and disable the SPI slave interface. @@ -160,8 +162,11 @@ void otPlatSpiSlaveDisable(void); * @retval OT_ERROR_INVALID_STATE otPlatSpiSlaveEnable() hasn't been called. * */ -otError otPlatSpiSlavePrepareTransaction(uint8_t *aOutputBuf, uint16_t aOutputBufLen, uint8_t *aInputBuf, - uint16_t aInputBufLen, bool aRequestTransactionFlag); +otError otPlatSpiSlavePrepareTransaction(uint8_t *aOutputBuf, + uint16_t aOutputBufLen, + uint8_t *aInputBuf, + uint16_t aInputBufLen, + bool aRequestTransactionFlag); /** * @} @@ -169,7 +174,7 @@ otError otPlatSpiSlavePrepareTransaction(uint8_t *aOutputBuf, uint16_t aOutputBu */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // SPI_SLAVE_H_ +#endif // SPI_SLAVE_H_ diff --git a/include/openthread/platform/toolchain.h b/include/openthread/platform/toolchain.h index 4283d066d..38bca7147 100644 --- a/include/openthread/platform/toolchain.h +++ b/include/openthread/platform/toolchain.h @@ -61,7 +61,6 @@ extern "C" { #endif - /** * @def OT_TOOL_PACKED_BEGIN * @@ -120,9 +119,9 @@ extern "C" { // http://www.keil.com/support/man/docs/armcc/armcc_chr1359124973480.htm #define OT_TOOL_PACKED_BEGIN -#define OT_TOOL_PACKED_FIELD __attribute__((packed)) -#define OT_TOOL_PACKED_END __attribute__((packed)) -#define OT_TOOL_WEAK __attribute__((weak)) +#define OT_TOOL_PACKED_FIELD __attribute__((packed)) +#define OT_TOOL_PACKED_END __attribute__((packed)) +#define OT_TOOL_WEAK __attribute__((weak)) #define OT_TOOL_ALIGN(X) @@ -132,23 +131,21 @@ extern "C" { #include "intrinsics.h" -#define OT_TOOL_PACKED_BEGIN __packed +#define OT_TOOL_PACKED_BEGIN __packed #define OT_TOOL_PACKED_FIELD #define OT_TOOL_PACKED_END -#define OT_TOOL_WEAK __weak - +#define OT_TOOL_WEAK __weak #define OT_TOOL_ALIGN(X) #elif defined(_MSC_VER) -#define OT_TOOL_PACKED_BEGIN __pragma(pack(push,1)) +#define OT_TOOL_PACKED_BEGIN __pragma(pack(push, 1)) #define OT_TOOL_PACKED_FIELD -#define OT_TOOL_PACKED_END __pragma(pack(pop)) +#define OT_TOOL_PACKED_END __pragma(pack(pop)) #define OT_TOOL_WEAK - -#define OT_TOOL_ALIGN(X) __declspec(align(4)) +#define OT_TOOL_ALIGN(X) __declspec(align(4)) #elif defined(__SDCC) @@ -235,40 +232,41 @@ extern "C" { #include -#define OT_UNUSED_VARIABLE(VARIABLE) \ - do \ - { \ - if (&VARIABLE == NULL) {} \ +#define OT_UNUSED_VARIABLE(VARIABLE) \ + do \ + { \ + if (&VARIABLE == NULL) \ + { \ + } \ } while (false) -#define OT_UNREACHABLE_CODE(CODE) \ - _Pragma("diag_suppress=Pe111") \ - _Pragma("diag_suppress=Pe128") \ - CODE \ - _Pragma("diag_default=Pe111") \ - _Pragma("diag_default=Pe128") +#define OT_UNREACHABLE_CODE(CODE) \ + _Pragma("diag_suppress=Pe111") _Pragma("diag_suppress=Pe128") CODE _Pragma("diag_default=Pe111") \ + _Pragma("diag_default=Pe128") #elif defined(__CC_ARM) #include -#define OT_UNUSED_VARIABLE(VARIABLE) \ - do \ - { \ - if (&VARIABLE == NULL) {} \ +#define OT_UNUSED_VARIABLE(VARIABLE) \ + do \ + { \ + if (&VARIABLE == NULL) \ + { \ + } \ } while (false) -#define OT_UNREACHABLE_CODE(CODE) CODE +#define OT_UNREACHABLE_CODE(CODE) CODE #else -#define OT_UNUSED_VARIABLE(VARIABLE) \ - do \ - { \ - (void)(VARIABLE); \ +#define OT_UNUSED_VARIABLE(VARIABLE) \ + do \ + { \ + (void)(VARIABLE); \ } while (false) -#define OT_UNREACHABLE_CODE(CODE) CODE +#define OT_UNREACHABLE_CODE(CODE) CODE #endif @@ -278,7 +276,7 @@ extern "C" { */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif #endif // TOOLCHAIN_H_ diff --git a/include/openthread/platform/uart.h b/include/openthread/platform/uart.h index 3a6bdb08d..faf178e6f 100644 --- a/include/openthread/platform/uart.h +++ b/include/openthread/platform/uart.h @@ -104,7 +104,7 @@ extern void otPlatUartReceived(const uint8_t *aBuf, uint16_t aBufLength); */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // UART_H_ +#endif // UART_H_ diff --git a/include/openthread/server.h b/include/openthread/server.h index af3ed7649..b93106d4d 100644 --- a/include/openthread/server.h +++ b/include/openthread/server.h @@ -60,8 +60,7 @@ extern "C" { * @param[inout] aDataLength On entry, size of the data buffer pointed to by @p aData. * On exit, number of copied bytes. */ -OTAPI otError OTCALL otServerGetNetDataLocal(otInstance *aInstance, bool aStable, uint8_t *aData, - uint8_t *aDataLength); +OTAPI otError OTCALL otServerGetNetDataLocal(otInstance *aInstance, bool aStable, uint8_t *aData, uint8_t *aDataLength); /** * Add a service configuration to the local network data. @@ -92,8 +91,10 @@ OTAPI otError OTCALL otServerAddService(otInstance *aInstance, const otServiceCo * @sa otServerAddService * @sa otServerRegister */ -OTAPI otError OTCALL otServerRemoveService(otInstance *aInstance, uint32_t aEnterpriseNumber, uint8_t *aServiceData, - uint8_t aServiceDataLength); +OTAPI otError OTCALL otServerRemoveService(otInstance *aInstance, + uint32_t aEnterpriseNumber, + uint8_t * aServiceData, + uint8_t aServiceDataLength); /** * This function gets the next service in the local Network Data. @@ -107,8 +108,9 @@ OTAPI otError OTCALL otServerRemoveService(otInstance *aInstance, uint32_t aEnte * @retval OT_ERROR_NOT_FOUND No subsequent service exists in the Thread Network Data. * */ -OTAPI otError OTCALL otServerGetNextService(otInstance *aInstance, otNetworkDataIterator *aIterator, - otServiceConfig *aConfig); +OTAPI otError OTCALL otServerGetNextService(otInstance * aInstance, + otNetworkDataIterator *aIterator, + otServiceConfig * aConfig); /** * This function gets the next service in the leader Network Data. @@ -122,8 +124,9 @@ OTAPI otError OTCALL otServerGetNextService(otInstance *aInstance, otNetworkData * @retval OT_ERROR_NOT_FOUND No subsequent service exists in the leader Network Data. * */ -OTAPI otError OTCALL otServerGetNextLeaderService(otInstance *aInstance, otNetworkDataIterator *aIterator, - otServiceConfig *aConfig); +OTAPI otError OTCALL otServerGetNextLeaderService(otInstance * aInstance, + otNetworkDataIterator *aIterator, + otServiceConfig * aConfig); /** * Immediately register the local network data with the Leader. @@ -143,7 +146,7 @@ OTAPI otError OTCALL otServerRegister(otInstance *aInstance); */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_SERVER_H_ +#endif // OPENTHREAD_SERVER_H_ diff --git a/include/openthread/tasklet.h b/include/openthread/tasklet.h index 3d915f1ed..da20da11b 100644 --- a/include/openthread/tasklet.h +++ b/include/openthread/tasklet.h @@ -82,7 +82,7 @@ extern void otTaskletsSignalPending(otInstance *aInstance); */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_TASKLET_H_ +#endif // OPENTHREAD_TASKLET_H_ diff --git a/include/openthread/thread.h b/include/openthread/thread.h index aebda6c42..f1dbd8db7 100644 --- a/include/openthread/thread.h +++ b/include/openthread/thread.h @@ -112,9 +112,13 @@ OTAPI bool OTCALL otThreadIsSingleton(otInstance *aInstance); * @retval OT_ERROR_BUSY Already performing an Thread Discovery. * */ -OTAPI otError OTCALL otThreadDiscover(otInstance *aInstance, uint32_t aScanChannels, uint16_t aPanId, bool aJoiner, - bool aEnableEui64Filtering, otHandleActiveScanResult aCallback, - void *aCallbackContext); +OTAPI otError OTCALL otThreadDiscover(otInstance * aInstance, + uint32_t aScanChannels, + uint16_t aPanId, + bool aJoiner, + bool aEnableEui64Filtering, + otHandleActiveScanResult aCallback, + void * aCallbackContext); /** * This function determines if an MLE Thread Discovery is currently in progress. @@ -390,8 +394,9 @@ OTAPI otError OTCALL otThreadBecomeChild(otInstance *aInstance); * @retval OT_ERROR_INVALID_ARGS @p aIterator or @p aInfo was NULL. * */ -OTAPI otError OTCALL otThreadGetNextNeighborInfo(otInstance *aInstance, otNeighborInfoIterator *aIterator, - otNeighborInfo *aInfo); +OTAPI otError OTCALL otThreadGetNextNeighborInfo(otInstance * aInstance, + otNeighborInfoIterator *aIterator, + otNeighborInfo * aInfo); /** * Get the device role. @@ -494,8 +499,7 @@ OTAPI otError OTCALL otThreadGetParentLastRssi(otInstance *aInstance, int8_t *aL * @param[in] aContext A pointer to application-specific context. * */ -typedef void (*otReceiveDiagnosticGetCallback)(otMessage *aMessage, const otMessageInfo *aMessageInfo, - void *aContext); +typedef void (*otReceiveDiagnosticGetCallback)(otMessage *aMessage, const otMessageInfo *aMessageInfo, void *aContext); /** * This function registers a callback to provide received raw Network Diagnostic Get response payload. @@ -506,8 +510,9 @@ typedef void (*otReceiveDiagnosticGetCallback)(otMessage *aMessage, const otMess * @param[in] aCallbackContext A pointer to application-specific context. * */ -void otThreadSetReceiveDiagnosticGetCallback(otInstance *aInstance, otReceiveDiagnosticGetCallback aCallback, - void *aCallbackContext); +void otThreadSetReceiveDiagnosticGetCallback(otInstance * aInstance, + otReceiveDiagnosticGetCallback aCallback, + void * aCallbackContext); /** * Send a Network Diagnostic Get request. @@ -518,8 +523,10 @@ void otThreadSetReceiveDiagnosticGetCallback(otInstance *aInstance, otReceiveDia * @param[in] aCount Number of types in aTlvTypes * */ -OTAPI otError OTCALL otThreadSendDiagnosticGet(otInstance *aInstance, const otIp6Address *aDestination, - const uint8_t aTlvTypes[], uint8_t aCount); +OTAPI otError OTCALL otThreadSendDiagnosticGet(otInstance * aInstance, + const otIp6Address *aDestination, + const uint8_t aTlvTypes[], + uint8_t aCount); /** * Send a Network Diagnostic Reset request. @@ -530,8 +537,10 @@ OTAPI otError OTCALL otThreadSendDiagnosticGet(otInstance *aInstance, const otIp * @param[in] aCount Number of types in aTlvTypes * */ -OTAPI otError OTCALL otThreadSendDiagnosticReset(otInstance *aInstance, const otIp6Address *aDestination, - const uint8_t aTlvTypes[], uint8_t aCount); +OTAPI otError OTCALL otThreadSendDiagnosticReset(otInstance * aInstance, + const otIp6Address *aDestination, + const uint8_t aTlvTypes[], + uint8_t aCount); /** * Get the IPv6 counters. @@ -549,7 +558,7 @@ OTAPI const otIpCounters *OTCALL otThreadGetIp6Counters(otInstance *aInstance); */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_THREAD_H_ +#endif // OPENTHREAD_THREAD_H_ diff --git a/include/openthread/thread_ftd.h b/include/openthread/thread_ftd.h index 5d36cb1f7..91d509c17 100644 --- a/include/openthread/thread_ftd.h +++ b/include/openthread/thread_ftd.h @@ -382,8 +382,10 @@ OTAPI otError OTCALL otThreadGetChildInfoByIndex(otInstance *aInstance, uint8_t * @sa otThreadGetChildInfoByIndex * */ -otError otThreadGetChildNextIp6Address(otInstance *aInstance, uint8_t aChildIndex, otChildIp6AddressIterator *aIterator, - otIp6Address *aAddress); +otError otThreadGetChildNextIp6Address(otInstance * aInstance, + uint8_t aChildIndex, + otChildIp6AddressIterator *aIterator, + otIp6Address * aAddress); /** * Get the current Router ID Sequence. @@ -489,10 +491,9 @@ OTAPI otError OTCALL otThreadSetParentPriority(otInstance *aInstance, int8_t aPa * removed. * */ -typedef enum otThreadChildTableEvent -{ - OT_THREAD_CHILD_TABLE_EVENT_CHILD_ADDED, ///< A child is being added. - OT_THREAD_CHILD_TABLE_EVENT_CHILD_REMOVED, ///< A child is being removed. +typedef enum otThreadChildTableEvent { + OT_THREAD_CHILD_TABLE_EVENT_CHILD_ADDED, ///< A child is being added. + OT_THREAD_CHILD_TABLE_EVENT_CHILD_REMOVED, ///< A child is being removed. } otThreadChildTableEvent; /** @@ -533,7 +534,7 @@ void otThreadSetChildTableCallback(otInstance *aInstance, otThreadChildTableCall */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_THREAD_FTD_H_ +#endif // OPENTHREAD_THREAD_FTD_H_ diff --git a/include/openthread/tmf_proxy.h b/include/openthread/tmf_proxy.h index b710d831f..92b1eea20 100644 --- a/include/openthread/tmf_proxy.h +++ b/include/openthread/tmf_proxy.h @@ -60,8 +60,7 @@ extern "C" { * @param[in] aContext A pointer to application-specific context. * */ -typedef void (*otTmfProxyStreamHandler)(otMessage *aMessage, uint16_t aLocator, uint16_t aPort, - void *aContext); +typedef void (*otTmfProxyStreamHandler)(otMessage *aMessage, uint16_t aLocator, uint16_t aPort, void *aContext); /** * Start the TMF proxy. @@ -101,8 +100,7 @@ otError otTmfProxyStop(otInstance *aInstance); * @warning No matter the call success or fail, the message is freed. * */ -otError otTmfProxySend(otInstance *aInstance, otMessage *aMessage, - uint16_t aLocator, uint16_t aPort); +otError otTmfProxySend(otInstance *aInstance, otMessage *aMessage, uint16_t aLocator, uint16_t aPort); /** * Get the TMF proxy status (enabled/disabled) @@ -119,7 +117,7 @@ bool otTmfProxyIsEnabled(otInstance *aInstance); */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_TMF_PROXY_H_ +#endif // OPENTHREAD_TMF_PROXY_H_ diff --git a/include/openthread/types.h b/include/openthread/types.h index 62b33d67d..10d10272d 100644 --- a/include/openthread/types.h +++ b/include/openthread/types.h @@ -35,8 +35,8 @@ #ifndef OPENTHREAD_TYPES_H_ #define OPENTHREAD_TYPES_H_ -#include #include +#include #ifdef OTDLL #include #endif @@ -48,7 +48,7 @@ extern "C" { #endif #ifdef _WIN32 -#pragma warning(disable:4214) // nonstandard extension used: bit field types other than int +#pragma warning(disable : 4214) // nonstandard extension used: bit field types other than int #ifdef _KERNEL_MODE #include #else @@ -92,8 +92,7 @@ typedef struct otDeviceList /** * This enumeration represents error codes used throughout OpenThread. */ -typedef enum otError -{ +typedef enum otError { /** * No error. */ @@ -271,14 +270,14 @@ typedef enum otError OT_ERROR_GENERIC = 255, } otError; -#define OT_IP6_IID_SIZE 8 ///< Size of an IPv6 Interface Identifier (bytes) +#define OT_IP6_IID_SIZE 8 ///< Size of an IPv6 Interface Identifier (bytes) -#define OT_MASTER_KEY_SIZE 16 ///< Size of the Thread Master Key (bytes) +#define OT_MASTER_KEY_SIZE 16 ///< Size of the Thread Master Key (bytes) /** * Maximum Number of Network Diagnostic TLV Types to Request or Reset. */ -#define OT_NETWORK_DIAGNOSTIC_TYPELIST_MAX_ENTRIES 19 +#define OT_NETWORK_DIAGNOSTIC_TYPELIST_MAX_ENTRIES 19 /** * @struct otMasterKey @@ -289,7 +288,7 @@ typedef enum otError OT_TOOL_PACKED_BEGIN struct otMasterKey { - uint8_t m8[OT_MASTER_KEY_SIZE]; ///< Byte values + uint8_t m8[OT_MASTER_KEY_SIZE]; ///< Byte values } OT_TOOL_PACKED_END; /** @@ -298,7 +297,7 @@ struct otMasterKey */ typedef struct otMasterKey otMasterKey; -#define OT_NETWORK_NAME_MAX_SIZE 16 ///< Maximum size of the Thread Network Name field (bytes) +#define OT_NETWORK_NAME_MAX_SIZE 16 ///< Maximum size of the Thread Network Name field (bytes) /** * This structure represents a Network Name. @@ -306,10 +305,10 @@ typedef struct otMasterKey otMasterKey; */ typedef struct otNetworkName { - char m8[OT_NETWORK_NAME_MAX_SIZE + 1]; ///< Byte values + char m8[OT_NETWORK_NAME_MAX_SIZE + 1]; ///< Byte values } otNetworkName; -#define OT_EXT_PAN_ID_SIZE 8 ///< Size of a Thread PAN ID (bytes) +#define OT_EXT_PAN_ID_SIZE 8 ///< Size of a Thread PAN ID (bytes) /** * This structure represents an Extended PAN ID. @@ -317,10 +316,10 @@ typedef struct otNetworkName */ typedef struct otExtendedPanId { - uint8_t m8[OT_EXT_PAN_ID_SIZE]; ///< Byte values + uint8_t m8[OT_EXT_PAN_ID_SIZE]; ///< Byte values } otExtendedPanId; -#define OT_MESH_LOCAL_PREFIX_SIZE 8 ///< Size of the Mesh Local Prefix (bytes) +#define OT_MESH_LOCAL_PREFIX_SIZE 8 ///< Size of the Mesh Local Prefix (bytes) /** * This structure represents a Mesh Local Prefix. @@ -328,31 +327,31 @@ typedef struct otExtendedPanId */ typedef struct otMeshLocalPrefix { - uint8_t m8[OT_MESH_LOCAL_PREFIX_SIZE]; ///< Byte values + uint8_t m8[OT_MESH_LOCAL_PREFIX_SIZE]; ///< Byte values } otMeshLocalPrefix; -#define OT_PSKC_MAX_SIZE 16 ///< Maximum size of the PSKc (bytes) +#define OT_PSKC_MAX_SIZE 16 ///< Maximum size of the PSKc (bytes) -#define OT_COMMISSIONING_PASSPHRASE_MIN_SIZE 6 ///< Minimum size of the Commissioning Passphrase -#define OT_COMMISSIONING_PASSPHRASE_MAX_SIZE 255 ///< Maximum size of the Commissioning Passphrase +#define OT_COMMISSIONING_PASSPHRASE_MIN_SIZE 6 ///< Minimum size of the Commissioning Passphrase +#define OT_COMMISSIONING_PASSPHRASE_MAX_SIZE 255 ///< Maximum size of the Commissioning Passphrase /** - * This structure represents PSKc. - * - */ + * This structure represents PSKc. + * + */ typedef struct otPSKc { - uint8_t m8[OT_PSKC_MAX_SIZE]; ///< Byte values + uint8_t m8[OT_PSKC_MAX_SIZE]; ///< Byte values } otPSKc; /** - * This structure represent Security Policy. - * - */ + * This structure represent Security Policy. + * + */ typedef struct otSecurityPolicy { - uint16_t mRotationTime; ///< The value for thrKeyRotation in units of hours - uint8_t mFlags; ///< Flags as defined in Thread 1.1 Section 8.10.1.15 + uint16_t mRotationTime; ///< The value for thrKeyRotation in units of hours + uint8_t mFlags; ///< Flags as defined in Thread 1.1 Section 8.10.1.15 } otSecurityPolicy; /** @@ -361,17 +360,17 @@ typedef struct otSecurityPolicy */ enum { - OT_SECURITY_POLICY_OBTAIN_MASTER_KEY = 1 << 7, ///< Obtaining the Master Key - OT_SECURITY_POLICY_NATIVE_COMMISSIONING = 1 << 6, ///< Native Commissioning - OT_SECURITY_POLICY_ROUTERS = 1 << 5, ///< Routers enabled - OT_SECURITY_POLICY_EXTERNAL_COMMISSIONER = 1 << 4, ///< External Commissioner allowed - OT_SECURITY_POLICY_BEACONS = 1 << 3, ///< Beacons enabled + OT_SECURITY_POLICY_OBTAIN_MASTER_KEY = 1 << 7, ///< Obtaining the Master Key + OT_SECURITY_POLICY_NATIVE_COMMISSIONING = 1 << 6, ///< Native Commissioning + OT_SECURITY_POLICY_ROUTERS = 1 << 5, ///< Routers enabled + OT_SECURITY_POLICY_EXTERNAL_COMMISSIONER = 1 << 4, ///< External Commissioner allowed + OT_SECURITY_POLICY_BEACONS = 1 << 3, ///< Beacons enabled }; /** - * This type represents Channel Mask Page 0. - * - */ + * This type represents Channel Mask Page 0. + * + */ typedef uint32_t otChannelMaskPage0; /** @@ -386,7 +385,7 @@ typedef uint16_t otPanId; */ typedef uint16_t otShortAddress; -#define OT_EXT_ADDRESS_SIZE 8 ///< Size of an IEEE 802.15.4 Extended Address (bytes) +#define OT_EXT_ADDRESS_SIZE 8 ///< Size of an IEEE 802.15.4 Extended Address (bytes) /** * @struct otExtAddress @@ -397,7 +396,7 @@ typedef uint16_t otShortAddress; OT_TOOL_PACKED_BEGIN struct otExtAddress { - uint8_t m8[OT_EXT_ADDRESS_SIZE]; ///< IEEE 802.15.4 Extended Address bytes + uint8_t m8[OT_EXT_ADDRESS_SIZE]; ///< IEEE 802.15.4 Extended Address bytes } OT_TOOL_PACKED_END; /** @@ -406,8 +405,8 @@ struct otExtAddress */ typedef struct otExtAddress otExtAddress; -#define OT_IP6_PREFIX_SIZE 8 ///< Size of an IPv6 prefix (bytes) -#define OT_IP6_ADDRESS_SIZE 16 ///< Size of an IPv6 address (bytes) +#define OT_IP6_PREFIX_SIZE 8 ///< Size of an IPv6 prefix (bytes) +#define OT_IP6_ADDRESS_SIZE 16 ///< Size of an IPv6 address (bytes) /** * @struct otIp6Address @@ -420,10 +419,10 @@ struct otIp6Address { union OT_TOOL_PACKED_FIELD { - uint8_t m8[OT_IP6_ADDRESS_SIZE]; ///< 8-bit fields - uint16_t m16[OT_IP6_ADDRESS_SIZE / sizeof(uint16_t)]; ///< 16-bit fields - uint32_t m32[OT_IP6_ADDRESS_SIZE / sizeof(uint32_t)]; ///< 32-bit fields - } mFields; ///< IPv6 accessor fields + uint8_t m8[OT_IP6_ADDRESS_SIZE]; ///< 8-bit fields + uint16_t m16[OT_IP6_ADDRESS_SIZE / sizeof(uint16_t)]; ///< 16-bit fields + uint32_t m32[OT_IP6_ADDRESS_SIZE / sizeof(uint32_t)]; ///< 32-bit fields + } mFields; ///< IPv6 accessor fields } OT_TOOL_PACKED_END; /** @@ -480,32 +479,31 @@ typedef struct otMessageInfo */ typedef struct otMessage { - struct otMessage *mNext; ///< A pointer to the next Message buffer. + struct otMessage *mNext; ///< A pointer to the next Message buffer. } otMessage; +#define OT_PANID_BROADCAST 0xffff ///< IEEE 802.15.4 Broadcast PAN ID -#define OT_PANID_BROADCAST 0xffff ///< IEEE 802.15.4 Broadcast PAN ID +#define OT_CHANNEL_11_MASK (1 << 11) ///< Channel 11 +#define OT_CHANNEL_12_MASK (1 << 12) ///< Channel 12 +#define OT_CHANNEL_13_MASK (1 << 13) ///< Channel 13 +#define OT_CHANNEL_14_MASK (1 << 14) ///< Channel 14 +#define OT_CHANNEL_15_MASK (1 << 15) ///< Channel 15 +#define OT_CHANNEL_16_MASK (1 << 16) ///< Channel 16 +#define OT_CHANNEL_17_MASK (1 << 17) ///< Channel 17 +#define OT_CHANNEL_18_MASK (1 << 18) ///< Channel 18 +#define OT_CHANNEL_19_MASK (1 << 19) ///< Channel 19 +#define OT_CHANNEL_20_MASK (1 << 20) ///< Channel 20 +#define OT_CHANNEL_21_MASK (1 << 21) ///< Channel 21 +#define OT_CHANNEL_22_MASK (1 << 22) ///< Channel 22 +#define OT_CHANNEL_23_MASK (1 << 23) ///< Channel 23 +#define OT_CHANNEL_24_MASK (1 << 24) ///< Channel 24 +#define OT_CHANNEL_25_MASK (1 << 25) ///< Channel 25 +#define OT_CHANNEL_26_MASK (1 << 26) ///< Channel 26 -#define OT_CHANNEL_11_MASK (1 << 11) ///< Channel 11 -#define OT_CHANNEL_12_MASK (1 << 12) ///< Channel 12 -#define OT_CHANNEL_13_MASK (1 << 13) ///< Channel 13 -#define OT_CHANNEL_14_MASK (1 << 14) ///< Channel 14 -#define OT_CHANNEL_15_MASK (1 << 15) ///< Channel 15 -#define OT_CHANNEL_16_MASK (1 << 16) ///< Channel 16 -#define OT_CHANNEL_17_MASK (1 << 17) ///< Channel 17 -#define OT_CHANNEL_18_MASK (1 << 18) ///< Channel 18 -#define OT_CHANNEL_19_MASK (1 << 19) ///< Channel 19 -#define OT_CHANNEL_20_MASK (1 << 20) ///< Channel 20 -#define OT_CHANNEL_21_MASK (1 << 21) ///< Channel 21 -#define OT_CHANNEL_22_MASK (1 << 22) ///< Channel 22 -#define OT_CHANNEL_23_MASK (1 << 23) ///< Channel 23 -#define OT_CHANNEL_24_MASK (1 << 24) ///< Channel 24 -#define OT_CHANNEL_25_MASK (1 << 25) ///< Channel 25 -#define OT_CHANNEL_26_MASK (1 << 26) ///< Channel 26 +#define OT_CHANNEL_ALL 0xffffffff ///< All channels -#define OT_CHANNEL_ALL 0xffffffff ///< All channels - -#define OT_STEERING_DATA_MAX_LENGTH 16 ///< Max steering data length (bytes) +#define OT_STEERING_DATA_MAX_LENGTH 16 ///< Max steering data length (bytes) /** * This structure represents the steering data. @@ -513,8 +511,8 @@ typedef struct otMessage */ typedef struct otSteeringData { - uint8_t mLength; ///< Length of steering data (bytes) - uint8_t m8[OT_STEERING_DATA_MAX_LENGTH]; ///< Byte values + uint8_t mLength; ///< Length of steering data (bytes) + uint8_t m8[OT_STEERING_DATA_MAX_LENGTH]; ///< Byte values } otSteeringData; /** @@ -523,18 +521,18 @@ typedef struct otSteeringData */ typedef struct otActiveScanResult { - otExtAddress mExtAddress; ///< IEEE 802.15.4 Extended Address - otNetworkName mNetworkName; ///< Thread Network Name - otExtendedPanId mExtendedPanId; ///< Thread Extended PAN ID - otSteeringData mSteeringData; ///< Steering Data - uint16_t mPanId; ///< IEEE 802.15.4 PAN ID - uint16_t mJoinerUdpPort; ///< Joiner UDP Port - uint8_t mChannel; ///< IEEE 802.15.4 Channel - int8_t mRssi; ///< RSSI (dBm) - uint8_t mLqi; ///< LQI - unsigned int mVersion : 4; ///< Version - bool mIsNative : 1; ///< Native Commissioner flag - bool mIsJoinable : 1; ///< Joining Permitted flag + otExtAddress mExtAddress; ///< IEEE 802.15.4 Extended Address + otNetworkName mNetworkName; ///< Thread Network Name + otExtendedPanId mExtendedPanId; ///< Thread Extended PAN ID + otSteeringData mSteeringData; ///< Steering Data + uint16_t mPanId; ///< IEEE 802.15.4 PAN ID + uint16_t mJoinerUdpPort; ///< Joiner UDP Port + uint8_t mChannel; ///< IEEE 802.15.4 Channel + int8_t mRssi; ///< RSSI (dBm) + uint8_t mLqi; ///< LQI + unsigned int mVersion : 4; ///< Version + bool mIsNative : 1; ///< Native Commissioner flag + bool mIsJoinable : 1; ///< Joining Permitted flag } otActiveScanResult; /** @@ -543,8 +541,8 @@ typedef struct otActiveScanResult */ typedef struct otEnergyScanResult { - uint8_t mChannel; ///< IEEE 802.15.4 Channel - int8_t mMaxRssi; ///< The max RSSI (dBm) + uint8_t mChannel; ///< IEEE 802.15.4 Channel + int8_t mMaxRssi; ///< The max RSSI (dBm) } otEnergyScanResult; /** @@ -553,31 +551,31 @@ typedef struct otEnergyScanResult */ typedef struct otOperationalDataset { - uint64_t mActiveTimestamp; ///< Active Timestamp - uint64_t mPendingTimestamp; ///< Pending Timestamp - otMasterKey mMasterKey; ///< Network Master Key - otNetworkName mNetworkName; ///< Network Name - otExtendedPanId mExtendedPanId; ///< Extended PAN ID - otMeshLocalPrefix mMeshLocalPrefix; ///< Mesh Local Prefix - uint32_t mDelay; ///< Delay Timer - otPanId mPanId; ///< PAN ID - uint16_t mChannel; ///< Channel - otPSKc mPSKc; ///< PSKc - otSecurityPolicy mSecurityPolicy; ///< Security Policy - otChannelMaskPage0 mChannelMaskPage0; ///< Channel Mask Page 0 + uint64_t mActiveTimestamp; ///< Active Timestamp + uint64_t mPendingTimestamp; ///< Pending Timestamp + otMasterKey mMasterKey; ///< Network Master Key + otNetworkName mNetworkName; ///< Network Name + otExtendedPanId mExtendedPanId; ///< Extended PAN ID + otMeshLocalPrefix mMeshLocalPrefix; ///< Mesh Local Prefix + uint32_t mDelay; ///< Delay Timer + otPanId mPanId; ///< PAN ID + uint16_t mChannel; ///< Channel + otPSKc mPSKc; ///< PSKc + otSecurityPolicy mSecurityPolicy; ///< Security Policy + otChannelMaskPage0 mChannelMaskPage0; ///< Channel Mask Page 0 - bool mIsActiveTimestampSet : 1; ///< TRUE if Active Timestamp is set, FALSE otherwise. - bool mIsPendingTimestampSet : 1; ///< TRUE if Pending Timestamp is set, FALSE otherwise. - bool mIsMasterKeySet : 1; ///< TRUE if Network Master Key is set, FALSE otherwise. - bool mIsNetworkNameSet : 1; ///< TRUE if Network Name is set, FALSE otherwise. - bool mIsExtendedPanIdSet : 1; ///< TRUE if Extended PAN ID is set, FALSE otherwise. - bool mIsMeshLocalPrefixSet : 1; ///< TRUE if Mesh Local Prefix is set, FALSE otherwise. - bool mIsDelaySet : 1; ///< TRUE if Delay Timer is set, FALSE otherwise. - bool mIsPanIdSet : 1; ///< TRUE if PAN ID is set, FALSE otherwise. - bool mIsChannelSet : 1; ///< TRUE if Channel is set, FALSE otherwise. - bool mIsPSKcSet : 1; ///< TRUE if PSKc is set, FALSE otherwise. - bool mIsSecurityPolicySet : 1; ///< TRUE if Security Policy is set, FALSE otherwise. - bool mIsChannelMaskPage0Set : 1; ///< TRUE if Channel Mask Page 0 is set, FALSE otherwise. + bool mIsActiveTimestampSet : 1; ///< TRUE if Active Timestamp is set, FALSE otherwise. + bool mIsPendingTimestampSet : 1; ///< TRUE if Pending Timestamp is set, FALSE otherwise. + bool mIsMasterKeySet : 1; ///< TRUE if Network Master Key is set, FALSE otherwise. + bool mIsNetworkNameSet : 1; ///< TRUE if Network Name is set, FALSE otherwise. + bool mIsExtendedPanIdSet : 1; ///< TRUE if Extended PAN ID is set, FALSE otherwise. + bool mIsMeshLocalPrefixSet : 1; ///< TRUE if Mesh Local Prefix is set, FALSE otherwise. + bool mIsDelaySet : 1; ///< TRUE if Delay Timer is set, FALSE otherwise. + bool mIsPanIdSet : 1; ///< TRUE if PAN ID is set, FALSE otherwise. + bool mIsChannelSet : 1; ///< TRUE if Channel is set, FALSE otherwise. + bool mIsPSKcSet : 1; ///< TRUE if PSKc is set, FALSE otherwise. + bool mIsSecurityPolicySet : 1; ///< TRUE if Security Policy is set, FALSE otherwise. + bool mIsChannelMaskPage0Set : 1; ///< TRUE if Channel Mask Page 0 is set, FALSE otherwise. } otOperationalDataset; /** @@ -586,59 +584,58 @@ typedef struct otOperationalDataset */ typedef struct otCommissioningDataset { - uint16_t mLocator; ///< Border Router RLOC16 - uint16_t mSessionId; ///< Commissioner Session Id - otSteeringData mSteeringData; ///< Steering Data - uint16_t mJoinerUdpPort; ///< Joiner UDP Port + uint16_t mLocator; ///< Border Router RLOC16 + uint16_t mSessionId; ///< Commissioner Session Id + otSteeringData mSteeringData; ///< Steering Data + uint16_t mJoinerUdpPort; ///< Joiner UDP Port - bool mIsLocatorSet : 1; ///< TRUE if Border Router RLOC16 is set, FALSE otherwise. - bool mIsSessionIdSet: 1; ///< TRUE if Commissioner Session Id is set, FALSE otherwise. - bool mIsSteeringDataSet : 1; ///< TRUE if Steering Data is set, FALSE otherwise. - bool mIsJoinerUdpPortSet : 1; ///< TRUE if Joiner UDP Port is set, FALSE otherwise. + bool mIsLocatorSet : 1; ///< TRUE if Border Router RLOC16 is set, FALSE otherwise. + bool mIsSessionIdSet : 1; ///< TRUE if Commissioner Session Id is set, FALSE otherwise. + bool mIsSteeringDataSet : 1; ///< TRUE if Steering Data is set, FALSE otherwise. + bool mIsJoinerUdpPortSet : 1; ///< TRUE if Joiner UDP Port is set, FALSE otherwise. } otCommissioningDataset; /** * This enumeration represents meshcop TLV types. * */ -typedef enum otMeshcopTlvType -{ - OT_MESHCOP_TLV_CHANNEL = 0, ///< meshcop Channel TLV - OT_MESHCOP_TLV_PANID = 1, ///< meshcop Pan Id TLV - OT_MESHCOP_TLV_EXTPANID = 2, ///< meshcop Extended Pan Id TLV - OT_MESHCOP_TLV_NETWORKNAME = 3, ///< meshcop Network Name TLV - OT_MESHCOP_TLV_PSKC = 4, ///< meshcop PSKc TLV - OT_MESHCOP_TLV_MASTERKEY = 5, ///< meshcop Network Master Key TLV - OT_MESHCOP_TLV_NETWORK_KEY_SEQUENCE = 6, ///< meshcop Network Key Sequence TLV - OT_MESHCOP_TLV_MESHLOCALPREFIX = 7, ///< meshcop Mesh Local Prefix TLV - OT_MESHCOP_TLV_STEERING_DATA = 8, ///< meshcop Steering Data TLV - OT_MESHCOP_TLV_BORDER_AGENT_RLOC = 9, ///< meshcop Border Agent Locator TLV - OT_MESHCOP_TLV_COMMISSIONER_ID = 10, ///< meshcop Commissioner ID TLV - OT_MESHCOP_TLV_COMM_SESSION_ID = 11, ///< meshcop Commissioner Session ID TLV - OT_MESHCOP_TLV_SECURITYPOLICY = 12, ///< meshcop Security Policy TLV - OT_MESHCOP_TLV_GET = 13, ///< meshcop Get TLV - OT_MESHCOP_TLV_ACTIVETIMESTAMP = 14, ///< meshcop Active Timestamp TLV - OT_MESHCOP_TLV_STATE = 16, ///< meshcop State TLV - OT_MESHCOP_TLV_JOINER_DTLS = 17, ///< meshcop Joiner DTLS Encapsulation TLV - OT_MESHCOP_TLV_JOINER_UDP_PORT = 18, ///< meshcop Joiner UDP Port TLV - OT_MESHCOP_TLV_JOINER_IID = 19, ///< meshcop Joiner IID TLV - OT_MESHCOP_TLV_JOINER_RLOC = 20, ///< meshcop Joiner Router Locator TLV - OT_MESHCOP_TLV_JOINER_ROUTER_KEK = 21, ///< meshcop Joiner Router KEK TLV - OT_MESHCOP_TLV_PROVISIONING_URL = 32, ///< meshcop Provisioning URL TLV - OT_MESHCOP_TLV_VENDOR_NAME_TLV = 33, ///< meshcop Vendor Name TLV - OT_MESHCOP_TLV_VENDOR_MODEL_TLV = 34, ///< meshcop Vendor Model TLV - OT_MESHCOP_TLV_VENDOR_SW_VERSION_TLV = 35, ///< meshcop Vendor SW Version TLV - OT_MESHCOP_TLV_VENDOR_DATA_TLV = 36, ///< meshcop Vendor Data TLV - OT_MESHCOP_TLV_VENDOR_STACK_VERSION_TLV = 37, ///< meshcop Vendor Stack Version TLV - OT_MESHCOP_TLV_PENDINGTIMESTAMP = 51, ///< meshcop Pending Timestamp TLV - OT_MESHCOP_TLV_DELAYTIMER = 52, ///< meshcop Delay Timer TLV - OT_MESHCOP_TLV_CHANNELMASK = 53, ///< meshcop Channel Mask TLV - OT_MESHCOP_TLV_COUNT = 54, ///< meshcop Count TLV - OT_MESHCOP_TLV_PERIOD = 55, ///< meshcop Period TLV - OT_MESHCOP_TLV_SCAN_DURATION = 56, ///< meshcop Scan Duration TLV - OT_MESHCOP_TLV_ENERGY_LIST = 57, ///< meshcop Energy List TLV - OT_MESHCOP_TLV_DISCOVERYREQUEST = 128, ///< meshcop Discovery Request TLV - OT_MESHCOP_TLV_DISCOVERYRESPONSE = 129, ///< meshcop Discovery Response TLV +typedef enum otMeshcopTlvType { + OT_MESHCOP_TLV_CHANNEL = 0, ///< meshcop Channel TLV + OT_MESHCOP_TLV_PANID = 1, ///< meshcop Pan Id TLV + OT_MESHCOP_TLV_EXTPANID = 2, ///< meshcop Extended Pan Id TLV + OT_MESHCOP_TLV_NETWORKNAME = 3, ///< meshcop Network Name TLV + OT_MESHCOP_TLV_PSKC = 4, ///< meshcop PSKc TLV + OT_MESHCOP_TLV_MASTERKEY = 5, ///< meshcop Network Master Key TLV + OT_MESHCOP_TLV_NETWORK_KEY_SEQUENCE = 6, ///< meshcop Network Key Sequence TLV + OT_MESHCOP_TLV_MESHLOCALPREFIX = 7, ///< meshcop Mesh Local Prefix TLV + OT_MESHCOP_TLV_STEERING_DATA = 8, ///< meshcop Steering Data TLV + OT_MESHCOP_TLV_BORDER_AGENT_RLOC = 9, ///< meshcop Border Agent Locator TLV + OT_MESHCOP_TLV_COMMISSIONER_ID = 10, ///< meshcop Commissioner ID TLV + OT_MESHCOP_TLV_COMM_SESSION_ID = 11, ///< meshcop Commissioner Session ID TLV + OT_MESHCOP_TLV_SECURITYPOLICY = 12, ///< meshcop Security Policy TLV + OT_MESHCOP_TLV_GET = 13, ///< meshcop Get TLV + OT_MESHCOP_TLV_ACTIVETIMESTAMP = 14, ///< meshcop Active Timestamp TLV + OT_MESHCOP_TLV_STATE = 16, ///< meshcop State TLV + OT_MESHCOP_TLV_JOINER_DTLS = 17, ///< meshcop Joiner DTLS Encapsulation TLV + OT_MESHCOP_TLV_JOINER_UDP_PORT = 18, ///< meshcop Joiner UDP Port TLV + OT_MESHCOP_TLV_JOINER_IID = 19, ///< meshcop Joiner IID TLV + OT_MESHCOP_TLV_JOINER_RLOC = 20, ///< meshcop Joiner Router Locator TLV + OT_MESHCOP_TLV_JOINER_ROUTER_KEK = 21, ///< meshcop Joiner Router KEK TLV + OT_MESHCOP_TLV_PROVISIONING_URL = 32, ///< meshcop Provisioning URL TLV + OT_MESHCOP_TLV_VENDOR_NAME_TLV = 33, ///< meshcop Vendor Name TLV + OT_MESHCOP_TLV_VENDOR_MODEL_TLV = 34, ///< meshcop Vendor Model TLV + OT_MESHCOP_TLV_VENDOR_SW_VERSION_TLV = 35, ///< meshcop Vendor SW Version TLV + OT_MESHCOP_TLV_VENDOR_DATA_TLV = 36, ///< meshcop Vendor Data TLV + OT_MESHCOP_TLV_VENDOR_STACK_VERSION_TLV = 37, ///< meshcop Vendor Stack Version TLV + OT_MESHCOP_TLV_PENDINGTIMESTAMP = 51, ///< meshcop Pending Timestamp TLV + OT_MESHCOP_TLV_DELAYTIMER = 52, ///< meshcop Delay Timer TLV + OT_MESHCOP_TLV_CHANNELMASK = 53, ///< meshcop Channel Mask TLV + OT_MESHCOP_TLV_COUNT = 54, ///< meshcop Count TLV + OT_MESHCOP_TLV_PERIOD = 55, ///< meshcop Period TLV + OT_MESHCOP_TLV_SCAN_DURATION = 56, ///< meshcop Scan Duration TLV + OT_MESHCOP_TLV_ENERGY_LIST = 57, ///< meshcop Energy List TLV + OT_MESHCOP_TLV_DISCOVERYREQUEST = 128, ///< meshcop Discovery Request TLV + OT_MESHCOP_TLV_DISCOVERYRESPONSE = 129, ///< meshcop Discovery Response TLV } otMeshcopTlvType; /** @@ -674,8 +671,8 @@ typedef struct otLinkModeConfig OT_TOOL_PACKED_BEGIN struct otIp6Prefix { - otIp6Address mPrefix; ///< The IPv6 prefix. - uint8_t mLength; ///< The IPv6 prefix length. + otIp6Address mPrefix; ///< The IPv6 prefix. + uint8_t mLength; ///< The IPv6 prefix length. } OT_TOOL_PACKED_END; /** @@ -683,9 +680,9 @@ struct otIp6Prefix */ typedef struct otIp6Prefix otIp6Prefix; -#define OT_NETWORK_DATA_ITERATOR_INIT 0 ///< Initializer for otNetworkDataIterator. +#define OT_NETWORK_DATA_ITERATOR_INIT 0 ///< Initializer for otNetworkDataIterator. -typedef uint32_t otNetworkDataIterator; ///< Used to iterate through Network Data information. +typedef uint32_t otNetworkDataIterator; ///< Used to iterate through Network Data information. /** * This structure represents a Border Router configuration. @@ -783,15 +780,15 @@ typedef struct otExternalRouteConfig /** * Defines valid values for member mPreference in otExternalRouteConfig and otBorderRouterConfig. */ -typedef enum otRoutePreference -{ - OT_ROUTE_PREFERENCE_LOW = -1, ///< Low route preference. - OT_ROUTE_PREFERENCE_MED = 0, ///< Medium route preference. - OT_ROUTE_PREFERENCE_HIGH = 1, ///< High route preference. +typedef enum otRoutePreference { + OT_ROUTE_PREFERENCE_LOW = -1, ///< Low route preference. + OT_ROUTE_PREFERENCE_MED = 0, ///< Medium route preference. + OT_ROUTE_PREFERENCE_HIGH = 1, ///< High route preference. } otRoutePreference; -#define OT_SERVICE_DATA_MAX_SIZE 252 ///< Maximum size of Service Data in bytes. -#define OT_SERVER_DATA_MAX_SIZE 248 ///< Maximum size of Server Data in bytes. This is theoretical limit, practical one is much lower. +#define OT_SERVICE_DATA_MAX_SIZE 252 ///< Maximum size of Service Data in bytes. +#define OT_SERVER_DATA_MAX_SIZE \ + 248 ///< Maximum size of Server Data in bytes. This is theoretical limit, practical one is much lower. /** * This structure represents a Server configuration. @@ -853,20 +850,19 @@ typedef struct otServiceConfig /** * Used to indicate no fixed received signal strength was set */ -#define OT_MAC_FILTER_FIXED_RSS_DISABLED 127 +#define OT_MAC_FILTER_FIXED_RSS_DISABLED 127 -#define OT_MAC_FILTER_ITERATOR_INIT 0 ///< Initializer for otMacFilterIterator. +#define OT_MAC_FILTER_ITERATOR_INIT 0 ///< Initializer for otMacFilterIterator. -typedef uint8_t otMacFilterIterator; ///< Used to iterate through mac filter entries. +typedef uint8_t otMacFilterIterator; ///< Used to iterate through mac filter entries. /** * Defines address mode of the mac filter. */ -typedef enum otMacFilterAddressMode -{ - OT_MAC_FILTER_ADDRESS_MODE_DISABLED, ///< Address filter is disabled. - OT_MAC_FILTER_ADDRESS_MODE_WHITELIST, ///< Whitelist address filter mode is enabled. - OT_MAC_FILTER_ADDRESS_MODE_BLACKLIST, ///< Blacklist address filter mode is enabled. +typedef enum otMacFilterAddressMode { + OT_MAC_FILTER_ADDRESS_MODE_DISABLED, ///< Address filter is disabled. + OT_MAC_FILTER_ADDRESS_MODE_WHITELIST, ///< Whitelist address filter mode is enabled. + OT_MAC_FILTER_ADDRESS_MODE_BLACKLIST, ///< Blacklist address filter mode is enabled. } otMacFilterAddressMode; /** @@ -875,21 +871,20 @@ typedef enum otMacFilterAddressMode */ typedef struct otMacFilterEntry { - otExtAddress mExtAddress; ///< IEEE 802.15.4 Extended Address - int8_t mRssIn; ///< Received signal strength - bool mFiltered; ///< Indicates whether or not this entry is filtered. + otExtAddress mExtAddress; ///< IEEE 802.15.4 Extended Address + int8_t mRssIn; ///< Received signal strength + bool mFiltered; ///< Indicates whether or not this entry is filtered. } otMacFilterEntry; /** * Represents a Thread device role. */ -typedef enum -{ - OT_DEVICE_ROLE_DISABLED = 0, ///< The Thread stack is disabled. - OT_DEVICE_ROLE_DETACHED = 1, ///< Not currently participating in a Thread network/partition. - OT_DEVICE_ROLE_CHILD = 2, ///< The Thread Child role. - OT_DEVICE_ROLE_ROUTER = 3, ///< The Thread Router role. - OT_DEVICE_ROLE_LEADER = 4, ///< The Thread Leader role. +typedef enum { + OT_DEVICE_ROLE_DISABLED = 0, ///< The Thread stack is disabled. + OT_DEVICE_ROLE_DETACHED = 1, ///< Not currently participating in a Thread network/partition. + OT_DEVICE_ROLE_CHILD = 2, ///< The Thread Child role. + OT_DEVICE_ROLE_ROUTER = 3, ///< The Thread Router role. + OT_DEVICE_ROLE_LEADER = 4, ///< The Thread Leader role. } otDeviceRole; /** @@ -900,26 +895,26 @@ typedef enum */ typedef struct { - otExtAddress mExtAddress; ///< IEEE 802.15.4 Extended Address - uint32_t mAge; ///< Time last heard - uint16_t mRloc16; ///< RLOC16 - uint32_t mLinkFrameCounter; ///< Link Frame Counter - uint32_t mMleFrameCounter; ///< MLE Frame Counter - uint8_t mLinkQualityIn; ///< Link Quality In - int8_t mAverageRssi; ///< Average RSSI - int8_t mLastRssi; ///< Last observed RSSI - uint16_t mFrameErrorRate; ///< Frame error rate (0xffff->100%). Requires error tracking feature. - uint16_t mMessageErrorRate; ///< (IPv6) msg error rate (0xffff->100%). Requires error tracking feature. - bool mRxOnWhenIdle : 1; ///< rx-on-when-idle - bool mSecureDataRequest : 1; ///< Secure Data Requests - bool mFullFunction : 1; ///< Full Function Device - bool mFullNetworkData : 1; ///< Full Network Data - bool mIsChild : 1; ///< Is the neighbor a child + otExtAddress mExtAddress; ///< IEEE 802.15.4 Extended Address + uint32_t mAge; ///< Time last heard + uint16_t mRloc16; ///< RLOC16 + uint32_t mLinkFrameCounter; ///< Link Frame Counter + uint32_t mMleFrameCounter; ///< MLE Frame Counter + uint8_t mLinkQualityIn; ///< Link Quality In + int8_t mAverageRssi; ///< Average RSSI + int8_t mLastRssi; ///< Last observed RSSI + uint16_t mFrameErrorRate; ///< Frame error rate (0xffff->100%). Requires error tracking feature. + uint16_t mMessageErrorRate; ///< (IPv6) msg error rate (0xffff->100%). Requires error tracking feature. + bool mRxOnWhenIdle : 1; ///< rx-on-when-idle + bool mSecureDataRequest : 1; ///< Secure Data Requests + bool mFullFunction : 1; ///< Full Function Device + bool mFullNetworkData : 1; ///< Full Network Data + bool mIsChild : 1; ///< Is the neighbor a child } otNeighborInfo; -#define OT_NEIGHBOR_INFO_ITERATOR_INIT 0 ///< Initializer for otNeighborInfoIterator. +#define OT_NEIGHBOR_INFO_ITERATOR_INIT 0 ///< Initializer for otNeighborInfoIterator. -typedef int16_t otNeighborInfoIterator; ///< Used to iterate through neighbor table. +typedef int16_t otNeighborInfoIterator; ///< Used to iterate through neighbor table. /** * This structure holds diagnostic information for a Thread Child @@ -930,27 +925,27 @@ typedef int16_t otNeighborInfoIterator; ///< Used to iterate through neighbor */ typedef struct { - otExtAddress mExtAddress; ///< IEEE 802.15.4 Extended Address - uint32_t mTimeout; ///< Timeout - uint32_t mAge; ///< Time last heard - uint16_t mRloc16; ///< RLOC16 - uint16_t mChildId; ///< Child ID - uint8_t mNetworkDataVersion; ///< Network Data Version - uint8_t mLinkQualityIn; ///< Link Quality In - int8_t mAverageRssi; ///< Average RSSI - int8_t mLastRssi; ///< Last observed RSSI - uint16_t mFrameErrorRate; ///< Frame error rate (0xffff->100%). Requires error tracking feature. - uint16_t mMessageErrorRate; ///< (IPv6) msg error rate (0xffff->100%). Requires error tracking feature. - bool mRxOnWhenIdle : 1; ///< rx-on-when-idle - bool mSecureDataRequest : 1; ///< Secure Data Requests - bool mFullFunction : 1; ///< Full Function Device - bool mFullNetworkData : 1; ///< Full Network Data - bool mIsStateRestoring : 1; ///< Is in restoring state + otExtAddress mExtAddress; ///< IEEE 802.15.4 Extended Address + uint32_t mTimeout; ///< Timeout + uint32_t mAge; ///< Time last heard + uint16_t mRloc16; ///< RLOC16 + uint16_t mChildId; ///< Child ID + uint8_t mNetworkDataVersion; ///< Network Data Version + uint8_t mLinkQualityIn; ///< Link Quality In + int8_t mAverageRssi; ///< Average RSSI + int8_t mLastRssi; ///< Last observed RSSI + uint16_t mFrameErrorRate; ///< Frame error rate (0xffff->100%). Requires error tracking feature. + uint16_t mMessageErrorRate; ///< (IPv6) msg error rate (0xffff->100%). Requires error tracking feature. + bool mRxOnWhenIdle : 1; ///< rx-on-when-idle + bool mSecureDataRequest : 1; ///< Secure Data Requests + bool mFullFunction : 1; ///< Full Function Device + bool mFullNetworkData : 1; ///< Full Network Data + bool mIsStateRestoring : 1; ///< Is in restoring state } otChildInfo; -#define OT_CHILD_IP6_ADDRESS_ITERATOR_INIT 0 ///< Initializer for otChildIP6AddressIterator +#define OT_CHILD_IP6_ADDRESS_ITERATOR_INIT 0 ///< Initializer for otChildIP6AddressIterator -typedef uint16_t otChildIp6AddressIterator; ///< Used to iterate through IPv6 addresses of a Thread Child entry. +typedef uint16_t otChildIp6AddressIterator; ///< Used to iterate through IPv6 addresses of a Thread Child entry. /** * This structure holds diagnostic information for a Thread Router @@ -959,16 +954,16 @@ typedef uint16_t otChildIp6AddressIterator; ///< Used to iterate through IPv OT_TOOL_ALIGN(4) typedef struct { - otExtAddress mExtAddress; ///< IEEE 802.15.4 Extended Address - uint16_t mRloc16; ///< RLOC16 - uint8_t mRouterId; ///< Router ID - uint8_t mNextHop; ///< Next hop to router - uint8_t mPathCost; ///< Path cost to router - uint8_t mLinkQualityIn; ///< Link Quality In - uint8_t mLinkQualityOut; ///< Link Quality Out - uint8_t mAge; ///< Time last heard - bool mAllocated : 1; ///< Router ID allocated or not - bool mLinkEstablished : 1; ///< Link established with Router ID or not + otExtAddress mExtAddress; ///< IEEE 802.15.4 Extended Address + uint16_t mRloc16; ///< RLOC16 + uint8_t mRouterId; ///< Router ID + uint8_t mNextHop; ///< Next hop to router + uint8_t mPathCost; ///< Path cost to router + uint8_t mLinkQualityIn; ///< Link Quality In + uint8_t mLinkQualityOut; ///< Link Quality Out + uint8_t mAge; ///< Time last heard + bool mAllocated : 1; ///< Router ID allocated or not + bool mLinkEstablished : 1; ///< Link established with Router ID or not } otRouterInfo; /** @@ -977,9 +972,9 @@ typedef struct */ typedef struct otEidCacheEntry { - otIp6Address mTarget; ///< Target - otShortAddress mRloc16; ///< RLOC16 - bool mValid : 1; ///< Indicates whether or not the cache entry is valid + otIp6Address mTarget; ///< Target + otShortAddress mRloc16; ///< RLOC16 + bool mValid : 1; ///< Indicates whether or not the cache entry is valid } otEidCacheEntry; /** @@ -988,11 +983,11 @@ typedef struct otEidCacheEntry */ typedef struct otLeaderData { - uint32_t mPartitionId; ///< Partition ID - uint8_t mWeighting; ///< Leader Weight - uint8_t mDataVersion; ///< Full Network Data Version - uint8_t mStableDataVersion; ///< Stable Network Data Version - uint8_t mLeaderRouterId; ///< Leader Router ID + uint32_t mPartitionId; ///< Partition ID + uint8_t mWeighting; ///< Leader Weight + uint8_t mDataVersion; ///< Full Network Data Version + uint8_t mStableDataVersion; ///< Stable Network Data Version + uint8_t mLeaderRouterId; ///< Leader Router ID } otLeaderData; /** @@ -1000,38 +995,39 @@ typedef struct otLeaderData */ typedef struct otMacCounters { - uint32_t mTxTotal; ///< The total number of transmissions. - uint32_t mTxUnicast; ///< The total number of unicast transmissions. - uint32_t mTxBroadcast; ///< The total number of broadcast transmissions. - uint32_t mTxAckRequested; ///< The number of transmissions with ack request. - uint32_t mTxAcked; ///< The number of transmissions that were acked. - uint32_t mTxNoAckRequested; ///< The number of transmissions without ack request. - uint32_t mTxData; ///< The number of transmitted data. - uint32_t mTxDataPoll; ///< The number of transmitted data poll. - uint32_t mTxBeacon; ///< The number of transmitted beacon. - uint32_t mTxBeaconRequest; ///< The number of transmitted beacon request. - uint32_t mTxOther; ///< The number of transmitted other types of frames. - uint32_t mTxRetry; ///< The number of retransmission times. - uint32_t mTxErrCca; ///< The number of CCA failure times. - uint32_t mTxErrAbort; ///< The number of frame transmission failures due to abort error. - uint32_t mTxErrBusyChannel; ///< The number of frames that were dropped due to a busy channel. - uint32_t mRxTotal; ///< The total number of received packets. - uint32_t mRxUnicast; ///< The total number of unicast packets received. - uint32_t mRxBroadcast; ///< The total number of broadcast packets received. - uint32_t mRxData; ///< The number of received data. - uint32_t mRxDataPoll; ///< The number of received data poll. - uint32_t mRxBeacon; ///< The number of received beacon. - uint32_t mRxBeaconRequest; ///< The number of received beacon request. - uint32_t mRxOther; ///< The number of received other types of frames. - uint32_t mRxAddressFiltered; ///< The number of received packets filtered by address filter (whitelist or blacklist). - uint32_t mRxDestAddrFiltered; ///< The number of received packets filtered by destination check. - uint32_t mRxDuplicated; ///< The number of received duplicated packets. - uint32_t mRxErrNoFrame; ///< The number of received packets with no or malformed content. - uint32_t mRxErrUnknownNeighbor; ///< The number of received packets from unknown neighbor. - uint32_t mRxErrInvalidSrcAddr; ///< The number of received packets whose source address is invalid. - uint32_t mRxErrSec; ///< The number of received packets with security error. - uint32_t mRxErrFcs; ///< The number of received packets with FCS error. - uint32_t mRxErrOther; ///< The number of received packets with other error. + uint32_t mTxTotal; ///< The total number of transmissions. + uint32_t mTxUnicast; ///< The total number of unicast transmissions. + uint32_t mTxBroadcast; ///< The total number of broadcast transmissions. + uint32_t mTxAckRequested; ///< The number of transmissions with ack request. + uint32_t mTxAcked; ///< The number of transmissions that were acked. + uint32_t mTxNoAckRequested; ///< The number of transmissions without ack request. + uint32_t mTxData; ///< The number of transmitted data. + uint32_t mTxDataPoll; ///< The number of transmitted data poll. + uint32_t mTxBeacon; ///< The number of transmitted beacon. + uint32_t mTxBeaconRequest; ///< The number of transmitted beacon request. + uint32_t mTxOther; ///< The number of transmitted other types of frames. + uint32_t mTxRetry; ///< The number of retransmission times. + uint32_t mTxErrCca; ///< The number of CCA failure times. + uint32_t mTxErrAbort; ///< The number of frame transmission failures due to abort error. + uint32_t mTxErrBusyChannel; ///< The number of frames that were dropped due to a busy channel. + uint32_t mRxTotal; ///< The total number of received packets. + uint32_t mRxUnicast; ///< The total number of unicast packets received. + uint32_t mRxBroadcast; ///< The total number of broadcast packets received. + uint32_t mRxData; ///< The number of received data. + uint32_t mRxDataPoll; ///< The number of received data poll. + uint32_t mRxBeacon; ///< The number of received beacon. + uint32_t mRxBeaconRequest; ///< The number of received beacon request. + uint32_t mRxOther; ///< The number of received other types of frames. + uint32_t + mRxAddressFiltered; ///< The number of received packets filtered by address filter (whitelist or blacklist). + uint32_t mRxDestAddrFiltered; ///< The number of received packets filtered by destination check. + uint32_t mRxDuplicated; ///< The number of received duplicated packets. + uint32_t mRxErrNoFrame; ///< The number of received packets with no or malformed content. + uint32_t mRxErrUnknownNeighbor; ///< The number of received packets from unknown neighbor. + uint32_t mRxErrInvalidSrcAddr; ///< The number of received packets whose source address is invalid. + uint32_t mRxErrSec; ///< The number of received packets with security error. + uint32_t mRxErrFcs; ///< The number of received packets with FCS error. + uint32_t mRxErrOther; ///< The number of received packets with other error. } otMacCounters; /** @@ -1039,10 +1035,10 @@ typedef struct otMacCounters */ typedef struct otIpCounters { - uint32_t mTxSuccess; ///< The number of IPv6 packets successfully transmitted. - uint32_t mRxSuccess; ///< The number of IPv6 packets successfully received. - uint32_t mTxFailure; ///< The number of IPv6 packets failed to transmit. - uint32_t mRxFailure; ///< The number of IPv6 packets failed to receive. + uint32_t mTxSuccess; ///< The number of IPv6 packets successfully transmitted. + uint32_t mRxSuccess; ///< The number of IPv6 packets successfully received. + uint32_t mTxFailure; ///< The number of IPv6 packets failed to transmit. + uint32_t mRxFailure; ///< The number of IPv6 packets failed to receive. } otIpCounters; /** @@ -1050,26 +1046,26 @@ typedef struct otIpCounters */ typedef struct otBufferInfo { - uint16_t mTotalBuffers; ///< The number of buffers in the pool. - uint16_t mFreeBuffers; ///< The number of free message buffers. - uint16_t m6loSendMessages; ///< The number of messages in the 6lo send queue. - uint16_t m6loSendBuffers; ///< The number of buffers in the 6lo send queue. - uint16_t m6loReassemblyMessages; ///< The number of messages in the 6LoWPAN reassembly queue. - uint16_t m6loReassemblyBuffers; ///< The number of buffers in the 6LoWPAN reassembly queue. - uint16_t mIp6Messages; ///< The number of messages in the IPv6 send queue. - uint16_t mIp6Buffers; ///< The number of buffers in the IPv6 send queue. - uint16_t mMplMessages; ///< The number of messages in the MPL send queue. - uint16_t mMplBuffers; ///< The number of buffers in the MPL send queue. - uint16_t mMleMessages; ///< The number of messages in the MLE send queue. - uint16_t mMleBuffers; ///< The number of buffers in the MLE send queue. - uint16_t mArpMessages; ///< The number of messages in the ARP send queue. - uint16_t mArpBuffers; ///< The number of buffers in the ARP send queue. - uint16_t mCoapMessages; ///< The number of messages in the CoAP send queue. - uint16_t mCoapBuffers; ///< The number of buffers in the CoAP send queue. - uint16_t mCoapSecureMessages; ///< The number of messages in the CoAP secure send queue. - uint16_t mCoapSecureBuffers; ///< The number of buffers in the CoAP secure send queue. - uint16_t mApplicationCoapMessages;///< The number of messages in the application CoAP send queue. - uint16_t mApplicationCoapBuffers; ///< The number of buffers in the application CoAP send queue. + uint16_t mTotalBuffers; ///< The number of buffers in the pool. + uint16_t mFreeBuffers; ///< The number of free message buffers. + uint16_t m6loSendMessages; ///< The number of messages in the 6lo send queue. + uint16_t m6loSendBuffers; ///< The number of buffers in the 6lo send queue. + uint16_t m6loReassemblyMessages; ///< The number of messages in the 6LoWPAN reassembly queue. + uint16_t m6loReassemblyBuffers; ///< The number of buffers in the 6LoWPAN reassembly queue. + uint16_t mIp6Messages; ///< The number of messages in the IPv6 send queue. + uint16_t mIp6Buffers; ///< The number of buffers in the IPv6 send queue. + uint16_t mMplMessages; ///< The number of messages in the MPL send queue. + uint16_t mMplBuffers; ///< The number of buffers in the MPL send queue. + uint16_t mMleMessages; ///< The number of messages in the MLE send queue. + uint16_t mMleBuffers; ///< The number of buffers in the MLE send queue. + uint16_t mArpMessages; ///< The number of messages in the ARP send queue. + uint16_t mArpBuffers; ///< The number of buffers in the ARP send queue. + uint16_t mCoapMessages; ///< The number of messages in the CoAP send queue. + uint16_t mCoapBuffers; ///< The number of buffers in the CoAP send queue. + uint16_t mCoapSecureMessages; ///< The number of messages in the CoAP secure send queue. + uint16_t mCoapSecureBuffers; ///< The number of buffers in the CoAP secure send queue. + uint16_t mApplicationCoapMessages; ///< The number of messages in the application CoAP send queue. + uint16_t mApplicationCoapBuffers; ///< The number of buffers in the application CoAP send queue. } otBufferInfo; /** @@ -1078,14 +1074,14 @@ typedef struct otBufferInfo */ typedef struct otNetifAddress { - otIp6Address mAddress; ///< The IPv6 unicast address. - uint8_t mPrefixLength; ///< The Prefix length. - bool mPreferred : 1; ///< TRUE if the address is preferred, FALSE otherwise. - bool mValid : 1; ///< TRUE if the address is valid, FALSE otherwise. - bool mScopeOverrideValid : 1; ///< TRUE if the mScopeOverride value is valid, FALSE otherwise. - unsigned int mScopeOverride : 4; ///< The IPv6 scope of this address. - bool mRloc : 1; ///< TRUE if the address is an RLOC, FALSE otherwise. - struct otNetifAddress *mNext; ///< A pointer to the next network interface address. + otIp6Address mAddress; ///< The IPv6 unicast address. + uint8_t mPrefixLength; ///< The Prefix length. + bool mPreferred : 1; ///< TRUE if the address is preferred, FALSE otherwise. + bool mValid : 1; ///< TRUE if the address is valid, FALSE otherwise. + bool mScopeOverrideValid : 1; ///< TRUE if the mScopeOverride value is valid, FALSE otherwise. + unsigned int mScopeOverride : 4; ///< The IPv6 scope of this address. + bool mRloc : 1; ///< TRUE if the address is an RLOC, FALSE otherwise. + struct otNetifAddress *mNext; ///< A pointer to the next network interface address. } otNetifAddress; /** @@ -1094,16 +1090,15 @@ typedef struct otNetifAddress */ typedef struct otNetifMulticastAddress { - otIp6Address mAddress; ///< The IPv6 multicast address. - const struct otNetifMulticastAddress *mNext; ///< A pointer to the next network interface multicast address. + otIp6Address mAddress; ///< The IPv6 multicast address. + const struct otNetifMulticastAddress *mNext; ///< A pointer to the next network interface multicast address. } otNetifMulticastAddress; /** * This enumeration represents the list of allowable values for an InterfaceId. */ -typedef enum otNetifInterfaceId -{ - OT_NETIF_INTERFACE_ID_THREAD = 1, ///< The Thread Network interface ID. +typedef enum otNetifInterfaceId { + OT_NETIF_INTERFACE_ID_THREAD = 1, ///< The Thread Network interface ID. } otNetifInterfaceId; /** @@ -1112,16 +1107,16 @@ typedef enum otNetifInterfaceId */ typedef struct { - uint8_t *mInterfaceId; ///< String of bytes representing interface ID. Like "eth0" or "wlan0". - uint8_t mInterfaceIdLength; ///< Length of interface ID string. + uint8_t *mInterfaceId; ///< String of bytes representing interface ID. Like "eth0" or "wlan0". + uint8_t mInterfaceIdLength; ///< Length of interface ID string. - uint8_t *mNetworkId; ///< Network ID (or name). Can be null if mNetworkIdLength is 0. - uint8_t mNetworkIdLength; ///< Length of Network ID string. + uint8_t *mNetworkId; ///< Network ID (or name). Can be null if mNetworkIdLength is 0. + uint8_t mNetworkIdLength; ///< Length of Network ID string. - uint8_t mDadCounter; ///< Duplicate address detection counter. + uint8_t mDadCounter; ///< Duplicate address detection counter. - uint8_t *mSecretKey; ///< Secret key used to create IID. Cannot be null. - uint16_t mSecretKeyLength; ///< Secret key length in bytes. Should be at least 16 bytes == 128 bits. + uint8_t *mSecretKey; ///< Secret key used to create IID. Cannot be null. + uint16_t mSecretKeyLength; ///< Secret key length in bytes. Should be at least 16 bytes == 128 bits. } otSemanticallyOpaqueIidGeneratorData; /** @@ -1129,9 +1124,9 @@ typedef struct */ typedef struct otSockAddr { - otIp6Address mAddress; ///< An IPv6 address. - uint16_t mPort; ///< A transport-layer port. - int8_t mScopeId; ///< An IPv6 scope identifier. + otIp6Address mAddress; ///< An IPv6 address. + uint16_t mPort; ///< A transport-layer port. + int8_t mScopeId; ///< An IPv6 scope identifier. } otSockAddr; /** @@ -1140,11 +1135,11 @@ typedef struct otSockAddr */ typedef struct otThreadLinkInfo { - uint16_t mPanId; ///< Source PAN ID - uint8_t mChannel; ///< 802.15.4 Channel - int8_t mRss; ///< Received Signal Strength in dBm. - uint8_t mLqi; ///< Link Quality Indicator for a received message. - bool mLinkSecurity; ///< Indicates whether or not link security is enabled. + uint16_t mPanId; ///< Source PAN ID + uint8_t mChannel; ///< 802.15.4 Channel + int8_t mRss; ///< Received Signal Strength in dBm. + uint8_t mLqi; ///< Link Quality Indicator for a received message. + bool mLinkSecurity; ///< Indicates whether or not link security is enabled. } otThreadLinkInfo; #ifdef OTDLL @@ -1157,7 +1152,7 @@ typedef struct otThreadLinkInfo * @param[in] aContext A pointer to application-specific context. * */ -typedef void (OTCALL *otDeviceAvailabilityChangedCallback)(bool aAdded, const GUID *aDeviceGuid, void *aContext); +typedef void(OTCALL *otDeviceAvailabilityChangedCallback)(bool aAdded, const GUID *aDeviceGuid, void *aContext); #endif // OTDLL @@ -1175,8 +1170,7 @@ typedef uint8_t otLogLevel; * This enumeration represents log regions. * */ -typedef enum otLogRegion -{ +typedef enum otLogRegion { OT_LOG_REGION_API = 1, ///< OpenThread API OT_LOG_REGION_MLE = 2, ///< MLE OT_LOG_REGION_ARP = 3, ///< EID-to-RLOC mapping. @@ -1201,7 +1195,7 @@ typedef enum otLogRegion */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_TYPES_H_ +#endif // OPENTHREAD_TYPES_H_ diff --git a/include/openthread/udp.h b/include/openthread/udp.h index 828c810d7..4c2e2e5fb 100644 --- a/include/openthread/udp.h +++ b/include/openthread/udp.h @@ -64,12 +64,12 @@ typedef void (*otUdpReceive)(void *aContext, otMessage *aMessage, const otMessag */ typedef struct otUdpSocket { - otSockAddr mSockName; ///< The local IPv6 socket address. - otSockAddr mPeerName; ///< The peer IPv6 socket address. - otUdpReceive mHandler; ///< A function pointer to the application callback. - void *mContext; ///< A pointer to application-specific context. - void *mTransport; ///< A pointer to the transport object (internal use only). - struct otUdpSocket *mNext; ///< A pointer to the next UDP socket (internal use only). + otSockAddr mSockName; ///< The local IPv6 socket address. + otSockAddr mPeerName; ///< The peer IPv6 socket address. + otUdpReceive mHandler; ///< A function pointer to the application callback. + void * mContext; ///< A pointer to application-specific context. + void * mTransport; ///< A pointer to the transport object (internal use only). + struct otUdpSocket *mNext; ///< A pointer to the next UDP socket (internal use only). } otUdpSocket; /** @@ -178,7 +178,7 @@ otError otUdpSend(otUdpSocket *aSocket, otMessage *aMessage, const otMessageInfo */ #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // OPENTHREAD_UDP_H_ +#endif // OPENTHREAD_UDP_H_ diff --git a/src/cli/cli.cpp b/src/cli/cli.cpp index bbbf48265..565969c5c 100644 --- a/src/cli/cli.cpp +++ b/src/cli/cli.cpp @@ -41,11 +41,11 @@ #include #include "utils/wrap_string.h" -#include #include #include #include #include +#include #if OPENTHREAD_FTD #include @@ -90,137 +90,136 @@ namespace ot { namespace Cli { -const struct Command Interpreter::sCommands[] = -{ - { "help", &Interpreter::ProcessHelp }, - { "autostart", &Interpreter::ProcessAutoStart }, - { "bufferinfo", &Interpreter::ProcessBufferInfo }, - { "channel", &Interpreter::ProcessChannel }, +const struct Command Interpreter::sCommands[] = { + {"help", &Interpreter::ProcessHelp}, + {"autostart", &Interpreter::ProcessAutoStart}, + {"bufferinfo", &Interpreter::ProcessBufferInfo}, + {"channel", &Interpreter::ProcessChannel}, #if OPENTHREAD_FTD - { "child", &Interpreter::ProcessChild }, - { "childmax", &Interpreter::ProcessChildMax }, + {"child", &Interpreter::ProcessChild}, + {"childmax", &Interpreter::ProcessChildMax}, #endif - { "childtimeout", &Interpreter::ProcessChildTimeout }, + {"childtimeout", &Interpreter::ProcessChildTimeout}, #if OPENTHREAD_ENABLE_APPLICATION_COAP - { "coap", &Interpreter::ProcessCoap }, + {"coap", &Interpreter::ProcessCoap}, #endif #if OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD - { "commissioner", &Interpreter::ProcessCommissioner }, + {"commissioner", &Interpreter::ProcessCommissioner}, #endif #if OPENTHREAD_FTD - { "contextreusedelay", &Interpreter::ProcessContextIdReuseDelay }, + {"contextreusedelay", &Interpreter::ProcessContextIdReuseDelay}, #endif - { "counter", &Interpreter::ProcessCounters }, - { "dataset", &Interpreter::ProcessDataset }, + {"counter", &Interpreter::ProcessCounters}, + {"dataset", &Interpreter::ProcessDataset}, #if OPENTHREAD_FTD - { "delaytimermin", &Interpreter::ProcessDelayTimerMin}, + {"delaytimermin", &Interpreter::ProcessDelayTimerMin}, #endif #if OPENTHREAD_ENABLE_DIAG - { "diag", &Interpreter::ProcessDiag }, + {"diag", &Interpreter::ProcessDiag}, #endif - { "discover", &Interpreter::ProcessDiscover }, + {"discover", &Interpreter::ProcessDiscover}, #if OPENTHREAD_ENABLE_DNS_CLIENT - { "dns", &Interpreter::ProcessDns }, + {"dns", &Interpreter::ProcessDns}, #endif #if OPENTHREAD_FTD - { "eidcache", &Interpreter::ProcessEidCache }, + {"eidcache", &Interpreter::ProcessEidCache}, #endif - { "eui64", &Interpreter::ProcessEui64 }, + {"eui64", &Interpreter::ProcessEui64}, #ifdef OPENTHREAD_EXAMPLES_POSIX - { "exit", &Interpreter::ProcessExit }, + {"exit", &Interpreter::ProcessExit}, #endif #if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_DEBUG_UART) && OPENTHREAD_EXAMPLES_POSIX - { "logfilename", &Interpreter::ProcessLogFilename }, + {"logfilename", &Interpreter::ProcessLogFilename}, #endif - { "extaddr", &Interpreter::ProcessExtAddress }, - { "extpanid", &Interpreter::ProcessExtPanId }, - { "factoryreset", &Interpreter::ProcessFactoryReset }, - { "ifconfig", &Interpreter::ProcessIfconfig }, + {"extaddr", &Interpreter::ProcessExtAddress}, + {"extpanid", &Interpreter::ProcessExtPanId}, + {"factoryreset", &Interpreter::ProcessFactoryReset}, + {"ifconfig", &Interpreter::ProcessIfconfig}, #ifdef OTDLL - { "instance", &Interpreter::ProcessInstance }, - { "instancelist", &Interpreter::ProcessInstanceList }, + {"instance", &Interpreter::ProcessInstance}, + {"instancelist", &Interpreter::ProcessInstanceList}, #endif - { "ipaddr", &Interpreter::ProcessIpAddr }, + {"ipaddr", &Interpreter::ProcessIpAddr}, #ifndef OTDLL - { "ipmaddr", &Interpreter::ProcessIpMulticastAddr }, + {"ipmaddr", &Interpreter::ProcessIpMulticastAddr}, #endif #if OPENTHREAD_ENABLE_JOINER - { "joiner", &Interpreter::ProcessJoiner }, - { "joinerid", &Interpreter::ProcessJoinerId }, + {"joiner", &Interpreter::ProcessJoiner}, + {"joinerid", &Interpreter::ProcessJoinerId}, #endif #if OPENTHREAD_FTD - { "joinerport", &Interpreter::ProcessJoinerPort }, + {"joinerport", &Interpreter::ProcessJoinerPort}, #endif - { "keysequence", &Interpreter::ProcessKeySequence }, - { "leaderdata", &Interpreter::ProcessLeaderData }, + {"keysequence", &Interpreter::ProcessKeySequence}, + {"leaderdata", &Interpreter::ProcessLeaderData}, #if OPENTHREAD_FTD - { "leaderpartitionid", &Interpreter::ProcessLeaderPartitionId }, - { "leaderweight", &Interpreter::ProcessLeaderWeight }, + {"leaderpartitionid", &Interpreter::ProcessLeaderPartitionId}, + {"leaderweight", &Interpreter::ProcessLeaderWeight}, #endif #if OPENTHREAD_ENABLE_MAC_FILTER - { "macfilter", &Interpreter::ProcessMacFilter }, + {"macfilter", &Interpreter::ProcessMacFilter}, #endif - { "masterkey", &Interpreter::ProcessMasterKey }, - { "mode", &Interpreter::ProcessMode }, + {"masterkey", &Interpreter::ProcessMasterKey}, + {"mode", &Interpreter::ProcessMode}, #if OPENTHREAD_FTD - { "neighbor", &Interpreter::ProcessNeighbor }, + {"neighbor", &Interpreter::ProcessNeighbor}, #endif #if OPENTHREAD_ENABLE_BORDER_ROUTER || OPENTHREAD_ENABLE_SERVICE - { "netdataregister", &Interpreter::ProcessNetworkDataRegister }, + {"netdataregister", &Interpreter::ProcessNetworkDataRegister}, #endif #if OPENTHREAD_ENABLE_SERVICE - { "netdatashow", &Interpreter::ProcessNetworkDataShow }, + {"netdatashow", &Interpreter::ProcessNetworkDataShow}, #endif #if OPENTHREAD_FTD || OPENTHREAD_ENABLE_MTD_NETWORK_DIAGNOSTIC - { "networkdiagnostic", &Interpreter::ProcessNetworkDiagnostic }, + {"networkdiagnostic", &Interpreter::ProcessNetworkDiagnostic}, #endif // OPENTHREAD_FTD || OPENTHREAD_ENABLE_MTD_NETWORK_DIAGNOSTIC #if OPENTHREAD_FTD - { "networkidtimeout", &Interpreter::ProcessNetworkIdTimeout }, + {"networkidtimeout", &Interpreter::ProcessNetworkIdTimeout}, #endif - { "networkname", &Interpreter::ProcessNetworkName }, - { "panid", &Interpreter::ProcessPanId }, - { "parent", &Interpreter::ProcessParent }, + {"networkname", &Interpreter::ProcessNetworkName}, + {"panid", &Interpreter::ProcessPanId}, + {"parent", &Interpreter::ProcessParent}, #if OPENTHREAD_FTD - { "parentpriority", &Interpreter::ProcessParentPriority }, + {"parentpriority", &Interpreter::ProcessParentPriority}, #endif #ifndef OTDLL - { "ping", &Interpreter::ProcessPing }, + {"ping", &Interpreter::ProcessPing}, #endif - { "pollperiod", &Interpreter::ProcessPollPeriod }, + {"pollperiod", &Interpreter::ProcessPollPeriod}, #ifndef OTDLL - { "promiscuous", &Interpreter::ProcessPromiscuous }, + {"promiscuous", &Interpreter::ProcessPromiscuous}, #endif #if OPENTHREAD_ENABLE_BORDER_ROUTER - { "prefix", &Interpreter::ProcessPrefix }, + {"prefix", &Interpreter::ProcessPrefix}, #endif #if OPENTHREAD_FTD - { "pskc", &Interpreter::ProcessPSKc }, - { "releaserouterid", &Interpreter::ProcessReleaseRouterId }, + {"pskc", &Interpreter::ProcessPSKc}, + {"releaserouterid", &Interpreter::ProcessReleaseRouterId}, #endif - { "reset", &Interpreter::ProcessReset }, - { "rloc16", &Interpreter::ProcessRloc16 }, + {"reset", &Interpreter::ProcessReset}, + {"rloc16", &Interpreter::ProcessRloc16}, #if OPENTHREAD_ENABLE_BORDER_ROUTER - { "route", &Interpreter::ProcessRoute }, + {"route", &Interpreter::ProcessRoute}, #endif #if OPENTHREAD_FTD - { "router", &Interpreter::ProcessRouter }, - { "routerdowngradethreshold", &Interpreter::ProcessRouterDowngradeThreshold }, - { "routerrole", &Interpreter::ProcessRouterRole }, - { "routerselectionjitter", &Interpreter::ProcessRouterSelectionJitter }, - { "routerupgradethreshold", &Interpreter::ProcessRouterUpgradeThreshold }, + {"router", &Interpreter::ProcessRouter}, + {"routerdowngradethreshold", &Interpreter::ProcessRouterDowngradeThreshold}, + {"routerrole", &Interpreter::ProcessRouterRole}, + {"routerselectionjitter", &Interpreter::ProcessRouterSelectionJitter}, + {"routerupgradethreshold", &Interpreter::ProcessRouterUpgradeThreshold}, #endif - { "scan", &Interpreter::ProcessScan }, + {"scan", &Interpreter::ProcessScan}, #if OPENTHREAD_ENABLE_SERVICE - { "service", &Interpreter::ProcessService }, + {"service", &Interpreter::ProcessService}, #endif - { "singleton", &Interpreter::ProcessSingleton }, - { "state", &Interpreter::ProcessState }, - { "thread", &Interpreter::ProcessThread }, + {"singleton", &Interpreter::ProcessSingleton}, + {"state", &Interpreter::ProcessState}, + {"thread", &Interpreter::ProcessThread}, #ifndef OTDLL - { "txpower", &Interpreter::ProcessTxPower }, - { "udp", &Interpreter::ProcessUdp }, + {"txpower", &Interpreter::ProcessTxPower}, + {"udp", &Interpreter::ProcessUdp}, #endif - { "version", &Interpreter::ProcessVersion }, + {"version", &Interpreter::ProcessVersion}, }; #ifdef OTDLL @@ -238,38 +237,55 @@ void otFreeMemory(const void *) template class otPtr { T *ptr; + public: - otPtr(T *_ptr) : ptr(_ptr) { } - ~otPtr() { if (ptr) { otFreeMemory(ptr); } } + otPtr(T *_ptr) + : ptr(_ptr) + { + } + ~otPtr() + { + if (ptr) + { + otFreeMemory(ptr); + } + } T *get() const { return ptr; } - operator T *() const { return ptr; } + operator T *() const { return ptr; } T *operator->() const { return ptr; } }; -typedef otPtr otMacCountersPtr; +typedef otPtr otMacCountersPtr; typedef otPtr otNetifAddressPtr; -typedef otPtr otBufferPtr; -typedef otPtr otStringPtr; +typedef otPtr otBufferPtr; +typedef otPtr otStringPtr; -Interpreter::Interpreter(Instance *aInstance): +Interpreter::Interpreter(Instance *aInstance) + : #if OPENTHREAD_ENABLE_APPLICATION_COAP - mCoap(*this), + mCoap(*this) + , #endif - mUserCommands(NULL), - mUserCommandsLength(0), - mServer(NULL), + mUserCommands(NULL) + , mUserCommandsLength(0) + , mServer(NULL) + , #ifdef OTDLL - mApiInstance(otApiInit()), - mInstanceIndex(0), + mApiInstance(otApiInit()) + , mInstanceIndex(0) + , #else - mLength(8), - mCount(1), - mInterval(1000), - mPingTimer(*aInstance, &Interpreter::s_HandlePingTimer, this), + mLength(8) + , mCount(1) + , mInterval(1000) + , mPingTimer(*aInstance, &Interpreter::s_HandlePingTimer, this) + , #if OPENTHREAD_ENABLE_DNS_CLIENT - mResolvingInProgress(0), + mResolvingInProgress(0) + , #endif - mUdp(*this), + mUdp(*this) + , #endif mInstance(aInstance) { @@ -289,7 +305,7 @@ Interpreter::Interpreter(Instance *aInstance): #if OPENTHREAD_ENABLE_DHCP6_CLIENT memset(mDhcpAddresses, 0, sizeof(mDhcpAddresses)); -#endif // OPENTHREAD_ENABLE_DHCP6_CLIENT +#endif // OPENTHREAD_ENABLE_DHCP6_CLIENT #if OPENTHREAD_ENABLE_DNS_CLIENT memset(mResolvingHostname, 0, sizeof(mResolvingHostname)); @@ -300,11 +316,11 @@ Interpreter::Interpreter(Instance *aInstance): int Interpreter::Hex2Bin(const char *aHex, uint8_t *aBin, uint16_t aBinLength) { - size_t hexLength = strlen(aHex); - const char *hexEnd = aHex + hexLength; - uint8_t *cur = aBin; - uint8_t numChars = hexLength & 1; - uint8_t byte = 0; + size_t hexLength = strlen(aHex); + const char *hexEnd = aHex + hexLength; + uint8_t * cur = aBin; + uint8_t numChars = hexLength & 1; + uint8_t byte = 0; if ((hexLength + 1) / 2 > aBinLength) { @@ -336,8 +352,8 @@ int Interpreter::Hex2Bin(const char *aHex, uint8_t *aBin, uint16_t aBinLength) if (numChars >= 2) { numChars = 0; - *cur++ = byte; - byte = 0; + *cur++ = byte; + byte = 0; } else { @@ -456,7 +472,7 @@ void Interpreter::ProcessBufferInfo(int argc, char *argv[]) void Interpreter::ProcessChannel(int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; if (argc == 0) { @@ -475,10 +491,10 @@ exit: #if OPENTHREAD_FTD void Interpreter::ProcessChild(int argc, char *argv[]) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; otChildInfo childInfo; - long value; - bool isTable; + long value; + bool isTable; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); @@ -488,14 +504,16 @@ void Interpreter::ProcessChild(int argc, char *argv[]) { if (isTable) { - mServer->OutputFormat("| ID | RLOC16 | Timeout | Age | LQ In | C_VN |R|S|D|N| Extended MAC |\r\n"); - mServer->OutputFormat("+-----+--------+------------+------------+-------+------+-+-+-+-+------------------+\r\n"); + mServer->OutputFormat( + "| ID | RLOC16 | Timeout | Age | LQ In | C_VN |R|S|D|N| Extended MAC |\r\n"); + mServer->OutputFormat( + "+-----+--------+------------+------------+-------+------+-+-+-+-+------------------+\r\n"); } // For certifcation: here intentionally not limits the upperbound for the index, // giving the chance to exit from below default case as OpenThread THCI expects // the content of "child list" and the result "Done" in seperate lines. - for (uint8_t i = 0; ; i++) + for (uint8_t i = 0;; i++) { switch (otThreadGetChildInfoByIndex(mInstance, i, &childInfo)) { @@ -591,7 +609,7 @@ exit: void Interpreter::ProcessChildMax(int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; if (argc == 0) { @@ -606,12 +624,12 @@ void Interpreter::ProcessChildMax(int argc, char *argv[]) exit: AppendResult(error); } -#endif // OPENTHREAD_FTD +#endif // OPENTHREAD_FTD void Interpreter::ProcessChildTimeout(int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; if (argc == 0) { @@ -642,7 +660,7 @@ void Interpreter::ProcessCoap(int argc, char *argv[]) void Interpreter::ProcessContextIdReuseDelay(int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; if (argc == 0) { @@ -657,7 +675,7 @@ void Interpreter::ProcessContextIdReuseDelay(int argc, char *argv[]) exit: AppendResult(error); } -#endif // OPENTHREAD_FTD +#endif // OPENTHREAD_FTD void Interpreter::ProcessCounters(int argc, char *argv[]) { @@ -740,9 +758,9 @@ exit: void Interpreter::ProcessDiscover(int argc, char *argv[]) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint32_t scanChannels = 0; - long value; + long value; if (argc > 0) { @@ -764,10 +782,10 @@ exit: #if OPENTHREAD_ENABLE_DNS_CLIENT void Interpreter::ProcessDns(int argc, char *argv[]) { - otError error = OT_ERROR_NONE; - long port = OT_DNS_DEFAULT_DNS_SERVER_PORT; + otError error = OT_ERROR_NONE; + long port = OT_DNS_DEFAULT_DNS_SERVER_PORT; Ip6::MessageInfo messageInfo; - otDnsQuery query; + otDnsQuery query; VerifyOrExit(argc > 0, error = OT_ERROR_INVALID_ARGS); @@ -817,12 +835,14 @@ exit: AppendResult(error); } -void Interpreter::s_HandleDnsResponse(void *aContext, const char *aHostname, otIp6Address *aAddress, - uint32_t aTtl, otError aResult) +void Interpreter::s_HandleDnsResponse(void * aContext, + const char * aHostname, + otIp6Address *aAddress, + uint32_t aTtl, + otError aResult) { - static_cast(aContext)->HandleDnsResponse(aHostname, - *static_cast(aAddress), - aTtl, aResult); + static_cast(aContext)->HandleDnsResponse(aHostname, *static_cast(aAddress), aTtl, + aResult); } void Interpreter::HandleDnsResponse(const char *aHostname, Ip6::Address &aAddress, uint32_t aTtl, otError aResult) @@ -831,16 +851,11 @@ void Interpreter::HandleDnsResponse(const char *aHostname, Ip6::Address &aAddres if (aResult == OT_ERROR_NONE) { - mServer->OutputFormat("[%x:%x:%x:%x:%x:%x:%x:%x] TTL: %d\r\n", - HostSwap16(aAddress.mFields.m16[0]), - HostSwap16(aAddress.mFields.m16[1]), - HostSwap16(aAddress.mFields.m16[2]), - HostSwap16(aAddress.mFields.m16[3]), - HostSwap16(aAddress.mFields.m16[4]), - HostSwap16(aAddress.mFields.m16[5]), - HostSwap16(aAddress.mFields.m16[6]), - HostSwap16(aAddress.mFields.m16[7]), - aTtl); + mServer->OutputFormat("[%x:%x:%x:%x:%x:%x:%x:%x] TTL: %d\r\n", HostSwap16(aAddress.mFields.m16[0]), + HostSwap16(aAddress.mFields.m16[1]), HostSwap16(aAddress.mFields.m16[2]), + HostSwap16(aAddress.mFields.m16[3]), HostSwap16(aAddress.mFields.m16[4]), + HostSwap16(aAddress.mFields.m16[5]), HostSwap16(aAddress.mFields.m16[6]), + HostSwap16(aAddress.mFields.m16[7]), aTtl); } else { @@ -856,7 +871,7 @@ void Interpreter::ProcessEidCache(int argc, char *argv[]) { otEidCacheEntry entry; - for (uint8_t i = 0; ; i++) + for (uint8_t i = 0;; i++) { SuccessOrExit(otThreadGetEidCacheEntry(mInstance, i, &entry)); @@ -865,16 +880,11 @@ void Interpreter::ProcessEidCache(int argc, char *argv[]) continue; } - mServer->OutputFormat("%x:%x:%x:%x:%x:%x:%x:%x %04x\r\n", - HostSwap16(entry.mTarget.mFields.m16[0]), - HostSwap16(entry.mTarget.mFields.m16[1]), - HostSwap16(entry.mTarget.mFields.m16[2]), - HostSwap16(entry.mTarget.mFields.m16[3]), - HostSwap16(entry.mTarget.mFields.m16[4]), - HostSwap16(entry.mTarget.mFields.m16[5]), - HostSwap16(entry.mTarget.mFields.m16[6]), - HostSwap16(entry.mTarget.mFields.m16[7]), - entry.mRloc16); + mServer->OutputFormat("%x:%x:%x:%x:%x:%x:%x:%x %04x\r\n", HostSwap16(entry.mTarget.mFields.m16[0]), + HostSwap16(entry.mTarget.mFields.m16[1]), HostSwap16(entry.mTarget.mFields.m16[2]), + HostSwap16(entry.mTarget.mFields.m16[3]), HostSwap16(entry.mTarget.mFields.m16[4]), + HostSwap16(entry.mTarget.mFields.m16[5]), HostSwap16(entry.mTarget.mFields.m16[6]), + HostSwap16(entry.mTarget.mFields.m16[7]), entry.mRloc16); } exit: @@ -882,11 +892,11 @@ exit: OT_UNUSED_VARIABLE(argv); AppendResult(OT_ERROR_NONE); } -#endif // OPENTHREAD_FTD +#endif // OPENTHREAD_FTD void Interpreter::ProcessEui64(int argc, char *argv[]) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; otExtAddress extAddress; VerifyOrExit(argc == 0, error = OT_ERROR_PARSE); @@ -1013,16 +1023,16 @@ exit: otError Interpreter::ProcessIpAddrAdd(int argc, char *argv[]) { - otError error; + otError error; otNetifAddress aAddress; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); SuccessOrExit(error = otIp6AddressFromString(argv[0], &aAddress.mAddress)); aAddress.mPrefixLength = 64; - aAddress.mPreferred = true; - aAddress.mValid = true; - error = otIp6AddUnicastAddress(mInstance, &aAddress); + aAddress.mPreferred = true; + aAddress.mValid = true; + error = otIp6AddUnicastAddress(mInstance, &aAddress); exit: return error; @@ -1030,7 +1040,7 @@ exit: otError Interpreter::ProcessIpAddrDel(int argc, char *argv[]) { - otError error; + otError error; struct otIp6Address address; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); @@ -1052,14 +1062,10 @@ void Interpreter::ProcessIpAddr(int argc, char *argv[]) for (const otNetifAddress *addr = unicastAddrs; addr; addr = addr->mNext) { - mServer->OutputFormat("%x:%x:%x:%x:%x:%x:%x:%x\r\n", - HostSwap16(addr->mAddress.mFields.m16[0]), - HostSwap16(addr->mAddress.mFields.m16[1]), - HostSwap16(addr->mAddress.mFields.m16[2]), - HostSwap16(addr->mAddress.mFields.m16[3]), - HostSwap16(addr->mAddress.mFields.m16[4]), - HostSwap16(addr->mAddress.mFields.m16[5]), - HostSwap16(addr->mAddress.mFields.m16[6]), + mServer->OutputFormat("%x:%x:%x:%x:%x:%x:%x:%x\r\n", HostSwap16(addr->mAddress.mFields.m16[0]), + HostSwap16(addr->mAddress.mFields.m16[1]), HostSwap16(addr->mAddress.mFields.m16[2]), + HostSwap16(addr->mAddress.mFields.m16[3]), HostSwap16(addr->mAddress.mFields.m16[4]), + HostSwap16(addr->mAddress.mFields.m16[5]), HostSwap16(addr->mAddress.mFields.m16[6]), HostSwap16(addr->mAddress.mFields.m16[7])); } } @@ -1082,7 +1088,7 @@ exit: #ifndef OTDLL otError Interpreter::ProcessIpMulticastAddrAdd(int argc, char *argv[]) { - otError error; + otError error; struct otIp6Address address; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); @@ -1096,7 +1102,7 @@ exit: otError Interpreter::ProcessIpMulticastAddrDel(int argc, char *argv[]) { - otError error; + otError error; struct otIp6Address address; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); @@ -1151,14 +1157,10 @@ void Interpreter::ProcessIpMulticastAddr(int argc, char *argv[]) { for (const otNetifMulticastAddress *addr = otIp6GetMulticastAddresses(mInstance); addr; addr = addr->mNext) { - mServer->OutputFormat("%x:%x:%x:%x:%x:%x:%x:%x\r\n", - HostSwap16(addr->mAddress.mFields.m16[0]), - HostSwap16(addr->mAddress.mFields.m16[1]), - HostSwap16(addr->mAddress.mFields.m16[2]), - HostSwap16(addr->mAddress.mFields.m16[3]), - HostSwap16(addr->mAddress.mFields.m16[4]), - HostSwap16(addr->mAddress.mFields.m16[5]), - HostSwap16(addr->mAddress.mFields.m16[6]), + mServer->OutputFormat("%x:%x:%x:%x:%x:%x:%x:%x\r\n", HostSwap16(addr->mAddress.mFields.m16[0]), + HostSwap16(addr->mAddress.mFields.m16[1]), HostSwap16(addr->mAddress.mFields.m16[2]), + HostSwap16(addr->mAddress.mFields.m16[3]), HostSwap16(addr->mAddress.mFields.m16[4]), + HostSwap16(addr->mAddress.mFields.m16[5]), HostSwap16(addr->mAddress.mFields.m16[6]), HostSwap16(addr->mAddress.mFields.m16[7])); } } @@ -1186,7 +1188,7 @@ exit: void Interpreter::ProcessKeySequence(int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; VerifyOrExit(argc == 1 || argc == 2, error = OT_ERROR_PARSE); @@ -1221,7 +1223,7 @@ exit: void Interpreter::ProcessLeaderData(int argc, char *argv[]) { - otError error; + otError error; otLeaderData leaderData; SuccessOrExit(error = otThreadGetLeaderData(mInstance, &leaderData)); @@ -1241,7 +1243,7 @@ exit: #if OPENTHREAD_FTD void Interpreter::ProcessLeaderPartitionId(int argc, char *argv[]) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; unsigned long value; if (argc == 0) @@ -1261,7 +1263,7 @@ exit: void Interpreter::ProcessLeaderWeight(int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; if (argc == 0) { @@ -1276,7 +1278,7 @@ void Interpreter::ProcessLeaderWeight(int argc, char *argv[]) exit: AppendResult(error); } -#endif // OPENTHREAD_FTD +#endif // OPENTHREAD_FTD #if OPENTHREAD_FTD void Interpreter::ProcessPSKc(int argc, char *argv[]) @@ -1336,7 +1338,7 @@ exit: void Interpreter::ProcessMode(int argc, char *argv[]) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; otLinkModeConfig linkMode; memset(&linkMode, 0, sizeof(otLinkModeConfig)); @@ -1404,9 +1406,9 @@ exit: #if OPENTHREAD_FTD void Interpreter::ProcessNeighbor(int argc, char *argv[]) { - otError error = OT_ERROR_NONE; - otNeighborInfo neighborInfo; - bool isTable; + otError error = OT_ERROR_NONE; + otNeighborInfo neighborInfo; + bool isTable; otNeighborInfoIterator iterator = OT_NEIGHBOR_INFO_ITERATOR_INIT; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); @@ -1488,7 +1490,7 @@ void Interpreter::ProcessService(int argc, char *argv[]) if (strcmp(argv[0], "add") == 0) { otServiceConfig cfg; - long enterpriseNumber = 0; + long enterpriseNumber = 0; VerifyOrExit(argc > 3, error = OT_ERROR_PARSE); @@ -1496,8 +1498,8 @@ void Interpreter::ProcessService(int argc, char *argv[]) cfg.mServiceDataLength = static_cast(strlen(argv[2])); memcpy(cfg.mServiceData, argv[2], cfg.mServiceDataLength); - cfg.mEnterpriseNumber = static_cast(enterpriseNumber); - cfg.mServerConfig.mStable = true; + cfg.mEnterpriseNumber = static_cast(enterpriseNumber); + cfg.mServerConfig.mStable = true; cfg.mServerConfig.mServerDataLength = static_cast(strlen(argv[3])); memcpy(cfg.mServerConfig.mServerData, argv[3], cfg.mServerConfig.mServerDataLength); @@ -1512,7 +1514,8 @@ void Interpreter::ProcessService(int argc, char *argv[]) SuccessOrExit(error = ParseLong(argv[1], enterpriseNumber)); SuccessOrExit(error = otServerRemoveService(mInstance, static_cast(enterpriseNumber), - reinterpret_cast(argv[2]), static_cast(strlen(argv[2])))); + reinterpret_cast(argv[2]), + static_cast(strlen(argv[2])))); } exit: @@ -1535,13 +1538,13 @@ exit: OT_UNUSED_VARIABLE(argv); AppendResult(error); } -#endif // OPENTHREAD_ENABLE_BORDER_ROUTER || OPENTHREAD_ENABLE_SERVICE +#endif // OPENTHREAD_ENABLE_BORDER_ROUTER || OPENTHREAD_ENABLE_SERVICE #if OPENTHREAD_FTD void Interpreter::ProcessNetworkIdTimeout(int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; if (argc == 0) { @@ -1556,7 +1559,7 @@ void Interpreter::ProcessNetworkIdTimeout(int argc, char *argv[]) exit: AppendResult(error); } -#endif // OPENTHREAD_FTD +#endif // OPENTHREAD_FTD void Interpreter::ProcessNetworkName(int argc, char *argv[]) { @@ -1579,7 +1582,7 @@ exit: void Interpreter::ProcessPanId(int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; if (argc == 0) { @@ -1597,7 +1600,7 @@ exit: void Interpreter::ProcessParent(int argc, char *argv[]) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; otRouterInfo parentInfo; SuccessOrExit(error = otThreadGetParentInfo(mInstance, &parentInfo)); @@ -1625,7 +1628,7 @@ exit: void Interpreter::ProcessParentPriority(int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; if (argc == 0) { @@ -1643,7 +1646,9 @@ exit: #endif #ifndef OTDLL -void Interpreter::s_HandleIcmpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo, +void Interpreter::s_HandleIcmpReceive(void * aContext, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, const otIcmp6Header *aIcmpHeader) { static_cast(aContext)->HandleIcmpReceive(*static_cast(aMessage), @@ -1651,27 +1656,24 @@ void Interpreter::s_HandleIcmpReceive(void *aContext, otMessage *aMessage, const *static_cast(aIcmpHeader)); } -void Interpreter::HandleIcmpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - const otIcmp6Header &aIcmpHeader) +void Interpreter::HandleIcmpReceive(Message & aMessage, + const Ip6::MessageInfo &aMessageInfo, + const otIcmp6Header & aIcmpHeader) { uint32_t timestamp = 0; VerifyOrExit(aIcmpHeader.mType == OT_ICMP6_TYPE_ECHO_REPLY); mServer->OutputFormat("%d bytes from ", aMessage.GetLength() - aMessage.GetOffset()); - mServer->OutputFormat("%x:%x:%x:%x:%x:%x:%x:%x", - HostSwap16(aMessageInfo.GetPeerAddr().mFields.m16[0]), - HostSwap16(aMessageInfo.GetPeerAddr().mFields.m16[1]), - HostSwap16(aMessageInfo.GetPeerAddr().mFields.m16[2]), - HostSwap16(aMessageInfo.GetPeerAddr().mFields.m16[3]), - HostSwap16(aMessageInfo.GetPeerAddr().mFields.m16[4]), - HostSwap16(aMessageInfo.GetPeerAddr().mFields.m16[5]), - HostSwap16(aMessageInfo.GetPeerAddr().mFields.m16[6]), - HostSwap16(aMessageInfo.GetPeerAddr().mFields.m16[7])); + mServer->OutputFormat( + "%x:%x:%x:%x:%x:%x:%x:%x", HostSwap16(aMessageInfo.GetPeerAddr().mFields.m16[0]), + HostSwap16(aMessageInfo.GetPeerAddr().mFields.m16[1]), HostSwap16(aMessageInfo.GetPeerAddr().mFields.m16[2]), + HostSwap16(aMessageInfo.GetPeerAddr().mFields.m16[3]), HostSwap16(aMessageInfo.GetPeerAddr().mFields.m16[4]), + HostSwap16(aMessageInfo.GetPeerAddr().mFields.m16[5]), HostSwap16(aMessageInfo.GetPeerAddr().mFields.m16[6]), + HostSwap16(aMessageInfo.GetPeerAddr().mFields.m16[7])); mServer->OutputFormat(": icmp_seq=%d hlim=%d", HostSwap16(aIcmpHeader.mData.m16[1]), aMessageInfo.mHopLimit); - if (aMessage.Read(aMessage.GetOffset(), sizeof(uint32_t), ×tamp) >= - static_cast(sizeof(uint32_t))) + if (aMessage.Read(aMessage.GetOffset(), sizeof(uint32_t), ×tamp) >= static_cast(sizeof(uint32_t))) { mServer->OutputFormat(" time=%dms", TimerMilli::GetNow() - HostSwap32(timestamp)); } @@ -1686,7 +1688,7 @@ void Interpreter::ProcessPing(int argc, char *argv[]) { otError error = OT_ERROR_NONE; uint8_t index = 1; - long value; + long value; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); @@ -1710,8 +1712,8 @@ void Interpreter::ProcessPing(int argc, char *argv[]) SuccessOrExit(error = mMessageInfo.GetPeerAddr().FromString(argv[0])); mMessageInfo.mInterfaceId = OT_NETIF_INTERFACE_ID_THREAD; - mLength = 8; - mCount = 1; + mLength = 8; + mCount = 1; mInterval = 1000; while (index < argc) @@ -1755,10 +1757,10 @@ void Interpreter::s_HandlePingTimer(Timer &aTimer) void Interpreter::HandlePingTimer() { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint32_t timestamp = HostSwap32(TimerMilli::GetNow()); - otMessage *message; + otMessage * message; const otMessageInfo *messageInfo = static_cast(&mMessageInfo); VerifyOrExit((message = otIp6NewMessage(mInstance, true)) != NULL, error = OT_ERROR_NO_BUFS); @@ -1785,16 +1787,16 @@ exit: void Interpreter::ProcessPollPeriod(int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; if (argc == 0) { - mServer->OutputFormat("%d\r\n", (otLinkGetPollPeriod(mInstance) / 1000)); // ms->s + mServer->OutputFormat("%d\r\n", (otLinkGetPollPeriod(mInstance) / 1000)); // ms->s } else { SuccessOrExit(error = ParseLong(argv[0], value)); - otLinkSetPollPeriod(mInstance, static_cast(value * 1000)); // s->ms + otLinkSetPollPeriod(mInstance, static_cast(value * 1000)); // s->ms } exit: @@ -1910,9 +1912,9 @@ void Interpreter::HandleLinkPcapReceive(const otRadioFrame *aFrame) #if OPENTHREAD_ENABLE_BORDER_ROUTER otError Interpreter::ProcessPrefixAdd(int argc, char *argv[]) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; otBorderRouterConfig config; - int argcur = 0; + int argcur = 0; memset(&config, 0, sizeof(otBorderRouterConfig)); @@ -2000,9 +2002,9 @@ exit: otError Interpreter::ProcessPrefixRemove(int argc, char *argv[]) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; struct otIp6Prefix prefix; - int argcur = 0; + int argcur = 0; memset(&prefix, 0, sizeof(otIp6Prefix)); @@ -2035,16 +2037,14 @@ exit: otError Interpreter::ProcessPrefixList(void) { otNetworkDataIterator iterator = OT_NETWORK_DATA_ITERATOR_INIT; - otBorderRouterConfig config; + otBorderRouterConfig config; while (otBorderRouterGetNextOnMeshPrefix(mInstance, &iterator, &config) == OT_ERROR_NONE) { - mServer->OutputFormat("%x:%x:%x:%x::/%d ", - HostSwap16(config.mPrefix.mPrefix.mFields.m16[0]), + mServer->OutputFormat("%x:%x:%x:%x::/%d ", HostSwap16(config.mPrefix.mPrefix.mFields.m16[0]), HostSwap16(config.mPrefix.mPrefix.mFields.m16[1]), HostSwap16(config.mPrefix.mPrefix.mFields.m16[2]), - HostSwap16(config.mPrefix.mPrefix.mFields.m16[3]), - config.mPrefix.mLength); + HostSwap16(config.mPrefix.mPrefix.mFields.m16[3]), config.mPrefix.mLength); if (config.mPreferred) { @@ -2124,13 +2124,13 @@ void Interpreter::ProcessPrefix(int argc, char *argv[]) exit: AppendResult(error); } -#endif // OPENTHREAD_ENABLE_BORDER_ROUTER +#endif // OPENTHREAD_ENABLE_BORDER_ROUTER #if OPENTHREAD_FTD void Interpreter::ProcessReleaseRouterId(int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); @@ -2140,7 +2140,7 @@ void Interpreter::ProcessReleaseRouterId(int argc, char *argv[]) exit: AppendResult(error); } -#endif // OPENTHREAD_FTD +#endif // OPENTHREAD_FTD void Interpreter::ProcessReset(int argc, char *argv[]) { @@ -2160,9 +2160,9 @@ void Interpreter::ProcessRloc16(int argc, char *argv[]) #if OPENTHREAD_ENABLE_BORDER_ROUTER otError Interpreter::ProcessRouteAdd(int argc, char *argv[]) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; otExternalRouteConfig config; - int argcur = 0; + int argcur = 0; memset(&config, 0, sizeof(otExternalRouteConfig)); @@ -2221,9 +2221,9 @@ exit: otError Interpreter::ProcessRouteRemove(int argc, char *argv[]) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; struct otIp6Prefix prefix; - int argcur = 0; + int argcur = 0; memset(&prefix, 0, sizeof(struct otIp6Prefix)); char *prefixLengthStr; @@ -2275,15 +2275,15 @@ void Interpreter::ProcessRoute(int argc, char *argv[]) exit: AppendResult(error); } -#endif // OPENTHREAD_ENABLE_BORDER_ROUTER +#endif // OPENTHREAD_ENABLE_BORDER_ROUTER #if OPENTHREAD_FTD void Interpreter::ProcessRouter(int argc, char *argv[]) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; otRouterInfo routerInfo; - long value; - bool isTable; + long value; + bool isTable; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); @@ -2293,11 +2293,13 @@ void Interpreter::ProcessRouter(int argc, char *argv[]) { if (isTable) { - mServer->OutputFormat("| ID | RLOC16 | Next Hop | Path Cost | LQ In | LQ Out | Age | Extended MAC |\r\n"); - mServer->OutputFormat("+----+--------+----------+-----------+-------+--------+-----+------------------+\r\n"); + mServer->OutputFormat( + "| ID | RLOC16 | Next Hop | Path Cost | LQ In | LQ Out | Age | Extended MAC |\r\n"); + mServer->OutputFormat( + "+----+--------+----------+-----------+-------+--------+-----+------------------+\r\n"); } - for (uint8_t i = 0; ; i++) + for (uint8_t i = 0;; i++) { if (otThreadGetRouterInfo(mInstance, i, &routerInfo) != OT_ERROR_NONE) { @@ -2369,7 +2371,7 @@ exit: void Interpreter::ProcessRouterDowngradeThreshold(int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; if (argc == 0) { @@ -2420,7 +2422,7 @@ exit: void Interpreter::ProcessRouterSelectionJitter(int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; if (argc == 0) { @@ -2440,7 +2442,7 @@ exit: void Interpreter::ProcessRouterUpgradeThreshold(int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; if (argc == 0) { @@ -2455,13 +2457,13 @@ void Interpreter::ProcessRouterUpgradeThreshold(int argc, char *argv[]) exit: AppendResult(error); } -#endif // OPENTHREAD_FTD +#endif // OPENTHREAD_FTD void Interpreter::ProcessScan(int argc, char *argv[]) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint32_t scanChannels = 0; - long value; + long value; if (argc > 0) { @@ -2558,7 +2560,7 @@ void Interpreter::ProcessState(int argc, char *argv[]) case OT_DEVICE_ROLE_LEADER: mServer->OutputFormat("leader\r\n"); break; -#endif // OPENTHREAD_FTD +#endif // OPENTHREAD_FTD default: mServer->OutputFormat("invalid state\r\n"); @@ -2586,7 +2588,7 @@ void Interpreter::ProcessState(int argc, char *argv[]) SuccessOrExit(error = otThreadBecomeLeader(mInstance)); } -#endif // OPENTHREAD_FTD +#endif // OPENTHREAD_FTD else { ExitNow(error = OT_ERROR_PARSE); @@ -2677,7 +2679,7 @@ void Interpreter::ProcessCommissioner(int argc, char *argv[]) } else if (strcmp(argv[0], "joiner") == 0) { - otExtAddress addr; + otExtAddress addr; const otExtAddress *addrPtr; VerifyOrExit(argc > 2, error = OT_ERROR_PARSE); @@ -2716,9 +2718,9 @@ void Interpreter::ProcessCommissioner(int argc, char *argv[]) } else if (strcmp(argv[0], "announce") == 0) { - long mask; - long count; - long period; + long mask; + long count; + long period; otIp6Address address; VerifyOrExit(argc > 4, error = OT_ERROR_PARSE); @@ -2735,18 +2737,16 @@ void Interpreter::ProcessCommissioner(int argc, char *argv[]) // destination SuccessOrExit(error = otIp6AddressFromString(argv[4], &address)); - SuccessOrExit(error = otCommissionerAnnounceBegin(mInstance, - static_cast(mask), - static_cast(count), - static_cast(period), + SuccessOrExit(error = otCommissionerAnnounceBegin(mInstance, static_cast(mask), + static_cast(count), static_cast(period), &address)); } else if (strcmp(argv[0], "energy") == 0) { - long mask; - long count; - long period; - long scanDuration; + long mask; + long count; + long period; + long scanDuration; otIp6Address address; VerifyOrExit(argc > 5, error = OT_ERROR_PARSE); @@ -2766,19 +2766,15 @@ void Interpreter::ProcessCommissioner(int argc, char *argv[]) // destination SuccessOrExit(error = otIp6AddressFromString(argv[5], &address)); - SuccessOrExit(error = otCommissionerEnergyScan(mInstance, - static_cast(mask), - static_cast(count), - static_cast(period), - static_cast(scanDuration), - &address, - Interpreter::s_HandleEnergyReport, - this)); + SuccessOrExit(error = + otCommissionerEnergyScan(mInstance, static_cast(mask), static_cast(count), + static_cast(period), static_cast(scanDuration), + &address, Interpreter::s_HandleEnergyReport, this)); } else if (strcmp(argv[0], "panid") == 0) { - long panid; - long mask; + long panid; + long mask; otIp6Address address; VerifyOrExit(argc > 3, error = OT_ERROR_PARSE); @@ -2792,18 +2788,15 @@ void Interpreter::ProcessCommissioner(int argc, char *argv[]) // destination SuccessOrExit(error = otIp6AddressFromString(argv[3], &address)); - SuccessOrExit(error = otCommissionerPanIdQuery(mInstance, - static_cast(panid), - static_cast(mask), - &address, - Interpreter::s_HandlePanIdConflict, - this)); + SuccessOrExit(error = + otCommissionerPanIdQuery(mInstance, static_cast(panid), static_cast(mask), + &address, Interpreter::s_HandlePanIdConflict, this)); } else if (strcmp(argv[0], "mgmtget") == 0) { uint8_t tlvs[32]; - long value; - int length = 0; + long value; + int length = 0; for (uint8_t index = 1; index < argc; index++) { @@ -2829,7 +2822,8 @@ void Interpreter::ProcessCommissioner(int argc, char *argv[]) { VerifyOrExit(++index < argc, error = OT_ERROR_PARSE); value = static_cast(strlen(argv[index]) + 1) / 2; - VerifyOrExit(static_cast(value) <= (sizeof(tlvs) - static_cast(length)), error = OT_ERROR_NO_BUFS); + VerifyOrExit(static_cast(value) <= (sizeof(tlvs) - static_cast(length)), + error = OT_ERROR_NO_BUFS); VerifyOrExit(Interpreter::Hex2Bin(argv[index], tlvs + length, static_cast(value)) >= 0, error = OT_ERROR_PARSE); length += value; @@ -2845,9 +2839,9 @@ void Interpreter::ProcessCommissioner(int argc, char *argv[]) else if (strcmp(argv[0], "mgmtset") == 0) { otCommissioningDataset dataset; - uint8_t tlvs[32]; - long value; - int length = 0; + uint8_t tlvs[32]; + long value; + int length = 0; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); @@ -2875,12 +2869,13 @@ void Interpreter::ProcessCommissioner(int argc, char *argv[]) { VerifyOrExit(++index < argc, error = OT_ERROR_PARSE); dataset.mIsSteeringDataSet = true; - length = static_cast((strlen(argv[index]) + 1) / 2); + length = static_cast((strlen(argv[index]) + 1) / 2); VerifyOrExit(static_cast(length) <= OT_STEERING_DATA_MAX_LENGTH, error = OT_ERROR_NO_BUFS); - VerifyOrExit(Interpreter::Hex2Bin(argv[index], dataset.mSteeringData.m8, static_cast(length)) >= 0, - error = OT_ERROR_PARSE); + VerifyOrExit( + Interpreter::Hex2Bin(argv[index], dataset.mSteeringData.m8, static_cast(length)) >= 0, + error = OT_ERROR_PARSE); dataset.mSteeringData.mLength = static_cast(length); - length = 0; + length = 0; } else if (strcmp(argv[index], "joinerudpport") == 0) { @@ -2914,9 +2909,10 @@ exit: AppendResult(error); } -void OTCALL Interpreter::s_HandleEnergyReport(uint32_t aChannelMask, const uint8_t *aEnergyList, - uint8_t aEnergyListLength, - void *aContext) +void OTCALL Interpreter::s_HandleEnergyReport(uint32_t aChannelMask, + const uint8_t *aEnergyList, + uint8_t aEnergyListLength, + void * aContext) { static_cast(aContext)->HandleEnergyReport(aChannelMask, aEnergyList, aEnergyListLength); } @@ -2958,9 +2954,8 @@ void Interpreter::ProcessJoiner(int argc, char *argv[]) const char *provisioningUrl; VerifyOrExit(argc > 1, error = OT_ERROR_PARSE); provisioningUrl = (argc > 2) ? argv[2] : NULL; - otJoinerStart(mInstance, argv[1], provisioningUrl, - PACKAGE_NAME, OPENTHREAD_CONFIG_PLATFORM_INFO, PACKAGE_VERSION, NULL, - &Interpreter::s_HandleJoinerCallback, this); + otJoinerStart(mInstance, argv[1], provisioningUrl, PACKAGE_NAME, OPENTHREAD_CONFIG_PLATFORM_INFO, + PACKAGE_VERSION, NULL, &Interpreter::s_HandleJoinerCallback, this); } else if (strcmp(argv[0], "stop") == 0) { @@ -2973,7 +2968,7 @@ exit: void Interpreter::ProcessJoinerId(int argc, char *argv[]) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; otExtAddress joinerId; VerifyOrExit(argc == 0, error = OT_ERROR_PARSE); @@ -3012,7 +3007,7 @@ void Interpreter::HandleJoinerCallback(otError aError) void Interpreter::ProcessJoinerPort(int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; if (argc == 0) { @@ -3063,9 +3058,9 @@ void Interpreter::ProcessMacFilter(int argc, char *argv[]) void Interpreter::PrintMacFilter(void) { - otMacFilterEntry entry; - otMacFilterIterator iterator = OT_MAC_FILTER_ITERATOR_INIT; - otMacFilterAddressMode mode = otLinkFilterGetAddressMode(mInstance); + otMacFilterEntry entry; + otMacFilterIterator iterator = OT_MAC_FILTER_ITERATOR_INIT; + otMacFilterAddressMode mode = otLinkFilterGetAddressMode(mInstance); if (mode == OT_MAC_FILTER_ADDRESS_MODE_DISABLED) { @@ -3095,7 +3090,7 @@ void Interpreter::PrintMacFilter(void) mServer->OutputFormat(" : rss %d", entry.mRssIn); -#endif // OTDLL +#endif // OTDLL } mServer->OutputFormat("\r\n"); @@ -3120,28 +3115,28 @@ void Interpreter::PrintMacFilter(void) if (i == OT_EXT_ADDRESS_SIZE) { - mServer->OutputFormat("Default rss : %d (lqi %d)\r\n", - entry.mRssIn, otLinkConvertRssToLinkQuality(mInstance, entry.mRssIn)); + mServer->OutputFormat("Default rss : %d (lqi %d)\r\n", entry.mRssIn, + otLinkConvertRssToLinkQuality(mInstance, entry.mRssIn)); } else { OutputBytes(entry.mExtAddress.m8, OT_EXT_ADDRESS_SIZE); - mServer->OutputFormat(" : rss %d (lqi %d)\r\n", - entry.mRssIn, otLinkConvertRssToLinkQuality(mInstance, entry.mRssIn)); + mServer->OutputFormat(" : rss %d (lqi %d)\r\n", entry.mRssIn, + otLinkConvertRssToLinkQuality(mInstance, entry.mRssIn)); } } -#endif // OTDLL +#endif // OTDLL } otError Interpreter::ProcessMacFilterAddress(int argc, char *argv[]) { - otError error = OT_ERROR_NONE; - otExtAddress extAddr; - otMacFilterEntry entry; - otMacFilterIterator iterator = OT_MAC_FILTER_ITERATOR_INIT; - otMacFilterAddressMode mode = otLinkFilterGetAddressMode(mInstance); - long value; + otError error = OT_ERROR_NONE; + otExtAddress extAddr; + otMacFilterEntry entry; + otMacFilterIterator iterator = OT_MAC_FILTER_ITERATOR_INIT; + otMacFilterAddressMode mode = otLinkFilterGetAddressMode(mInstance); + long value; if (argc == 0) { @@ -3173,7 +3168,7 @@ otError Interpreter::ProcessMacFilterAddress(int argc, char *argv[]) mServer->OutputFormat(" : rss %d", entry.mRssIn); -#endif // OTDLL +#endif // OTDLL } mServer->OutputFormat("\r\n"); @@ -3241,12 +3236,12 @@ exit: otError Interpreter::ProcessMacFilterRss(int argc, char *argv[]) { - otError error = OT_ERROR_NONE; - otMacFilterEntry entry; + otError error = OT_ERROR_NONE; + otMacFilterEntry entry; otMacFilterIterator iterator = OT_MAC_FILTER_ITERATOR_INIT; - otExtAddress extAddr; - long value; - int8_t rss; + otExtAddress extAddr; + long value; + int8_t rss; if (argc == 0) { @@ -3264,14 +3259,14 @@ otError Interpreter::ProcessMacFilterRss(int argc, char *argv[]) if (i == OT_EXT_ADDRESS_SIZE) { - mServer->OutputFormat("Default rss: %d (lqi %d)\r\n", - entry.mRssIn, otLinkConvertRssToLinkQuality(mInstance, entry.mRssIn)); + mServer->OutputFormat("Default rss: %d (lqi %d)\r\n", entry.mRssIn, + otLinkConvertRssToLinkQuality(mInstance, entry.mRssIn)); } else { OutputBytes(entry.mExtAddress.m8, OT_EXT_ADDRESS_SIZE); - mServer->OutputFormat(" : rss %d (lqi %d)\r\n", - entry.mRssIn, otLinkConvertRssToLinkQuality(mInstance, entry.mRssIn)); + mServer->OutputFormat(" : rss %d (lqi %d)\r\n", entry.mRssIn, + otLinkConvertRssToLinkQuality(mInstance, entry.mRssIn)); } } } @@ -3346,9 +3341,9 @@ exit: return error; } -#endif // OTDLL +#endif // OTDLL -#endif // OPENTHREAD_ENABLE_MAC_FILTER +#endif // OPENTHREAD_ENABLE_MAC_FILTER #if OPENTHREAD_ENABLE_DIAG void Interpreter::ProcessDiag(int argc, char *argv[]) @@ -3360,20 +3355,20 @@ void Interpreter::ProcessDiag(int argc, char *argv[]) void Interpreter::ProcessLine(char *aBuf, uint16_t aBufLength, Server &aServer) { - char *argv[kMaxArgs]; - char *cmd; + char * argv[kMaxArgs]; + char * cmd; uint8_t argc = 0, i = 0; mServer = &aServer; VerifyOrExit(aBuf != NULL); - for (; *aBuf == ' '; aBuf++, aBufLength--); + for (; *aBuf == ' '; aBuf++, aBufLength--) + ; for (cmd = aBuf + 1; (cmd < aBuf + aBufLength) && (cmd != NULL); ++cmd) { - VerifyOrExit(argc < kMaxArgs, - mServer->OutputFormat("Error: too many args (max %d)\r\n", kMaxArgs)); + VerifyOrExit(argc < kMaxArgs, mServer->OutputFormat("Error: too many args (max %d)\r\n", kMaxArgs)); if (*cmd == ' ' || *cmd == '\r' || *cmd == '\n') { @@ -3389,8 +3384,9 @@ void Interpreter::ProcessLine(char *aBuf, uint16_t aBufLength, Server &aServer) cmd = aBuf; #if OPENTHREAD_ENABLE_DIAG - VerifyOrExit((!otDiagIsEnabled() || (strcmp(cmd, "diag") == 0)), - mServer->OutputFormat("under diagnostics mode, execute 'diag stop' before running any other commands.\r\n")); + VerifyOrExit( + (!otDiagIsEnabled() || (strcmp(cmd, "diag") == 0)), + mServer->OutputFormat("under diagnostics mode, execute 'diag stop' before running any other commands.\r\n")); #endif for (i = 0; i < sizeof(sCommands) / sizeof(sCommands[0]); i++) @@ -3448,11 +3444,11 @@ void Interpreter::HandleNetifStateChanged(uint32_t aFlags) otIp6CreateRandomIid, NULL); #if OPENTHREAD_ENABLE_DHCP6_SERVER otDhcp6ServerUpdate(mInstance); -#endif // OPENTHREAD_ENABLE_DHCP6_SERVER +#endif // OPENTHREAD_ENABLE_DHCP6_SERVER #if OPENTHREAD_ENABLE_DHCP6_CLIENT otDhcp6ClientUpdate(mInstance, mDhcpAddresses, sizeof(mDhcpAddresses) / sizeof(mDhcpAddresses[0]), NULL); -#endif // OPENTHREAD_ENABLE_DHCP6_CLIENT +#endif // OPENTHREAD_ENABLE_DHCP6_CLIENT #endif exit: @@ -3462,11 +3458,11 @@ exit: #if OPENTHREAD_FTD || OPENTHREAD_ENABLE_MTD_NETWORK_DIAGNOSTIC void Interpreter::ProcessNetworkDiagnostic(int argc, char *argv[]) { - otError error = OT_ERROR_NONE; - struct otIp6Address address; - uint8_t tlvTypes[OT_NETWORK_DIAGNOSTIC_TYPELIST_MAX_ENTRIES]; - uint8_t count = 0; - uint8_t argvIndex = 0; + otError error = OT_ERROR_NONE; + struct otIp6Address address; + uint8_t tlvTypes[OT_NETWORK_DIAGNOSTIC_TYPELIST_MAX_ENTRIES]; + uint8_t count = 0; + uint8_t argvIndex = 0; // Include operation, address and type tlv list. VerifyOrExit(argc > 2, error = OT_ERROR_PARSE); @@ -3499,19 +3495,18 @@ exit: #endif // OPENTHREAD_FTD || OPENTHREAD_ENABLE_MTD_NETWORK_DIAGNOSTIC #ifndef OTDLL -void Interpreter::s_HandleDiagnosticGetResponse(otMessage *aMessage, const otMessageInfo *aMessageInfo, - void *aContext) +void Interpreter::s_HandleDiagnosticGetResponse(otMessage *aMessage, const otMessageInfo *aMessageInfo, void *aContext) { - static_cast(aContext)->HandleDiagnosticGetResponse(*static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleDiagnosticGetResponse( + *static_cast(aMessage), *static_cast(aMessageInfo)); } void Interpreter::HandleDiagnosticGetResponse(Message &aMessage, const Ip6::MessageInfo &) { - uint8_t buf[16]; + uint8_t buf[16]; uint16_t bytesToPrint; uint16_t bytesPrinted = 0; - uint16_t length = aMessage.GetLength() - aMessage.GetOffset(); + uint16_t length = aMessage.GetLength() - aMessage.GetOffset(); mServer->OutputFormat("DIAG_GET.rsp/ans: "); @@ -3522,7 +3517,7 @@ void Interpreter::HandleDiagnosticGetResponse(Message &aMessage, const Ip6::Mess OutputBytes(buf, static_cast(bytesToPrint)); - length -= bytesToPrint; + length -= bytesToPrint; bytesPrinted += bytesToPrint; } @@ -3532,7 +3527,7 @@ void Interpreter::HandleDiagnosticGetResponse(Message &aMessage, const Ip6::Mess void Interpreter::SetUserCommands(const otCliCommand *aCommands, uint8_t aLength) { - mUserCommands = aCommands; + mUserCommands = aCommands; mUserCommandsLength = aLength; } @@ -3547,5 +3542,5 @@ Interpreter &Interpreter::GetOwner(OwnerLocator &aOwnerLocator) return interpreter; } -} // namespace Cli -} // namespace ot +} // namespace Cli +} // namespace ot diff --git a/src/cli/cli.hpp b/src/cli/cli.hpp index d1909424d..930970417 100644 --- a/src/cli/cli.hpp +++ b/src/cli/cli.hpp @@ -38,10 +38,10 @@ #include -#include -#include -#include #include +#include +#include +#include #include "cli/cli_server.hpp" #include "cli/cli_udp_example.hpp" @@ -84,8 +84,8 @@ class Interpreter; */ struct Command { - const char *mName; ///< A pointer to the command string. - void (Interpreter::*mCommand)(int argc, char *argv[]); ///< A function pointer to process the command. + const char *mName; ///< A pointer to the command string. + void (Interpreter::*mCommand)(int argc, char *argv[]); ///< A function pointer to process the command. }; /** @@ -98,7 +98,6 @@ class Interpreter friend class UdpExample; public: - /** * Constructor * @@ -177,12 +176,11 @@ public: private: enum { - kMaxArgs = 32, - kMaxAutoAddresses = 8, - kDefaultJoinerTimeout = 120, ///< Default timeout for Joiners, in seconds. + kMaxArgs = 32, + kMaxAutoAddresses = 8, + kDefaultJoinerTimeout = 120, ///< Default timeout for Joiners, in seconds. }; - void ProcessHelp(int argc, char *argv[]); void ProcessAutoStart(int argc, char *argv[]); void ProcessBufferInfo(int argc, char *argv[]); @@ -194,10 +192,10 @@ private: void ProcessChildTimeout(int argc, char *argv[]); #if OPENTHREAD_ENABLE_APPLICATION_COAP void ProcessCoap(int argc, char *argv[]); -#endif //OPENTHREAD_ENABLE_APPLICATION_COAP +#endif // OPENTHREAD_ENABLE_APPLICATION_COAP #if OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD void ProcessCommissioner(int argc, char *argv[]); -#endif // OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD +#endif // OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD #if OPENTHREAD_FTD void ProcessContextIdReuseDelay(int argc, char *argv[]); #endif @@ -208,7 +206,7 @@ private: #endif #if OPENTHREAD_ENABLE_DIAG void ProcessDiag(int argc, char *argv[]); -#endif // OPENTHREAD_ENABLE_DIAG +#endif // OPENTHREAD_ENABLE_DIAG void ProcessDiscover(int argc, char *argv[]); #if OPENTHREAD_ENABLE_DNS_CLIENT void ProcessDns(int argc, char *argv[]); @@ -223,14 +221,14 @@ private: #if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_DEBUG_UART) && OPENTHREAD_EXAMPLES_POSIX void ProcessLogFilename(int argc, char *argv[]); #endif - void ProcessExtAddress(int argc, char *argv[]); - void ProcessExtPanId(int argc, char *argv[]); - void ProcessFactoryReset(int argc, char *argv[]); - void ProcessIfconfig(int argc, char *argv[]); - void ProcessIpAddr(int argc, char *argv[]); + void ProcessExtAddress(int argc, char *argv[]); + void ProcessExtPanId(int argc, char *argv[]); + void ProcessFactoryReset(int argc, char *argv[]); + void ProcessIfconfig(int argc, char *argv[]); + void ProcessIpAddr(int argc, char *argv[]); otError ProcessIpAddrAdd(int argc, char *argv[]); otError ProcessIpAddrDel(int argc, char *argv[]); - void ProcessIpMulticastAddr(int argc, char *argv[]); + void ProcessIpMulticastAddr(int argc, char *argv[]); #ifndef OTDLL otError ProcessIpMulticastAddrAdd(int argc, char *argv[]); otError ProcessIpMulticastAddrDel(int argc, char *argv[]); @@ -239,7 +237,7 @@ private: #if OPENTHREAD_ENABLE_JOINER void ProcessJoiner(int argc, char *argv[]); void ProcessJoinerId(int argc, char *argv[]); -#endif // OPENTHREAD_ENABLE_JOINER +#endif // OPENTHREAD_ENABLE_JOINER #if OPENTHREAD_FTD void ProcessJoinerPort(int argc, char *argv[]); #endif @@ -276,7 +274,7 @@ private: void ProcessPing(int argc, char *argv[]); void ProcessPollPeriod(int argc, char *argv[]); #if OPENTHREAD_ENABLE_BORDER_ROUTER - void ProcessPrefix(int argc, char *argv[]); + void ProcessPrefix(int argc, char *argv[]); otError ProcessPrefixAdd(int argc, char *argv[]); otError ProcessPrefixRemove(int argc, char *argv[]); otError ProcessPrefixList(void); @@ -288,7 +286,7 @@ private: #endif void ProcessReset(int argc, char *argv[]); #if OPENTHREAD_ENABLE_BORDER_ROUTER - void ProcessRoute(int argc, char *argv[]); + void ProcessRoute(int argc, char *argv[]); otError ProcessRouteAdd(int argc, char *argv[]); otError ProcessRouteRemove(int argc, char *argv[]); #endif @@ -310,13 +308,13 @@ private: #endif void ProcessVersion(int argc, char *argv[]); #if OPENTHREAD_ENABLE_MAC_FILTER - void ProcessMacFilter(int argc, char *argv[]); - void PrintMacFilter(void); + void ProcessMacFilter(int argc, char *argv[]); + void PrintMacFilter(void); otError ProcessMacFilterAddress(int argc, char *argv[]); #ifndef OTDLL otError ProcessMacFilterRss(int argc, char *argv[]); -#endif // OTDLL -#endif // OPENTHREAD_ENABLE_MAC_FILTER +#endif // OTDLL +#endif // OPENTHREAD_ENABLE_MAC_FILTER #ifdef OTDLL void ProcessInstanceList(int argc, char *argv[]); @@ -324,7 +322,9 @@ private: #endif #ifndef OTDLL - static void s_HandleIcmpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo, + static void s_HandleIcmpReceive(void * aContext, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, const otIcmp6Header *aIcmpHeader); static void s_HandlePingTimer(Timer &aTimer); #endif @@ -333,23 +333,28 @@ private: #ifndef OTDLL static void s_HandleLinkPcapReceive(const otRadioFrame *aFrame, void *aContext); #endif - static void OTCALL s_HandleEnergyReport(uint32_t aChannelMask, const uint8_t *aEnergyList, uint8_t aEnergyListLength, - void *aContext); + static void OTCALL s_HandleEnergyReport(uint32_t aChannelMask, + const uint8_t *aEnergyList, + uint8_t aEnergyListLength, + void * aContext); static void OTCALL s_HandlePanIdConflict(uint16_t aPanId, uint32_t aChannelMask, void *aContext); #ifndef OTDLL - static void OTCALL s_HandleDiagnosticGetResponse(otMessage *aMessage, const otMessageInfo *aMessageInfo, - void *aContext); + static void OTCALL s_HandleDiagnosticGetResponse(otMessage * aMessage, + const otMessageInfo *aMessageInfo, + void * aContext); #endif static void OTCALL s_HandleJoinerCallback(otError aError, void *aContext); #if OPENTHREAD_ENABLE_DNS_CLIENT - static void s_HandleDnsResponse(void *aContext, const char *aHostname, otIp6Address *aAddress, - uint32_t aTtl, otError aResult); + static void s_HandleDnsResponse(void * aContext, + const char * aHostname, + otIp6Address *aAddress, + uint32_t aTtl, + otError aResult); #endif #ifndef OTDLL - void HandleIcmpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - const otIcmp6Header &aIcmpHeader); + void HandleIcmpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo, const otIcmp6Header &aIcmpHeader); void HandlePingTimer(); #endif void HandleActiveScanResult(otActiveScanResult *aResult); @@ -381,8 +386,8 @@ private: #endif // OPENTHREAD_ENABLE_APPLICATION_COAP static const struct Command sCommands[]; - const otCliCommand *mUserCommands; - uint8_t mUserCommandsLength; + const otCliCommand * mUserCommands; + uint8_t mUserCommandsLength; Server *mServer; @@ -395,30 +400,30 @@ private: struct otCliContext { Interpreter *mInterpreter; - Instance *mInstance; + Instance * mInstance; }; otCliContext mInstances[MAX_CLI_OT_INSTANCES]; - uint8_t mInstancesLength; - uint8_t mInstanceIndex; + uint8_t mInstancesLength; + uint8_t mInstanceIndex; #else Ip6::MessageInfo mMessageInfo; - uint16_t mLength; - uint16_t mCount; - uint32_t mInterval; + uint16_t mLength; + uint16_t mCount; + uint32_t mInterval; TimerMilli mPingTimer; - otNetifAddress mSlaacAddresses[OPENTHREAD_CONFIG_NUM_SLAAC_ADDRESSES]; + otNetifAddress mSlaacAddresses[OPENTHREAD_CONFIG_NUM_SLAAC_ADDRESSES]; #if OPENTHREAD_ENABLE_DHCP6_CLIENT otDhcpAddress mDhcpAddresses[OPENTHREAD_CONFIG_NUM_DHCP_PREFIXES]; #endif // OPENTHREAD_ENABLE_DHCP6_CLIENT otIcmp6Handler mIcmpHandler; #if OPENTHREAD_ENABLE_DNS_CLIENT - bool mResolvingInProgress; - char mResolvingHostname[OT_DNS_MAX_HOSTNAME_LENGTH]; + bool mResolvingInProgress; + char mResolvingHostname[OT_DNS_MAX_HOSTNAME_LENGTH]; #endif UdpExample mUdp; @@ -428,7 +433,7 @@ private: Instance *mInstance; }; -} // namespace Cli -} // namespace ot +} // namespace Cli +} // namespace ot -#endif // CLI_HPP_ +#endif // CLI_HPP_ diff --git a/src/cli/cli_coap.cpp b/src/cli/cli_coap.cpp index f4ecdc244..e536bb39a 100644 --- a/src/cli/cli_coap.cpp +++ b/src/cli/cli_coap.cpp @@ -43,18 +43,18 @@ namespace ot { namespace Cli { -Coap::Coap(Interpreter &aInterpreter): - mInterpreter(aInterpreter) +Coap::Coap(Interpreter &aInterpreter) + : mInterpreter(aInterpreter) { memset(&mResource, 0, sizeof(mResource)); } void Coap::PrintPayload(otMessage *aMessage) const { - uint8_t buf[kMaxBufferSize]; + uint8_t buf[kMaxBufferSize]; uint16_t bytesToPrint; uint16_t bytesPrinted = 0; - uint16_t length = otMessageGetLength(aMessage) - otMessageGetOffset(aMessage); + uint16_t length = otMessageGetLength(aMessage) - otMessageGetOffset(aMessage); if (length > 0) { @@ -67,7 +67,7 @@ void Coap::PrintPayload(otMessage *aMessage) const mInterpreter.OutputBytes(buf, static_cast(bytesToPrint)); - length -= bytesToPrint; + length -= bytesToPrint; bytesPrinted += bytesToPrint; } } @@ -115,7 +115,9 @@ exit: return error; } -void OTCALL Coap::HandleServerResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void OTCALL Coap::HandleServerResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { static_cast(aContext)->HandleServerResponse(aHeader, aMessage, aMessageInfo); @@ -123,21 +125,18 @@ void OTCALL Coap::HandleServerResponse(void *aContext, otCoapHeader *aHeader, ot void Coap::HandleServerResponse(otCoapHeader *aHeader, otMessage *aMessage, const otMessageInfo *aMessageInfo) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; otCoapHeader responseHeader; - otMessage *responseMessage; - otCoapCode responseCode = OT_COAP_CODE_EMPTY; - char responseContent = '0'; + otMessage * responseMessage; + otCoapCode responseCode = OT_COAP_CODE_EMPTY; + char responseContent = '0'; - mInterpreter.mServer->OutputFormat("Received coap request from [%x:%x:%x:%x:%x:%x:%x:%x]: ", - HostSwap16(aMessageInfo->mSockAddr.mFields.m16[0]), - HostSwap16(aMessageInfo->mSockAddr.mFields.m16[1]), - HostSwap16(aMessageInfo->mSockAddr.mFields.m16[2]), - HostSwap16(aMessageInfo->mSockAddr.mFields.m16[3]), - HostSwap16(aMessageInfo->mSockAddr.mFields.m16[4]), - HostSwap16(aMessageInfo->mSockAddr.mFields.m16[5]), - HostSwap16(aMessageInfo->mSockAddr.mFields.m16[6]), - HostSwap16(aMessageInfo->mSockAddr.mFields.m16[7])); + mInterpreter.mServer->OutputFormat( + "Received coap request from [%x:%x:%x:%x:%x:%x:%x:%x]: ", HostSwap16(aMessageInfo->mSockAddr.mFields.m16[0]), + HostSwap16(aMessageInfo->mSockAddr.mFields.m16[1]), HostSwap16(aMessageInfo->mSockAddr.mFields.m16[2]), + HostSwap16(aMessageInfo->mSockAddr.mFields.m16[3]), HostSwap16(aMessageInfo->mSockAddr.mFields.m16[4]), + HostSwap16(aMessageInfo->mSockAddr.mFields.m16[5]), HostSwap16(aMessageInfo->mSockAddr.mFields.m16[6]), + HostSwap16(aMessageInfo->mSockAddr.mFields.m16[7])); switch (otCoapHeaderGetCode(aHeader)) { @@ -199,8 +198,8 @@ exit: if (error != OT_ERROR_NONE && responseMessage != NULL) { - mInterpreter.mServer->OutputFormat("Cannot send coap response message: Error %d: %s\r\n", - error, otThreadErrorToString(error)); + mInterpreter.mServer->OutputFormat("Cannot send coap response message: Error %d: %s\r\n", error, + otThreadErrorToString(error)); otMessageFree(responseMessage); } else if (responseCode >= OT_COAP_CODE_RESPONSE_MIN) @@ -211,16 +210,16 @@ exit: otError Coap::ProcessRequest(int argc, char *argv[]) { - otError error = OT_ERROR_NONE; - otMessage *message = NULL; + otError error = OT_ERROR_NONE; + otMessage * message = NULL; otMessageInfo messageInfo; - otCoapHeader header; - uint16_t payloadLength = 0; + otCoapHeader header; + uint16_t payloadLength = 0; // Default parameters - char coapUri[kMaxUriLength] = "test"; - otCoapType coapType = OT_COAP_TYPE_NON_CONFIRMABLE; - otCoapCode coapCode = OT_COAP_CODE_GET; + char coapUri[kMaxUriLength] = "test"; + otCoapType coapType = OT_COAP_TYPE_NON_CONFIRMABLE; + otCoapCode coapCode = OT_COAP_CODE_GET; otIp6Address coapDestinationIp; VerifyOrExit(argc > 0, error = OT_ERROR_INVALID_ARGS); @@ -300,8 +299,8 @@ otError Coap::ProcessRequest(int argc, char *argv[]) } memset(&messageInfo, 0, sizeof(messageInfo)); - messageInfo.mPeerAddr = coapDestinationIp; - messageInfo.mPeerPort = OT_DEFAULT_COAP_PORT; + messageInfo.mPeerAddr = coapDestinationIp; + messageInfo.mPeerPort = OT_DEFAULT_COAP_PORT; messageInfo.mInterfaceId = OT_NETIF_INTERFACE_ID_THREAD; if ((coapType == OT_COAP_TYPE_CONFIRMABLE) || (coapCode == OT_COAP_CODE_GET)) @@ -325,19 +324,24 @@ exit: return error; } -void OTCALL Coap::HandleClientResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError aError) +void OTCALL Coap::HandleClientResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aError) { static_cast(aContext)->HandleClientResponse(aHeader, aMessage, aMessageInfo, aError); } -void Coap::HandleClientResponse(otCoapHeader *aHeader, otMessage *aMessage, const otMessageInfo *aMessageInfo, - otError aError) +void Coap::HandleClientResponse(otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aError) { if (aError != OT_ERROR_NONE) { - mInterpreter.mServer->OutputFormat("Error receiving coap response message: Error %d: %s\r\n", - aError, otThreadErrorToString(aError)); + mInterpreter.mServer->OutputFormat("Error receiving coap response message: Error %d: %s\r\n", aError, + otThreadErrorToString(aError)); } else { @@ -349,7 +353,7 @@ void Coap::HandleClientResponse(otCoapHeader *aHeader, otMessage *aMessage, cons OT_UNUSED_VARIABLE(aMessageInfo); } -} // namespace Cli -} // namespace ot +} // namespace Cli +} // namespace ot #endif // OPENTHREAD_ENABLE_APPLICATION_COAP diff --git a/src/cli/cli_coap.hpp b/src/cli/cli_coap.hpp index db09f0f58..2513d9c59 100644 --- a/src/cli/cli_coap.hpp +++ b/src/cli/cli_coap.hpp @@ -74,7 +74,7 @@ public: private: enum { - kMaxUriLength = 32, + kMaxUriLength = 32, kMaxBufferSize = 16 }; @@ -82,24 +82,31 @@ private: otError ProcessRequest(int argc, char *argv[]); - static void OTCALL HandleServerResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void OTCALL HandleServerResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); void HandleServerResponse(otCoapHeader *aHeader, otMessage *aMessage, const otMessageInfo *aMessageInfo); - static void OTCALL HandleClientResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError aError); - void HandleClientResponse(otCoapHeader *aHeader, otMessage *aMessage, const otMessageInfo *aMessageInfo, - otError aError); + static void OTCALL HandleClientResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aError); + void HandleClientResponse(otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aError); otCoapResource mResource; - char mUriPath[kMaxUriLength]; + char mUriPath[kMaxUriLength]; Interpreter &mInterpreter; }; -} // namespace Cli -} // namespace ot +} // namespace Cli +} // namespace ot -#endif // OPENTHREAD_ENABLE_APPLICATION_COAP +#endif // OPENTHREAD_ENABLE_APPLICATION_COAP -#endif // CLI_COAP_HPP_ +#endif // CLI_COAP_HPP_ diff --git a/src/cli/cli_console.cpp b/src/cli/cli_console.cpp index 126f9f769..bfe25545c 100644 --- a/src/cli/cli_console.cpp +++ b/src/cli/cli_console.cpp @@ -53,7 +53,7 @@ extern "C" void otCliConsoleInit(otInstance *aInstance, otCliConsoleOutputCallba { Instance *instance = static_cast(aInstance); - sServer = new(&sCliConsoleRaw) Console(instance); + sServer = new (&sCliConsoleRaw) Console(instance); sServer->SetOutputCallback(aCallback); sServer->SetContext(aContext); } @@ -63,12 +63,11 @@ extern "C" void otCliConsoleInputLine(char *aBuf, uint16_t aBufLength) sServer->ReceiveTask(aBuf, aBufLength); } -Console::Console(Instance *aInstance): - mCallback(NULL), - mContext(NULL), - mInterpreter(aInstance) +Console::Console(Instance *aInstance) + : mCallback(NULL) + , mContext(NULL) + , mInterpreter(aInstance) { - } void Console::SetContext(void *aContext) @@ -93,7 +92,7 @@ int Console::Output(const char *aBuf, uint16_t aBufLength) int Console::OutputFormat(const char *fmt, ...) { - char buf[kMaxLineLength]; + char buf[kMaxLineLength]; va_list ap; va_start(ap, fmt); @@ -103,5 +102,5 @@ int Console::OutputFormat(const char *fmt, ...) return Output(buf, static_cast(strlen(buf))); } -} // namespace Cli -} // namespace ot +} // namespace Cli +} // namespace ot diff --git a/src/cli/cli_console.hpp b/src/cli/cli_console.hpp index 51808ed55..c1cb15a5f 100644 --- a/src/cli/cli_console.hpp +++ b/src/cli/cli_console.hpp @@ -48,7 +48,7 @@ namespace Cli { * This class implements the CLI server on top of the CONSOLE platform abstraction. * */ -class Console: public Server +class Console : public Server { public: /** @@ -106,13 +106,12 @@ private: }; otCliConsoleOutputCallback mCallback; - void *mContext; + void * mContext; Interpreter mInterpreter; - }; -} // namespace Cli -} // namespace ot +} // namespace Cli +} // namespace ot -#endif // CLI_CONSOLE_HPP_ +#endif // CLI_CONSOLE_HPP_ diff --git a/src/cli/cli_dataset.cpp b/src/cli/cli_dataset.cpp index d16fbdb9e..a0af7b724 100644 --- a/src/cli/cli_dataset.cpp +++ b/src/cli/cli_dataset.cpp @@ -48,34 +48,33 @@ namespace ot { namespace Cli { -const DatasetCommand Dataset::sCommands[] = -{ - { "help", &ProcessHelp }, - { "active", &ProcessActive }, +const DatasetCommand Dataset::sCommands[] = { + {"help", &ProcessHelp}, + {"active", &ProcessActive}, #if OPENTHREAD_FTD - { "activetimestamp", &ProcessActiveTimestamp }, - { "channel", &ProcessChannel }, - { "channelmask", &ProcessChannelMask }, - { "clear", &ProcessClear }, - { "commit", &ProcessCommit }, - { "delay", &ProcessDelay }, - { "extpanid", &ProcessExtPanId }, - { "masterkey", &ProcessMasterKey }, - { "meshlocalprefix", &ProcessMeshLocalPrefix }, - { "mgmtgetcommand", &ProcessMgmtGetCommand }, - { "mgmtsetcommand", &ProcessMgmtSetCommand }, - { "networkname", &ProcessNetworkName }, - { "panid", &ProcessPanId }, + {"activetimestamp", &ProcessActiveTimestamp}, + {"channel", &ProcessChannel}, + {"channelmask", &ProcessChannelMask}, + {"clear", &ProcessClear}, + {"commit", &ProcessCommit}, + {"delay", &ProcessDelay}, + {"extpanid", &ProcessExtPanId}, + {"masterkey", &ProcessMasterKey}, + {"meshlocalprefix", &ProcessMeshLocalPrefix}, + {"mgmtgetcommand", &ProcessMgmtGetCommand}, + {"mgmtsetcommand", &ProcessMgmtSetCommand}, + {"networkname", &ProcessNetworkName}, + {"panid", &ProcessPanId}, #endif - { "pending", &ProcessPending }, + {"pending", &ProcessPending}, #if OPENTHREAD_FTD - { "pendingtimestamp", &ProcessPendingTimestamp }, - { "pskc", &ProcessPSKc }, - { "securitypolicy", &ProcessSecurityPolicy }, + {"pendingtimestamp", &ProcessPendingTimestamp}, + {"pskc", &ProcessPSKc}, + {"securitypolicy", &ProcessSecurityPolicy}, #endif }; -Server *Dataset::sServer; +Server * Dataset::sServer; otOperationalDataset Dataset::sDataset; void Dataset::OutputBytes(const uint8_t *aBytes, uint8_t aLength) @@ -123,11 +122,10 @@ otError Dataset::Print(otOperationalDataset &aDataset) if (aDataset.mIsMeshLocalPrefixSet) { const uint8_t *prefix = aDataset.mMeshLocalPrefix.m8; - sServer->OutputFormat("Mesh Local Prefix: %x:%x:%x:%x/64\r\n", - (static_cast(prefix[0]) << 8) | prefix[1], - (static_cast(prefix[2]) << 8) | prefix[3], - (static_cast(prefix[4]) << 8) | prefix[5], - (static_cast(prefix[6]) << 8) | prefix[7]); + sServer->OutputFormat( + "Mesh Local Prefix: %x:%x:%x:%x/64\r\n", (static_cast(prefix[0]) << 8) | prefix[1], + (static_cast(prefix[2]) << 8) | prefix[3], (static_cast(prefix[4]) << 8) | prefix[5], + (static_cast(prefix[6]) << 8) | prefix[7]); } if (aDataset.mIsMasterKeySet) @@ -230,7 +228,7 @@ otError Dataset::ProcessHelp(otInstance *aInstance, int argc, char *argv[]) otError Dataset::ProcessActive(otInstance *aInstance, int argc, char *argv[]) { otOperationalDataset dataset; - otError error; + otError error; SuccessOrExit(error = otDatasetGetActive(aInstance, &dataset)); error = Print(dataset); @@ -244,7 +242,7 @@ exit: otError Dataset::ProcessPending(otInstance *aInstance, int argc, char *argv[]) { otOperationalDataset dataset; - otError error; + otError error; SuccessOrExit(error = otDatasetGetPending(aInstance, &dataset)); error = Print(dataset); @@ -259,11 +257,11 @@ exit: otError Dataset::ProcessActiveTimestamp(otInstance *aInstance, int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); SuccessOrExit(error = Interpreter::ParseLong(argv[0], value)); - sDataset.mActiveTimestamp = static_cast(value); + sDataset.mActiveTimestamp = static_cast(value); sDataset.mIsActiveTimestampSet = true; OT_UNUSED_VARIABLE(aInstance); @@ -275,11 +273,11 @@ exit: otError Dataset::ProcessChannel(otInstance *aInstance, int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); SuccessOrExit(error = Interpreter::ParseLong(argv[0], value)); - sDataset.mChannel = static_cast(value); + sDataset.mChannel = static_cast(value); sDataset.mIsChannelSet = true; OT_UNUSED_VARIABLE(aInstance); @@ -291,11 +289,11 @@ exit: otError Dataset::ProcessChannelMask(otInstance *aInstance, int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); SuccessOrExit(error = Interpreter::ParseLong(argv[0], value)); - sDataset.mChannelMaskPage0 = static_cast(value); + sDataset.mChannelMaskPage0 = static_cast(value); sDataset.mIsChannelMaskPage0Set = true; OT_UNUSED_VARIABLE(aInstance); @@ -340,11 +338,11 @@ exit: otError Dataset::ProcessDelay(otInstance *aInstance, int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); SuccessOrExit(error = Interpreter::ParseLong(argv[0], value)); - sDataset.mDelay = static_cast(value); + sDataset.mDelay = static_cast(value); sDataset.mIsDelaySet = true; OT_UNUSED_VARIABLE(aInstance); @@ -376,8 +374,7 @@ otError Dataset::ProcessMasterKey(otInstance *aInstance, int argc, char *argv[]) uint8_t key[OT_MASTER_KEY_SIZE]; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); - VerifyOrExit((Interpreter::Hex2Bin(argv[0], key, sizeof(key))) == OT_MASTER_KEY_SIZE, - error = OT_ERROR_PARSE); + VerifyOrExit((Interpreter::Hex2Bin(argv[0], key, sizeof(key))) == OT_MASTER_KEY_SIZE, error = OT_ERROR_PARSE); memcpy(sDataset.mMasterKey.m8, key, sizeof(sDataset.mMasterKey)); sDataset.mIsMasterKeySet = true; @@ -390,7 +387,7 @@ exit: otError Dataset::ProcessMeshLocalPrefix(otInstance *aInstance, int argc, char *argv[]) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; otIp6Address prefix; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); @@ -408,7 +405,7 @@ exit: otError Dataset::ProcessNetworkName(otInstance *aInstance, int argc, char *argv[]) { otError error = OT_ERROR_NONE; - size_t length; + size_t length; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); VerifyOrExit((length = strlen(argv[0])) <= OT_NETWORK_NAME_MAX_SIZE, error = OT_ERROR_PARSE); @@ -426,11 +423,11 @@ exit: otError Dataset::ProcessPanId(otInstance *aInstance, int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); SuccessOrExit(error = Interpreter::ParseLong(argv[0], value)); - sDataset.mPanId = static_cast(value); + sDataset.mPanId = static_cast(value); sDataset.mIsPanIdSet = true; OT_UNUSED_VARIABLE(aInstance); @@ -442,11 +439,11 @@ exit: otError Dataset::ProcessPendingTimestamp(otInstance *aInstance, int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); SuccessOrExit(error = Interpreter::ParseLong(argv[0], value)); - sDataset.mPendingTimestamp = static_cast(value); + sDataset.mPendingTimestamp = static_cast(value); sDataset.mIsPendingTimestampSet = true; OT_UNUSED_VARIABLE(aInstance); @@ -457,12 +454,12 @@ exit: otError Dataset::ProcessMgmtSetCommand(otInstance *aInstance, int argc, char *argv[]) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; otOperationalDataset dataset; - uint8_t tlvs[128]; - long value; - int length = 0; - otIp6Address prefix; + uint8_t tlvs[128]; + long value; + int length = 0; + otIp6Address prefix; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); @@ -489,7 +486,8 @@ otError Dataset::ProcessMgmtSetCommand(otInstance *aInstance, int argc, char *ar VerifyOrExit(index < argc, error = OT_ERROR_PARSE); dataset.mIsMasterKeySet = true; VerifyOrExit((length = Interpreter::Hex2Bin(argv[++index], dataset.mMasterKey.m8, - sizeof(dataset.mMasterKey.m8))) == OT_MASTER_KEY_SIZE, error = OT_ERROR_PARSE); + sizeof(dataset.mMasterKey.m8))) == OT_MASTER_KEY_SIZE, + error = OT_ERROR_PARSE); length = 0; } else if (strcmp(argv[index], "networkname") == 0) @@ -506,8 +504,9 @@ otError Dataset::ProcessMgmtSetCommand(otInstance *aInstance, int argc, char *ar { VerifyOrExit(index < argc, error = OT_ERROR_PARSE); dataset.mIsExtendedPanIdSet = true; - VerifyOrExit(Interpreter::Hex2Bin(argv[++index], dataset.mExtendedPanId.m8, - sizeof(dataset.mExtendedPanId.m8)) >= 0, error = OT_ERROR_PARSE); + VerifyOrExit( + Interpreter::Hex2Bin(argv[++index], dataset.mExtendedPanId.m8, sizeof(dataset.mExtendedPanId.m8)) >= 0, + error = OT_ERROR_PARSE); } else if (strcmp(argv[index], "localprefix") == 0) { @@ -579,13 +578,13 @@ exit: otError Dataset::ProcessMgmtGetCommand(otInstance *aInstance, int argc, char *argv[]) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; otOperationalDataset dataset; - uint8_t tlvs[32]; - long value; - int length = 0; - bool destAddrSpecified = false; - otIp6Address address; + uint8_t tlvs[32]; + long value; + int length = 0; + bool destAddrSpecified = false; + otIp6Address address; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); @@ -635,7 +634,8 @@ otError Dataset::ProcessMgmtGetCommand(otInstance *aInstance, int argc, char *ar { VerifyOrExit((index + 1) < argc, error = OT_ERROR_PARSE); value = static_cast(strlen(argv[++index]) + 1) / 2; - VerifyOrExit(static_cast(value) <= (sizeof(tlvs) - static_cast(length)), error = OT_ERROR_NO_BUFS); + VerifyOrExit(static_cast(value) <= (sizeof(tlvs) - static_cast(length)), + error = OT_ERROR_NO_BUFS); VerifyOrExit(Interpreter::Hex2Bin(argv[index], tlvs + length, static_cast(value)) >= 0, error = OT_ERROR_PARSE); length += value; @@ -675,7 +675,7 @@ exit: otError Dataset::ProcessPSKc(otInstance *aInstance, int argc, char *argv[]) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint16_t length; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); @@ -694,13 +694,13 @@ exit: otError Dataset::ProcessSecurityPolicy(otInstance *aInstance, int argc, char *argv[]) { otError error = OT_ERROR_NONE; - long value; + long value; VerifyOrExit(argc > 0, error = OT_ERROR_PARSE); SuccessOrExit(error = Interpreter::ParseLong(argv[0], value)); sDataset.mSecurityPolicy.mRotationTime = static_cast(value); - sDataset.mSecurityPolicy.mFlags = 0; + sDataset.mSecurityPolicy.mFlags = 0; if (argc > 1) { @@ -740,7 +740,7 @@ otError Dataset::ProcessSecurityPolicy(otInstance *aInstance, int argc, char *ar exit: return error; } -#endif // OPENTHREAD_FTD +#endif // OPENTHREAD_FTD -} // namespace Cli -} // namespace ot +} // namespace Cli +} // namespace ot diff --git a/src/cli/cli_dataset.hpp b/src/cli/cli_dataset.hpp index 6b96db668..4d059a2ef 100644 --- a/src/cli/cli_dataset.hpp +++ b/src/cli/cli_dataset.hpp @@ -50,7 +50,7 @@ namespace Cli { struct DatasetCommand { const char *mName; ///< A pointer to the command string. - otError(*mCommand)(otInstance *aInstance, int argc, char *argv[]); ///< A function pointer to process the command. + otError (*mCommand)(otInstance *aInstance, int argc, char *argv[]); ///< A function pointer to process the command. }; /** @@ -70,7 +70,7 @@ public: static otError Process(otInstance *aInstance, int argc, char *argv[], Server &aServer); private: - static void OutputBytes(const uint8_t *aBytes, uint8_t aLength); + static void OutputBytes(const uint8_t *aBytes, uint8_t aLength); static otError Print(otOperationalDataset &aDataset); static otError ProcessHelp(otInstance *aInstance, int argc, char *argv[]); @@ -95,10 +95,10 @@ private: static const DatasetCommand sCommands[]; static otOperationalDataset sDataset; - static Server *sServer; + static Server * sServer; }; -} // namespace Cli -} // namespace ot +} // namespace Cli +} // namespace ot -#endif // CLI_DATASET_HPP_ +#endif // CLI_DATASET_HPP_ diff --git a/src/cli/cli_server.hpp b/src/cli/cli_server.hpp index f9ce50c79..58cc7bcbf 100644 --- a/src/cli/cli_server.hpp +++ b/src/cli/cli_server.hpp @@ -71,7 +71,7 @@ public: virtual int OutputFormat(const char *fmt, ...) = 0; }; -} // namespace Cli -} // namespace ot +} // namespace Cli +} // namespace ot -#endif // CLI_SERVER_HPP_ +#endif // CLI_SERVER_HPP_ diff --git a/src/cli/cli_uart.cpp b/src/cli/cli_uart.cpp index 296c18984..493d2d66e 100644 --- a/src/cli/cli_uart.cpp +++ b/src/cli/cli_uart.cpp @@ -44,11 +44,11 @@ #include "cli/cli.hpp" #include "common/code_utils.hpp" #include "common/encoding.hpp" +#include "common/logging.hpp" #include "common/new.hpp" #include "common/tasklet.hpp" -#include "common/logging.hpp" -#if OPENTHREAD_CONFIG_ENABLE_DEBUG_UART +#if OPENTHREAD_CONFIG_ENABLE_DEBUG_UART #include #endif @@ -56,9 +56,9 @@ namespace ot { namespace Cli { static const char sCommandPrompt[] = {'>', ' '}; -static const char sEraseString[] = {'\b', ' ', '\b'}; -static const char CRNL[] = {'\r', '\n'}; -Uart *Uart::sUartServer; +static const char sEraseString[] = {'\b', ' ', '\b'}; +static const char CRNL[] = {'\r', '\n'}; +Uart * Uart::sUartServer; static otDEFINE_ALIGNED_VAR(sCliUartRaw, sizeof(Uart), uint64_t); @@ -66,7 +66,7 @@ extern "C" void otCliUartInit(otInstance *aInstance) { Instance *instance = static_cast(aInstance); - Uart::sUartServer = new(&sCliUartRaw) Uart(instance); + Uart::sUartServer = new (&sCliUartRaw) Uart(instance); } extern "C" void otCliUartSetUserCommands(const otCliCommand *aUserCommands, uint8_t aLength) @@ -92,12 +92,12 @@ extern "C" void otCliUartAppendResult(otError aError) Uart::sUartServer->GetInterpreter().AppendResult(aError); } -Uart::Uart(Instance *aInstance): - mInterpreter(aInstance) +Uart::Uart(Instance *aInstance) + : mInterpreter(aInstance) { - mRxLength = 0; - mTxHead = 0; - mTxLength = 0; + mRxLength = 0; + mTxHead = 0; + mTxLength = 0; mSendLength = 0; otPlatUartEnable(); @@ -176,32 +176,32 @@ otError Uart::ProcessCommand(void) mRxBuffer[--mRxLength] = '\0'; } -#if OPENTHREAD_CONFIG_LOG_OUTPUT != OPENTHREAD_CONFIG_LOG_OUTPUT_NONE - /* - * Note this is here for this reason: - * - * TEXT (command) input ... in a test automation script occurs - * rapidly and often without gaps between the command and the - * terminal CR - * - * In contrast as a human is typing there is a delay between the - * last character of a command and the terminal CR which executes - * a command. - * - * During that human induced delay a tasklet may be scheduled and - * the LOG becomes confusing and it is hard to determine when - * something happened. Which happened first? the command-CR or - * the tasklet. - * - * Yes, while rare it is a race condition that is hard to debug. - * - * Thus this is here to affirmatively LOG exactly when the CLI - * command is being executed. - */ +#if OPENTHREAD_CONFIG_LOG_OUTPUT != OPENTHREAD_CONFIG_LOG_OUTPUT_NONE + /* + * Note this is here for this reason: + * + * TEXT (command) input ... in a test automation script occurs + * rapidly and often without gaps between the command and the + * terminal CR + * + * In contrast as a human is typing there is a delay between the + * last character of a command and the terminal CR which executes + * a command. + * + * During that human induced delay a tasklet may be scheduled and + * the LOG becomes confusing and it is hard to determine when + * something happened. Which happened first? the command-CR or + * the tasklet. + * + * Yes, while rare it is a race condition that is hard to debug. + * + * Thus this is here to affirmatively LOG exactly when the CLI + * command is being executed. + */ #if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES - /* TODO: how exactly do we get the instance here? */ + /* TODO: how exactly do we get the instance here? */ #else - otLogInfoCli(&Instance::Get(), "execute command: %s", mRxBuffer); + otLogInfoCli(&Instance::Get(), "execute command: %s", mRxBuffer); #endif #endif mInterpreter.ProcessLine(mRxBuffer, mRxLength, *this); @@ -223,7 +223,7 @@ int Uart::Output(const char *aBuf, uint16_t aBufLength) for (int i = 0; i < aBufLength; i++) { - tail = (mTxHead + mTxLength) % kTxBufferSize; + tail = (mTxHead + mTxLength) % kTxBufferSize; mTxBuffer[tail] = *aBuf++; mTxLength++; } @@ -235,7 +235,7 @@ int Uart::Output(const char *aBuf, uint16_t aBufLength) int Uart::OutputFormat(const char *fmt, ...) { - char buf[kMaxLineLength]; + char buf[kMaxLineLength]; va_list ap; va_start(ap, fmt); @@ -308,5 +308,5 @@ extern "C" void otCliPlatLogv(otLogLevel aLogLevel, otLogRegion aLogRegion, cons OT_UNUSED_VARIABLE(aLogRegion); } -} // namespace Cli -} // namespace ot +} // namespace Cli +} // namespace ot diff --git a/src/cli/cli_uart.hpp b/src/cli/cli_uart.hpp index 7f0f79cd6..0c6435733 100644 --- a/src/cli/cli_uart.hpp +++ b/src/cli/cli_uart.hpp @@ -43,7 +43,6 @@ #include "common/instance.hpp" #include "common/tasklet.hpp" - namespace ot { namespace Cli { @@ -51,7 +50,7 @@ namespace Cli { * This class implements the CLI server on top of the UART platform abstraction. * */ -class Uart: public Server +class Uart : public Server { public: /** @@ -111,18 +110,18 @@ public: private: enum { - kRxBufferSize = OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE, - kTxBufferSize = OPENTHREAD_CONFIG_CLI_UART_TX_BUFFER_SIZE, + kRxBufferSize = OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE, + kTxBufferSize = OPENTHREAD_CONFIG_CLI_UART_TX_BUFFER_SIZE, kMaxLineLength = OPENTHREAD_CONFIG_CLI_MAX_LINE_LENGTH, }; otError ProcessCommand(void); - void Send(void); + void Send(void); - char mRxBuffer[kRxBufferSize]; + char mRxBuffer[kRxBufferSize]; uint16_t mRxLength; - char mTxBuffer[kTxBufferSize]; + char mTxBuffer[kTxBufferSize]; uint16_t mTxHead; uint16_t mTxLength; @@ -133,7 +132,7 @@ private: friend class Interpreter; }; -} // namespace Cli -} // namespace ot +} // namespace Cli +} // namespace ot -#endif // CLI_UART_HPP_ +#endif // CLI_UART_HPP_ diff --git a/src/cli/cli_udp_example.cpp b/src/cli/cli_udp_example.cpp index 7e16b56ce..783191d49 100644 --- a/src/cli/cli_udp_example.cpp +++ b/src/cli/cli_udp_example.cpp @@ -44,18 +44,12 @@ using ot::Encoding::BigEndian::HostSwap16; namespace ot { namespace Cli { -const struct UdpExample::Command UdpExample::sCommands[] = -{ - { "help", &UdpExample::ProcessHelp }, - { "bind", &UdpExample::ProcessBind }, - { "close", &UdpExample::ProcessClose }, - { "connect", &UdpExample::ProcessConnect }, - { "open", &UdpExample::ProcessOpen }, - { "send", &UdpExample::ProcessSend } -}; +const struct UdpExample::Command UdpExample::sCommands[] = { + {"help", &UdpExample::ProcessHelp}, {"bind", &UdpExample::ProcessBind}, {"close", &UdpExample::ProcessClose}, + {"connect", &UdpExample::ProcessConnect}, {"open", &UdpExample::ProcessOpen}, {"send", &UdpExample::ProcessSend}}; -UdpExample::UdpExample(Interpreter &aInterpreter): - mInterpreter(aInterpreter) +UdpExample::UdpExample(Interpreter &aInterpreter) + : mInterpreter(aInterpreter) { memset(&mSocket, 0, sizeof(mSocket)); } @@ -75,9 +69,9 @@ otError UdpExample::ProcessHelp(int argc, char *argv[]) otError UdpExample::ProcessBind(int argc, char *argv[]) { - otError error; + otError error; otSockAddr sockaddr; - long value; + long value; VerifyOrExit(argc == 2, error = OT_ERROR_PARSE); @@ -89,7 +83,7 @@ otError UdpExample::ProcessBind(int argc, char *argv[]) error = Interpreter::ParseLong(argv[1], value); SuccessOrExit(error); - sockaddr.mPort = static_cast(value); + sockaddr.mPort = static_cast(value); sockaddr.mScopeId = OT_NETIF_INTERFACE_ID_THREAD; error = otUdpBind(&mSocket, &sockaddr); @@ -100,9 +94,9 @@ exit: otError UdpExample::ProcessConnect(int argc, char *argv[]) { - otError error; + otError error; otSockAddr sockaddr; - long value; + long value; VerifyOrExit(argc == 2, error = OT_ERROR_PARSE); @@ -114,7 +108,7 @@ otError UdpExample::ProcessConnect(int argc, char *argv[]) error = Interpreter::ParseLong(argv[1], value); SuccessOrExit(error); - sockaddr.mPort = static_cast(value); + sockaddr.mPort = static_cast(value); sockaddr.mScopeId = OT_NETIF_INTERFACE_ID_THREAD; error = otUdpConnect(&mSocket, &sockaddr); @@ -141,10 +135,10 @@ otError UdpExample::ProcessOpen(int argc, char *argv[]) otError UdpExample::ProcessSend(int argc, char *argv[]) { - otError error; + otError error; otMessageInfo messageInfo; - otMessage *message = NULL; - int curArg = 0; + otMessage * message = NULL; + int curArg = 0; memset(&messageInfo, 0, sizeof(messageInfo)); @@ -160,7 +154,7 @@ otError UdpExample::ProcessSend(int argc, char *argv[]) error = Interpreter::ParseLong(argv[curArg++], value); SuccessOrExit(error); - messageInfo.mPeerPort = static_cast(value); + messageInfo.mPeerPort = static_cast(value); messageInfo.mInterfaceId = OT_NETIF_INTERFACE_ID_THREAD; } @@ -206,25 +200,21 @@ void UdpExample::HandleUdpReceive(void *aContext, otMessage *aMessage, const otM void UdpExample::HandleUdpReceive(otMessage *aMessage, const otMessageInfo *aMessageInfo) { uint8_t buf[1500]; - int length; + int length; mInterpreter.mServer->OutputFormat("%d bytes from ", otMessageGetLength(aMessage) - otMessageGetOffset(aMessage)); - mInterpreter.mServer->OutputFormat("%x:%x:%x:%x:%x:%x:%x:%x %d ", - HostSwap16(aMessageInfo->mPeerAddr.mFields.m16[0]), - HostSwap16(aMessageInfo->mPeerAddr.mFields.m16[1]), - HostSwap16(aMessageInfo->mPeerAddr.mFields.m16[2]), - HostSwap16(aMessageInfo->mPeerAddr.mFields.m16[3]), - HostSwap16(aMessageInfo->mPeerAddr.mFields.m16[4]), - HostSwap16(aMessageInfo->mPeerAddr.mFields.m16[5]), - HostSwap16(aMessageInfo->mPeerAddr.mFields.m16[6]), - HostSwap16(aMessageInfo->mPeerAddr.mFields.m16[7]), - aMessageInfo->mPeerPort); + mInterpreter.mServer->OutputFormat( + "%x:%x:%x:%x:%x:%x:%x:%x %d ", HostSwap16(aMessageInfo->mPeerAddr.mFields.m16[0]), + HostSwap16(aMessageInfo->mPeerAddr.mFields.m16[1]), HostSwap16(aMessageInfo->mPeerAddr.mFields.m16[2]), + HostSwap16(aMessageInfo->mPeerAddr.mFields.m16[3]), HostSwap16(aMessageInfo->mPeerAddr.mFields.m16[4]), + HostSwap16(aMessageInfo->mPeerAddr.mFields.m16[5]), HostSwap16(aMessageInfo->mPeerAddr.mFields.m16[6]), + HostSwap16(aMessageInfo->mPeerAddr.mFields.m16[7]), aMessageInfo->mPeerPort); - length = otMessageRead(aMessage, otMessageGetOffset(aMessage), buf, sizeof(buf) - 1); + length = otMessageRead(aMessage, otMessageGetOffset(aMessage), buf, sizeof(buf) - 1); buf[length] = '\0'; mInterpreter.mServer->OutputFormat("%s\r\n", buf); } -} // namespace Cli -} // namespace ot +} // namespace Cli +} // namespace ot diff --git a/src/cli/cli_udp_example.hpp b/src/cli/cli_udp_example.hpp index 12a3614a8..7fcc2fec7 100644 --- a/src/cli/cli_udp_example.hpp +++ b/src/cli/cli_udp_example.hpp @@ -36,8 +36,8 @@ #include "openthread-core-config.h" -#include #include +#include namespace ot { namespace Cli { @@ -72,7 +72,7 @@ private: struct Command { const char *mName; - otError(UdpExample::*mCommand)(int argc, char *argv[]); + otError (UdpExample::*mCommand)(int argc, char *argv[]); }; otError ProcessHelp(int argc, char *argv[]); @@ -83,15 +83,15 @@ private: otError ProcessSend(int argc, char *argv[]); static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo); - void HandleUdpReceive(otMessage *aMessage, const otMessageInfo *aMessageInfo); + void HandleUdpReceive(otMessage *aMessage, const otMessageInfo *aMessageInfo); static const Command sCommands[]; - Interpreter &mInterpreter; + Interpreter & mInterpreter; otUdpSocket mSocket; }; -} // namespace Cli -} // namespace ot +} // namespace Cli +} // namespace ot -#endif // CLI_UDP_EXAMPLE_HPP_ +#endif // CLI_UDP_EXAMPLE_HPP_ diff --git a/src/core/api/border_router_api.cpp b/src/core/api/border_router_api.cpp index b1c7da3ea..a8ed43992 100644 --- a/src/core/api/border_router_api.cpp +++ b/src/core/api/border_router_api.cpp @@ -43,7 +43,7 @@ using namespace ot; otError otBorderRouterGetNetData(otInstance *aInstance, bool aStable, uint8_t *aData, uint8_t *aDataLength) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aData != NULL && aDataLength != NULL, error = OT_ERROR_INVALID_ARGS); @@ -56,7 +56,7 @@ exit: otError otBorderRouterAddOnMeshPrefix(otInstance *aInstance, const otBorderRouterConfig *aConfig) { - uint8_t flags = 0; + uint8_t flags = 0; Instance &instance = *static_cast(aInstance); if (aConfig->mPreferred) @@ -89,9 +89,8 @@ otError otBorderRouterAddOnMeshPrefix(otInstance *aInstance, const otBorderRoute flags |= NetworkData::BorderRouterEntry::kOnMeshFlag; } - return instance.GetThreadNetif().GetNetworkDataLocal().AddOnMeshPrefix(aConfig->mPrefix.mPrefix.mFields.m8, - aConfig->mPrefix.mLength, - aConfig->mPreference, flags, aConfig->mStable); + return instance.GetThreadNetif().GetNetworkDataLocal().AddOnMeshPrefix( + aConfig->mPrefix.mPrefix.mFields.m8, aConfig->mPrefix.mLength, aConfig->mPreference, flags, aConfig->mStable); } otError otBorderRouterRemoveOnMeshPrefix(otInstance *aInstance, const otIp6Prefix *aPrefix) @@ -102,10 +101,11 @@ otError otBorderRouterRemoveOnMeshPrefix(otInstance *aInstance, const otIp6Prefi aPrefix->mLength); } -otError otBorderRouterGetNextOnMeshPrefix(otInstance *aInstance, otNetworkDataIterator *aIterator, - otBorderRouterConfig *aConfig) +otError otBorderRouterGetNextOnMeshPrefix(otInstance * aInstance, + otNetworkDataIterator *aIterator, + otBorderRouterConfig * aConfig) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aIterator && aConfig, error = OT_ERROR_INVALID_ARGS); @@ -120,9 +120,8 @@ otError otBorderRouterAddRoute(otInstance *aInstance, const otExternalRouteConfi { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetNetworkDataLocal().AddHasRoutePrefix(aConfig->mPrefix.mPrefix.mFields.m8, - aConfig->mPrefix.mLength, - aConfig->mPreference, aConfig->mStable); + return instance.GetThreadNetif().GetNetworkDataLocal().AddHasRoutePrefix( + aConfig->mPrefix.mPrefix.mFields.m8, aConfig->mPrefix.mLength, aConfig->mPreference, aConfig->mStable); } otError otBorderRouterRemoveRoute(otInstance *aInstance, const otIp6Prefix *aPrefix) @@ -133,10 +132,11 @@ otError otBorderRouterRemoveRoute(otInstance *aInstance, const otIp6Prefix *aPre aPrefix->mLength); } -otError otBorderRouterGetNextRoute(otInstance *aInstance, otNetworkDataIterator *aIterator, +otError otBorderRouterGetNextRoute(otInstance * aInstance, + otNetworkDataIterator *aIterator, otExternalRouteConfig *aConfig) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aIterator && aConfig, error = OT_ERROR_INVALID_ARGS); @@ -154,4 +154,4 @@ otError otBorderRouterRegister(otInstance *aInstance) return instance.GetThreadNetif().GetNetworkDataLocal().SendServerDataNotification(); } -#endif // OPENTHREAD_ENABLE_BORDER_ROUTER +#endif // OPENTHREAD_ENABLE_BORDER_ROUTER diff --git a/src/core/api/channel_manager_api.cpp b/src/core/api/channel_manager_api.cpp index 36b2bb2fc..e8afed6db 100644 --- a/src/core/api/channel_manager_api.cpp +++ b/src/core/api/channel_manager_api.cpp @@ -76,11 +76,11 @@ uint32_t otChannelManagerGetSupportedChannels(otInstance *aInstance) return instance.GetChannelManager().GetSupportedChannels(); } -void otChannelManagerSetSupportedChannels(otInstance *aInstance, uint32_t aChannelMask) +void otChannelManagerSetSupportedChannels(otInstance *aInstance, uint32_t aChannelMask) { Instance &instance = *static_cast(aInstance); return instance.GetChannelManager().SetSupportedChannels(aChannelMask); } -#endif // OPENTHREAD_ENABLE_CHANNEL_MANAGER && OPENTHREAD_FTD +#endif // OPENTHREAD_ENABLE_CHANNEL_MANAGER && OPENTHREAD_FTD diff --git a/src/core/api/channel_monitor_api.cpp b/src/core/api/channel_monitor_api.cpp index 199add129..73121c7c0 100644 --- a/src/core/api/channel_monitor_api.cpp +++ b/src/core/api/channel_monitor_api.cpp @@ -75,4 +75,4 @@ uint16_t otChannelMonitorGetChannelQuality(otInstance *aInstance, uint8_t aChann return instance.GetChannelMonitor().GetChannelQuality(aChannel); } -#endif // OPENTHREAD_ENABLE_CHANNEL_MONITOR +#endif // OPENTHREAD_ENABLE_CHANNEL_MONITOR diff --git a/src/core/api/child_supervision_api.cpp b/src/core/api/child_supervision_api.cpp index f667f5326..e7f87af40 100644 --- a/src/core/api/child_supervision_api.cpp +++ b/src/core/api/child_supervision_api.cpp @@ -68,4 +68,4 @@ void otChildSupervisionSetCheckTimeout(otInstance *aInstance, uint16_t aTimeout) instance.GetThreadNetif().GetSupervisionListener().SetTimeout(aTimeout); } -#endif // OPENTHREAD_ENABLE_CHILD_SUPERVISION +#endif // OPENTHREAD_ENABLE_CHILD_SUPERVISION diff --git a/src/core/api/coap_api.cpp b/src/core/api/coap_api.cpp index 4b6209a00..8355bcf3e 100644 --- a/src/core/api/coap_api.cpp +++ b/src/core/api/coap_api.cpp @@ -35,8 +35,8 @@ #include -#include "common/instance.hpp" #include "coap/coap_header.hpp" +#include "common/instance.hpp" #if OPENTHREAD_ENABLE_APPLICATION_COAP @@ -140,7 +140,7 @@ const otCoapOption *otCoapHeaderGetNextOption(otCoapHeader *aHeader) otMessage *otCoapNewMessage(otInstance *aInstance, const otCoapHeader *aHeader) { - Message *message; + Message * message; Instance &instance = *static_cast(aInstance); VerifyOrExit(aHeader != NULL, message = NULL); @@ -149,15 +149,16 @@ exit: return message; } -otError otCoapSendRequest(otInstance *aInstance, otMessage *aMessage, const otMessageInfo *aMessageInfo, - otCoapResponseHandler aHandler, void *aContext) +otError otCoapSendRequest(otInstance * aInstance, + otMessage * aMessage, + const otMessageInfo * aMessageInfo, + otCoapResponseHandler aHandler, + void * aContext) { Instance &instance = *static_cast(aInstance); return instance.GetApplicationCoap().SendMessage( - *static_cast(aMessage), - *static_cast(aMessageInfo), - aHandler, aContext); + *static_cast(aMessage), *static_cast(aMessageInfo), aHandler, aContext); } otError otCoapStart(otInstance *aInstance, uint16_t aPort) @@ -199,8 +200,8 @@ otError otCoapSendResponse(otInstance *aInstance, otMessage *aMessage, const otM { Instance &instance = *static_cast(aInstance); - return instance.GetApplicationCoap().SendMessage( - *static_cast(aMessage), *static_cast(aMessageInfo)); + return instance.GetApplicationCoap().SendMessage(*static_cast(aMessage), + *static_cast(aMessageInfo)); } #endif // OPENTHREAD_ENABLE_APPLICATION_COAP diff --git a/src/core/api/commissioner_api.cpp b/src/core/api/commissioner_api.cpp index 467a49f97..4e8c250b9 100644 --- a/src/core/api/commissioner_api.cpp +++ b/src/core/api/commissioner_api.cpp @@ -69,12 +69,10 @@ otError otCommissionerStop(otInstance *aInstance) return error; } -otError otCommissionerAddJoiner(otInstance *aInstance, const otExtAddress *aEui64, const char *aPSKd, - uint32_t aTimeout) +otError otCommissionerAddJoiner(otInstance *aInstance, const otExtAddress *aEui64, const char *aPSKd, uint32_t aTimeout) { otError error = OT_ERROR_DISABLED_FEATURE; - #if OPENTHREAD_FTD && OPENTHREAD_ENABLE_COMMISSIONER Instance &instance = *static_cast(aInstance); @@ -122,7 +120,10 @@ otError otCommissionerSetProvisioningUrl(otInstance *aInstance, const char *aPro return error; } -otError otCommissionerAnnounceBegin(otInstance *aInstance, uint32_t aChannelMask, uint8_t aCount, uint16_t aPeriod, +otError otCommissionerAnnounceBegin(otInstance * aInstance, + uint32_t aChannelMask, + uint8_t aCount, + uint16_t aPeriod, const otIp6Address *aAddress) { otError error = OT_ERROR_DISABLED_FEATURE; @@ -131,7 +132,7 @@ otError otCommissionerAnnounceBegin(otInstance *aInstance, uint32_t aChannelMask Instance &instance = *static_cast(aInstance); error = instance.GetThreadNetif().GetCommissioner().GetAnnounceBeginClient().SendRequest( - aChannelMask, aCount, aPeriod, *static_cast(aAddress)); + aChannelMask, aCount, aPeriod, *static_cast(aAddress)); #else OT_UNUSED_VARIABLE(aInstance); OT_UNUSED_VARIABLE(aChannelMask); @@ -143,9 +144,14 @@ otError otCommissionerAnnounceBegin(otInstance *aInstance, uint32_t aChannelMask return error; } -otError otCommissionerEnergyScan(otInstance *aInstance, uint32_t aChannelMask, uint8_t aCount, uint16_t aPeriod, - uint16_t aScanDuration, const otIp6Address *aAddress, - otCommissionerEnergyReportCallback aCallback, void *aContext) +otError otCommissionerEnergyScan(otInstance * aInstance, + uint32_t aChannelMask, + uint8_t aCount, + uint16_t aPeriod, + uint16_t aScanDuration, + const otIp6Address * aAddress, + otCommissionerEnergyReportCallback aCallback, + void * aContext) { otError error = OT_ERROR_DISABLED_FEATURE; @@ -153,8 +159,8 @@ otError otCommissionerEnergyScan(otInstance *aInstance, uint32_t aChannelMask, u Instance &instance = *static_cast(aInstance); error = instance.GetThreadNetif().GetCommissioner().GetEnergyScanClient().SendQuery( - aChannelMask, aCount, aPeriod, aScanDuration, *static_cast(aAddress), - aCallback, aContext); + aChannelMask, aCount, aPeriod, aScanDuration, *static_cast(aAddress), aCallback, + aContext); #else OT_UNUSED_VARIABLE(aInstance); OT_UNUSED_VARIABLE(aChannelMask); @@ -169,9 +175,12 @@ otError otCommissionerEnergyScan(otInstance *aInstance, uint32_t aChannelMask, u return error; } -otError otCommissionerPanIdQuery(otInstance *aInstance, uint16_t aPanId, uint32_t aChannelMask, - const otIp6Address *aAddress, - otCommissionerPanIdConflictCallback aCallback, void *aContext) +otError otCommissionerPanIdQuery(otInstance * aInstance, + uint16_t aPanId, + uint32_t aChannelMask, + const otIp6Address * aAddress, + otCommissionerPanIdConflictCallback aCallback, + void * aContext) { otError error = OT_ERROR_DISABLED_FEATURE; @@ -179,7 +188,7 @@ otError otCommissionerPanIdQuery(otInstance *aInstance, uint16_t aPanId, uint32_ Instance &instance = *static_cast(aInstance); error = instance.GetThreadNetif().GetCommissioner().GetPanIdQueryClient().SendQuery( - aPanId, aChannelMask, *static_cast(aAddress), aCallback, aContext); + aPanId, aChannelMask, *static_cast(aAddress), aCallback, aContext); #else OT_UNUSED_VARIABLE(aInstance); OT_UNUSED_VARIABLE(aPanId); @@ -209,8 +218,10 @@ otError otCommissionerSendMgmtGet(otInstance *aInstance, const uint8_t *aTlvs, u return error; } -otError otCommissionerSendMgmtSet(otInstance *aInstance, const otCommissioningDataset *aDataset, - const uint8_t *aTlvs, uint8_t aLength) +otError otCommissionerSendMgmtSet(otInstance * aInstance, + const otCommissioningDataset *aDataset, + const uint8_t * aTlvs, + uint8_t aLength) { otError error = OT_ERROR_DISABLED_FEATURE; @@ -258,8 +269,11 @@ otCommissionerState otCommissionerGetState(otInstance *aInstance) return state; } -otError otCommissionerGeneratePSKc(otInstance *aInstance, const char *aPassPhrase, const char *aNetworkName, - const uint8_t *aExtPanId, uint8_t *aPSKc) +otError otCommissionerGeneratePSKc(otInstance * aInstance, + const char * aPassPhrase, + const char * aNetworkName, + const uint8_t *aExtPanId, + uint8_t * aPSKc) { otError error = OT_ERROR_DISABLED_FEATURE; diff --git a/src/core/api/crypto_api.cpp b/src/core/api/crypto_api.cpp index 83d5bce6c..fd6ae54cc 100644 --- a/src/core/api/crypto_api.cpp +++ b/src/core/api/crypto_api.cpp @@ -41,10 +41,11 @@ using namespace ot::Crypto; -void otCryptoHmacSha256( - const uint8_t *aKey, uint16_t aKeyLength, - const uint8_t *aBuf, uint16_t aBufLength, - uint8_t *aHash) +void otCryptoHmacSha256(const uint8_t *aKey, + uint16_t aKeyLength, + const uint8_t *aBuf, + uint16_t aBufLength, + uint8_t * aHash) { HmacSha256 hmac; @@ -55,15 +56,20 @@ void otCryptoHmacSha256( hmac.Finish(aHash); } -void otCryptoAesCcm( - const uint8_t *aKey, uint16_t aKeyLength, - uint8_t aTagLength, - const void *aNonce, uint8_t aNonceLength, - const void *aHeader, uint32_t aHeaderLength, - void *aPlainText, void *aCipherText, uint32_t aLength, bool aEncrypt, - void *aTag) +void otCryptoAesCcm(const uint8_t *aKey, + uint16_t aKeyLength, + uint8_t aTagLength, + const void * aNonce, + uint8_t aNonceLength, + const void * aHeader, + uint32_t aHeaderLength, + void * aPlainText, + void * aCipherText, + uint32_t aLength, + bool aEncrypt, + void * aTag) { - AesCcm aesCcm; + AesCcm aesCcm; uint8_t tagLength; assert((aKey != NULL) && (aNonce != NULL) && (aPlainText != NULL) && (aCipherText != NULL) && (aTag != NULL)); diff --git a/src/core/api/dataset_api.cpp b/src/core/api/dataset_api.cpp index a1eac0f62..b03067195 100644 --- a/src/core/api/dataset_api.cpp +++ b/src/core/api/dataset_api.cpp @@ -45,8 +45,8 @@ bool otDatasetIsCommissioned(otInstance *aInstance) otDatasetGetActive(aInstance, &dataset); - if ((dataset.mIsMasterKeySet) && (dataset.mIsNetworkNameSet) && - (dataset.mIsExtendedPanIdSet) && (dataset.mIsPanIdSet) && (dataset.mIsChannelSet)) + if ((dataset.mIsMasterKeySet) && (dataset.mIsNetworkNameSet) && (dataset.mIsExtendedPanIdSet) && + (dataset.mIsPanIdSet) && (dataset.mIsChannelSet)) { return true; } @@ -56,7 +56,7 @@ bool otDatasetIsCommissioned(otInstance *aInstance) otError otDatasetGetActive(otInstance *aInstance, otOperationalDataset *aDataset) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aDataset != NULL, error = OT_ERROR_INVALID_ARGS); @@ -69,7 +69,7 @@ exit: otError otDatasetGetPending(otInstance *aInstance, otOperationalDataset *aDataset) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aDataset != NULL, error = OT_ERROR_INVALID_ARGS); diff --git a/src/core/api/dataset_ftd_api.cpp b/src/core/api/dataset_ftd_api.cpp index 5cbed5df8..ac4a2600e 100644 --- a/src/core/api/dataset_ftd_api.cpp +++ b/src/core/api/dataset_ftd_api.cpp @@ -43,7 +43,7 @@ using namespace ot; otError otDatasetSetActive(otInstance *aInstance, const otOperationalDataset *aDataset) { - otError error; + otError error; Instance &instance = *static_cast(aInstance); VerifyOrExit(aDataset != NULL, error = OT_ERROR_INVALID_ARGS); @@ -56,7 +56,7 @@ exit: otError otDatasetSetPending(otInstance *aInstance, const otOperationalDataset *aDataset) { - otError error; + otError error; Instance &instance = *static_cast(aInstance); VerifyOrExit(aDataset != NULL, error = OT_ERROR_INVALID_ARGS); @@ -67,7 +67,9 @@ exit: return error; } -otError otDatasetSendMgmtActiveGet(otInstance *aInstance, const uint8_t *aTlvTypes, uint8_t aLength, +otError otDatasetSendMgmtActiveGet(otInstance * aInstance, + const uint8_t * aTlvTypes, + uint8_t aLength, const otIp6Address *aAddress) { Instance &instance = *static_cast(aInstance); @@ -75,15 +77,19 @@ otError otDatasetSendMgmtActiveGet(otInstance *aInstance, const uint8_t *aTlvTyp return instance.GetThreadNetif().GetActiveDataset().SendGetRequest(aTlvTypes, aLength, aAddress); } -otError otDatasetSendMgmtActiveSet(otInstance *aInstance, const otOperationalDataset *aDataset, - const uint8_t *aTlvs, uint8_t aLength) +otError otDatasetSendMgmtActiveSet(otInstance * aInstance, + const otOperationalDataset *aDataset, + const uint8_t * aTlvs, + uint8_t aLength) { Instance &instance = *static_cast(aInstance); return instance.GetThreadNetif().GetActiveDataset().SendSetRequest(*aDataset, aTlvs, aLength); } -otError otDatasetSendMgmtPendingGet(otInstance *aInstance, const uint8_t *aTlvTypes, uint8_t aLength, +otError otDatasetSendMgmtPendingGet(otInstance * aInstance, + const uint8_t * aTlvTypes, + uint8_t aLength, const otIp6Address *aAddress) { Instance &instance = *static_cast(aInstance); @@ -91,8 +97,10 @@ otError otDatasetSendMgmtPendingGet(otInstance *aInstance, const uint8_t *aTlvTy return instance.GetThreadNetif().GetPendingDataset().SendGetRequest(aTlvTypes, aLength, aAddress); } -otError otDatasetSendMgmtPendingSet(otInstance *aInstance, const otOperationalDataset *aDataset, - const uint8_t *aTlvs, uint8_t aLength) +otError otDatasetSendMgmtPendingSet(otInstance * aInstance, + const otOperationalDataset *aDataset, + const uint8_t * aTlvs, + uint8_t aLength) { Instance &instance = *static_cast(aInstance); @@ -113,4 +121,4 @@ otError otDatasetSetDelayTimerMinimal(otInstance *aInstance, uint32_t aDelayTime return instance.GetThreadNetif().GetLeader().SetDelayTimerMinimal(aDelayTimerMinimal); } -#endif // OPENTHREAD_FTD +#endif // OPENTHREAD_FTD diff --git a/src/core/api/dns_api.cpp b/src/core/api/dns_api.cpp index 54e5be3c1..5b015838f 100644 --- a/src/core/api/dns_api.cpp +++ b/src/core/api/dns_api.cpp @@ -40,8 +40,7 @@ using namespace ot; #if OPENTHREAD_ENABLE_DNS_CLIENT -otError otDnsClientQuery(otInstance *aInstance, const otDnsQuery *aQuery, otDnsResponseHandler aHandler, - void *aContext) +otError otDnsClientQuery(otInstance *aInstance, const otDnsQuery *aQuery, otDnsResponseHandler aHandler, void *aContext) { Instance &instance = *static_cast(aInstance); diff --git a/src/core/api/icmp6_api.cpp b/src/core/api/icmp6_api.cpp index 719600598..20887524c 100644 --- a/src/core/api/icmp6_api.cpp +++ b/src/core/api/icmp6_api.cpp @@ -60,12 +60,13 @@ otError otIcmp6RegisterHandler(otInstance *aInstance, otIcmp6Handler *aHandler) return instance.GetIp6().GetIcmp().RegisterHandler(*static_cast(aHandler)); } -otError otIcmp6SendEchoRequest(otInstance *aInstance, otMessage *aMessage, - const otMessageInfo *aMessageInfo, uint16_t aIdentifier) +otError otIcmp6SendEchoRequest(otInstance * aInstance, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + uint16_t aIdentifier) { Instance &instance = *static_cast(aInstance); - return instance.GetIp6().GetIcmp().SendEchoRequest(*static_cast(aMessage), - *static_cast(aMessageInfo), - aIdentifier); + return instance.GetIp6().GetIcmp().SendEchoRequest( + *static_cast(aMessage), *static_cast(aMessageInfo), aIdentifier); } diff --git a/src/core/api/instance_api.cpp b/src/core/api/instance_api.cpp index 0d70f91e6..fac04cac9 100644 --- a/src/core/api/instance_api.cpp +++ b/src/core/api/instance_api.cpp @@ -62,7 +62,6 @@ otInstance *otInstanceInitSingle(void) } #endif // #if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES - bool otInstanceIsInitialized(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); diff --git a/src/core/api/ip6_api.cpp b/src/core/api/ip6_api.cpp index a47ddf45b..64d4cd2d0 100644 --- a/src/core/api/ip6_api.cpp +++ b/src/core/api/ip6_api.cpp @@ -45,7 +45,7 @@ using namespace ot; otError otIp6SetEnabled(otInstance *aInstance, bool aEnabled) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); if (aEnabled) @@ -88,7 +88,7 @@ otError otIp6AddUnicastAddress(otInstance *aInstance, const otNetifAddress *aAdd Instance &instance = *static_cast(aInstance); return instance.GetThreadNetif().AddExternalUnicastAddress( - *static_cast(aAddress)); + *static_cast(aAddress)); } otError otIp6RemoveUnicastAddress(otInstance *aInstance, const otIp6Address *aAddress) @@ -133,8 +133,11 @@ void otIp6SetMulticastPromiscuousEnabled(otInstance *aInstance, bool aEnabled) instance.GetThreadNetif().SetMulticastPromiscuous(aEnabled); } -void otIp6SlaacUpdate(otInstance *aInstance, otNetifAddress *aAddresses, uint32_t aNumAddresses, - otIp6SlaacIidCreate aIidCreate, void *aContext) +void otIp6SlaacUpdate(otInstance * aInstance, + otNetifAddress * aAddresses, + uint32_t aNumAddresses, + otIp6SlaacIidCreate aIidCreate, + void * aContext) { Utils::Slaac::UpdateAddresses(aInstance, aAddresses, aNumAddresses, aIidCreate, aContext); } @@ -183,11 +186,10 @@ void otIp6SetReceiveFilterEnabled(otInstance *aInstance, bool aEnabled) otError otIp6Send(otInstance *aInstance, otMessage *aMessage) { - otError error; + otError error; Instance &instance = *static_cast(aInstance); - error = instance.GetIp6().SendRaw(*static_cast(aMessage), - instance.GetThreadNetif().GetInterfaceId()); + error = instance.GetIp6().SendRaw(*static_cast(aMessage), instance.GetThreadNetif().GetInterfaceId()); return error; } @@ -195,7 +197,7 @@ otError otIp6Send(otInstance *aInstance, otMessage *aMessage) otMessage *otIp6NewMessage(otInstance *aInstance, bool aLinkSecurityEnabled) { Instance &instance = *static_cast(aInstance); - Message *message = instance.GetMessagePool().New(Message::kTypeIp6, 0); + Message * message = instance.GetMessagePool().New(Message::kTypeIp6, 0); if (message) { diff --git a/src/core/api/jam_detection_api.cpp b/src/core/api/jam_detection_api.cpp index 57893c08d..edfd77ed6 100644 --- a/src/core/api/jam_detection_api.cpp +++ b/src/core/api/jam_detection_api.cpp @@ -118,4 +118,4 @@ uint64_t otJamDetectionGetHistoryBitmap(otInstance *aInstance) return instance.GetThreadNetif().GetJamDetector().GetHistoryBitmap(); } -#endif // OPENTHREAD_ENABLE_JAM_DETECTION +#endif // OPENTHREAD_ENABLE_JAM_DETECTION diff --git a/src/core/api/joiner_api.cpp b/src/core/api/joiner_api.cpp index df3fba69a..19bd5de40 100644 --- a/src/core/api/joiner_api.cpp +++ b/src/core/api/joiner_api.cpp @@ -39,10 +39,15 @@ using namespace ot; -otError otJoinerStart(otInstance *aInstance, const char *aPSKd, const char *aProvisioningUrl, - const char *aVendorName, const char *aVendorModel, - const char *aVendorSwVersion, const char *aVendorData, - otJoinerCallback aCallback, void *aContext) +otError otJoinerStart(otInstance * aInstance, + const char * aPSKd, + const char * aProvisioningUrl, + const char * aVendorName, + const char * aVendorModel, + const char * aVendorSwVersion, + const char * aVendorData, + otJoinerCallback aCallback, + void * aContext) { otError error = OT_ERROR_DISABLED_FEATURE; #if OPENTHREAD_ENABLE_JOINER diff --git a/src/core/api/link_api.cpp b/src/core/api/link_api.cpp index 21ada295c..aaed41955 100644 --- a/src/core/api/link_api.cpp +++ b/src/core/api/link_api.cpp @@ -51,7 +51,7 @@ uint8_t otLinkGetChannel(otInstance *aInstance) otError otLinkSetChannel(otInstance *aInstance, uint8_t aChannel) { - otError error; + otError error; Instance &instance = *static_cast(aInstance); VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, @@ -74,7 +74,7 @@ const otExtAddress *otLinkGetExtendedAddress(otInstance *aInstance) otError otLinkSetExtendedAddress(otInstance *aInstance, const otExtAddress *aExtAddress) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aExtAddress != NULL, error = OT_ERROR_INVALID_ARGS); @@ -103,7 +103,7 @@ otPanId otLinkGetPanId(otInstance *aInstance) otError otLinkSetPanId(otInstance *aInstance, otPanId aPanId) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, @@ -163,12 +163,13 @@ otError otLinkFilterSetAddressMode(otInstance *aInstance, otMacFilterAddressMode otError otLinkFilterAddAddress(otInstance *aInstance, const otExtAddress *aExtAddress) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aExtAddress != NULL, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetMac().GetFilter().AddAddress(*static_cast(aExtAddress)); + error = + instance.GetThreadNetif().GetMac().GetFilter().AddAddress(*static_cast(aExtAddress)); exit: return error; @@ -176,13 +177,13 @@ exit: otError otLinkFilterRemoveAddress(otInstance *aInstance, const otExtAddress *aExtAddress) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aExtAddress != NULL, error = OT_ERROR_INVALID_ARGS); error = instance.GetThreadNetif().GetMac().GetFilter().RemoveAddress( - *static_cast(aExtAddress)); + *static_cast(aExtAddress)); exit: return error; @@ -197,7 +198,7 @@ void otLinkFilterClearAddresses(otInstance *aInstance) otError otLinkFilterGetNextAddress(otInstance *aInstance, otMacFilterIterator *aIterator, otMacFilterEntry *aEntry) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aIterator != NULL && aEntry != NULL, error = OT_ERROR_INVALID_ARGS); @@ -212,15 +213,16 @@ otError otLinkFilterAddRssIn(otInstance *aInstance, const otExtAddress *aExtAddr { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMac().GetFilter().AddRssIn( - static_cast(aExtAddress), aRss); + return instance.GetThreadNetif().GetMac().GetFilter().AddRssIn(static_cast(aExtAddress), + aRss); } otError otLinkFilterRemoveRssIn(otInstance *aInstance, const otExtAddress *aExtAddress) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMac().GetFilter().RemoveRssIn(static_cast(aExtAddress)); + return instance.GetThreadNetif().GetMac().GetFilter().RemoveRssIn( + static_cast(aExtAddress)); } void otLinkFilterClearRssIn(otInstance *aInstance) @@ -232,7 +234,7 @@ void otLinkFilterClearRssIn(otInstance *aInstance) otError otLinkFilterGetNextRssIn(otInstance *aInstance, otMacFilterIterator *aIterator, otMacFilterEntry *aEntry) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aIterator != NULL && aEntry != NULL, error = OT_ERROR_INVALID_ARGS); @@ -257,7 +259,7 @@ int8_t otLinkConvertLinkQualityToRss(otInstance *aInstance, uint8_t aLinkQuality return LinkQualityInfo::ConvertLinkQualityToRss(instance.GetThreadNetif().GetMac().GetNoiseFloor(), aLinkQuality); } -#endif // OPENTHREAD_ENABLE_MAC_FILTER +#endif // OPENTHREAD_ENABLE_MAC_FILTER void otLinkSetPcapCallback(otInstance *aInstance, otLinkPcapCallback aPcapCallback, void *aCallbackContext) { @@ -275,7 +277,7 @@ bool otLinkIsPromiscuous(otInstance *aInstance) otError otLinkSetPromiscuous(otInstance *aInstance, bool aPromiscuous) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); // cannot enable IEEE 802.15.4 promiscuous mode if the Thread interface is enabled @@ -294,14 +296,17 @@ const otMacCounters *otLinkGetCounters(otInstance *aInstance) return &instance.GetThreadNetif().GetMac().GetCounters(); } -otError otLinkActiveScan(otInstance *aInstance, uint32_t aScanChannels, uint16_t aScanDuration, - otHandleActiveScanResult aCallback, void *aCallbackContext) +otError otLinkActiveScan(otInstance * aInstance, + uint32_t aScanChannels, + uint16_t aScanDuration, + otHandleActiveScanResult aCallback, + void * aCallbackContext) { Instance &instance = *static_cast(aInstance); instance.RegisterActiveScanCallback(aCallback, aCallbackContext); - return instance.GetThreadNetif().GetMac().ActiveScan(aScanChannels, aScanDuration, - &HandleActiveScanResult, aInstance); + return instance.GetThreadNetif().GetMac().ActiveScan(aScanChannels, aScanDuration, &HandleActiveScanResult, + aInstance); } bool otLinkIsActiveScanInProgress(otInstance *aInstance) @@ -328,14 +333,17 @@ void HandleActiveScanResult(void *aContext, Mac::Frame *aFrame) } } -otError otLinkEnergyScan(otInstance *aInstance, uint32_t aScanChannels, uint16_t aScanDuration, - otHandleEnergyScanResult aCallback, void *aCallbackContext) +otError otLinkEnergyScan(otInstance * aInstance, + uint32_t aScanChannels, + uint16_t aScanDuration, + otHandleEnergyScanResult aCallback, + void * aCallbackContext) { Instance &instance = *static_cast(aInstance); instance.RegisterEnergyScanCallback(aCallback, aCallbackContext); - return instance.GetThreadNetif().GetMac().EnergyScan(aScanChannels, aScanDuration, - &HandleEnergyScanResult, aInstance); + return instance.GetThreadNetif().GetMac().EnergyScan(aScanChannels, aScanDuration, &HandleEnergyScanResult, + aInstance); } void HandleEnergyScanResult(void *aContext, otEnergyScanResult *aResult) diff --git a/src/core/api/link_raw.hpp b/src/core/api/link_raw.hpp index 4151f6ca8..005512aa7 100644 --- a/src/core/api/link_raw.hpp +++ b/src/core/api/link_raw.hpp @@ -40,7 +40,8 @@ #include "common/timer.hpp" -#if OPENTHREAD_CONFIG_ENABLE_SOFTWARE_ACK_TIMEOUT || OPENTHREAD_CONFIG_ENABLE_SOFTWARE_RETRANSMIT || OPENTHREAD_CONFIG_ENABLE_SOFTWARE_ENERGY_SCAN +#if OPENTHREAD_CONFIG_ENABLE_SOFTWARE_ACK_TIMEOUT || OPENTHREAD_CONFIG_ENABLE_SOFTWARE_RETRANSMIT || \ + OPENTHREAD_CONFIG_ENABLE_SOFTWARE_ENERGY_SCAN #define OPENTHREAD_LINKRAW_TIMER_REQUIRED 1 #else #define OPENTHREAD_LINKRAW_TIMER_REQUIRED 0 @@ -114,7 +115,7 @@ public: private: otError DoTransmit(otRadioFrame *aFrame); - otInstance &mInstance; + otInstance & mInstance; bool mEnabled; uint8_t mReceiveChannel; otLinkRawReceiveDone mReceiveDoneCallback; @@ -131,21 +132,21 @@ private: kTimerReasonEnergyScanComplete, }; - TimerMilli mTimer; - TimerReason mTimerReason; + TimerMilli mTimer; + TimerReason mTimerReason; #if OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_TIMER - TimerMicro mTimerMicro; + TimerMicro mTimerMicro; #endif static void HandleTimer(Timer &aTimer); - void HandleTimer(void); + void HandleTimer(void); #endif // OPENTHREAD_LINKRAW_TIMER_REQUIRED #if OPENTHREAD_CONFIG_ENABLE_SOFTWARE_RETRANSMIT - uint8_t mTransmitAttempts; - uint8_t mCsmaAttempts; + uint8_t mTransmitAttempts; + uint8_t mCsmaAttempts; void StartCsmaBackoff(void); @@ -158,15 +159,15 @@ private: kInvalidRssiValue = 127 }; - Tasklet mEnergyScanTask; - int8_t mEnergyScanRssi; + Tasklet mEnergyScanTask; + int8_t mEnergyScanRssi; static void HandleEnergyScanTask(Tasklet &aTasklet); - void HandleEnergyScanTask(void); + void HandleEnergyScanTask(void); #endif // OPENTHREAD_CONFIG_ENABLE_SOFTWARE_ENERGY_SCAN }; -} // namespace ot +} // namespace ot -#endif // LINK_RAW_HPP_ +#endif // LINK_RAW_HPP_ diff --git a/src/core/api/link_raw_api.cpp b/src/core/api/link_raw_api.cpp index 8bba8543d..a7d0bd17f 100644 --- a/src/core/api/link_raw_api.cpp +++ b/src/core/api/link_raw_api.cpp @@ -46,7 +46,7 @@ using namespace ot; otError otLinkRawSetEnable(otInstance *aInstance, bool aEnabled) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(!instance.GetThreadNetif().IsUp(), error = OT_ERROR_INVALID_STATE); @@ -68,7 +68,7 @@ bool otLinkRawIsEnabled(otInstance *aInstance) otError otLinkRawSetPanId(otInstance *aInstance, uint16_t aPanId) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(instance.GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); @@ -81,8 +81,8 @@ exit: otError otLinkRawSetExtendedAddress(otInstance *aInstance, const otExtAddress *aExtAddress) { - otError error = OT_ERROR_NONE; - Instance &instance = *static_cast(aInstance); + otError error = OT_ERROR_NONE; + Instance & instance = *static_cast(aInstance); otExtAddress address; VerifyOrExit(instance.GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); @@ -100,7 +100,7 @@ exit: otError otLinkRawSetShortAddress(otInstance *aInstance, uint16_t aShortAddress) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(instance.GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); @@ -118,7 +118,7 @@ bool otLinkRawGetPromiscuous(otInstance *aInstance) otError otLinkRawSetPromiscuous(otInstance *aInstance, bool aEnable) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(instance.GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); @@ -133,7 +133,7 @@ exit: otError otLinkRawSleep(otInstance *aInstance) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(instance.GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); @@ -156,8 +156,8 @@ otError otLinkRawReceive(otInstance *aInstance, uint8_t aChannel, otLinkRawRecei otRadioFrame *otLinkRawGetTransmitBuffer(otInstance *aInstance) { - otRadioFrame *buffer = NULL; - Instance &instance = *static_cast(aInstance); + otRadioFrame *buffer = NULL; + Instance & instance = *static_cast(aInstance); VerifyOrExit(instance.GetLinkRaw().IsEnabled()); @@ -187,7 +187,9 @@ otRadioCaps otLinkRawGetCaps(otInstance *aInstance) return instance.GetLinkRaw().GetCaps(); } -otError otLinkRawEnergyScan(otInstance *aInstance, uint8_t aScanChannel, uint16_t aScanDuration, +otError otLinkRawEnergyScan(otInstance * aInstance, + uint8_t aScanChannel, + uint16_t aScanDuration, otLinkRawEnergyScanDone aCallback) { Instance &instance = *static_cast(aInstance); @@ -197,7 +199,7 @@ otError otLinkRawEnergyScan(otInstance *aInstance, uint8_t aScanChannel, uint16_ otError otLinkRawSrcMatchEnable(otInstance *aInstance, bool aEnable) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(instance.GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); @@ -210,7 +212,7 @@ exit: otError otLinkRawSrcMatchAddShortEntry(otInstance *aInstance, const uint16_t aShortAddress) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(instance.GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); @@ -223,7 +225,7 @@ exit: otError otLinkRawSrcMatchAddExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(instance.GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); @@ -236,7 +238,7 @@ exit: otError otLinkRawSrcMatchClearShortEntry(otInstance *aInstance, const uint16_t aShortAddress) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(instance.GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); @@ -249,7 +251,7 @@ exit: otError otLinkRawSrcMatchClearExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(instance.GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); @@ -262,7 +264,7 @@ exit: otError otLinkRawSrcMatchClearShortEntries(otInstance *aInstance) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(instance.GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); @@ -275,7 +277,7 @@ exit: otError otLinkRawSrcMatchClearExtEntries(otInstance *aInstance) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(instance.GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); @@ -288,13 +290,13 @@ exit: namespace ot { -LinkRaw::LinkRaw(Instance &aInstance): - mInstance(aInstance), - mEnabled(false), - mReceiveChannel(OPENTHREAD_CONFIG_DEFAULT_CHANNEL), - mReceiveDoneCallback(NULL), - mTransmitDoneCallback(NULL), - mEnergyScanDoneCallback(NULL) +LinkRaw::LinkRaw(Instance &aInstance) + : mInstance(aInstance) + , mEnabled(false) + , mReceiveChannel(OPENTHREAD_CONFIG_DEFAULT_CHANNEL) + , mReceiveDoneCallback(NULL) + , mTransmitDoneCallback(NULL) + , mEnergyScanDoneCallback(NULL) #if OPENTHREAD_LINKRAW_TIMER_REQUIRED , mTimer(aInstance, &LinkRaw::HandleTimer, this) , mTimerReason(kTimerReasonNone) @@ -341,9 +343,9 @@ otError LinkRaw::Receive(uint8_t aChannel, otLinkRawReceiveDone aCallback) if (mEnabled) { - mReceiveChannel = aChannel; + mReceiveChannel = aChannel; mReceiveDoneCallback = aCallback; - error = otPlatRadioReceive(&mInstance, aChannel); + error = otPlatRadioReceive(&mInstance, aChannel); } return error; @@ -377,7 +379,7 @@ otError LinkRaw::Transmit(otRadioFrame *aFrame, otLinkRawTransmitDone aCallback) #if OPENTHREAD_CONFIG_ENABLE_SOFTWARE_RETRANSMIT OT_UNUSED_VARIABLE(aFrame); mTransmitAttempts = 0; - mCsmaAttempts = 0; + mCsmaAttempts = 0; // Start the transmission backlog logic StartCsmaBackoff(); @@ -485,7 +487,7 @@ otError LinkRaw::EnergyScan(uint8_t aScanChannel, uint16_t aScanDuration, otLink // Reset the RSSI value and start scanning mEnergyScanRssi = kInvalidRssiValue; - mTimerReason = kTimerReasonEnergyScanComplete; + mTimerReason = kTimerReasonEnergyScanComplete; mTimer.Start(aScanDuration); mEnergyScanTask.Post(); #else @@ -516,7 +518,7 @@ void LinkRaw::HandleTimer(Timer &aTimer) void LinkRaw::HandleTimer(void) { TimerReason timerReason = mTimerReason; - mTimerReason = kTimerReasonNone; + mTimerReason = kTimerReasonNone; switch (timerReason) { @@ -591,7 +593,7 @@ void LinkRaw::StartCsmaBackoff(void) #if OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_TIMER mTimerMicro.Start(backoff); -#else // OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_TIMER +#else // OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_TIMER mTimer.Start(backoff / 1000UL); #endif // OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_TIMER } diff --git a/src/core/api/message_api.cpp b/src/core/api/message_api.cpp index c4acfa5e2..4e3da3d5d 100644 --- a/src/core/api/message_api.cpp +++ b/src/core/api/message_api.cpp @@ -119,22 +119,22 @@ void otMessageQueueInit(otMessageQueue *aQueue) otError otMessageQueueEnqueue(otMessageQueue *aQueue, otMessage *aMessage) { - Message &message = *static_cast(aMessage); - MessageQueue &queue = *static_cast(aQueue); + Message & message = *static_cast(aMessage); + MessageQueue &queue = *static_cast(aQueue); return queue.Enqueue(message); } otError otMessageQueueEnqueueAtHead(otMessageQueue *aQueue, otMessage *aMessage) { - Message &message = *static_cast(aMessage); - MessageQueue &queue = *static_cast(aQueue); + Message & message = *static_cast(aMessage); + MessageQueue &queue = *static_cast(aQueue); return queue.Enqueue(message, MessageQueue::kQueuePositionHead); } otError otMessageQueueDequeue(otMessageQueue *aQueue, otMessage *aMessage) { - Message &message = *static_cast(aMessage); - MessageQueue &queue = *static_cast(aQueue); + Message & message = *static_cast(aMessage); + MessageQueue &queue = *static_cast(aQueue); return queue.Dequeue(message); } @@ -152,7 +152,7 @@ otMessage *otMessageQueueGetNext(otMessageQueue *aQueue, const otMessage *aMessa { const Message &message = *static_cast(aMessage); - MessageQueue &queue = *static_cast(aQueue); + MessageQueue & queue = *static_cast(aQueue); VerifyOrExit(message.GetMessageQueue() == &queue, next = NULL); next = message.GetNext(); @@ -164,7 +164,7 @@ exit: void otMessageGetBufferInfo(otInstance *aInstance, otBufferInfo *aBufferInfo) { - uint16_t messages, buffers; + uint16_t messages, buffers; Instance &instance = *static_cast(aInstance); aBufferInfo->mTotalBuffers = OPENTHREAD_CONFIG_NUM_MESSAGE_BUFFERS; @@ -182,17 +182,15 @@ void otMessageGetBufferInfo(otInstance *aInstance, otBufferInfo *aBufferInfo) aBufferInfo->mArpBuffers); #else aBufferInfo->mArpMessages = 0; - aBufferInfo->mArpBuffers = 0; + aBufferInfo->mArpBuffers = 0; #endif - instance.GetThreadNetif().GetIp6().GetSendQueue().GetInfo(aBufferInfo->mIp6Messages, - aBufferInfo->mIp6Buffers); + instance.GetThreadNetif().GetIp6().GetSendQueue().GetInfo(aBufferInfo->mIp6Messages, aBufferInfo->mIp6Buffers); instance.GetThreadNetif().GetIp6().GetMpl().GetBufferedMessageSet().GetInfo(aBufferInfo->mMplMessages, aBufferInfo->mMplBuffers); - instance.GetThreadNetif().GetMle().GetMessageQueue().GetInfo(aBufferInfo->mMleMessages, - aBufferInfo->mMleBuffers); + instance.GetThreadNetif().GetMle().GetMessageQueue().GetInfo(aBufferInfo->mMleMessages, aBufferInfo->mMleBuffers); instance.GetThreadNetif().GetCoap().GetRequestMessages().GetInfo(aBufferInfo->mCoapMessages, aBufferInfo->mCoapBuffers); @@ -207,8 +205,8 @@ void otMessageGetBufferInfo(otInstance *aInstance, otBufferInfo *aBufferInfo) aBufferInfo->mCoapSecureMessages += messages; aBufferInfo->mCoapSecureBuffers += buffers; #else - aBufferInfo->mCoapSecureMessages = 0; - aBufferInfo->mCoapSecureBuffers = 0; + aBufferInfo->mCoapSecureMessages = 0; + aBufferInfo->mCoapSecureBuffers = 0; #endif #if OPENTHREAD_ENABLE_APPLICATION_COAP @@ -219,6 +217,6 @@ void otMessageGetBufferInfo(otInstance *aInstance, otBufferInfo *aBufferInfo) aBufferInfo->mApplicationCoapBuffers += buffers; #else aBufferInfo->mApplicationCoapMessages = 0; - aBufferInfo->mApplicationCoapBuffers = 0; + aBufferInfo->mApplicationCoapBuffers = 0; #endif } diff --git a/src/core/api/netdata_api.cpp b/src/core/api/netdata_api.cpp index febf6f66e..27e3986ad 100644 --- a/src/core/api/netdata_api.cpp +++ b/src/core/api/netdata_api.cpp @@ -41,7 +41,7 @@ using namespace ot; otError otNetDataGet(otInstance *aInstance, bool aStable, uint8_t *aData, uint8_t *aDataLength) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aData != NULL && aDataLength != NULL, error = OT_ERROR_INVALID_ARGS); @@ -52,10 +52,11 @@ exit: return error; } -otError otNetDataGetNextOnMeshPrefix(otInstance *aInstance, otNetworkDataIterator *aIterator, - otBorderRouterConfig *aConfig) +otError otNetDataGetNextOnMeshPrefix(otInstance * aInstance, + otNetworkDataIterator *aIterator, + otBorderRouterConfig * aConfig) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aIterator && aConfig, error = OT_ERROR_INVALID_ARGS); @@ -66,10 +67,9 @@ exit: return error; } -otError otNetDataGetNextRoute(otInstance *aInstance, otNetworkDataIterator *aIterator, - otExternalRouteConfig *aConfig) +otError otNetDataGetNextRoute(otInstance *aInstance, otNetworkDataIterator *aIterator, otExternalRouteConfig *aConfig) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aIterator && aConfig, error = OT_ERROR_INVALID_ARGS); diff --git a/src/core/api/server_api.cpp b/src/core/api/server_api.cpp index 71549107b..306dc0222 100644 --- a/src/core/api/server_api.cpp +++ b/src/core/api/server_api.cpp @@ -43,7 +43,7 @@ using namespace ot; otError otServerGetNetDataLocal(otInstance *aInstance, bool aStable, uint8_t *aData, uint8_t *aDataLength) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aData != NULL && aDataLength != NULL, error = OT_ERROR_INVALID_ARGS); @@ -59,13 +59,15 @@ otError otServerAddService(otInstance *aInstance, const otServiceConfig *aConfig Instance &instance = *static_cast(aInstance); return instance.GetThreadNetif().GetNetworkDataLocal().AddService( - aConfig->mEnterpriseNumber, &aConfig->mServiceData[0], aConfig->mServiceDataLength, - aConfig->mServerConfig.mStable, &aConfig->mServerConfig.mServerData[0], aConfig->mServerConfig.mServerDataLength - ); + aConfig->mEnterpriseNumber, &aConfig->mServiceData[0], aConfig->mServiceDataLength, + aConfig->mServerConfig.mStable, &aConfig->mServerConfig.mServerData[0], + aConfig->mServerConfig.mServerDataLength); } -otError otServerRemoveService(otInstance *aInstance, uint32_t aEnterpriseNumber, uint8_t *aServiceData, - uint8_t aServiceDataLength) +otError otServerRemoveService(otInstance *aInstance, + uint32_t aEnterpriseNumber, + uint8_t * aServiceData, + uint8_t aServiceDataLength) { Instance &instance = *static_cast(aInstance); @@ -73,10 +75,9 @@ otError otServerRemoveService(otInstance *aInstance, uint32_t aEnterpriseNumber, aServiceDataLength); } -otError otServerGetNextService(otInstance *aInstance, otNetworkDataIterator *aIterator, - otServiceConfig *aConfig) +otError otServerGetNextService(otInstance *aInstance, otNetworkDataIterator *aIterator, otServiceConfig *aConfig) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aIterator && aConfig, error = OT_ERROR_INVALID_ARGS); @@ -87,10 +88,9 @@ exit: return error; } -otError otServerGetNextLeaderService(otInstance *aInstance, otNetworkDataIterator *aIterator, - otServiceConfig *aConfig) +otError otServerGetNextLeaderService(otInstance *aInstance, otNetworkDataIterator *aIterator, otServiceConfig *aConfig) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aIterator && aConfig, error = OT_ERROR_INVALID_ARGS); @@ -108,4 +108,4 @@ otError otServerRegister(otInstance *aInstance) return instance.GetThreadNetif().GetNetworkDataLocal().SendServerDataNotification(); } -#endif // OPENTHREAD_ENABLE_SERVICE +#endif // OPENTHREAD_ENABLE_SERVICE diff --git a/src/core/api/tasklet_api.cpp b/src/core/api/tasklet_api.cpp index cb3dccd1b..23900f681 100644 --- a/src/core/api/tasklet_api.cpp +++ b/src/core/api/tasklet_api.cpp @@ -56,7 +56,7 @@ exit: bool otTaskletsArePending(otInstance *aInstance) { - bool retval = false; + bool retval = false; Instance &instance = *static_cast(aInstance); VerifyOrExit(otInstanceIsInitialized(aInstance)); @@ -71,4 +71,3 @@ OT_TOOL_WEAK void otTaskletsSignalPending(otInstance *) { } #endif - diff --git a/src/core/api/thread_api.cpp b/src/core/api/thread_api.cpp index cd7ec1bea..99760a62b 100644 --- a/src/core/api/thread_api.cpp +++ b/src/core/api/thread_api.cpp @@ -67,9 +67,9 @@ const uint8_t *otThreadGetExtendedPanId(otInstance *aInstance) otError otThreadSetExtendedPanId(otInstance *aInstance, const uint8_t *aExtendedPanId) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); - uint8_t mlPrefix[8]; + uint8_t mlPrefix[8]; VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); @@ -91,7 +91,7 @@ exit: otError otThreadGetLeaderRloc(otInstance *aInstance, otIp6Address *aAddress) { - otError error; + otError error; Instance &instance = *static_cast(aInstance); VerifyOrExit(aAddress != NULL, error = OT_ERROR_INVALID_ARGS); @@ -105,8 +105,8 @@ exit: otLinkModeConfig otThreadGetLinkMode(otInstance *aInstance) { otLinkModeConfig config; - Instance &instance = *static_cast(aInstance); - uint8_t mode = instance.GetThreadNetif().GetMle().GetDeviceMode(); + Instance & instance = *static_cast(aInstance); + uint8_t mode = instance.GetThreadNetif().GetMle().GetDeviceMode(); memset(&config, 0, sizeof(otLinkModeConfig)); @@ -135,7 +135,7 @@ otLinkModeConfig otThreadGetLinkMode(otInstance *aInstance) otError otThreadSetLinkMode(otInstance *aInstance, otLinkModeConfig aConfig) { - uint8_t mode = 0; + uint8_t mode = 0; Instance &instance = *static_cast(aInstance); if (aConfig.mRxOnWhenIdle) @@ -170,7 +170,7 @@ const otMasterKey *otThreadGetMasterKey(otInstance *aInstance) otError otThreadSetMasterKey(otInstance *aInstance, const otMasterKey *aKey) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aKey != NULL, error = OT_ERROR_INVALID_ARGS); @@ -201,7 +201,7 @@ const uint8_t *otThreadGetMeshLocalPrefix(otInstance *aInstance) otError otThreadSetMeshLocalPrefix(otInstance *aInstance, const uint8_t *aMeshLocalPrefix) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, @@ -231,7 +231,7 @@ const char *otThreadGetNetworkName(otInstance *aInstance) otError otThreadSetNetworkName(otInstance *aInstance, const char *aNetworkName) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, @@ -289,7 +289,7 @@ otError otThreadBecomeChild(otInstance *aInstance) otError otThreadGetNextNeighborInfo(otInstance *aInstance, otNeighborInfoIterator *aIterator, otNeighborInfo *aInfo) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit((aInfo != NULL) && (aIterator != NULL), error = OT_ERROR_INVALID_ARGS); @@ -309,7 +309,7 @@ otDeviceRole otThreadGetDeviceRole(otInstance *aInstance) otError otThreadGetLeaderData(otInstance *aInstance, otLeaderData *aLeaderData) { - otError error; + otError error; Instance &instance = *static_cast(aInstance); VerifyOrExit(aLeaderData != NULL, error = OT_ERROR_INVALID_ARGS); @@ -350,22 +350,21 @@ uint16_t otThreadGetRloc16(otInstance *aInstance) otError otThreadGetParentInfo(otInstance *aInstance, otRouterInfo *aParentInfo) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); - Router *parent; + Router * parent; VerifyOrExit(aParentInfo != NULL, error = OT_ERROR_INVALID_ARGS); - parent = instance.GetThreadNetif().GetMle().GetParent(); - aParentInfo->mExtAddress = parent->GetExtAddress(); - aParentInfo->mRloc16 = parent->GetRloc16(); - aParentInfo->mRouterId = Mle::Mle::GetRouterId(parent->GetRloc16()); - aParentInfo->mNextHop = parent->GetNextHop(); - aParentInfo->mPathCost = parent->GetCost(); - aParentInfo->mLinkQualityIn = parent->GetLinkInfo().GetLinkQuality(); - aParentInfo->mLinkQualityOut = parent->GetLinkQualityOut(); - aParentInfo->mAge = static_cast(TimerMilli::MsecToSec(TimerMilli::GetNow() - - parent->GetLastHeard())); + parent = instance.GetThreadNetif().GetMle().GetParent(); + aParentInfo->mExtAddress = parent->GetExtAddress(); + aParentInfo->mRloc16 = parent->GetRloc16(); + aParentInfo->mRouterId = Mle::Mle::GetRouterId(parent->GetRloc16()); + aParentInfo->mNextHop = parent->GetNextHop(); + aParentInfo->mPathCost = parent->GetCost(); + aParentInfo->mLinkQualityIn = parent->GetLinkInfo().GetLinkQuality(); + aParentInfo->mLinkQualityOut = parent->GetLinkQualityOut(); + aParentInfo->mAge = static_cast(TimerMilli::MsecToSec(TimerMilli::GetNow() - parent->GetLastHeard())); aParentInfo->mAllocated = parent->IsAllocated(); aParentInfo->mLinkEstablished = parent->GetState() == Neighbor::kStateValid; @@ -375,13 +374,13 @@ exit: otError otThreadGetParentAverageRssi(otInstance *aInstance, int8_t *aParentRssi) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); - Router *parent; + Router * parent; VerifyOrExit(aParentRssi != NULL, error = OT_ERROR_INVALID_ARGS); - parent = instance.GetThreadNetif().GetMle().GetParent(); + parent = instance.GetThreadNetif().GetMle().GetParent(); *aParentRssi = parent->GetLinkInfo().GetAverageRss(); VerifyOrExit(*aParentRssi != OT_RADIO_RSSI_INVALID, error = OT_ERROR_FAILED); @@ -392,13 +391,13 @@ exit: otError otThreadGetParentLastRssi(otInstance *aInstance, int8_t *aLastRssi) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); - Router *parent; + Router * parent; VerifyOrExit(aLastRssi != NULL, error = OT_ERROR_INVALID_ARGS); - parent = instance.GetThreadNetif().GetMle().GetParent(); + parent = instance.GetThreadNetif().GetMle().GetParent(); *aLastRssi = parent->GetLinkInfo().GetLastRss(); VerifyOrExit(*aLastRssi != OT_RADIO_RSSI_INVALID, error = OT_ERROR_FAILED); @@ -409,34 +408,33 @@ exit: const char *otGetVersionString(void) { - /** - * PLATFORM_VERSION_ATTR_PREFIX and PLATFORM_VERSION_ATTR_SUFFIX are - * intended to be used to specify compiler directives to indicate - * what linker section the platform version string should be stored. - * - * This is useful for specifying an exact locaiton of where the version - * string will be located so that it can be easily retrieved from the - * raw firmware image. - * - * If PLATFORM_VERSION_ATTR_PREFIX is unspecified, the keyword `static` - * is used instead. - * - * If both are unspecified, the location of the string in the firmware - * image will be undefined and may change. - */ +/** + * PLATFORM_VERSION_ATTR_PREFIX and PLATFORM_VERSION_ATTR_SUFFIX are + * intended to be used to specify compiler directives to indicate + * what linker section the platform version string should be stored. + * + * This is useful for specifying an exact locaiton of where the version + * string will be located so that it can be easily retrieved from the + * raw firmware image. + * + * If PLATFORM_VERSION_ATTR_PREFIX is unspecified, the keyword `static` + * is used instead. + * + * If both are unspecified, the location of the string in the firmware + * image will be undefined and may change. + */ #ifdef PLATFORM_VERSION_ATTR_PREFIX PLATFORM_VERSION_ATTR_PREFIX #else static #endif - const char sVersion[] = - PACKAGE_NAME "/" PACKAGE_VERSION "; " OPENTHREAD_CONFIG_PLATFORM_INFO + const char sVersion[] = PACKAGE_NAME "/" PACKAGE_VERSION "; " OPENTHREAD_CONFIG_PLATFORM_INFO #if defined(__DATE__) - "; " __DATE__ " " __TIME__ + "; " __DATE__ " " __TIME__ #endif #ifdef PLATFORM_VERSION_ATTR_SUFFIX - PLATFORM_VERSION_ATTR_SUFFIX + PLATFORM_VERSION_ATTR_SUFFIX #endif ; // Trailing semicolon to end statement. @@ -444,40 +442,41 @@ const char *otGetVersionString(void) } #if OPENTHREAD_FTD || OPENTHREAD_ENABLE_MTD_NETWORK_DIAGNOSTIC -void otThreadSetReceiveDiagnosticGetCallback(otInstance *aInstance, otReceiveDiagnosticGetCallback aCallback, - void *aCallbackContext) +void otThreadSetReceiveDiagnosticGetCallback(otInstance * aInstance, + otReceiveDiagnosticGetCallback aCallback, + void * aCallbackContext) { Instance &instance = *static_cast(aInstance); instance.GetThreadNetif().GetNetworkDiagnostic().SetReceiveDiagnosticGetCallback(aCallback, aCallbackContext); } -otError otThreadSendDiagnosticGet(otInstance *aInstance, const otIp6Address *aDestination, - const uint8_t aTlvTypes[], uint8_t aCount) +otError otThreadSendDiagnosticGet(otInstance * aInstance, + const otIp6Address *aDestination, + const uint8_t aTlvTypes[], + uint8_t aCount) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetNetworkDiagnostic().SendDiagnosticGet(*static_cast - (aDestination), - aTlvTypes, - aCount); + return instance.GetThreadNetif().GetNetworkDiagnostic().SendDiagnosticGet( + *static_cast(aDestination), aTlvTypes, aCount); } -otError otThreadSendDiagnosticReset(otInstance *aInstance, const otIp6Address *aDestination, - const uint8_t aTlvTypes[], uint8_t aCount) +otError otThreadSendDiagnosticReset(otInstance * aInstance, + const otIp6Address *aDestination, + const uint8_t aTlvTypes[], + uint8_t aCount) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetNetworkDiagnostic().SendDiagnosticReset(*static_cast - (aDestination), - aTlvTypes, - aCount); + return instance.GetThreadNetif().GetNetworkDiagnostic().SendDiagnosticReset( + *static_cast(aDestination), aTlvTypes, aCount); } #endif // OPENTHREAD_FTD || OPENTHREAD_ENABLE_MTD_NETWORK_DIAGNOSTIC otError otThreadSetEnabled(otInstance *aInstance, bool aEnabled) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); if (aEnabled) @@ -498,11 +497,10 @@ exit: bool otThreadGetAutoStart(otInstance *aInstance) { #if OPENTHREAD_CONFIG_ENABLE_AUTO_START_SUPPORT - uint8_t autoStart = 0; + uint8_t autoStart = 0; uint16_t autoStartLength = sizeof(autoStart); - if (otPlatSettingsGet(aInstance, Settings::kKeyThreadAutoStart, 0, &autoStart, &autoStartLength) != - OT_ERROR_NONE) + if (otPlatSettingsGet(aInstance, Settings::kKeyThreadAutoStart, 0, &autoStart, &autoStartLength) != OT_ERROR_NONE) { autoStart = 0; } @@ -533,8 +531,13 @@ bool otThreadIsSingleton(otInstance *aInstance) return instance.GetThreadNetif().GetMle().IsSingleton(); } -otError otThreadDiscover(otInstance *aInstance, uint32_t aScanChannels, uint16_t aPanId, bool aJoiner, - bool aEnableEui64Filtering, otHandleActiveScanResult aCallback, void *aCallbackContext) +otError otThreadDiscover(otInstance * aInstance, + uint32_t aScanChannels, + uint16_t aPanId, + bool aJoiner, + bool aEnableEui64Filtering, + otHandleActiveScanResult aCallback, + void * aCallbackContext) { Instance &instance = *static_cast(aInstance); diff --git a/src/core/api/thread_ftd_api.cpp b/src/core/api/thread_ftd_api.cpp index c226f818f..f843eaac0 100644 --- a/src/core/api/thread_ftd_api.cpp +++ b/src/core/api/thread_ftd_api.cpp @@ -47,7 +47,7 @@ using namespace ot; uint8_t otThreadGetMaxAllowedChildren(otInstance *aInstance) { - uint8_t aNumChildren; + uint8_t aNumChildren; Instance &instance = *static_cast(aInstance); (void)instance.GetThreadNetif().GetMle().GetChildren(&aNumChildren); @@ -176,7 +176,7 @@ otError otThreadReleaseRouterId(otInstance *aInstance, uint8_t aRouterId) otError otThreadBecomeRouter(otInstance *aInstance) { - otError error = OT_ERROR_INVALID_STATE; + otError error = OT_ERROR_INVALID_STATE; Instance &instance = *static_cast(aInstance); switch (instance.GetThreadNetif().GetMle().GetRole()) @@ -235,7 +235,7 @@ void otThreadSetRouterSelectionJitter(otInstance *aInstance, uint8_t aRouterJitt otError otThreadGetChildInfoById(otInstance *aInstance, uint16_t aChildId, otChildInfo *aChildInfo) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aChildInfo != NULL, error = OT_ERROR_INVALID_ARGS); @@ -248,7 +248,7 @@ exit: otError otThreadGetChildInfoByIndex(otInstance *aInstance, uint8_t aChildIndex, otChildInfo *aChildInfo) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aChildInfo != NULL, error = OT_ERROR_INVALID_ARGS); @@ -259,13 +259,15 @@ exit: return error; } -otError otThreadGetChildNextIp6Address(otInstance *aInstance, uint8_t aChildIndex, otChildIp6AddressIterator *aIterator, - otIp6Address *aAddress) +otError otThreadGetChildNextIp6Address(otInstance * aInstance, + uint8_t aChildIndex, + otChildIp6AddressIterator *aIterator, + otIp6Address * aAddress) { - otError error = OT_ERROR_NONE; - Instance &instance = *static_cast(aInstance); + otError error = OT_ERROR_NONE; + Instance & instance = *static_cast(aInstance); Child::Ip6AddressIterator iterator; - Ip6::Address *address; + Ip6::Address * address; VerifyOrExit(aIterator != NULL && aAddress != NULL, error = OT_ERROR_INVALID_ARGS); @@ -295,7 +297,7 @@ uint8_t otThreadGetMaxRouterId(otInstance *aInstance) otError otThreadGetRouterInfo(otInstance *aInstance, uint16_t aRouterId, otRouterInfo *aRouterInfo) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(aRouterInfo != NULL, error = OT_ERROR_INVALID_ARGS); @@ -308,7 +310,7 @@ exit: otError otThreadGetEidCacheEntry(otInstance *aInstance, uint8_t aIndex, otEidCacheEntry *aEntry) { - otError error; + otError error; Instance &instance = *static_cast(aInstance); VerifyOrExit(aEntry != NULL, error = OT_ERROR_INVALID_ARGS); @@ -345,7 +347,7 @@ const uint8_t *otThreadGetPSKc(otInstance *aInstance) otError otThreadSetPSKc(otInstance *aInstance, const uint8_t *aPSKc) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, diff --git a/src/core/api/udp_api.cpp b/src/core/api/udp_api.cpp index 00e7b7d6c..481324112 100644 --- a/src/core/api/udp_api.cpp +++ b/src/core/api/udp_api.cpp @@ -42,7 +42,7 @@ using namespace ot; otMessage *otUdpNewMessage(otInstance *aInstance, bool aLinkSecurityEnabled) { Instance &instance = *static_cast(aInstance); - Message *message = instance.GetIp6().GetUdp().NewMessage(0); + Message * message = instance.GetIp6().GetUdp().NewMessage(0); if (message) { @@ -54,14 +54,14 @@ otMessage *otUdpNewMessage(otInstance *aInstance, bool aLinkSecurityEnabled) otError otUdpOpen(otInstance *aInstance, otUdpSocket *aSocket, otUdpReceive aCallback, void *aCallbackContext) { - otError error = OT_ERROR_INVALID_ARGS; - Instance &instance = *static_cast(aInstance); - Ip6::UdpSocket &socket = *static_cast(aSocket); + otError error = OT_ERROR_INVALID_ARGS; + Instance & instance = *static_cast(aInstance); + Ip6::UdpSocket &socket = *static_cast(aSocket); if (socket.mTransport == NULL) { socket.mTransport = &instance.GetIp6().GetUdp(); - error = socket.Open(aCallback, aCallbackContext); + error = socket.Open(aCallback, aCallbackContext); } return error; @@ -69,7 +69,7 @@ otError otUdpOpen(otInstance *aInstance, otUdpSocket *aSocket, otUdpReceive aCal otError otUdpClose(otUdpSocket *aSocket) { - otError error = OT_ERROR_INVALID_STATE; + otError error = OT_ERROR_INVALID_STATE; Ip6::UdpSocket &socket = *static_cast(aSocket); if (socket.mTransport != NULL) @@ -100,6 +100,5 @@ otError otUdpConnect(otUdpSocket *aSocket, otSockAddr *aSockName) otError otUdpSend(otUdpSocket *aSocket, otMessage *aMessage, const otMessageInfo *aMessageInfo) { Ip6::UdpSocket &socket = *static_cast(aSocket); - return socket.SendTo(*static_cast(aMessage), - *static_cast(aMessageInfo)); + return socket.SendTo(*static_cast(aMessage), *static_cast(aMessageInfo)); } diff --git a/src/core/coap/coap.cpp b/src/core/coap/coap.cpp index 0ed48aa71..c8778b950 100644 --- a/src/core/coap/coap.cpp +++ b/src/core/coap/coap.cpp @@ -49,24 +49,25 @@ namespace ot { namespace Coap { -CoapBase::CoapBase(Instance &aInstance, Timer::Handler aRetransmissionTimerHandler, - Timer::Handler aResponsesQueueTimerHandler): - InstanceLocator(aInstance), - mSocket(aInstance.GetThreadNetif().GetIp6().GetUdp()), - mRetransmissionTimer(aInstance, aRetransmissionTimerHandler, this), - mResources(NULL), - mContext(NULL), - mInterceptor(NULL), - mResponsesQueue(aInstance, aResponsesQueueTimerHandler, this), - mDefaultHandler(NULL), - mDefaultHandlerContext(NULL) +CoapBase::CoapBase(Instance & aInstance, + Timer::Handler aRetransmissionTimerHandler, + Timer::Handler aResponsesQueueTimerHandler) + : InstanceLocator(aInstance) + , mSocket(aInstance.GetThreadNetif().GetIp6().GetUdp()) + , mRetransmissionTimer(aInstance, aRetransmissionTimerHandler, this) + , mResources(NULL) + , mContext(NULL) + , mInterceptor(NULL) + , mResponsesQueue(aInstance, aResponsesQueueTimerHandler, this) + , mDefaultHandler(NULL) + , mDefaultHandlerContext(NULL) { mMessageId = static_cast(otPlatRandomGet()); } otError CoapBase::Start(uint16_t aPort) { - otError error; + otError error; Ip6::SockAddr sockaddr; sockaddr.mPort = aPort; @@ -79,15 +80,15 @@ exit: otError CoapBase::Stop(void) { - Message *message = mPendingRequests.GetHead(); - Message *messageToRemove; + Message * message = mPendingRequests.GetHead(); + Message * messageToRemove; CoapMetadata coapMetadata; // Remove all pending messages. while (message != NULL) { messageToRemove = message; - message = message->GetNext(); + message = message->GetNext(); coapMetadata.ReadFrom(*messageToRemove); FinalizeCoapTransaction(*messageToRemove, coapMetadata, NULL, NULL, NULL, OT_ERROR_ABORT); @@ -108,7 +109,7 @@ otError CoapBase::AddResource(Resource &aResource) } aResource.mNext = mResources; - mResources = &aResource; + mResources = &aResource; exit: return error; @@ -138,7 +139,7 @@ exit: void CoapBase::SetDefaultHandler(otCoapRequestHandler aHandler, void *aContext) { - mDefaultHandler = aHandler; + mDefaultHandler = aHandler; mDefaultHandlerContext = aContext; } @@ -158,14 +159,16 @@ exit: return message; } -otError CoapBase::SendMessage(Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - otCoapResponseHandler aHandler, void *aContext) +otError CoapBase::SendMessage(Message & aMessage, + const Ip6::MessageInfo &aMessageInfo, + otCoapResponseHandler aHandler, + void * aContext) { - otError error; - Header header; + otError error; + Header header; CoapMetadata coapMetadata; - Message *storedCopy = NULL; - uint16_t copyLength = 0; + Message * storedCopy = NULL; + uint16_t copyLength = 0; SuccessOrExit(error = header.FromMessage(aMessage, 0)); @@ -218,11 +221,12 @@ otError CoapBase::Send(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) return mSocket.SendTo(aMessage, aMessageInfo); } -otError CoapBase::SendEmptyMessage(Header::Type aType, const Header &aRequestHeader, +otError CoapBase::SendEmptyMessage(Header::Type aType, + const Header & aRequestHeader, const Ip6::MessageInfo &aMessageInfo) { - otError error = OT_ERROR_NONE; - Header responseHeader; + otError error = OT_ERROR_NONE; + Header responseHeader; Message *message = NULL; VerifyOrExit(aRequestHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE, error = OT_ERROR_INVALID_ARGS); @@ -244,13 +248,14 @@ exit: return error; } -otError CoapBase::SendHeaderResponse(Header::Code aCode, const Header &aRequestHeader, +otError CoapBase::SendHeaderResponse(Header::Code aCode, + const Header & aRequestHeader, const Ip6::MessageInfo &aMessageInfo) { - otError error = OT_ERROR_NONE; - Header responseHeader; + otError error = OT_ERROR_NONE; + Header responseHeader; Header::Type requestType; - Message *message = NULL; + Message * message = NULL; VerifyOrExit(aRequestHeader.IsRequest(), error = OT_ERROR_INVALID_ARGS); @@ -291,11 +296,11 @@ exit: void CoapBase::HandleRetransmissionTimer(void) { - uint32_t now = TimerMilli::GetNow(); - uint32_t nextDelta = 0xffffffff; - CoapMetadata coapMetadata; - Message *message = mPendingRequests.GetHead(); - Message *nextMessage = NULL; + uint32_t now = TimerMilli::GetNow(); + uint32_t nextDelta = 0xffffffff; + CoapMetadata coapMetadata; + Message * message = mPendingRequests.GetHead(); + Message * nextMessage = NULL; Ip6::MessageInfo messageInfo; while (message != NULL) @@ -311,8 +316,7 @@ void CoapBase::HandleRetransmissionTimer(void) nextDelta = coapMetadata.mNextTimerShot - now; } } - else if ((coapMetadata.mConfirmable) && - (coapMetadata.mRetransmissionCount < kMaxRetransmit)) + else if ((coapMetadata.mConfirmable) && (coapMetadata.mRetransmissionCount < kMaxRetransmit)) { // Increment retransmission counter and timer. coapMetadata.mRetransmissionCount++; @@ -352,24 +356,27 @@ void CoapBase::HandleRetransmissionTimer(void) } } -void CoapBase::FinalizeCoapTransaction(Message &aRequest, const CoapMetadata &aCoapMetadata, - Header *aResponseHeader, Message *aResponse, - const Ip6::MessageInfo *aMessageInfo, otError aResult) +void CoapBase::FinalizeCoapTransaction(Message & aRequest, + const CoapMetadata & aCoapMetadata, + Header * aResponseHeader, + Message * aResponse, + const Ip6::MessageInfo *aMessageInfo, + otError aResult) { DequeueMessage(aRequest); if (aCoapMetadata.mResponseHandler != NULL) { - aCoapMetadata.mResponseHandler(aCoapMetadata.mResponseContext, aResponseHeader, - aResponse, aMessageInfo, aResult); + aCoapMetadata.mResponseHandler(aCoapMetadata.mResponseContext, aResponseHeader, aResponse, aMessageInfo, + aResult); } } otError CoapBase::AbortTransaction(otCoapResponseHandler aHandler, void *aContext) { - otError error = OT_ERROR_NOT_FOUND; - Message *message; - Message *nextMessage; + otError error = OT_ERROR_NOT_FOUND; + Message * message; + Message * nextMessage; CoapMetadata coapMetadata; for (message = mPendingRequests.GetHead(); message != NULL; message = nextMessage) @@ -387,11 +394,11 @@ otError CoapBase::AbortTransaction(otCoapResponseHandler aHandler, void *aContex return error; } - -Message *CoapBase::CopyAndEnqueueMessage(const Message &aMessage, uint16_t aCopyLength, +Message *CoapBase::CopyAndEnqueueMessage(const Message & aMessage, + uint16_t aCopyLength, const CoapMetadata &aCoapMetadata) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Message *messageCopy = NULL; uint32_t alarmFireTime; @@ -450,7 +457,7 @@ void CoapBase::DequeueMessage(Message &aMessage) otError CoapBase::SendCopy(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - otError error; + otError error; Message *messageCopy = NULL; // Create a message copy for lower layers. @@ -470,8 +477,10 @@ exit: return error; } -Message *CoapBase::FindRelatedRequest(const Header &aResponseHeader, const Ip6::MessageInfo &aMessageInfo, - Header &aRequestHeader, CoapMetadata &aCoapMetadata) +Message *CoapBase::FindRelatedRequest(const Header & aResponseHeader, + const Ip6::MessageInfo &aMessageInfo, + Header & aRequestHeader, + CoapMetadata & aCoapMetadata) { Message *message = mPendingRequests.GetHead(); @@ -526,7 +535,7 @@ void CoapBase::HandleUdpReceive(void *aContext, otMessage *aMessage, const otMes void CoapBase::Receive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { otError error; - Header header; + Header header; SuccessOrExit(error = header.FromMessage(aMessage, 0)); @@ -547,13 +556,12 @@ exit: } } -void CoapBase::ProcessReceivedResponse(Header &aResponseHeader, Message &aMessage, - const Ip6::MessageInfo &aMessageInfo) +void CoapBase::ProcessReceivedResponse(Header &aResponseHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - Header requestHeader; + Header requestHeader; CoapMetadata coapMetadata; - Message *message = NULL; - otError error = OT_ERROR_NONE; + Message * message = NULL; + otError error = OT_ERROR_NONE; aMessage.MoveOffset(aResponseHeader.GetLength()); @@ -605,7 +613,7 @@ void CoapBase::ProcessReceivedResponse(Header &aResponseHeader, Message &aMessag // Send empty ACK if it is a CON message. SendAck(aResponseHeader, aMessageInfo); - // fall through + // fall through case OT_COAP_TYPE_NON_CONFIRMABLE: // Separate response. @@ -628,11 +636,11 @@ exit: void CoapBase::ProcessReceivedRequest(Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - char uriPath[Resource::kMaxReceivedUriPath] = ""; - char *curUriPath = uriPath; + char uriPath[Resource::kMaxReceivedUriPath] = ""; + char * curUriPath = uriPath; const Header::Option *coapOption; - Message *cachedResponse = NULL; - otError error = OT_ERROR_NOT_FOUND; + Message * cachedResponse = NULL; + otError error = OT_ERROR_NOT_FOUND; if (mInterceptor != NULL) { @@ -719,19 +727,21 @@ exit: return; } -CoapMetadata::CoapMetadata(bool aConfirmable, const Ip6::MessageInfo &aMessageInfo, - otCoapResponseHandler aHandler, void *aContext) +CoapMetadata::CoapMetadata(bool aConfirmable, + const Ip6::MessageInfo &aMessageInfo, + otCoapResponseHandler aHandler, + void * aContext) { - mSourceAddress = aMessageInfo.GetSockAddr(); - mDestinationPort = aMessageInfo.GetPeerPort(); - mDestinationAddress = aMessageInfo.GetPeerAddr(); - mResponseHandler = aHandler; - mResponseContext = aContext; - mRetransmissionCount = 0; + mSourceAddress = aMessageInfo.GetSockAddr(); + mDestinationPort = aMessageInfo.GetPeerPort(); + mDestinationAddress = aMessageInfo.GetPeerAddr(); + mResponseHandler = aHandler; + mResponseContext = aContext; + mRetransmissionCount = 0; mRetransmissionTimeout = TimerMilli::SecToMsec(kAckTimeout); - mRetransmissionTimeout += otPlatRandomGet() % - (TimerMilli::SecToMsec(kAckTimeout) * kAckRandomFactorNumerator / kAckRandomFactorDenominator - - TimerMilli::SecToMsec(kAckTimeout) + 1); + mRetransmissionTimeout += otPlatRandomGet() % (TimerMilli::SecToMsec(kAckTimeout) * kAckRandomFactorNumerator / + kAckRandomFactorDenominator - + TimerMilli::SecToMsec(kAckTimeout) + 1); if (aConfirmable) { @@ -745,21 +755,21 @@ CoapMetadata::CoapMetadata(bool aConfirmable, const Ip6::MessageInfo &aMessageIn } mAcknowledged = false; - mConfirmable = aConfirmable; + mConfirmable = aConfirmable; } -ResponsesQueue::ResponsesQueue(Instance &aInstance, Timer::Handler aHandler, void *aContext): - mQueue(), - mTimer(aInstance, aHandler, aContext) +ResponsesQueue::ResponsesQueue(Instance &aInstance, Timer::Handler aHandler, void *aContext) + : mQueue() + , mTimer(aInstance, aHandler, aContext) { } -otError ResponsesQueue::GetMatchedResponseCopy(const Header &aHeader, +otError ResponsesQueue::GetMatchedResponseCopy(const Header & aHeader, const Ip6::MessageInfo &aMessageInfo, - Message **aResponse) + Message ** aResponse) { otError error = OT_ERROR_NOT_FOUND; - Message *message; + Message * message; EnqueuedResponseHeader enqueuedResponseHeader; Ip6::MessageInfo messageInfo; Header header; @@ -804,9 +814,9 @@ exit: return error; } -otError ResponsesQueue::GetMatchedResponseCopy(const Message &aRequest, +otError ResponsesQueue::GetMatchedResponseCopy(const Message & aRequest, const Ip6::MessageInfo &aMessageInfo, - Message **aResponse) + Message ** aResponse) { otError error = OT_ERROR_NONE; Header header; @@ -822,7 +832,7 @@ exit: void ResponsesQueue::EnqueueResponse(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { Header header; - Message *copy; + Message * copy; EnqueuedResponseHeader enqueuedResponseHeader(aMessageInfo); uint16_t messageCount; uint16_t bufferCount; @@ -837,7 +847,7 @@ void ResponsesQueue::EnqueueResponse(Message &aMessage, const Ip6::MessageInfo & case OT_ERROR_NONE: copy->Free(); - // fall through + // fall through case OT_ERROR_NO_BUFS: default: @@ -889,7 +899,7 @@ void ResponsesQueue::DequeueAllResponses(void) void ResponsesQueue::HandleTimer(void) { - Message *message; + Message * message; EnqueuedResponseHeader enqueuedResponseHeader; while ((message = mQueue.GetHead()) != NULL) @@ -915,8 +925,8 @@ uint32_t EnqueuedResponseHeader::GetRemainingTime(void) const return remainingTime >= 0 ? static_cast(remainingTime) : 0; } -Coap::Coap(Instance &aInstance): - CoapBase(aInstance, &Coap::HandleRetransmissionTimer, &Coap::HandleResponsesQueueTimer) +Coap::Coap(Instance &aInstance) + : CoapBase(aInstance, &Coap::HandleRetransmissionTimer, &Coap::HandleResponsesQueueTimer) { } @@ -932,8 +942,8 @@ void Coap::HandleResponsesQueueTimer(Timer &aTimer) #if OPENTHREAD_ENABLE_APPLICATION_COAP -ApplicationCoap::ApplicationCoap(Instance &aInstance): - CoapBase(aInstance, &ApplicationCoap::HandleRetransmissionTimer, &ApplicationCoap::HandleResponsesQueueTimer) +ApplicationCoap::ApplicationCoap(Instance &aInstance) + : CoapBase(aInstance, &ApplicationCoap::HandleRetransmissionTimer, &ApplicationCoap::HandleResponsesQueueTimer) { } @@ -949,5 +959,5 @@ void ApplicationCoap::HandleResponsesQueueTimer(Timer &aTimer) #endif // OPENTHREAD_ENABLE_APPLICATION_COAP -} // namespace Coap -} // namespace ot +} // namespace Coap +} // namespace ot diff --git a/src/core/coap/coap.hpp b/src/core/coap/coap.hpp index 78f33f40d..c1c72c245 100644 --- a/src/core/coap/coap.hpp +++ b/src/core/coap/coap.hpp @@ -75,15 +75,15 @@ enum kProbingRate = 1, // Note that 2 << (kMaxRetransmit - 1) is equal to kMaxRetransmit power of 2 - kMaxTransmitSpan = kAckTimeout * ((2 << (kMaxRetransmit - 1)) - 1) * - kAckRandomFactorNumerator / kAckRandomFactorDenominator, - kMaxTransmitWait = kAckTimeout * ((2 << kMaxRetransmit) - 1) * - kAckRandomFactorNumerator / kAckRandomFactorDenominator, - kMaxLatency = 100, - kProcessingDelay = kAckTimeout, - kMaxRtt = 2 * kMaxLatency + kProcessingDelay, - kExchangeLifetime = kMaxTransmitSpan + 2 * (kMaxLatency) + kProcessingDelay, - kNonLifetime = kMaxTransmitSpan + kMaxLatency + kMaxTransmitSpan = + kAckTimeout * ((2 << (kMaxRetransmit - 1)) - 1) * kAckRandomFactorNumerator / kAckRandomFactorDenominator, + kMaxTransmitWait = + kAckTimeout * ((2 << kMaxRetransmit) - 1) * kAckRandomFactorNumerator / kAckRandomFactorDenominator, + kMaxLatency = 100, + kProcessingDelay = kAckTimeout, + kMaxRtt = 2 * kMaxLatency + kProcessingDelay, + kExchangeLifetime = kMaxTransmitSpan + 2 * (kMaxLatency) + kProcessingDelay, + kNonLifetime = kMaxTransmitSpan + kMaxLatency }; /** @@ -96,20 +96,19 @@ class CoapMetadata friend class CoapBase; public: - /** * Default constructor for the object. * */ - CoapMetadata(void): - mDestinationPort(0), - mResponseHandler(NULL), - mResponseContext(NULL), - mNextTimerShot(0), - mRetransmissionTimeout(0), - mRetransmissionCount(0), - mAcknowledged(false), - mConfirmable(false) {}; + CoapMetadata(void) + : mDestinationPort(0) + , mResponseHandler(NULL) + , mResponseContext(NULL) + , mNextTimerShot(0) + , mRetransmissionTimeout(0) + , mRetransmissionCount(0) + , mAcknowledged(false) + , mConfirmable(false){}; /** * This constructor initializes the object with specific values. @@ -120,8 +119,10 @@ public: * @param[in] aContext Context for the handler function. * */ - CoapMetadata(bool aConfirmable, const Ip6::MessageInfo &aMessageInfo, - otCoapResponseHandler aHandler, void *aContext); + CoapMetadata(bool aConfirmable, + const Ip6::MessageInfo &aMessageInfo, + otCoapResponseHandler aHandler, + void * aContext); /** * This method appends request data to the message. @@ -132,9 +133,7 @@ public: * @retval OT_ERROR_NO_BUFS Insufficient available buffers to grow the message. * */ - otError AppendTo(Message &aMessage) const { - return aMessage.Append(this, sizeof(*this)); - }; + otError AppendTo(Message &aMessage) const { return aMessage.Append(this, sizeof(*this)); }; /** * This method reads request data from the message. @@ -144,7 +143,8 @@ public: * @returns The number of bytes read. * */ - uint16_t ReadFrom(const Message &aMessage) { + uint16_t ReadFrom(const Message &aMessage) + { return aMessage.Read(aMessage.GetLength() - sizeof(*this), sizeof(*this), this); }; @@ -156,7 +156,8 @@ public: * @returns The number of bytes updated. * */ - int UpdateIn(Message &aMessage) const { + int UpdateIn(Message &aMessage) const + { return aMessage.Write(aMessage.GetLength() - sizeof(*this), sizeof(*this), this); } @@ -185,12 +186,12 @@ private: Ip6::Address mDestinationAddress; ///< IPv6 address of the message destination. uint16_t mDestinationPort; ///< UDP port of the message destination. otCoapResponseHandler mResponseHandler; ///< A function pointer that is called on response reception. - void *mResponseContext; ///< A pointer to arbitrary context information. + void * mResponseContext; ///< A pointer to arbitrary context information. uint32_t mNextTimerShot; ///< Time when the timer should shoot for this message. uint32_t mRetransmissionTimeout; ///< Delay that is applied to next retransmission. uint8_t mRetransmissionCount; ///< Number of retransmissions. - bool mAcknowledged: 1; ///< Information that request was acknowledged. - bool mConfirmable: 1; ///< Information that message is confirmable. + bool mAcknowledged : 1; ///< Information that request was acknowledged. + bool mConfirmable : 1; ///< Information that message is confirmable. } OT_TOOL_PACKED_END; /** @@ -204,7 +205,7 @@ class Resource : public otCoapResource public: enum { - kMaxReceivedUriPath = 32, ///< Maximum supported URI path on received messages. + kMaxReceivedUriPath = 32, ///< Maximum supported URI path on received messages. }; /** @@ -214,11 +215,12 @@ public: * @param[in] aHandler A function pointer that is called when receiving a CoAP message for @p aUriPath. * @param[in] aContext A pointer to arbitrary context information. */ - Resource(const char *aUriPath, otCoapRequestHandler aHandler, void *aContext) { + Resource(const char *aUriPath, otCoapRequestHandler aHandler, void *aContext) + { mUriPath = aUriPath; mHandler = aHandler; mContext = aContext; - mNext = NULL; + mNext = NULL; } /** @@ -230,7 +232,8 @@ public: Resource *GetNext(void) const { return static_cast(mNext); }; private: - void HandleRequest(Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) const { + void HandleRequest(Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) const + { mHandler(mContext, &aHeader, &aMessage, &aMessageInfo); } }; @@ -246,7 +249,11 @@ public: * Default constructor creating empty object. * */ - EnqueuedResponseHeader(void): mDequeueTime(0), mMessageInfo() {} + EnqueuedResponseHeader(void) + : mDequeueTime(0) + , mMessageInfo() + { + } /** * Constructor creating object with valid dequeue time and message info. @@ -254,9 +261,11 @@ public: * @param[in] aMessageInfo The message info containing source endpoint identification. * */ - EnqueuedResponseHeader(const Ip6::MessageInfo &aMessageInfo): - mDequeueTime(TimerMilli::GetNow() + TimerMilli::SecToMsec(kExchangeLifetime)), - mMessageInfo(aMessageInfo) {} + EnqueuedResponseHeader(const Ip6::MessageInfo &aMessageInfo) + : mDequeueTime(TimerMilli::GetNow() + TimerMilli::SecToMsec(kExchangeLifetime)) + , mMessageInfo(aMessageInfo) + { + } /** * This method append metadata to the message. @@ -276,7 +285,8 @@ public: * @returns The number of bytes read. * */ - uint16_t ReadFrom(const Message &aMessage) { + uint16_t ReadFrom(const Message &aMessage) + { return aMessage.Read(aMessage.GetLength() - sizeof(*this), sizeof(*this), this); } @@ -286,7 +296,8 @@ public: * @param[in] aMessage A reference to the message. * */ - static void RemoveFrom(Message &aMessage) { + static void RemoveFrom(Message &aMessage) + { assert(aMessage.SetLength(aMessage.GetLength() - sizeof(EnqueuedResponseHeader)) == OT_ERROR_NONE); } @@ -318,7 +329,7 @@ public: const Ip6::MessageInfo &GetMessageInfo(void) const { return mMessageInfo; } private: - uint32_t mDequeueTime; + uint32_t mDequeueTime; const Ip6::MessageInfo mMessageInfo; }; @@ -376,9 +387,7 @@ public: * @retval OT_ERROR_NOT_FOUND Matching response not found. * */ - otError GetMatchedResponseCopy(const Header &aHeader, - const Ip6::MessageInfo &aMessageInfo, - Message **aResponse); + otError GetMatchedResponseCopy(const Header &aHeader, const Ip6::MessageInfo &aMessageInfo, Message **aResponse); /** * Get a copy of CoAP response from the cache that matches given Message ID and source endpoint. @@ -393,9 +402,7 @@ public: * @retval OT_ERROR_PARSE Could not parse CoAP header in the request message. * */ - otError GetMatchedResponseCopy(const Message &aRequest, - const Ip6::MessageInfo &aMessageInfo, - Message **aResponse); + otError GetMatchedResponseCopy(const Message &aRequest, const Ip6::MessageInfo &aMessageInfo, Message **aResponse); /** * Get a reference to the cached CoAP responses queue. @@ -420,7 +427,11 @@ private: kMaxCachedResponses = OPENTHREAD_CONFIG_COAP_SERVER_MAX_CACHED_RESPONSES, }; - void DequeueResponse(Message &aMessage) { mQueue.Dequeue(aMessage); aMessage.Free(); } + void DequeueResponse(Message &aMessage) + { + mQueue.Dequeue(aMessage); + aMessage.Free(); + } MessageQueue mQueue; TimerMilli mTimer; @@ -430,7 +441,7 @@ private: * This class implements the common base for CoAP client and server. * */ -class CoapBase: public InstanceLocator +class CoapBase : public InstanceLocator { friend class ResponsesQueue; @@ -448,7 +459,7 @@ public: * @retval OT_ERROR_NOT_TMF The message is not a TMF message. * */ - typedef otError(* Interceptor)(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, void *aContext); + typedef otError (*Interceptor)(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, void *aContext); /** * This method starts the CoAP service. @@ -529,8 +540,10 @@ public: * @retval OT_ERROR_NO_BUFS Failed to allocate retransmission data. * */ - otError SendMessage(Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - otCoapResponseHandler aHandler = NULL, void *aContext = NULL); + otError SendMessage(Message & aMessage, + const Ip6::MessageInfo &aMessageInfo, + otCoapResponseHandler aHandler = NULL, + void * aContext = NULL); /** * This method sends a CoAP reset message. @@ -543,7 +556,8 @@ public: * @retval OT_ERROR_INVALID_ARGS The @p aRequestHeader header is not of confirmable type. * */ - otError SendReset(Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo) { + otError SendReset(Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo) + { return SendEmptyMessage(OT_COAP_TYPE_RESET, aRequestHeader, aMessageInfo); }; @@ -572,7 +586,8 @@ public: * @retval OT_ERROR_INVALID_ARGS The @p aRequestHeader header is not of confirmable type. * */ - otError SendAck(Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo) { + otError SendAck(Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo) + { return SendEmptyMessage(OT_COAP_TYPE_ACKNOWLEDGMENT, aRequestHeader, aMessageInfo); }; @@ -587,10 +602,11 @@ public: * @retval OT_ERROR_INVALID_ARGS The @p aRequestHeader header is not of confirmable type. * */ - otError SendEmptyAck(const Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo) { - return (aRequestHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE ? - SendHeaderResponse(OT_COAP_CODE_CHANGED, aRequestHeader, aMessageInfo) : - OT_ERROR_INVALID_ARGS); + otError SendEmptyAck(const Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo) + { + return (aRequestHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE + ? SendHeaderResponse(OT_COAP_CODE_CHANGED, aRequestHeader, aMessageInfo) + : OT_ERROR_INVALID_ARGS); } /** @@ -603,7 +619,8 @@ public: * @retval OT_ERROR_NO_BUFS Insufficient buffers available to send the CoAP response. * */ - otError SendNotFound(const Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo) { + otError SendNotFound(const Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo) + { return SendHeaderResponse(OT_COAP_CODE_NOT_FOUND, aRequestHeader, aMessageInfo); } @@ -628,9 +645,10 @@ public: * @param[in] aContext A pointer to arbitrary context information. * */ - void SetInterceptor(Interceptor aInterceptor, void *aContext) { + void SetInterceptor(Interceptor aInterceptor, void *aContext) + { mInterceptor = aInterceptor; - mContext = aContext; + mContext = aContext; } /** @@ -658,7 +676,8 @@ protected: * @param[in] aResponsesQueueTimerHandler A timer handler provided by sub-class for `mReponsesQueue` timer. * */ - CoapBase(Instance &aInstance, Timer::Handler aRetransmissionTimerHandler, + CoapBase(Instance & aInstance, + Timer::Handler aRetransmissionTimerHandler, Timer::Handler aResponsesQueueTimerHandler); /** @@ -707,40 +726,44 @@ private: static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo); - Message *CopyAndEnqueueMessage(const Message &aMessage, uint16_t aCopyLength, - const CoapMetadata &aCoapMetadata); - void DequeueMessage(Message &aMessage); - Message *FindRelatedRequest(const Header &aResponseHeader, const Ip6::MessageInfo &aMessageInfo, - Header &aRequestHeader, CoapMetadata &aCoapMetadata); - void FinalizeCoapTransaction(Message &aRequest, const CoapMetadata &aCoapMetadata, Header *aResponseHeader, - Message *aResponse, const Ip6::MessageInfo *aMessageInfo, otError aResult); + Message *CopyAndEnqueueMessage(const Message &aMessage, uint16_t aCopyLength, const CoapMetadata &aCoapMetadata); + void DequeueMessage(Message &aMessage); + Message *FindRelatedRequest(const Header & aResponseHeader, + const Ip6::MessageInfo &aMessageInfo, + Header & aRequestHeader, + CoapMetadata & aCoapMetadata); + void FinalizeCoapTransaction(Message & aRequest, + const CoapMetadata & aCoapMetadata, + Header * aResponseHeader, + Message * aResponse, + const Ip6::MessageInfo *aMessageInfo, + otError aResult); void ProcessReceivedRequest(Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); void ProcessReceivedResponse(Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); otError SendCopy(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - otError SendEmptyMessage(Header::Type aType, const Header &aRequestHeader, - const Ip6::MessageInfo &aMessageInfo); + otError SendEmptyMessage(Header::Type aType, const Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo); MessageQueue mPendingRequests; - uint16_t mMessageId; - TimerMilli mRetransmissionTimer; + uint16_t mMessageId; + TimerMilli mRetransmissionTimer; Resource *mResources; - void *mContext; + void * mContext; Interceptor mInterceptor; ResponsesQueue mResponsesQueue; otCoapRequestHandler mDefaultHandler; - void *mDefaultHandlerContext; + void * mDefaultHandlerContext; }; /** * This class implements the CoAP client and server. * */ -class Coap: public CoapBase +class Coap : public CoapBase { public: /** @@ -762,7 +785,7 @@ private: * This class implements the application CoAP client and server. * */ -class ApplicationCoap: public CoapBase +class ApplicationCoap : public CoapBase { public: /** @@ -780,7 +803,7 @@ private: #endif -} // namespace Coap -} // namespace ot +} // namespace Coap +} // namespace ot -#endif // COAP_HPP_ +#endif // COAP_HPP_ diff --git a/src/core/coap/coap_header.cpp b/src/core/coap/coap_header.cpp index 90071cbb2..28bf2c7ae 100644 --- a/src/core/coap/coap_header.cpp +++ b/src/core/coap/coap_header.cpp @@ -46,10 +46,10 @@ namespace Coap { void Header::Init(void) { - mHeaderLength = kMinHeaderLength; - mOptionLast = 0; + mHeaderLength = kMinHeaderLength; + mOptionLast = 0; mFirstOptionOffset = 0; - mNextOptionOffset = 0; + mNextOptionOffset = 0; memset(&mOption, 0, sizeof(mOption)); memset(&mHeader, 0, sizeof(mHeader)); SetVersion(kVersion1); @@ -64,11 +64,11 @@ void Header::Init(Type aType, Code aCode) otError Header::FromMessage(const Message &aMessage, uint16_t aMetadataSize) { - otError error = OT_ERROR_PARSE; + otError error = OT_ERROR_PARSE; uint16_t offset = aMessage.GetOffset(); uint16_t length = aMessage.GetLength() - aMessage.GetOffset(); - uint8_t tokenLength; - bool firstOption = true; + uint8_t tokenLength; + bool firstOption = true; uint16_t optionDelta; uint16_t optionLength; @@ -109,7 +109,7 @@ otError Header::FromMessage(const Message &aMessage, uint16_t aMetadataSize) mFirstOptionOffset = mHeaderLength; } - optionDelta = mHeader.mBytes[mHeaderLength] >> 4; + optionDelta = mHeader.mBytes[mHeaderLength] >> 4; optionLength = mHeader.mBytes[mHeaderLength] & 0xf; mHeaderLength += sizeof(uint8_t); offset += sizeof(uint8_t); @@ -126,9 +126,8 @@ otError Header::FromMessage(const Message &aMessage, uint16_t aMetadataSize) } else if (optionDelta == kOption2ByteExtension) { - optionDelta = kOption2ByteExtensionOffset + - static_cast((mHeader.mBytes[mHeaderLength] << 8) | - (mHeader.mBytes[mHeaderLength + 1])); + optionDelta = kOption2ByteExtensionOffset + static_cast((mHeader.mBytes[mHeaderLength] << 8) | + (mHeader.mBytes[mHeaderLength + 1])); mHeaderLength += sizeof(uint16_t); offset += sizeof(uint16_t); } @@ -149,9 +148,8 @@ otError Header::FromMessage(const Message &aMessage, uint16_t aMetadataSize) } else if (optionLength == kOption2ByteExtension) { - optionLength = kOption2ByteExtensionOffset + - static_cast((mHeader.mBytes[mHeaderLength] << 8) | - (mHeader.mBytes[mHeaderLength + 1])); + optionLength = kOption2ByteExtensionOffset + static_cast((mHeader.mBytes[mHeaderLength] << 8) | + (mHeader.mBytes[mHeaderLength + 1])); mHeaderLength += sizeof(uint16_t); offset += sizeof(uint16_t); } @@ -162,11 +160,11 @@ otError Header::FromMessage(const Message &aMessage, uint16_t aMetadataSize) if (firstOption) { - mOption.mNumber = optionDelta; - mOption.mLength = optionLength; - mOption.mValue = mHeader.mBytes + mHeaderLength; + mOption.mNumber = optionDelta; + mOption.mLength = optionLength; + mOption.mValue = mHeader.mBytes + mHeaderLength; mNextOptionOffset = mHeaderLength + optionLength; - firstOption = false; + firstOption = false; } VerifyOrExit(mHeaderLength + optionLength <= kMaxHeaderLength); @@ -196,9 +194,9 @@ exit: otError Header::AppendOption(const Option &aOption) { - otError error = OT_ERROR_NONE; - uint8_t *buf = mHeader.mBytes + mHeaderLength; - uint8_t *cur = buf + 1; + otError error = OT_ERROR_NONE; + uint8_t *buf = mHeader.mBytes + mHeaderLength; + uint8_t *cur = buf + 1; uint16_t optionDelta = aOption.mNumber - mOptionLast; uint16_t optionLength; @@ -207,10 +205,9 @@ otError Header::AppendOption(const Option &aOption) // Calculate the total option size and check the buffers. optionLength = 1 + aOption.mLength; - optionLength += optionDelta < kOption1ByteExtensionOffset ? 0 : - (optionDelta < kOption2ByteExtensionOffset ? 1 : 2); - optionLength += aOption.mLength < kOption1ByteExtensionOffset ? 0 : - (aOption.mLength < kOption2ByteExtensionOffset ? 1 : 2); + optionLength += optionDelta < kOption1ByteExtensionOffset ? 0 : (optionDelta < kOption2ByteExtensionOffset ? 1 : 2); + optionLength += + aOption.mLength < kOption1ByteExtensionOffset ? 0 : (aOption.mLength < kOption2ByteExtensionOffset ? 1 : 2); VerifyOrExit(mHeaderLength + optionLength < kMaxHeaderLength, error = OT_ERROR_NO_BUFS); // Insert option delta. @@ -245,8 +242,8 @@ otError Header::AppendOption(const Option &aOption) { *buf |= kOption2ByteExtension; optionLength = aOption.mLength - kOption2ByteExtensionOffset; - *cur++ = optionLength >> 8; - *cur++ = optionLength & 0xff; + *cur++ = optionLength >> 8; + *cur++ = optionLength & 0xff; } // Insert option value. @@ -264,10 +261,10 @@ otError Header::AppendUintOption(uint16_t aNumber, uint32_t aValue) { Option coapOption; - aValue = Encoding::BigEndian::HostSwap32(aValue); + aValue = Encoding::BigEndian::HostSwap32(aValue); coapOption.mNumber = aNumber; coapOption.mLength = 4; - coapOption.mValue = reinterpret_cast(&aValue); + coapOption.mValue = reinterpret_cast(&aValue); // skip preceding zeros while (coapOption.mValue[0] == 0 && coapOption.mLength > 0) @@ -286,9 +283,9 @@ otError Header::AppendObserveOption(uint32_t aObserve) otError Header::AppendUriPathOptions(const char *aUriPath) { - otError error = OT_ERROR_NONE; - const char *cur = aUriPath; - const char *end; + otError error = OT_ERROR_NONE; + const char * cur = aUriPath; + const char * end; Header::Option coapOption; coapOption.mNumber = OT_COAP_OPTION_URI_PATH; @@ -296,13 +293,13 @@ otError Header::AppendUriPathOptions(const char *aUriPath) while ((end = strchr(cur, '/')) != NULL) { coapOption.mLength = static_cast(end - cur); - coapOption.mValue = reinterpret_cast(cur); + coapOption.mValue = reinterpret_cast(cur); SuccessOrExit(error = AppendOption(coapOption)); cur = end + 1; } coapOption.mLength = static_cast(strlen(cur)); - coapOption.mValue = reinterpret_cast(cur); + coapOption.mValue = reinterpret_cast(cur); SuccessOrExit(error = AppendOption(coapOption)); exit: @@ -347,13 +344,13 @@ exit: const Header::Option *Header::GetNextOption(void) { - Option *rval = NULL; + Option * rval = NULL; uint16_t optionDelta; uint16_t optionLength; VerifyOrExit(mNextOptionOffset < mHeaderLength); - optionDelta = mHeader.mBytes[mNextOptionOffset] >> 4; + optionDelta = mHeader.mBytes[mNextOptionOffset] >> 4; optionLength = mHeader.mBytes[mNextOptionOffset] & 0xf; mNextOptionOffset += sizeof(uint8_t); @@ -368,8 +365,8 @@ const Header::Option *Header::GetNextOption(void) } else if (optionDelta == kOption2ByteExtension) { - optionDelta = kOption2ByteExtensionOffset + - static_cast((mHeader.mBytes[mNextOptionOffset] << 8) | mHeader.mBytes[mNextOptionOffset + 1]); + optionDelta = kOption2ByteExtensionOffset + static_cast((mHeader.mBytes[mNextOptionOffset] << 8) | + mHeader.mBytes[mNextOptionOffset + 1]); mNextOptionOffset += sizeof(uint16_t); } else @@ -388,8 +385,8 @@ const Header::Option *Header::GetNextOption(void) } else if (optionLength == kOption2ByteExtension) { - optionLength = kOption2ByteExtensionOffset + - static_cast((mHeader.mBytes[mNextOptionOffset] << 8) | mHeader.mBytes[mNextOptionOffset + 1]); + optionLength = kOption2ByteExtensionOffset + static_cast((mHeader.mBytes[mNextOptionOffset] << 8) | + mHeader.mBytes[mNextOptionOffset + 1]); mNextOptionOffset += sizeof(uint16_t); } else @@ -399,7 +396,7 @@ const Header::Option *Header::GetNextOption(void) mOption.mNumber += optionDelta; mOption.mLength = optionLength; - mOption.mValue = mHeader.mBytes + mNextOptionOffset; + mOption.mValue = mHeader.mBytes + mNextOptionOffset; mNextOptionOffset += optionLength; rval = static_cast(&mOption); @@ -422,7 +419,7 @@ void Header::SetToken(uint8_t aTokenLength) { assert(aTokenLength <= kMaxTokenLength); - uint8_t token[kMaxTokenLength] = { 0 }; + uint8_t token[kMaxTokenLength] = {0}; for (uint8_t i = 0; i < aTokenLength; i++) { @@ -439,5 +436,5 @@ void Header::SetDefaultResponseHeader(const Header &aRequestHeader) SetToken(aRequestHeader.GetToken(), aRequestHeader.GetTokenLength()); } -} // namespace Coap -} // namespace ot +} // namespace Coap +} // namespace ot diff --git a/src/core/coap/coap_header.hpp b/src/core/coap/coap_header.hpp index 762bfc3c0..2fd2a2ca3 100644 --- a/src/core/coap/coap_header.hpp +++ b/src/core/coap/coap_header.hpp @@ -133,7 +133,8 @@ public: * @param[in] aVersion The Version value. * */ - void SetVersion(uint8_t aVersion) { + void SetVersion(uint8_t aVersion) + { mHeader.mFields.mVersionTypeToken &= ~kVersionMask; mHeader.mFields.mVersionTypeToken |= aVersion << kVersionOffset; } @@ -152,7 +153,8 @@ public: * @param[in] aType The Type value. * */ - void SetType(Type aType) { + void SetType(Type aType) + { mHeader.mFields.mVersionTypeToken &= ~kTypeMask; mHeader.mFields.mVersionTypeToken |= aType; } @@ -195,7 +197,10 @@ public: * @returns The Token length. * */ - uint8_t GetTokenLength(void) const { return (mHeader.mFields.mVersionTypeToken & kTokenLengthMask) >> kTokenLengthOffset; } + uint8_t GetTokenLength(void) const + { + return (mHeader.mFields.mVersionTypeToken & kTokenLengthMask) >> kTokenLengthOffset; + } /** * This method returns a pointer to the Token value. @@ -212,7 +217,8 @@ public: * @param[in] aTokenLength The Length of @p aToken. * */ - void SetToken(const uint8_t *aToken, uint8_t aTokenLength) { + void SetToken(const uint8_t *aToken, uint8_t aTokenLength) + { mHeader.mFields.mVersionTypeToken = (mHeader.mFields.mVersionTypeToken & ~kTokenLengthMask) | ((aTokenLength << kTokenLengthOffset) & kTokenLengthMask); memcpy(mHeader.mBytes + kTokenOffset, aToken, aTokenLength); @@ -236,7 +242,8 @@ public: * @retval FALSE If Tokens differ in length or value. * */ - bool IsTokenEqual(const Header &aHeader) const { + bool IsTokenEqual(const Header &aHeader) const + { return ((this->GetTokenLength() == aHeader.GetTokenLength()) && (memcmp(this->GetToken(), aHeader.GetToken(), this->GetTokenLength()) == 0)); } @@ -253,8 +260,8 @@ public: */ enum { - kOptionDeltaOffset = 4, ///< Delta Offset - kOptionDeltaMask = 0xf << kOptionDeltaOffset, ///< Delta Mask + kOptionDeltaOffset = 4, ///< Delta Offset + kOptionDeltaMask = 0xf << kOptionDeltaOffset, ///< Delta Mask }; /** @@ -456,7 +463,7 @@ public: * @retval FALSE Header is not is a RST message header. * */ - bool IsReset(void) const { return (GetType() == OT_COAP_TYPE_RESET); }; + bool IsReset(void) const { return (GetType() == OT_COAP_TYPE_RESET); }; private: /** @@ -465,23 +472,23 @@ private: */ enum { - kVersionMask = 0xc0, ///< Version mask as specified (RFC 7252). - kVersionOffset = 6, ///< Version offset as specified (RFC 7252). + kVersionMask = 0xc0, ///< Version mask as specified (RFC 7252). + kVersionOffset = 6, ///< Version offset as specified (RFC 7252). - kTypeMask = 0x30, ///< Type mask as specified (RFC 7252). + kTypeMask = 0x30, ///< Type mask as specified (RFC 7252). - kTokenLengthMask = 0x0f, ///< Token Length mask as specified (RFC 7252). - kTokenLengthOffset = 0, ///< Token Length offset as specified (RFC 7252). - kTokenOffset = 4, ///< Token offset as specified (RFC 7252). - kMaxTokenLength = 8, ///< Max token length as specified (RFC 7252). + kTokenLengthMask = 0x0f, ///< Token Length mask as specified (RFC 7252). + kTokenLengthOffset = 0, ///< Token Length offset as specified (RFC 7252). + kTokenOffset = 4, ///< Token offset as specified (RFC 7252). + kMaxTokenLength = 8, ///< Max token length as specified (RFC 7252). - kMaxOptionHeaderSize = 5, ///< Maximum size of an Option header + kMaxOptionHeaderSize = 5, ///< Maximum size of an Option header - kOption1ByteExtension = 13, ///< Indicates a 1 byte extension (RFC 7252). - kOption2ByteExtension = 14, ///< Indicates a 1 byte extension (RFC 7252). + kOption1ByteExtension = 13, ///< Indicates a 1 byte extension (RFC 7252). + kOption2ByteExtension = 14, ///< Indicates a 1 byte extension (RFC 7252). - kOption1ByteExtensionOffset = 13, ///< Delta/Length offset as specified (RFC 7252). - kOption2ByteExtensionOffset = 269, ///< Delta/Length offset as specified (RFC 7252). + kOption1ByteExtensionOffset = 13, ///< Delta/Length offset as specified (RFC 7252). + kOption2ByteExtensionOffset = 269, ///< Delta/Length offset as specified (RFC 7252). }; }; @@ -490,7 +497,7 @@ private: * */ -} // namespace Coap -} // namespace ot +} // namespace Coap +} // namespace ot -#endif // COAP_HEADER_HPP_ +#endif // COAP_HEADER_HPP_ diff --git a/src/core/coap/coap_secure.cpp b/src/core/coap/coap_secure.cpp index 4d754f056..2f1610c7f 100644 --- a/src/core/coap/coap_secure.cpp +++ b/src/core/coap/coap_secure.cpp @@ -46,22 +46,22 @@ namespace ot { namespace Coap { -CoapSecure::CoapSecure(Instance &aInstance): - CoapBase(aInstance, &CoapSecure::HandleRetransmissionTimer, &CoapSecure::HandleResponsesQueueTimer), - mConnectedCallback(NULL), - mConnectedContext(NULL), - mTransportCallback(NULL), - mTransportContext(NULL), - mTransmitMessage(NULL), - mTransmitTask(aInstance, &CoapSecure::HandleUdpTransmit, this) +CoapSecure::CoapSecure(Instance &aInstance) + : CoapBase(aInstance, &CoapSecure::HandleRetransmissionTimer, &CoapSecure::HandleResponsesQueueTimer) + , mConnectedCallback(NULL) + , mConnectedContext(NULL) + , mTransportCallback(NULL) + , mTransportContext(NULL) + , mTransmitMessage(NULL) + , mTransmitTask(aInstance, &CoapSecure::HandleUdpTransmit, this) { } otError CoapSecure::Start(uint16_t aPort, TransportCallback aCallback, void *aContext) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; mTransportCallback = aCallback; - mTransportContext = aContext; + mTransportContext = aContext; // Passing mTransportCallback means that we do not want to use socket // to transmit/receive messages, so do not open it in that case. @@ -87,16 +87,16 @@ otError CoapSecure::Stop(void) } mTransportCallback = NULL; - mTransportContext = NULL; + mTransportContext = NULL; return CoapBase::Stop(); } otError CoapSecure::Connect(const Ip6::MessageInfo &aMessageInfo, ConnectedCallback aCallback, void *aContext) { - mPeerAddress = aMessageInfo; + mPeerAddress = aMessageInfo; mConnectedCallback = aCallback; - mConnectedContext = aContext; + mConnectedContext = aContext; return GetNetif().GetDtls().Start(true, &CoapSecure::HandleDtlsConnected, &CoapSecure::HandleDtlsReceive, &CoapSecure::HandleDtlsSend, this); @@ -139,8 +139,10 @@ exit: return error; } -otError CoapSecure::SendMessage(Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - otCoapResponseHandler aHandler, void *aContext) +otError CoapSecure::SendMessage(Message & aMessage, + const Ip6::MessageInfo &aMessageInfo, + otCoapResponseHandler aHandler, + void * aContext) { return CoapBase::SendMessage(aMessage, aMessageInfo, aHandler, aContext); } @@ -159,7 +161,7 @@ void CoapSecure::Receive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo { Ip6::SockAddr sockAddr; sockAddr.mAddress = aMessageInfo.GetPeerAddr(); - sockAddr.mPort = aMessageInfo.GetPeerPort(); + sockAddr.mPort = aMessageInfo.GetPeerPort(); mSocket.Connect(sockAddr); mPeerAddress.SetPeerAddr(aMessageInfo.GetPeerAddr()); @@ -173,8 +175,8 @@ void CoapSecure::Receive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo mPeerAddress.SetSockPort(aMessageInfo.GetSockPort()); - netif.GetDtls().Start(false, &CoapSecure::HandleDtlsConnected, - &CoapSecure::HandleDtlsReceive, CoapSecure::HandleDtlsSend, this); + netif.GetDtls().Start(false, &CoapSecure::HandleDtlsConnected, &CoapSecure::HandleDtlsReceive, + CoapSecure::HandleDtlsSend, this); } else { @@ -183,8 +185,7 @@ void CoapSecure::Receive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo (mPeerAddress.GetPeerPort() == aMessageInfo.GetPeerPort())); } - netif.GetDtls().SetClientId(mPeerAddress.GetPeerAddr().mFields.m8, - sizeof(mPeerAddress.GetPeerAddr().mFields)); + netif.GetDtls().SetClientId(mPeerAddress.GetPeerAddr().mFields.m8, sizeof(mPeerAddress.GetPeerAddr().mFields)); netif.GetDtls().Receive(aMessage, aMessage.GetOffset(), aMessage.GetLength() - aMessage.GetOffset()); exit: @@ -303,7 +304,7 @@ void CoapSecure::HandleResponsesQueueTimer(Timer &aTimer) aTimer.GetOwner().CoapBase::HandleResponsesQueueTimer(); } -} // namespace Coap -} // namespace ot +} // namespace Coap +} // namespace ot #endif // OPENTHREAD_ENABLE_DTLS diff --git a/src/core/coap/coap_secure.hpp b/src/core/coap/coap_secure.hpp index 396efcc9b..46cd58541 100644 --- a/src/core/coap/coap_secure.hpp +++ b/src/core/coap/coap_secure.hpp @@ -45,16 +45,16 @@ class ThreadNetif; namespace Coap { -class CoapSecure: public CoapBase +class CoapSecure : public CoapBase { public: /** - * This function pointer is called once DTLS connection is established. - * - * @param[in] aConnected TRUE if a connection was established, FALSE otherwise. - * @param[in] aContext A pointer to arbitrary context information. - * - */ + * This function pointer is called once DTLS connection is established. + * + * @param[in] aConnected TRUE if a connection was established, FALSE otherwise. + * @param[in] aContext A pointer to arbitrary context information. + * + */ typedef void (*ConnectedCallback)(bool aConnected, void *aContext); /** @@ -65,7 +65,7 @@ public: * @param[in] aMessageInfo A reference to the message info associated with @p aMessage. * */ - typedef otError(*TransportCallback)(void *aContext, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + typedef otError (*TransportCallback)(void *aContext, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); /** * This constructor initializes the object. @@ -188,8 +188,10 @@ public: * @retvak OT_ERROR_INVALID_STATE DTLS connection was not initialized. * */ - otError SendMessage(Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - otCoapResponseHandler aHandler = NULL, void *aContext = NULL); + otError SendMessage(Message & aMessage, + const Ip6::MessageInfo &aMessageInfo, + otCoapResponseHandler aHandler = NULL, + void * aContext = NULL); /** * This method is used to pass messages to the secure CoAP server. @@ -205,30 +207,30 @@ private: virtual otError Send(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); static void HandleDtlsConnected(void *aContext, bool aConnected); - void HandleDtlsConnected(bool aConnected); + void HandleDtlsConnected(bool aConnected); static void HandleDtlsReceive(void *aContext, uint8_t *aBuf, uint16_t aLength); - void HandleDtlsReceive(uint8_t *aBuf, uint16_t aLength); + void HandleDtlsReceive(uint8_t *aBuf, uint16_t aLength); static otError HandleDtlsSend(void *aContext, const uint8_t *aBuf, uint16_t aLength, uint8_t aMessageSubType); - otError HandleDtlsSend(const uint8_t *aBuf, uint16_t aLength, uint8_t aMessageSubType); + otError HandleDtlsSend(const uint8_t *aBuf, uint16_t aLength, uint8_t aMessageSubType); static void HandleUdpTransmit(Tasklet &aTasklet); - void HandleUdpTransmit(void); + void HandleUdpTransmit(void); static void HandleRetransmissionTimer(Timer &aTimer); static void HandleResponsesQueueTimer(Timer &aTimer); - Ip6::MessageInfo mPeerAddress; + Ip6::MessageInfo mPeerAddress; ConnectedCallback mConnectedCallback; - void *mConnectedContext; + void * mConnectedContext; TransportCallback mTransportCallback; - void *mTransportContext; - Message *mTransmitMessage; - Tasklet mTransmitTask; + void * mTransportContext; + Message * mTransmitMessage; + Tasklet mTransmitTask; }; -} // namespace Coap -} // namespace ot +} // namespace Coap +} // namespace ot -#endif // COAP_SECURE_HPP_ +#endif // COAP_SECURE_HPP_ diff --git a/src/core/common/code_utils.hpp b/src/core/common/code_utils.hpp index 481ddc5ae..1ee0f7dc2 100644 --- a/src/core/common/code_utils.hpp +++ b/src/core/common/code_utils.hpp @@ -39,12 +39,11 @@ #include "utils/wrap_stdbool.h" // Calculates the aligned variable size. -#define otALIGNED_VAR_SIZE(size, align_type) \ - (((size) + (sizeof (align_type) - 1)) / sizeof (align_type)) +#define otALIGNED_VAR_SIZE(size, align_type) (((size) + (sizeof(align_type) - 1)) / sizeof(align_type)) // Allocate the structure using "raw" storage. -#define otDEFINE_ALIGNED_VAR(name, size, align_type) \ - align_type name[(((size) + (sizeof (align_type) - 1)) / sizeof (align_type))] +#define otDEFINE_ALIGNED_VAR(name, size, align_type) \ + align_type name[(((size) + (sizeof(align_type) - 1)) / sizeof(align_type))] /** * This checks for the specified status, which is expected to @@ -54,13 +53,13 @@ * @param[in] aStatus A scalar status to be evaluated against zero (0). * */ -#define SuccessOrExit(aStatus) \ - do \ - { \ - if ((aStatus) != 0) \ - { \ - goto exit; \ - } \ +#define SuccessOrExit(aStatus) \ + do \ + { \ + if ((aStatus) != 0) \ + { \ + goto exit; \ + } \ } while (false) /** @@ -73,14 +72,14 @@ * assertion fails. * */ -#define VerifyOrExit(aCondition, ...) \ - do \ - { \ - if (!(aCondition)) \ - { \ - __VA_ARGS__; \ - goto exit; \ - } \ +#define VerifyOrExit(aCondition, ...) \ + do \ + { \ + if (!(aCondition)) \ + { \ + __VA_ARGS__; \ + goto exit; \ + } \ } while (false) /** @@ -95,11 +94,11 @@ * when the assertion fails. * */ -#define ExitNow(...) \ - do \ - { \ - __VA_ARGS__; \ - goto exit; \ +#define ExitNow(...) \ + do \ + { \ + __VA_ARGS__; \ + goto exit; \ } while (false) /* @@ -111,10 +110,12 @@ * @param[in] aStatement The function/method to execute. * */ -#define IgnoreReturnValue(aStatement) \ - do \ - { \ - if (aStatement) {} \ +#define IgnoreReturnValue(aStatement) \ + do \ + { \ + if (aStatement) \ + { \ + } \ } while (false) -#endif // CODE_UTILS_HPP_ +#endif // CODE_UTILS_HPP_ diff --git a/src/core/common/crc16.cpp b/src/core/common/crc16.cpp index 1a707032a..f3f60ef1d 100644 --- a/src/core/common/crc16.cpp +++ b/src/core/common/crc16.cpp @@ -46,7 +46,7 @@ void Crc16::Update(uint8_t aByte) uint8_t i; mCrc = mCrc ^ static_cast(aByte << 8); - i = 8; + i = 8; do { @@ -58,8 +58,7 @@ void Crc16::Update(uint8_t aByte) { mCrc = static_cast(mCrc << 1); } - } - while (--i); + } while (--i); } -} // namespace ot +} // namespace ot diff --git a/src/core/common/crc16.hpp b/src/core/common/crc16.hpp index cf84f89c3..2d2ef35dd 100644 --- a/src/core/common/crc16.hpp +++ b/src/core/common/crc16.hpp @@ -49,8 +49,8 @@ class Crc16 public: enum Polynomial { - kCcitt = 0x1021, ///< CRC16_CCITT - kAnsi = 0x8005, ///< CRC16-ANSI + kCcitt = 0x1021, ///< CRC16_CCITT + kAnsi = 0x8005, ///< CRC16-ANSI }; /** @@ -88,6 +88,6 @@ private: uint16_t mCrc; }; -} // namespace ot +} // namespace ot -#endif // CRC16_HPP_ +#endif // CRC16_HPP_ diff --git a/src/core/common/debug.hpp b/src/core/common/debug.hpp index 0a4019005..13f0aa4da 100644 --- a/src/core/common/debug.hpp +++ b/src/core/common/debug.hpp @@ -48,10 +48,7 @@ #include -#define assert(exp) \ - ((!(exp)) ? \ - (RtlAssert( #exp, __FILE__, __LINE__, NULL ),FALSE) : \ - TRUE) +#define assert(exp) ((!(exp)) ? (RtlAssert(#exp, __FILE__, __LINE__, NULL), FALSE) : TRUE) #elif defined(_WIN32) @@ -61,23 +58,31 @@ #include "openthread/platform/misc.h" -#define assert(cond) \ - do { \ - if (!(cond)) { \ - otPlatAssertFail(__FILE__, __LINE__); \ - while (1) {} \ - } \ - } while (0) +#define assert(cond) \ + do \ + { \ + if (!(cond)) \ + { \ + otPlatAssertFail(__FILE__, __LINE__); \ + while (1) \ + { \ + } \ + } \ + } while (0) #else -#define assert(cond) \ - do { \ - if (!(cond)) { \ - while (1) {} \ - } \ - } while (0) +#define assert(cond) \ + do \ + { \ + if (!(cond)) \ + { \ + while (1) \ + { \ + } \ + } \ + } while (0) #endif -#endif // DEBUG_HPP_ +#endif // DEBUG_HPP_ diff --git a/src/core/common/encoding.hpp b/src/core/common/encoding.hpp index 21603e4cb..bf35678a0 100644 --- a/src/core/common/encoding.hpp +++ b/src/core/common/encoding.hpp @@ -44,62 +44,73 @@ namespace Encoding { inline uint16_t Swap16(uint16_t v) { - return - (((v & 0x00ffU) << 8) & 0xff00) | - (((v & 0xff00U) >> 8) & 0x00ff); + return (((v & 0x00ffU) << 8) & 0xff00) | (((v & 0xff00U) >> 8) & 0x00ff); } inline uint32_t Swap32(uint32_t v) { - return - ((v & static_cast(0x000000ffUL)) << 24) | - ((v & static_cast(0x0000ff00UL)) << 8) | - ((v & static_cast(0x00ff0000UL)) >> 8) | - ((v & static_cast(0xff000000UL)) >> 24); + return ((v & static_cast(0x000000ffUL)) << 24) | ((v & static_cast(0x0000ff00UL)) << 8) | + ((v & static_cast(0x00ff0000UL)) >> 8) | ((v & static_cast(0xff000000UL)) >> 24); } inline uint64_t Swap64(uint64_t v) { - return - ((v & static_cast(0x00000000000000ffULL)) << 56) | - ((v & static_cast(0x000000000000ff00ULL)) << 40) | - ((v & static_cast(0x0000000000ff0000ULL)) << 24) | - ((v & static_cast(0x00000000ff000000ULL)) << 8) | - ((v & static_cast(0x000000ff00000000ULL)) >> 8) | - ((v & static_cast(0x0000ff0000000000ULL)) >> 24) | - ((v & static_cast(0x00ff000000000000ULL)) >> 40) | - ((v & static_cast(0xff00000000000000ULL)) >> 56); + return ((v & static_cast(0x00000000000000ffULL)) << 56) | + ((v & static_cast(0x000000000000ff00ULL)) << 40) | + ((v & static_cast(0x0000000000ff0000ULL)) << 24) | + ((v & static_cast(0x00000000ff000000ULL)) << 8) | + ((v & static_cast(0x000000ff00000000ULL)) >> 8) | + ((v & static_cast(0x0000ff0000000000ULL)) >> 24) | + ((v & static_cast(0x00ff000000000000ULL)) >> 40) | + ((v & static_cast(0xff00000000000000ULL)) >> 56); } inline uint32_t Reverse32(uint32_t v) { - v = ((v & 0x55555555) << 1) | ((v & 0xaaaaaaaa) >> 1); - v = ((v & 0x33333333) << 2) | ((v & 0xcccccccc) >> 2); - v = ((v & 0x0f0f0f0f) << 4) | ((v & 0xf0f0f0f0) >> 4); - v = ((v & 0x00ff00ff) << 8) | ((v & 0xff00ff00) >> 8); + v = ((v & 0x55555555) << 1) | ((v & 0xaaaaaaaa) >> 1); + v = ((v & 0x33333333) << 2) | ((v & 0xcccccccc) >> 2); + v = ((v & 0x0f0f0f0f) << 4) | ((v & 0xf0f0f0f0) >> 4); + v = ((v & 0x00ff00ff) << 8) | ((v & 0xff00ff00) >> 8); v = ((v & 0x0000ffff) << 16) | ((v & 0xffff0000) >> 16); return v; } -#define BitVectorBytes(x) \ - (((x) + (CHAR_BIT-1)) / CHAR_BIT) +#define BitVectorBytes(x) (((x) + (CHAR_BIT - 1)) / CHAR_BIT) namespace BigEndian { #if BYTE_ORDER_BIG_ENDIAN -inline uint16_t HostSwap16(uint16_t v) { return v; } -inline uint32_t HostSwap32(uint32_t v) { return v; } -inline uint64_t HostSwap64(uint64_t v) { return v; } +inline uint16_t HostSwap16(uint16_t v) +{ + return v; +} +inline uint32_t HostSwap32(uint32_t v) +{ + return v; +} +inline uint64_t HostSwap64(uint64_t v) +{ + return v; +} #else /* BYTE_ORDER_LITTLE_ENDIAN */ -inline uint16_t HostSwap16(uint16_t v) { return Swap16(v); } -inline uint32_t HostSwap32(uint32_t v) { return Swap32(v); } -inline uint64_t HostSwap64(uint64_t v) { return Swap64(v); } +inline uint16_t HostSwap16(uint16_t v) +{ + return Swap16(v); +} +inline uint32_t HostSwap32(uint32_t v) +{ + return Swap32(v); +} +inline uint64_t HostSwap64(uint64_t v) +{ + return Swap64(v); +} -#endif // LITTLE_ENDIAN +#endif // LITTLE_ENDIAN /** * This function reads a `uint16_t` value from a given buffer assuming big-ending encoding. @@ -124,10 +135,8 @@ inline uint16_t ReadUint16(const uint8_t *aBuffer) */ inline uint32_t ReadUint32(const uint8_t *aBuffer) { - return ((static_cast(aBuffer[0]) << 24) | - (static_cast(aBuffer[1]) << 16) | - (static_cast(aBuffer[2]) << 8) | - (static_cast(aBuffer[3]) << 0)); + return ((static_cast(aBuffer[0]) << 24) | (static_cast(aBuffer[1]) << 16) | + (static_cast(aBuffer[2]) << 8) | (static_cast(aBuffer[3]) << 0)); } /** @@ -154,25 +163,43 @@ inline void WriteUint32(uint32_t aValue, uint8_t *aBuffer) { aBuffer[0] = (aValue >> 24) & 0xff; aBuffer[1] = (aValue >> 16) & 0xff; - aBuffer[2] = (aValue >> 8) & 0xff; - aBuffer[3] = (aValue >> 0) & 0xff; + aBuffer[2] = (aValue >> 8) & 0xff; + aBuffer[3] = (aValue >> 0) & 0xff; } -} // namespace BigEndian +} // namespace BigEndian namespace LittleEndian { #if BYTE_ORDER_BIG_ENDIAN -inline uint16_t HostSwap16(uint16_t v) { return Swap16(v); } -inline uint32_t HostSwap32(uint32_t v) { return Swap32(v); } -inline uint64_t HostSwap64(uint64_t v) { return Swap64(v); } +inline uint16_t HostSwap16(uint16_t v) +{ + return Swap16(v); +} +inline uint32_t HostSwap32(uint32_t v) +{ + return Swap32(v); +} +inline uint64_t HostSwap64(uint64_t v) +{ + return Swap64(v); +} #else /* BYTE_ORDER_LITTLE_ENDIAN */ -inline uint16_t HostSwap16(uint16_t v) { return v; } -inline uint32_t HostSwap32(uint32_t v) { return v; } -inline uint64_t HostSwap64(uint64_t v) { return v; } +inline uint16_t HostSwap16(uint16_t v) +{ + return v; +} +inline uint32_t HostSwap32(uint32_t v) +{ + return v; +} +inline uint64_t HostSwap64(uint64_t v) +{ + return v; +} #endif @@ -199,10 +226,8 @@ inline uint16_t ReadUint16(const uint8_t *aBuffer) */ inline uint32_t ReadUint32(const uint8_t *aBuffer) { - return ((static_cast(aBuffer[0]) << 0) | - (static_cast(aBuffer[1]) << 8) | - (static_cast(aBuffer[2]) << 16) | - (static_cast(aBuffer[3]) << 24)); + return ((static_cast(aBuffer[0]) << 0) | (static_cast(aBuffer[1]) << 8) | + (static_cast(aBuffer[2]) << 16) | (static_cast(aBuffer[3]) << 24)); } /** @@ -227,14 +252,14 @@ inline void WriteUint16(uint16_t aValue, uint8_t *aBuffer) */ inline void WriteUint32(uint32_t aValue, uint8_t *aBuffer) { - aBuffer[0] = (aValue >> 0) & 0xff; - aBuffer[1] = (aValue >> 8) & 0xff; + aBuffer[0] = (aValue >> 0) & 0xff; + aBuffer[1] = (aValue >> 8) & 0xff; aBuffer[2] = (aValue >> 16) & 0xff; aBuffer[3] = (aValue >> 24) & 0xff; } -} // namespace LittleEndian -} // namespace Encoding -} // namespace ot +} // namespace LittleEndian +} // namespace Encoding +} // namespace ot -#endif // ENCODING_HPP_ +#endif // ENCODING_HPP_ diff --git a/src/core/common/instance.cpp b/src/core/common/instance.cpp index b911bf004..12f76e0ee 100644 --- a/src/core/common/instance.cpp +++ b/src/core/common/instance.cpp @@ -50,35 +50,43 @@ static otDEFINE_ALIGNED_VAR(sInstanceRaw, sizeof(Instance), uint64_t); #endif -Instance::Instance(void) : - mActiveScanCallback(NULL), - mActiveScanCallbackContext(NULL), - mEnergyScanCallback(NULL), - mEnergyScanCallbackContext(NULL), - mNotifier(*this), - mTimerMilliScheduler(*this), +Instance::Instance(void) + : mActiveScanCallback(NULL) + , mActiveScanCallbackContext(NULL) + , mEnergyScanCallback(NULL) + , mEnergyScanCallbackContext(NULL) + , mNotifier(*this) + , mTimerMilliScheduler(*this) + , #if OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_TIMER - mTimerMicroScheduler(*this), + mTimerMicroScheduler(*this) + , #endif - mIp6(*this), - mThreadNetif(*this), + mIp6(*this) + , mThreadNetif(*this) + , #if OPENTHREAD_ENABLE_RAW_LINK_API - mLinkRaw(*this), + mLinkRaw(*this) + , #endif #if OPENTHREAD_ENABLE_APPLICATION_COAP - mApplicationCoap(*this), + mApplicationCoap(*this) + , #endif #if OPENTHREAD_CONFIG_ENABLE_DYNAMIC_LOG_LEVEL - mLogLevel(static_cast(OPENTHREAD_CONFIG_LOG_LEVEL)), + mLogLevel(static_cast(OPENTHREAD_CONFIG_LOG_LEVEL)) + , #endif #if OPENTHREAD_ENABLE_CHANNEL_MONITOR - mChannelMonitor(*this), + mChannelMonitor(*this) + , #endif #if OPENTHREAD_ENABLE_CHANNEL_MANAGER - mChannelManager(*this), + mChannelManager(*this) + , #endif - mMessagePool(*this), - mIsInitialized(false) + mMessagePool(*this) + , mIsInitialized(false) { } @@ -90,7 +98,7 @@ Instance &Instance::InitSingle(void) VerifyOrExit(instance->mIsInitialized == false); - instance = new(&sInstanceRaw)Instance(); + instance = new (&sInstanceRaw) Instance(); instance->AfterInit(); @@ -118,7 +126,7 @@ Instance *Instance::Init(void *aBuffer, size_t *aBufferSize) VerifyOrExit(aBuffer != NULL); - instance = new(aBuffer)Instance(); + instance = new (aBuffer) Instance(); instance->AfterInit(); @@ -183,7 +191,7 @@ otError Instance::ErasePersistentInfo(void) { otError error = OT_ERROR_NONE; - VerifyOrExit(mThreadNetif.GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); + VerifyOrExit(mThreadNetif.GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); otPlatSettingsWipe(this); exit: @@ -192,7 +200,7 @@ exit: void Instance::RegisterActiveScanCallback(otHandleActiveScanResult aCallback, void *aContext) { - mActiveScanCallback = aCallback; + mActiveScanCallback = aCallback; mActiveScanCallbackContext = aContext; } @@ -206,7 +214,7 @@ void Instance::InvokeActiveScanCallback(otActiveScanResult *aResult) const void Instance::RegisterEnergyScanCallback(otHandleEnergyScanResult aCallback, void *aContext) { - mEnergyScanCallback = aCallback; + mEnergyScanCallback = aCallback; mEnergyScanCallbackContext = aContext; } @@ -220,193 +228,193 @@ void Instance::InvokeEnergyScanCallback(otEnergyScanResult *aResult) const // Specializations of the `Get()` method. -template<> Notifier &Instance::Get(void) +template <> Notifier &Instance::Get(void) { return GetNotifier(); } -template<> TaskletScheduler &Instance::Get(void) +template <> TaskletScheduler &Instance::Get(void) { return GetTaskletScheduler(); } -template<> MeshForwarder &Instance::Get(void) +template <> MeshForwarder &Instance::Get(void) { return GetThreadNetif().GetMeshForwarder(); } -template<> Mle::Mle &Instance::Get(void) +template <> Mle::Mle &Instance::Get(void) { return GetThreadNetif().GetMle(); } -template<> Mle::MleRouter &Instance::Get(void) +template <> Mle::MleRouter &Instance::Get(void) { return GetThreadNetif().GetMle(); } -template<> Ip6::Netif &Instance::Get(void) +template <> Ip6::Netif &Instance::Get(void) { return GetThreadNetif(); } -template<> Ip6::Ip6 &Instance::Get(void) +template <> Ip6::Ip6 &Instance::Get(void) { return GetIp6(); } -template<> Mac::Mac &Instance::Get(void) +template <> Mac::Mac &Instance::Get(void) { return GetThreadNetif().GetMac(); } -template<> KeyManager &Instance::Get(void) +template <> KeyManager &Instance::Get(void) { return GetThreadNetif().GetKeyManager(); } #if OPENTHREAD_FTD -template<> AddressResolver &Instance::Get(void) +template <> AddressResolver &Instance::Get(void) { return GetThreadNetif().GetAddressResolver(); } -template<> MeshCoP::Leader &Instance::Get(void) +template <> MeshCoP::Leader &Instance::Get(void) { return GetThreadNetif().GetLeader(); } -template<> MeshCoP::JoinerRouter &Instance::Get(void) +template <> MeshCoP::JoinerRouter &Instance::Get(void) { return GetThreadNetif().GetJoinerRouter(); } #endif // OPENTHREAD_FTD -template<> AnnounceBeginServer &Instance::Get(void) +template <> AnnounceBeginServer &Instance::Get(void) { return GetThreadNetif().GetAnnounceBeginServer(); } -template<> DataPollManager &Instance::Get(void) +template <> DataPollManager &Instance::Get(void) { return GetThreadNetif().GetMeshForwarder().GetDataPollManager(); } -template<> EnergyScanServer &Instance::Get(void) +template <> EnergyScanServer &Instance::Get(void) { return GetThreadNetif().GetEnergyScanServer(); } -template<> PanIdQueryServer &Instance::Get(void) +template <> PanIdQueryServer &Instance::Get(void) { return GetThreadNetif().GetPanIdQueryServer(); } -template<> NetworkData::Leader &Instance::Get(void) +template <> NetworkData::Leader &Instance::Get(void) { return GetThreadNetif().GetNetworkDataLeader(); } -template<> Ip6::Mpl &Instance::Get(void) +template <> Ip6::Mpl &Instance::Get(void) { return GetIp6().GetMpl(); } -template<> Coap::Coap &Instance::Get(void) +template <> Coap::Coap &Instance::Get(void) { return GetThreadNetif().GetCoap(); } -template<> MeshCoP::ActiveDataset &Instance::Get(void) +template <> MeshCoP::ActiveDataset &Instance::Get(void) { return GetThreadNetif().GetActiveDataset(); } -template<> MeshCoP::PendingDataset &Instance::Get(void) +template <> MeshCoP::PendingDataset &Instance::Get(void) { return GetThreadNetif().GetPendingDataset(); } #if OPENTHREAD_ENABLE_APPLICATION_COAP -template<> Coap::ApplicationCoap &Instance::Get(void) +template <> Coap::ApplicationCoap &Instance::Get(void) { return GetApplicationCoap(); } #endif #if OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD -template<> MeshCoP::Commissioner &Instance::Get(void) +template <> MeshCoP::Commissioner &Instance::Get(void) { return GetThreadNetif().GetCommissioner(); } #endif #if OPENTHREAD_ENABLE_JOINER -template<> MeshCoP::Joiner &Instance::Get(void) +template <> MeshCoP::Joiner &Instance::Get(void) { return GetThreadNetif().GetJoiner(); } #endif #if OPENTHREAD_ENABLE_DNS_CLIENT -template<> Dns::Client &Instance::Get(void) +template <> Dns::Client &Instance::Get(void) { return GetThreadNetif().GetDnsClient(); } #endif #if OPENTHREAD_ENABLE_DTLS -template<> MeshCoP::Dtls &Instance::Get(void) +template <> MeshCoP::Dtls &Instance::Get(void) { return GetThreadNetif().GetDtls(); } -template<> Coap::CoapSecure &Instance::Get(void) +template <> Coap::CoapSecure &Instance::Get(void) { return GetThreadNetif().GetCoapSecure(); } #endif #if OPENTHREAD_ENABLE_RAW_LINK_API -template<> LinkRaw &Instance::Get(void) +template <> LinkRaw &Instance::Get(void) { return GetLinkRaw(); } #endif #if OPENTHREAD_ENABLE_DHCP6_CLIENT -template<> Dhcp6::Dhcp6Client &Instance::Get(void) +template <> Dhcp6::Dhcp6Client &Instance::Get(void) { return GetThreadNetif().GetDhcp6Client(); } #endif #if OPENTHREAD_ENABLE_JAM_DETECTION -template<> Utils::JamDetector &Instance::Get(void) +template <> Utils::JamDetector &Instance::Get(void) { return GetThreadNetif().GetJamDetector(); } #endif -template<> Utils::ChildSupervisor &Instance::Get(void) +template <> Utils::ChildSupervisor &Instance::Get(void) { return GetThreadNetif().GetChildSupervisor(); } -template<> Utils::SupervisionListener &Instance::Get(void) +template <> Utils::SupervisionListener &Instance::Get(void) { return GetThreadNetif().GetSupervisionListener(); } #if OPENTHREAD_ENABLE_CHANNEL_MONITOR -template<> Utils::ChannelMonitor &Instance::Get(void) +template <> Utils::ChannelMonitor &Instance::Get(void) { return GetChannelMonitor(); } #endif #if OPENTHREAD_ENABLE_CHANNEL_MANAGER -template<> Utils::ChannelManager &Instance::Get(void) +template <> Utils::ChannelManager &Instance::Get(void) { return GetChannelManager(); } diff --git a/src/core/common/instance.hpp b/src/core/common/instance.hpp index 6e84c29d0..a38e0953a 100644 --- a/src/core/common/instance.hpp +++ b/src/core/common/instance.hpp @@ -36,8 +36,8 @@ #include "openthread-core-config.h" -#include "utils/wrap_stdint.h" #include "utils/wrap_stdbool.h" +#include "utils/wrap_stdint.h" #include #include @@ -45,8 +45,8 @@ #if OPENTHREAD_ENABLE_RAW_LINK_API #include "api/link_raw.hpp" #endif -#include "common/code_utils.hpp" #include "coap/coap.hpp" +#include "common/code_utils.hpp" #if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES #include "crypto/heap.hpp" #include "crypto/mbedtls.hpp" @@ -91,8 +91,7 @@ namespace ot { class Instance : public otInstance { public: - -#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES /** * This static method initializes the OpenThread instance. * @@ -350,57 +349,56 @@ public: * @returns A reference to the `Type` object of the instance. * */ - template - Type &Get(void); + template Type &Get(void); private: Instance(void); void AfterInit(void); - otHandleActiveScanResult mActiveScanCallback; - void *mActiveScanCallbackContext; - otHandleEnergyScanResult mEnergyScanCallback; - void *mEnergyScanCallbackContext; + otHandleActiveScanResult mActiveScanCallback; + void * mActiveScanCallbackContext; + otHandleEnergyScanResult mEnergyScanCallback; + void * mEnergyScanCallbackContext; - Notifier mNotifier; + Notifier mNotifier; - TaskletScheduler mTaskletScheduler; - TimerMilliScheduler mTimerMilliScheduler; + TaskletScheduler mTaskletScheduler; + TimerMilliScheduler mTimerMilliScheduler; #if OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_TIMER - TimerMicroScheduler mTimerMicroScheduler; + TimerMicroScheduler mTimerMicroScheduler; #endif #if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES - Crypto::MbedTls mMbedTls; - Crypto::Heap mMbedTlsHeap; + Crypto::MbedTls mMbedTls; + Crypto::Heap mMbedTlsHeap; #endif - Ip6::Ip6 mIp6; - ThreadNetif mThreadNetif; + Ip6::Ip6 mIp6; + ThreadNetif mThreadNetif; #if OPENTHREAD_ENABLE_RAW_LINK_API - LinkRaw mLinkRaw; + LinkRaw mLinkRaw; #endif #if OPENTHREAD_ENABLE_APPLICATION_COAP - Coap::ApplicationCoap mApplicationCoap; + Coap::ApplicationCoap mApplicationCoap; #endif #if OPENTHREAD_CONFIG_ENABLE_DYNAMIC_LOG_LEVEL - otLogLevel mLogLevel; + otLogLevel mLogLevel; #endif #if OPENTHREAD_ENABLE_CHANNEL_MONITOR - Utils::ChannelMonitor mChannelMonitor; + Utils::ChannelMonitor mChannelMonitor; #endif #if OPENTHREAD_ENABLE_CHANNEL_MANAGER - Utils::ChannelManager mChannelManager; + Utils::ChannelManager mChannelManager; #endif - MessagePool mMessagePool; - bool mIsInitialized; + MessagePool mMessagePool; + bool mIsInitialized; }; /** @@ -408,6 +406,6 @@ private: * */ -} // namespace ot +} // namespace ot -#endif // INSTANCE_HPP_ +#endif // INSTANCE_HPP_ diff --git a/src/core/common/locator.cpp b/src/core/common/locator.cpp index 0748c3dcd..40dc1f1e5 100644 --- a/src/core/common/locator.cpp +++ b/src/core/common/locator.cpp @@ -62,4 +62,4 @@ Notifier &InstanceLocator::GetNotifier(void) const return GetInstance().GetNotifier(); } -} // namespace ot +} // namespace ot diff --git a/src/core/common/locator.hpp b/src/core/common/locator.hpp index 32a626520..ca35bc8c2 100644 --- a/src/core/common/locator.hpp +++ b/src/core/common/locator.hpp @@ -43,8 +43,9 @@ namespace ot { class Instance; class ThreadNetif; class Notifier; -namespace Ip6 { class Ip6; } - +namespace Ip6 { +class Ip6; +} /** * @addtogroup core-locator @@ -83,11 +84,11 @@ public: #endif /** - * This method returns a reference to the Ip6. - * - * @returns A reference to the Ip6. - * - */ + * This method returns a reference to the Ip6. + * + * @returns A reference to the Ip6. + * + */ Ip6::Ip6 &GetIp6(void) const; /** @@ -136,7 +137,6 @@ private: class OwnerLocator { public: - /** * This template method returns a reference to the owner object. * @@ -145,10 +145,11 @@ public: * @returns A reference to the owner of this object. * */ - template - OwnerType &GetOwner(void) + template OwnerType &GetOwner(void) #if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES - { return *static_cast(mOwner); } + { + return *static_cast(mOwner); + } #else // Implemented in `owner-locator.hpp` ; @@ -180,6 +181,6 @@ private: * */ -} // namespace ot +} // namespace ot -#endif // LOCATOR_HPP_ +#endif // LOCATOR_HPP_ diff --git a/src/core/common/logging.cpp b/src/core/common/logging.cpp index 1459ae18f..b125e6693 100644 --- a/src/core/common/logging.cpp +++ b/src/core/common/logging.cpp @@ -49,8 +49,8 @@ #endif #ifndef WINDOWS_LOGGING -#define otLogDump(aFormat, ...) \ - _otDynamicLog(aInstance, aLogLevel, aLogRegion, aFormat OPENTHREAD_CONFIG_LOG_SUFFIX, ## __VA_ARGS__) +#define otLogDump(aFormat, ...) \ + _otDynamicLog(aInstance, aLogLevel, aLogRegion, aFormat OPENTHREAD_CONFIG_LOG_SUFFIX, ##__VA_ARGS__) #endif #ifdef __cplusplus @@ -67,10 +67,13 @@ extern "C" { * @param[in] aLength Number of bytes in the buffer. * */ -static void DumpLine(otInstance *aInstance, otLogLevel aLogLevel, otLogRegion aLogRegion, const void *aBuf, +static void DumpLine(otInstance * aInstance, + otLogLevel aLogLevel, + otLogRegion aLogRegion, + const void * aBuf, const size_t aLength) { - char buf[80]; + char buf[80]; char *cur = buf; snprintf(cur, sizeof(buf) - static_cast(cur - buf), "|"); @@ -120,13 +123,17 @@ static void DumpLine(otInstance *aInstance, otLogLevel aLogLevel, otLogRegion aL OT_UNUSED_VARIABLE(aInstance); } -void otDump(otInstance *aInstance, otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aId, const void *aBuf, +void otDump(otInstance * aInstance, + otLogLevel aLogLevel, + otLogRegion aLogRegion, + const char * aId, + const void * aBuf, const size_t aLength) { - size_t idlen = strlen(aId); + size_t idlen = strlen(aId); const size_t width = 72; - char buf[80]; - char *cur = buf; + char buf[80]; + char * cur = buf; for (size_t i = 0; i < (width - idlen) / 2 - 5; i++) { @@ -160,8 +167,10 @@ void otDump(otInstance *aInstance, otLogLevel aLogLevel, otLogRegion aLogRegion, otLogDump("%s", buf); } -#else // OPENTHREAD_CONFIG_LOG_PKT_DUMP -void otDump(otInstance *, otLogLevel, otLogRegion, const char *, const void *, const size_t) {} +#else // OPENTHREAD_CONFIG_LOG_PKT_DUMP +void otDump(otInstance *, otLogLevel, otLogRegion, const char *, const void *, const size_t) +{ +} #endif // OPENTHREAD_CONFIG_LOG_PKT_DUMP #ifdef OPENTHREAD_CONFIG_LOG_PREPEND_LEVEL diff --git a/src/core/common/logging.hpp b/src/core/common/logging.hpp index 08a3fa572..85eebd83d 100644 --- a/src/core/common/logging.hpp +++ b/src/core/common/logging.hpp @@ -70,8 +70,8 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_CRIT -#define otLogCrit(aInstance, aRegion, aFormat, ...) \ - _otLogFormatter(aInstance, OT_LOG_LEVEL_CRIT, aRegion, aFormat, ## __VA_ARGS__) +#define otLogCrit(aInstance, aRegion, aFormat, ...) \ + _otLogFormatter(aInstance, OT_LOG_LEVEL_CRIT, aRegion, aFormat, ##__VA_ARGS__) #else #define otLogCrit(aInstance, aRegion, aFormat, ...) #endif @@ -88,8 +88,8 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN -#define otLogWarn(aInstance, aRegion, aFormat, ...) \ - _otLogFormatter(aInstance, OT_LOG_LEVEL_WARN, aRegion, aFormat, ## __VA_ARGS__) +#define otLogWarn(aInstance, aRegion, aFormat, ...) \ + _otLogFormatter(aInstance, OT_LOG_LEVEL_WARN, aRegion, aFormat, ##__VA_ARGS__) #else #define otLogWarn(aInstance, aRegion, aFormat, ...) #endif @@ -106,8 +106,8 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO -#define otLogInfo(aInstance, aRegion, aFormat, ...) \ - _otLogFormatter(aInstance, OT_LOG_LEVEL_INFO, aRegion, aFormat, ## __VA_ARGS__) +#define otLogInfo(aInstance, aRegion, aFormat, ...) \ + _otLogFormatter(aInstance, OT_LOG_LEVEL_INFO, aRegion, aFormat, ##__VA_ARGS__) #else #define otLogInfo(aInstance, aRegion, aFormat, ...) #endif @@ -124,8 +124,8 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_DEBG -#define otLogDebg(aInstance, aRegion, aFormat, ...) \ - _otLogFormatter(aInstance, OT_LOG_LEVEL_DEBG, aRegion, aFormat, ## __VA_ARGS__) +#define otLogDebg(aInstance, aRegion, aFormat, ...) \ + _otLogFormatter(aInstance, OT_LOG_LEVEL_DEBG, aRegion, aFormat, ##__VA_ARGS__) #else #define otLogDebg(aInstance, aRegion, aFormat, ...) #endif @@ -176,10 +176,10 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_API == 1 -#define otLogCritApi(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_API, aFormat, ## __VA_ARGS__) -#define otLogWarnApi(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_API, aFormat, ## __VA_ARGS__) -#define otLogInfoApi(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_API, aFormat, ## __VA_ARGS__) -#define otLogDebgApi(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_API, aFormat, ## __VA_ARGS__) +#define otLogCritApi(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_API, aFormat, ##__VA_ARGS__) +#define otLogWarnApi(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_API, aFormat, ##__VA_ARGS__) +#define otLogInfoApi(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_API, aFormat, ##__VA_ARGS__) +#define otLogDebgApi(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_API, aFormat, ##__VA_ARGS__) #else #define otLogCritApi(aInstance, aFormat, ...) #define otLogWarnApi(aInstance, aFormat, ...) @@ -232,14 +232,10 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_MLE == 1 -#define otLogCritMeshCoP(aInstance, aFormat, ...) \ - otLogCrit(&aInstance, OT_LOG_REGION_MESH_COP, aFormat, ## __VA_ARGS__) -#define otLogWarnMeshCoP(aInstance, aFormat, ...) \ - otLogWarn(&aInstance, OT_LOG_REGION_MESH_COP, aFormat, ## __VA_ARGS__) -#define otLogInfoMeshCoP(aInstance, aFormat, ...) \ - otLogInfo(&aInstance, OT_LOG_REGION_MESH_COP, aFormat, ## __VA_ARGS__) -#define otLogDebgMeshCoP(aInstance, aFormat, ...) \ - otLogDebg(&aInstance, OT_LOG_REGION_MESH_COP, aFormat, ## __VA_ARGS__) +#define otLogCritMeshCoP(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_MESH_COP, aFormat, ##__VA_ARGS__) +#define otLogWarnMeshCoP(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_MESH_COP, aFormat, ##__VA_ARGS__) +#define otLogInfoMeshCoP(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_MESH_COP, aFormat, ##__VA_ARGS__) +#define otLogDebgMeshCoP(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_MESH_COP, aFormat, ##__VA_ARGS__) #else #define otLogCritMeshCoP(aInstance, aFormat, ...) #define otLogWarnMeshCoP(aInstance, aFormat, ...) @@ -247,10 +243,10 @@ extern "C" { #define otLogDebgMeshCoP(aInstance, aFormat, ...) #endif -#define otLogCritMbedTls(aInstance, aFormat, ...) otLogCritMeshCoP(aInstance, aFormat, ## __VA_ARGS__) -#define otLogWarnMbedTls(aInstance, aFormat, ...) otLogWarnMeshCoP(aInstance, aFormat, ## __VA_ARGS__) -#define otLogInfoMbedTls(aInstance, aFormat, ...) otLogInfoMeshCoP(aInstance, aFormat, ## __VA_ARGS__) -#define otLogDebgMbedTls(aInstance, aFormat, ...) otLogDebgMeshCoP(aInstance, aFormat, ## __VA_ARGS__) +#define otLogCritMbedTls(aInstance, aFormat, ...) otLogCritMeshCoP(aInstance, aFormat, ##__VA_ARGS__) +#define otLogWarnMbedTls(aInstance, aFormat, ...) otLogWarnMeshCoP(aInstance, aFormat, ##__VA_ARGS__) +#define otLogInfoMbedTls(aInstance, aFormat, ...) otLogInfoMeshCoP(aInstance, aFormat, ##__VA_ARGS__) +#define otLogDebgMbedTls(aInstance, aFormat, ...) otLogDebgMeshCoP(aInstance, aFormat, ##__VA_ARGS__) /** * @def otLogCritMle @@ -297,12 +293,12 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_MLE == 1 -#define otLogCritMle(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_MLE, aFormat, ## __VA_ARGS__) -#define otLogWarnMle(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_MLE, aFormat, ## __VA_ARGS__) -#define otLogWarnMleErr(aInstance, aError, aFormat, ...) \ - otLogWarn(&aInstance, OT_LOG_REGION_MLE, "Error %s: " aFormat, otThreadErrorToString(aError), ## __VA_ARGS__) -#define otLogInfoMle(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_MLE, aFormat, ## __VA_ARGS__) -#define otLogDebgMle(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_MLE, aFormat, ## __VA_ARGS__) +#define otLogCritMle(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_MLE, aFormat, ##__VA_ARGS__) +#define otLogWarnMle(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_MLE, aFormat, ##__VA_ARGS__) +#define otLogWarnMleErr(aInstance, aError, aFormat, ...) \ + otLogWarn(&aInstance, OT_LOG_REGION_MLE, "Error %s: " aFormat, otThreadErrorToString(aError), ##__VA_ARGS__) +#define otLogInfoMle(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_MLE, aFormat, ##__VA_ARGS__) +#define otLogDebgMle(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_MLE, aFormat, ##__VA_ARGS__) #else #define otLogCritMle(aInstance, aFormat, ...) #define otLogWarnMle(aInstance, aFormat, ...) @@ -356,10 +352,10 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_ARP == 1 -#define otLogCritArp(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_ARP, aFormat, ## __VA_ARGS__) -#define otLogWarnArp(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_ARP, aFormat, ## __VA_ARGS__) -#define otLogInfoArp(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_ARP, aFormat, ## __VA_ARGS__) -#define otLogDebgArp(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_ARP, aFormat, ## __VA_ARGS__) +#define otLogCritArp(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_ARP, aFormat, ##__VA_ARGS__) +#define otLogWarnArp(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_ARP, aFormat, ##__VA_ARGS__) +#define otLogInfoArp(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_ARP, aFormat, ##__VA_ARGS__) +#define otLogDebgArp(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_ARP, aFormat, ##__VA_ARGS__) #else #define otLogCritArp(aInstance, aFormat, ...) #define otLogWarnArp(aInstance, aFormat, ...) @@ -411,14 +407,10 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_NETDATA == 1 -#define otLogCritNetData(aInstance, aFormat, ...) \ - otLogCrit(&aInstance, OT_LOG_REGION_NET_DATA, aFormat, ## __VA_ARGS__) -#define otLogWarnNetData(aInstance, aFormat, ...) \ - otLogWarn(&aInstance, OT_LOG_REGION_NET_DATA, aFormat, ## __VA_ARGS__) -#define otLogInfoNetData(aInstance, aFormat, ...) \ - otLogInfo(&aInstance, OT_LOG_REGION_NET_DATA, aFormat, ## __VA_ARGS__) -#define otLogDebgNetData(aInstance, aFormat, ...) \ - otLogDebg(&aInstance, OT_LOG_REGION_NET_DATA, aFormat, ## __VA_ARGS__) +#define otLogCritNetData(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_NET_DATA, aFormat, ##__VA_ARGS__) +#define otLogWarnNetData(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_NET_DATA, aFormat, ##__VA_ARGS__) +#define otLogInfoNetData(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_NET_DATA, aFormat, ##__VA_ARGS__) +#define otLogDebgNetData(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_NET_DATA, aFormat, ##__VA_ARGS__) #else #define otLogCritNetData(aInstance, aFormat, ...) #define otLogWarnNetData(aInstance, aFormat, ...) @@ -470,10 +462,10 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_ICMP == 1 -#define otLogCritIcmp(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_ICMP, aFormat, ## __VA_ARGS__) -#define otLogWarnIcmp(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_ICMP, aFormat, ## __VA_ARGS__) -#define otLogInfoIcmp(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_ICMP, aFormat, ## __VA_ARGS__) -#define otLogDebgIcmp(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_ICMP, aFormat, ## __VA_ARGS__) +#define otLogCritIcmp(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_ICMP, aFormat, ##__VA_ARGS__) +#define otLogWarnIcmp(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_ICMP, aFormat, ##__VA_ARGS__) +#define otLogInfoIcmp(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_ICMP, aFormat, ##__VA_ARGS__) +#define otLogDebgIcmp(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_ICMP, aFormat, ##__VA_ARGS__) #else #define otLogCritIcmp(aInstance, aFormat, ...) #define otLogWarnIcmp(aInstance, aFormat, ...) @@ -525,10 +517,10 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_IP6 == 1 -#define otLogCritIp6(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_IP6, aFormat, ## __VA_ARGS__) -#define otLogWarnIp6(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_IP6, aFormat, ## __VA_ARGS__) -#define otLogInfoIp6(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_IP6, aFormat, ## __VA_ARGS__) -#define otLogDebgIp6(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_IP6, aFormat, ## __VA_ARGS__) +#define otLogCritIp6(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_IP6, aFormat, ##__VA_ARGS__) +#define otLogWarnIp6(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_IP6, aFormat, ##__VA_ARGS__) +#define otLogInfoIp6(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_IP6, aFormat, ##__VA_ARGS__) +#define otLogDebgIp6(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_IP6, aFormat, ##__VA_ARGS__) #else #define otLogCritIp6(aInstance, aFormat, ...) #define otLogWarnIp6(aInstance, aFormat, ...) @@ -581,12 +573,12 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_MAC == 1 -#define otLogCritMac(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_MAC, aFormat, ## __VA_ARGS__) -#define otLogWarnMac(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_MAC, aFormat, ## __VA_ARGS__) -#define otLogInfoMac(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_MAC, aFormat, ## __VA_ARGS__) -#define otLogDebgMac(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_MAC, aFormat, ## __VA_ARGS__) -#define otLogDebgMacErr(aInstance, aError, aFormat, ...) \ - otLogWarn(aInstance, OT_LOG_REGION_MAC, "Error %s: " aFormat, otThreadErrorToString(aError), ## __VA_ARGS__) +#define otLogCritMac(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_MAC, aFormat, ##__VA_ARGS__) +#define otLogWarnMac(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_MAC, aFormat, ##__VA_ARGS__) +#define otLogInfoMac(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_MAC, aFormat, ##__VA_ARGS__) +#define otLogDebgMac(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_MAC, aFormat, ##__VA_ARGS__) +#define otLogDebgMacErr(aInstance, aError, aFormat, ...) \ + otLogWarn(aInstance, OT_LOG_REGION_MAC, "Error %s: " aFormat, otThreadErrorToString(aError), ##__VA_ARGS__) #else #define otLogCritMac(aInstance, aFormat, ...) #define otLogWarnMac(aInstance, aFormat, ...) @@ -639,12 +631,12 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_CORE == 1 -#define otLogCritCore(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_CORE, aFormat, ## __VA_ARGS__) -#define otLogWarnCore(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_CORE, aFormat, ## __VA_ARGS__) -#define otLogInfoCore(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_CORE, aFormat, ## __VA_ARGS__) -#define otLogDebgCore(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_CORE, aFormat, ## __VA_ARGS__) -#define otLogDebgCoreErr(aInstance, aError, aFormat, ...) \ - otLogWarn(aInstance, OT_LOG_REGION_CORE, "Error %s: " aFormat, otThreadErrorToString(aError), ## __VA_ARGS__) +#define otLogCritCore(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_CORE, aFormat, ##__VA_ARGS__) +#define otLogWarnCore(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_CORE, aFormat, ##__VA_ARGS__) +#define otLogInfoCore(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_CORE, aFormat, ##__VA_ARGS__) +#define otLogDebgCore(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_CORE, aFormat, ##__VA_ARGS__) +#define otLogDebgCoreErr(aInstance, aError, aFormat, ...) \ + otLogWarn(aInstance, OT_LOG_REGION_CORE, "Error %s: " aFormat, otThreadErrorToString(aError), ##__VA_ARGS__) #else #define otLogCritCore(aInstance, aFormat, ...) #define otLogWarnCore(aInstance, aFormat, ...) @@ -699,10 +691,10 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_MEM == 1 -#define otLogCritMem(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_MEM, aFormat, ## __VA_ARGS__) -#define otLogWarnMem(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_MEM, aFormat, ## __VA_ARGS__) -#define otLogInfoMem(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_MEM, aFormat, ## __VA_ARGS__) -#define otLogDebgMem(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_MEM, aFormat, ## __VA_ARGS__) +#define otLogCritMem(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_MEM, aFormat, ##__VA_ARGS__) +#define otLogWarnMem(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_MEM, aFormat, ##__VA_ARGS__) +#define otLogInfoMem(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_MEM, aFormat, ##__VA_ARGS__) +#define otLogDebgMem(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_MEM, aFormat, ##__VA_ARGS__) #else #define otLogCritMem(aInstance, aFormat, ...) #define otLogWarnMem(aInstance, aFormat, ...) @@ -754,12 +746,12 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_UTIL == 1 -#define otLogCritUtil(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_UTIL, aFormat, ## __VA_ARGS__) -#define otLogWarnUtil(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_UTIL, aFormat, ## __VA_ARGS__) -#define otLogInfoUtil(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_UTIL, aFormat, ## __VA_ARGS__) -#define otLogInfoUtilErr(aInstance, aError, aFormat, ...) \ - otLogInfo(&aInstance, OT_LOG_REGION_UTIL, "Error %s: " aFormat, otThreadErrorToString(aError), ## __VA_ARGS__) -#define otLogDebgUtil(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_UTIL, aFormat, ## __VA_ARGS__) +#define otLogCritUtil(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_UTIL, aFormat, ##__VA_ARGS__) +#define otLogWarnUtil(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_UTIL, aFormat, ##__VA_ARGS__) +#define otLogInfoUtil(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_UTIL, aFormat, ##__VA_ARGS__) +#define otLogInfoUtilErr(aInstance, aError, aFormat, ...) \ + otLogInfo(&aInstance, OT_LOG_REGION_UTIL, "Error %s: " aFormat, otThreadErrorToString(aError), ##__VA_ARGS__) +#define otLogDebgUtil(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_UTIL, aFormat, ##__VA_ARGS__) #else #define otLogCritUtil(aInstance, aFormat, ...) #define otLogWarnUtil(aInstance, aFormat, ...) @@ -812,14 +804,10 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_NETDIAG == 1 -#define otLogCritNetDiag(aInstance, aFormat, ...) \ - otLogCrit(&aInstance, OT_LOG_REGION_NET_DIAG, aFormat, ## __VA_ARGS__) -#define otLogWarnNetDiag(aInstance, aFormat, ...) \ - otLogWarn(&aInstance, OT_LOG_REGION_NET_DIAG, aFormat, ## __VA_ARGS__) -#define otLogInfoNetDiag(aInstance, aFormat, ...) \ - otLogInfo(&aInstance, OT_LOG_REGION_NET_DIAG, aFormat, ## __VA_ARGS__) -#define otLogDebgNetDiag(aInstance, aFormat, ...) \ - otLogDebg(&aInstance, OT_LOG_REGION_NET_DIAG, aFormat, ## __VA_ARGS__) +#define otLogCritNetDiag(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_NET_DIAG, aFormat, ##__VA_ARGS__) +#define otLogWarnNetDiag(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_NET_DIAG, aFormat, ##__VA_ARGS__) +#define otLogInfoNetDiag(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_NET_DIAG, aFormat, ##__VA_ARGS__) +#define otLogDebgNetDiag(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_NET_DIAG, aFormat, ##__VA_ARGS__) #else #define otLogCritNetDiag(aInstance, aFormat, ...) #define otLogWarnNetDiag(aInstance, aFormat, ...) @@ -839,8 +827,8 @@ extern "C" { * */ #if OPENTHREAD_ENABLE_CERT_LOG -#define otLogCertMeshCoP(aInstance, aFormat, ...) \ - _otLogFormatter(&aInstance, OT_LOG_LEVEL_NONE, OT_LOG_REGION_MESH_COP, aFormat, ## __VA_ARGS__) +#define otLogCertMeshCoP(aInstance, aFormat, ...) \ + _otLogFormatter(&aInstance, OT_LOG_LEVEL_NONE, OT_LOG_REGION_MESH_COP, aFormat, ##__VA_ARGS__) #else #define otLogCertMeshCoP(aInstance, aFormat, ...) #endif @@ -889,12 +877,12 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_CLI == 1 -#define otLogCritCli(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_CLI, aFormat, ## __VA_ARGS__) -#define otLogWarnCli(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_CLI, aFormat, ## __VA_ARGS__) -#define otLogInfoCli(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_CLI, aFormat, ## __VA_ARGS__) -#define otLogInfoCliErr(aInstance, aError, aFormat, ...) \ - otLogInfo(&aInstance, OT_LOG_REGION_CLI, "Error %s: " aFormat, otThreadErrorToString(aError), ## __VA_ARGS__) -#define otLogDebgCli(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_CLI, aFormat, ## __VA_ARGS__) +#define otLogCritCli(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_CLI, aFormat, ##__VA_ARGS__) +#define otLogWarnCli(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_CLI, aFormat, ##__VA_ARGS__) +#define otLogInfoCli(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_CLI, aFormat, ##__VA_ARGS__) +#define otLogInfoCliErr(aInstance, aError, aFormat, ...) \ + otLogInfo(&aInstance, OT_LOG_REGION_CLI, "Error %s: " aFormat, otThreadErrorToString(aError), ##__VA_ARGS__) +#define otLogDebgCli(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_CLI, aFormat, ##__VA_ARGS__) #else #define otLogCritCli(aInstance, aFormat, ...) #define otLogWarnCli(aInstance, aFormat, ...) @@ -947,12 +935,12 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_COAP == 1 -#define otLogCritCoap(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_COAP, aFormat, ## __VA_ARGS__) -#define otLogWarnCoap(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_COAP, aFormat, ## __VA_ARGS__) -#define otLogInfoCoap(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_COAP, aFormat, ## __VA_ARGS__) -#define otLogInfoCoapErr(aInstance, aError, aFormat, ...) \ - otLogInfo(&aInstance, OT_LOG_REGION_COAP, "Error %s: " aFormat, otThreadErrorToString(aError), ## __VA_ARGS__) -#define otLogDebgCoap(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_COAP, aFormat, ## __VA_ARGS__) +#define otLogCritCoap(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_COAP, aFormat, ##__VA_ARGS__) +#define otLogWarnCoap(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_COAP, aFormat, ##__VA_ARGS__) +#define otLogInfoCoap(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_COAP, aFormat, ##__VA_ARGS__) +#define otLogInfoCoapErr(aInstance, aError, aFormat, ...) \ + otLogInfo(&aInstance, OT_LOG_REGION_COAP, "Error %s: " aFormat, otThreadErrorToString(aError), ##__VA_ARGS__) +#define otLogDebgCoap(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_COAP, aFormat, ##__VA_ARGS__) #else #define otLogCritCoap(aInstance, aFormat, ...) #define otLogWarnCoap(aInstance, aFormat, ...) @@ -962,53 +950,53 @@ extern "C" { #endif /** -* @def otLogCritPlat -* -* This method generates a log with level critical for the Platform region. -* -* @param[in] aInstance A pointer to the OpenThread instance. -* @param[in] aFormat A pointer to the format string. -* @param[in] ... Arguments for the format specification. -* -*/ + * @def otLogCritPlat + * + * This method generates a log with level critical for the Platform region. + * + * @param[in] aInstance A pointer to the OpenThread instance. + * @param[in] aFormat A pointer to the format string. + * @param[in] ... Arguments for the format specification. + * + */ /** -* @def otLogWarnPlat -* -* This method generates a log with level warning for the Platform region. -* -* @param[in] aInstance A pointer to the OpenThread instance. -* @param[in] aFormat A pointer to the format string. -* @param[in] ... Arguments for the format specification. -* -*/ + * @def otLogWarnPlat + * + * This method generates a log with level warning for the Platform region. + * + * @param[in] aInstance A pointer to the OpenThread instance. + * @param[in] aFormat A pointer to the format string. + * @param[in] ... Arguments for the format specification. + * + */ /** -* @def otLogInfoPlat -* -* This method generates a log with level info for the Platform region. -* -* @param[in] aInstance A pointer to the OpenThread instance. -* @param[in] aFormat A pointer to the format string. -* @param[in] ... Arguments for the format specification. -* -*/ + * @def otLogInfoPlat + * + * This method generates a log with level info for the Platform region. + * + * @param[in] aInstance A pointer to the OpenThread instance. + * @param[in] aFormat A pointer to the format string. + * @param[in] ... Arguments for the format specification. + * + */ /** -* @def otLogDebgPlat -* -* This method generates a log with level debug for the Platform region. -* -* @param[in] aInstance A pointer to the OpenThread instance. -* @param[in] aFormat A pointer to the format string. -* @param[in] ... Arguments for the format specification. -* -*/ + * @def otLogDebgPlat + * + * This method generates a log with level debug for the Platform region. + * + * @param[in] aInstance A pointer to the OpenThread instance. + * @param[in] aFormat A pointer to the format string. + * @param[in] ... Arguments for the format specification. + * + */ #if OPENTHREAD_CONFIG_LOG_PLATFORM == 1 -#define otLogCritPlat(aInstance, aFormat, ...) otLogCrit(aInstance, OT_LOG_REGION_PLATFORM, aFormat, ## __VA_ARGS__) -#define otLogWarnPlat(aInstance, aFormat, ...) otLogWarn(aInstance, OT_LOG_REGION_PLATFORM, aFormat, ## __VA_ARGS__) -#define otLogInfoPlat(aInstance, aFormat, ...) otLogInfo(aInstance, OT_LOG_REGION_PLATFORM, aFormat, ## __VA_ARGS__) -#define otLogDebgPlat(aInstance, aFormat, ...) otLogDebg(aInstance, OT_LOG_REGION_PLATFORM, aFormat, ## __VA_ARGS__) +#define otLogCritPlat(aInstance, aFormat, ...) otLogCrit(aInstance, OT_LOG_REGION_PLATFORM, aFormat, ##__VA_ARGS__) +#define otLogWarnPlat(aInstance, aFormat, ...) otLogWarn(aInstance, OT_LOG_REGION_PLATFORM, aFormat, ##__VA_ARGS__) +#define otLogInfoPlat(aInstance, aFormat, ...) otLogInfo(aInstance, OT_LOG_REGION_PLATFORM, aFormat, ##__VA_ARGS__) +#define otLogDebgPlat(aInstance, aFormat, ...) otLogDebg(aInstance, OT_LOG_REGION_PLATFORM, aFormat, ##__VA_ARGS__) #else #define otLogCritPlat(aInstance, aFormat, ...) #define otLogWarnPlat(aInstance, aFormat, ...) @@ -1031,7 +1019,7 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_CRIT -#define otDumpCrit(aInstance, aRegion, aId, aBuf, aLength) \ +#define otDumpCrit(aInstance, aRegion, aId, aBuf, aLength) \ otDump(&aInstance, OT_LOG_LEVEL_CRIT, aRegion, aId, aBuf, aLength) #else #define otDumpCrit(aInstance, aRegion, aId, aBuf, aLength) @@ -1050,7 +1038,7 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN -#define otDumpWarn(aInstance, aRegion, aId, aBuf, aLength) \ +#define otDumpWarn(aInstance, aRegion, aId, aBuf, aLength) \ otDump(&aInstance, OT_LOG_LEVEL_WARN, aRegion, aId, aBuf, aLength) #else #define otDumpWarn(aInstance, aRegion, aId, aBuf, aLength) @@ -1069,7 +1057,7 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO -#define otDumpInfo(aInstance, aRegion, aId, aBuf, aLength) \ +#define otDumpInfo(aInstance, aRegion, aId, aBuf, aLength) \ otDump(&aInstance, OT_LOG_LEVEL_INFO, aRegion, aId, aBuf, aLength) #else #define otDumpInfo(aInstance, aRegion, aId, aBuf, aLength) @@ -1088,7 +1076,7 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_DEBG -#define otDumpDebg(aInstance, aRegion, aId, aBuf, aLength) \ +#define otDumpDebg(aInstance, aRegion, aId, aBuf, aLength) \ otDump(&aInstance, OT_LOG_LEVEL_DEBG, aRegion, aId, aBuf, aLength) #else #define otDumpDebg(aInstance, aRegion, aId, aBuf, aLength) @@ -1139,13 +1127,13 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_NETDATA == 1 -#define otDumpCritNetData(aInstance, aId, aBuf, aLength) \ +#define otDumpCritNetData(aInstance, aId, aBuf, aLength) \ otDumpCrit(aInstance, OT_LOG_REGION_NET_DATA, aId, aBuf, aLength) -#define otDumpWarnNetData(aInstance, aId, aBuf, aLength) \ +#define otDumpWarnNetData(aInstance, aId, aBuf, aLength) \ otDumpWarn(aInstance, OT_LOG_REGION_NET_DATA, aId, aBuf, aLength) -#define otDumpInfoNetData(aInstance, aId, aBuf, aLength) \ +#define otDumpInfoNetData(aInstance, aId, aBuf, aLength) \ otDumpInfo(aInstance, OT_LOG_REGION_NET_DATA, aId, aBuf, aLength) -#define otDumpDebgNetData(aInstance, aId, aBuf, aLength) \ +#define otDumpDebgNetData(aInstance, aId, aBuf, aLength) \ otDumpDebg(aInstance, OT_LOG_REGION_NET_DATA, aId, aBuf, aLength) #else #define otDumpCritNetData(aInstance, aId, aBuf, aLength) @@ -1320,14 +1308,10 @@ extern "C" { * */ #if OPENTHREAD_CONFIG_LOG_ICMP == 1 -#define otDumpCritIcmp(aInstance, aId, aBuf, aLength) \ - otDumpCrit(aInstance, OT_LOG_REGION_ICMP, aId, aBuf, aLength) -#define otDumpWarnIcmp(aInstance, aId, aBuf, aLength) \ - otDumpWarn(aInstance, OT_LOG_REGION_ICMP, aId, aBuf, aLength) -#define otDumpInfoIcmp(aInstance, aId, aBuf, aLength) \ - otDumpInfo(aInstance, OT_LOG_REGION_ICMP, aId, aBuf, aLength) -#define otDumpDebgIcmp(aInstance, aId, aBuf, aLength) \ - otDumpDebg(aInstance, OT_LOG_REGION_ICMP, aId, aBuf, aLength) +#define otDumpCritIcmp(aInstance, aId, aBuf, aLength) otDumpCrit(aInstance, OT_LOG_REGION_ICMP, aId, aBuf, aLength) +#define otDumpWarnIcmp(aInstance, aId, aBuf, aLength) otDumpWarn(aInstance, OT_LOG_REGION_ICMP, aId, aBuf, aLength) +#define otDumpInfoIcmp(aInstance, aId, aBuf, aLength) otDumpInfo(aInstance, OT_LOG_REGION_ICMP, aId, aBuf, aLength) +#define otDumpDebgIcmp(aInstance, aId, aBuf, aLength) otDumpDebg(aInstance, OT_LOG_REGION_ICMP, aId, aBuf, aLength) #else #define otDumpCritIcmp(aInstance, aId, aBuf, aLength) #define otDumpWarnIcmp(aInstance, aId, aBuf, aLength) @@ -1453,7 +1437,6 @@ extern "C" { #define otDumpDebgMac(aInstance, aId, aBuf, aLength) #endif - /** * @def otDumpCritCore * @@ -1584,7 +1567,7 @@ extern "C" { * */ #if OPENTHREAD_ENABLE_CERT_LOG -#define otDumpCertMeshCoP(aInstance, aId, aBuf, aLength) \ +#define otDumpCertMeshCoP(aInstance, aId, aBuf, aLength) \ otDump(&aInstance, OT_LOG_LEVEL_NONE, OT_LOG_REGION_MESH_COP, aId, aBuf, aLength) #else #define otDumpCertMeshCoP(aInstance, aId, aBuf, aLength) @@ -1601,18 +1584,22 @@ extern "C" { * @param[in] aLength Number of bytes to print. * */ -void otDump(otInstance *aIntsance, otLogLevel aLevel, otLogRegion aRegion, const char *aId, const void *aBuf, +void otDump(otInstance * aIntsance, + otLogLevel aLevel, + otLogRegion aRegion, + const char * aId, + const void * aBuf, const size_t aLength); #if OPENTHREAD_CONFIG_LOG_PREPEND_LEVEL == 1 /** -* This method converts the log level value into a string -* -* @param[in] aLevel The log level. -* -* @returns A const char pointer to the C string corresponding to the log level. -* -*/ + * This method converts the log level value into a string + * + * @param[in] aLevel The log level. + * + * @returns A const char pointer to the C string corresponding to the log level. + * + */ const char *otLogLevelToString(otLogLevel aLevel); #endif @@ -1635,64 +1622,39 @@ const char *otLogRegionToString(otLogRegion aRegion); /** * Local/private macro to format the log message */ -#define _otLogFormatter(aInstance, aLogLevel, aRegion, aFormat, ...) \ - _otDynamicLog( \ - aInstance, \ - aLogLevel, \ - aRegion, \ - "[%s]%s: " aFormat OPENTHREAD_CONFIG_LOG_SUFFIX, \ - otLogLevelToString(aLogLevel), \ - otLogRegionToString(aRegion), \ - ## __VA_ARGS__ \ - ) +#define _otLogFormatter(aInstance, aLogLevel, aRegion, aFormat, ...) \ + _otDynamicLog(aInstance, aLogLevel, aRegion, "[%s]%s: " aFormat OPENTHREAD_CONFIG_LOG_SUFFIX, \ + otLogLevelToString(aLogLevel), otLogRegionToString(aRegion), ##__VA_ARGS__) -#else // OPENTHREAD_CONFIG_LOG_PREPEND_REGION +#else // OPENTHREAD_CONFIG_LOG_PREPEND_REGION /** -* Local/private macro to format the log message -*/ -#define _otLogFormatter(aInstanc, aLogLevel, aRegion, aFormat, ...) \ - _otDynamicLog( \ - aInstance, \ - aLogLevel, \ - aRegion, \ - "[%s]: " aFormat OPENTHREAD_CONFIG_LOG_SUFFIX, \ - otLogLevelToString(aLogLevel), \ - ## __VA_ARGS__ \ - ) + * Local/private macro to format the log message + */ +#define _otLogFormatter(aInstanc, aLogLevel, aRegion, aFormat, ...) \ + _otDynamicLog(aInstance, aLogLevel, aRegion, "[%s]: " aFormat OPENTHREAD_CONFIG_LOG_SUFFIX, \ + otLogLevelToString(aLogLevel), ##__VA_ARGS__) #endif -#else // OPENTHREAD_CONFIG_LOG_PREPEND_LEVEL +#else // OPENTHREAD_CONFIG_LOG_PREPEND_LEVEL #if OPENTHREAD_CONFIG_LOG_PREPEND_REGION == 1 /** -* Local/private macro to format the log message -*/ -#define _otLogFormatter(aInstance, aLogLevel, aRegion, aFormat, ...) \ - _otDynamicLog( \ - aInstance, \ - aLogLevel, \ - aRegion, \ - "%s: " aFormat OPENTHREAD_CONFIG_LOG_SUFFIX, \ - otLogRegionToString(aRegion), \ - ## __VA_ARGS__ \ - ) + * Local/private macro to format the log message + */ +#define _otLogFormatter(aInstance, aLogLevel, aRegion, aFormat, ...) \ + _otDynamicLog(aInstance, aLogLevel, aRegion, "%s: " aFormat OPENTHREAD_CONFIG_LOG_SUFFIX, \ + otLogRegionToString(aRegion), ##__VA_ARGS__) -#else // OPENTHREAD_CONFIG_LOG_PREPEND_REGION +#else // OPENTHREAD_CONFIG_LOG_PREPEND_REGION /** -* Local/private macro to format the log message -*/ -#define _otLogFormatter(aInstance, aLogLevel, aRegion, aFormat, ...) \ - _otDynamicLog( \ - aInstance, \ - aLogLevel, \ - aRegion, \ - aFormat OPENTHREAD_CONFIG_LOG_SUFFIX, \ - ## __VA_ARGS__ \ - ) + * Local/private macro to format the log message + */ +#define _otLogFormatter(aInstance, aLogLevel, aRegion, aFormat, ...) \ + _otDynamicLog(aInstance, aLogLevel, aRegion, aFormat OPENTHREAD_CONFIG_LOG_SUFFIX, ##__VA_ARGS__) #endif @@ -1701,18 +1663,19 @@ const char *otLogRegionToString(otLogRegion aRegion); #if OPENTHREAD_CONFIG_ENABLE_DYNAMIC_LOG_LEVEL == 1 /** -* Local/private macro to dynamically filter log level. -*/ -#define _otDynamicLog(aInstance, aLogLevel, aRegion, aFormat, ...) \ - do { \ - if (otGetDynamicLogLevel(aInstance) >= aLogLevel) \ - _otPlatLog(aLogLevel, aRegion, aFormat, ## __VA_ARGS__); \ + * Local/private macro to dynamically filter log level. + */ +#define _otDynamicLog(aInstance, aLogLevel, aRegion, aFormat, ...) \ + do \ + { \ + if (otGetDynamicLogLevel(aInstance) >= aLogLevel) \ + _otPlatLog(aLogLevel, aRegion, aFormat, ##__VA_ARGS__); \ } while (false) #else // OPENTHREAD_CONFIG_ENABLE_DYNAMIC_LOG_LEVEL -#define _otDynamicLog(aInstance, aLogLevel, aRegion, aFormat, ...) \ - _otPlatLog(aLogLevel, aRegion, aFormat, ## __VA_ARGS__) +#define _otDynamicLog(aInstance, aLogLevel, aRegion, aFormat, ...) \ + _otPlatLog(aLogLevel, aRegion, aFormat, ##__VA_ARGS__) #endif // OPENTHREAD_CONFIG_ENABLE_DYNAMIC_LOG_LEVEL @@ -1720,11 +1683,11 @@ const char *otLogRegionToString(otLogRegion aRegion); * `OPENTHREAD_CONFIG_PLAT_LOG_FUNCTION` is a configuration parameter (see `openthread-core-default-config.h`) which * specifies the function/macro to be used for logging in OpenThread. By default it is set to `otPlatLog()`. */ -#define _otPlatLog(aLogLevel, aRegion, aFormat, ...) \ - OPENTHREAD_CONFIG_PLAT_LOG_FUNCTION(aLogLevel, aRegion, aFormat, ## __VA_ARGS__) +#define _otPlatLog(aLogLevel, aRegion, aFormat, ...) \ + OPENTHREAD_CONFIG_PLAT_LOG_FUNCTION(aLogLevel, aRegion, aFormat, ##__VA_ARGS__) #ifdef __cplusplus }; #endif -#endif // LOGGING_HPP_ +#endif // LOGGING_HPP_ diff --git a/src/core/common/message.cpp b/src/core/common/message.cpp index 480852471..35f1a46e1 100644 --- a/src/core/common/message.cpp +++ b/src/core/common/message.cpp @@ -43,9 +43,9 @@ namespace ot { -MessagePool::MessagePool(Instance &aInstance) : - InstanceLocator(aInstance), - mAllQueue() +MessagePool::MessagePool(Instance &aInstance) + : InstanceLocator(aInstance) + , mAllQueue() { #if OPENTHREAD_CONFIG_PLATFORM_MESSAGE_MANAGEMENT // Initialize Platform buffer pool management. @@ -92,11 +92,9 @@ exit: void MessagePool::Free(Message *aMessage) { - assert(aMessage->Next(MessageInfo::kListAll) == NULL && - aMessage->Prev(MessageInfo::kListAll) == NULL); + assert(aMessage->Next(MessageInfo::kListAll) == NULL && aMessage->Prev(MessageInfo::kListAll) == NULL); - assert(aMessage->Next(MessageInfo::kListInterface) == NULL && - aMessage->Prev(MessageInfo::kListInterface) == NULL); + assert(aMessage->Next(MessageInfo::kListInterface) == NULL && aMessage->Prev(MessageInfo::kListInterface) == NULL); FreeBuffers(static_cast(aMessage)); } @@ -113,7 +111,7 @@ Buffer *MessagePool::NewBuffer(void) if (mFreeBuffers != NULL) { - buffer = mFreeBuffers; + buffer = mFreeBuffers; mFreeBuffers = mFreeBuffers->GetNextBuffer(); buffer->SetNextBuffer(NULL); mNumFreeBuffers--; @@ -136,7 +134,7 @@ void MessagePool::FreeBuffers(Buffer *aBuffer) Buffer *tmpBuffer = aBuffer->GetNextBuffer(); #if OPENTHREAD_CONFIG_PLATFORM_MESSAGE_MANAGEMENT otPlatMessagePoolFree(&GetInstance(), aBuffer); -#else // OPENTHREAD_CONFIG_PLATFORM_MESSAGE_MANAGEMENT +#else // OPENTHREAD_CONFIG_PLATFORM_MESSAGE_MANAGEMENT aBuffer->SetNextBuffer(mFreeBuffers); mFreeBuffers = aBuffer; mNumFreeBuffers++; @@ -237,8 +235,8 @@ otError Message::ResizeMessage(uint16_t aLength) otError error = OT_ERROR_NONE; // add buffers - Buffer *curBuffer = this; - Buffer *lastBuffer; + Buffer * curBuffer = this; + Buffer * lastBuffer; uint16_t curLength = kHeadBufferDataSize; while (curLength < aLength) @@ -255,7 +253,7 @@ otError Message::ResizeMessage(uint16_t aLength) // remove buffers lastBuffer = curBuffer; - curBuffer = curBuffer->GetNextBuffer(); + curBuffer = curBuffer->GetNextBuffer(); lastBuffer->SetNextBuffer(NULL); GetMessagePool()->FreeBuffers(curBuffer); @@ -295,10 +293,10 @@ exit: otError Message::SetLength(uint16_t aLength) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint16_t totalLengthRequest = GetReserved() + aLength; uint16_t totalLengthCurrent = GetReserved() + GetLength(); - int bufs = 0; + int bufs = 0; if (totalLengthRequest > kHeadBufferDataSize) { @@ -366,8 +364,7 @@ bool Message::IsSubTypeMle(void) const mBuffer.mHead.mInfo.mSubType == kSubTypeMleDiscoverRequest || mBuffer.mHead.mInfo.mSubType == kSubTypeMleDiscoverResponse || mBuffer.mHead.mInfo.mSubType == kSubTypeMleChildUpdateRequest || - mBuffer.mHead.mInfo.mSubType == kSubTypeMleDataResponse || - mBuffer.mHead.mInfo.mSubType == kSubTypeMleGeneral) + mBuffer.mHead.mInfo.mSubType == kSubTypeMleDataResponse || mBuffer.mHead.mInfo.mSubType == kSubTypeMleGeneral) { rval = true; } @@ -377,7 +374,7 @@ bool Message::IsSubTypeMle(void) const otError Message::SetPriority(uint8_t aPriority) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; PriorityQueue *priorityQueue = NULL; VerifyOrExit(aPriority < kNumPriorities, error = OT_ERROR_INVALID_ARGS); @@ -412,9 +409,9 @@ exit: otError Message::Append(const void *aBuf, uint16_t aLength) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint16_t oldLength = GetLength(); - int bytesWritten; + int bytesWritten; SuccessOrExit(error = SetLength(GetLength() + aLength)); bytesWritten = Write(oldLength, aLength, aBuf); @@ -428,7 +425,7 @@ exit: otError Message::Prepend(const void *aBuf, uint16_t aLength) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Buffer *newBuffer = NULL; while (aLength > GetReserved()) @@ -482,7 +479,7 @@ otError Message::RemoveHeader(uint16_t aLength) uint16_t Message::Read(uint16_t aOffset, uint16_t aLength, void *aBuf) const { - Buffer *curBuffer; + Buffer * curBuffer; uint16_t bytesCopied = 0; uint16_t bytesToCopy; @@ -551,7 +548,7 @@ uint16_t Message::Read(uint16_t aOffset, uint16_t aLength, void *aBuf) const aBuf = static_cast(aBuf) + bytesToCopy; curBuffer = curBuffer->GetNextBuffer(); - aOffset = 0; + aOffset = 0; } exit: @@ -560,7 +557,7 @@ exit: int Message::Write(uint16_t aOffset, uint16_t aLength, const void *aBuf) { - Buffer *curBuffer; + Buffer * curBuffer; uint16_t bytesCopied = 0; uint16_t bytesToCopy; @@ -626,7 +623,7 @@ int Message::Write(uint16_t aOffset, uint16_t aLength, const void *aBuf) aBuf = static_cast(aBuf) + bytesToCopy; curBuffer = curBuffer->GetNextBuffer(); - aOffset = 0; + aOffset = 0; } return bytesCopied; @@ -636,7 +633,7 @@ int Message::CopyTo(uint16_t aSourceOffset, uint16_t aDestinationOffset, uint16_ { uint16_t bytesCopied = 0; uint16_t bytesToCopy; - uint8_t buf[16]; + uint8_t buf[16]; while (aLength > 0) { @@ -656,7 +653,7 @@ int Message::CopyTo(uint16_t aSourceOffset, uint16_t aDestinationOffset, uint16_ Message *Message::Clone(uint16_t aLength) const { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Message *messageCopy; VerifyOrExit((messageCopy = GetMessagePool()->New(GetType(), GetReserved())) != NULL, error = OT_ERROR_NO_BUFS); @@ -735,7 +732,7 @@ uint16_t Message::UpdateChecksum(uint16_t aChecksum, const void *aBuf, uint16_t uint16_t Message::UpdateChecksum(uint16_t aChecksum, uint16_t aOffset, uint16_t aLength) const { - Buffer *curBuffer; + Buffer * curBuffer; uint16_t bytesCovered = 0; uint16_t bytesToCover; @@ -794,7 +791,7 @@ uint16_t Message::UpdateChecksum(uint16_t aChecksum, uint16_t aOffset, uint16_t bytesCovered += bytesToCover; curBuffer = curBuffer->GetNextBuffer(); - aOffset = 0; + aOffset = 0; } return aChecksum; @@ -803,13 +800,13 @@ uint16_t Message::UpdateChecksum(uint16_t aChecksum, uint16_t aOffset, uint16_t void Message::SetMessageQueue(MessageQueue *aMessageQueue) { mBuffer.mHead.mInfo.mQueue.mMessage = aMessageQueue; - mBuffer.mHead.mInfo.mInPriorityQ = false; + mBuffer.mHead.mInfo.mInPriorityQ = false; } void Message::SetPriorityQueue(PriorityQueue *aPriorityQueue) { mBuffer.mHead.mInfo.mQueue.mPriority = aPriorityQueue; - mBuffer.mHead.mInfo.mInPriorityQ = true; + mBuffer.mHead.mInfo.mInPriorityQ = true; } MessageQueue::MessageQueue(void) @@ -835,7 +832,7 @@ void MessageQueue::AddToList(uint8_t aList, Message &aMessage, QueuePosition aPo aMessage.Next(aList) = head; aMessage.Prev(aList) = GetTail(); - head->Prev(aList) = &aMessage; + head->Prev(aList) = &aMessage; GetTail()->Next(aList) = &aMessage; if (aPosition == kQueuePositionTail) @@ -906,7 +903,7 @@ exit: void MessageQueue::GetInfo(uint16_t &aMessageCount, uint16_t &aBufferCount) const { aMessageCount = 0; - aBufferCount = 0; + aBufferCount = 0; for (const Message *message = GetHead(); message != NULL; message = message->GetNext()) { @@ -926,7 +923,7 @@ PriorityQueue::PriorityQueue(void) Message *PriorityQueue::FindFirstNonNullTail(uint8_t aStartPriorityLevel) const { Message *tail = NULL; - uint8_t priority; + uint8_t priority; priority = aStartPriorityLevel; @@ -939,8 +936,7 @@ Message *PriorityQueue::FindFirstNonNullTail(uint8_t aStartPriorityLevel) const } priority = PrevPriority(priority); - } - while (priority != aStartPriorityLevel); + } while (priority != aStartPriorityLevel); return tail; } @@ -982,7 +978,7 @@ Message *PriorityQueue::GetTail(void) const void PriorityQueue::AddToList(uint8_t aList, Message &aMessage) { - uint8_t priority; + uint8_t priority; Message *tail; Message *next; @@ -996,8 +992,8 @@ void PriorityQueue::AddToList(uint8_t aList, Message &aMessage) aMessage.Next(aList) = next; aMessage.Prev(aList) = tail; - next->Prev(aList) = &aMessage; - tail->Next(aList) = &aMessage; + next->Prev(aList) = &aMessage; + tail->Next(aList) = &aMessage; } else { @@ -1010,7 +1006,7 @@ void PriorityQueue::AddToList(uint8_t aList, Message &aMessage) void PriorityQueue::RemoveFromList(uint8_t aList, Message &aMessage) { - uint8_t priority; + uint8_t priority; Message *tail; priority = aMessage.GetPriority(); @@ -1031,8 +1027,8 @@ void PriorityQueue::RemoveFromList(uint8_t aList, Message &aMessage) aMessage.Next(aList)->Prev(aList) = aMessage.Prev(aList); aMessage.Prev(aList)->Next(aList) = aMessage.Next(aList); - aMessage.Next(aList) = NULL; - aMessage.Prev(aList) = NULL; + aMessage.Next(aList) = NULL; + aMessage.Prev(aList) = NULL; } otError PriorityQueue::Enqueue(Message &aMessage) @@ -1068,7 +1064,7 @@ exit: void PriorityQueue::GetInfo(uint16_t &aMessageCount, uint16_t &aBufferCount) const { aMessageCount = 0; - aBufferCount = 0; + aBufferCount = 0; for (const Message *message = GetHead(); message != NULL; message = message->GetNext()) { @@ -1077,4 +1073,4 @@ void PriorityQueue::GetInfo(uint16_t &aMessageCount, uint16_t &aBufferCount) con } } -} // namespace ot +} // namespace ot diff --git a/src/core/common/message.hpp b/src/core/common/message.hpp index be88ac872..d7b4895c8 100644 --- a/src/core/common/message.hpp +++ b/src/core/common/message.hpp @@ -78,42 +78,42 @@ struct MessageInfo { enum { - kListAll = 0, ///< Identifies the all messages list (maintained by the MessagePool). - kListInterface = 1, ///< Identifies the list for per-interface message queue. - kNumLists = 2, ///< Number of lists. + kListAll = 0, ///< Identifies the all messages list (maintained by the MessagePool). + kListInterface = 1, ///< Identifies the list for per-interface message queue. + kNumLists = 2, ///< Number of lists. }; - Message *mNext[kNumLists]; ///< A pointer to the next Message in a doubly linked list. - Message *mPrev[kNumLists]; ///< A pointer to the previous Message in a doubly linked list. - MessagePool *mMessagePool; ///< Identifies the message pool for this message. + Message * mNext[kNumLists]; ///< A pointer to the next Message in a doubly linked list. + Message * mPrev[kNumLists]; ///< A pointer to the previous Message in a doubly linked list. + MessagePool *mMessagePool; ///< Identifies the message pool for this message. union { - MessageQueue *mMessage; ///< Identifies the message queue (if any) where this message is queued. - PriorityQueue *mPriority; ///< Identifies the priority queue (if any) where this message is queued. - } mQueue; ///< Identifies the queue (if any) where this message is queued. + MessageQueue * mMessage; ///< Identifies the message queue (if any) where this message is queued. + PriorityQueue *mPriority; ///< Identifies the priority queue (if any) where this message is queued. + } mQueue; ///< Identifies the queue (if any) where this message is queued. - uint16_t mReserved; ///< Number of header bytes reserved for the message. - uint16_t mLength; ///< Number of bytes within the message. - uint16_t mOffset; ///< A byte offset within the message. - uint16_t mDatagramTag; ///< The datagram tag used for 6LoWPAN fragmentation. - RssAverager mRssAverager; ///< The averager maintaining the received signal strength (RSS) average. + uint16_t mReserved; ///< Number of header bytes reserved for the message. + uint16_t mLength; ///< Number of bytes within the message. + uint16_t mOffset; ///< A byte offset within the message. + uint16_t mDatagramTag; ///< The datagram tag used for 6LoWPAN fragmentation. + RssAverager mRssAverager; ///< The averager maintaining the received signal strength (RSS) average. - uint8_t mChildMask[8]; ///< A bit-vector to indicate which sleepy children need to receive this. - uint8_t mTimeout; ///< Seconds remaining before dropping the message. - int8_t mInterfaceId; ///< The interface ID. + uint8_t mChildMask[8]; ///< A bit-vector to indicate which sleepy children need to receive this. + uint8_t mTimeout; ///< Seconds remaining before dropping the message. + int8_t mInterfaceId; ///< The interface ID. union { - uint16_t mPanId; ///< Used for MLE Discover Request and Response messages. - uint8_t mChannel; ///< Used for MLE Announce. - } mPanIdChannel; ///< Used for MLE Discover Request, Response, and Announce messages. + uint16_t mPanId; ///< Used for MLE Discover Request and Response messages. + uint8_t mChannel; ///< Used for MLE Announce. + } mPanIdChannel; ///< Used for MLE Discover Request, Response, and Announce messages. - uint8_t mType : 2; ///< Identifies the type of message. - uint8_t mSubType : 4; ///< Identifies the message sub type. - bool mDirectTx : 1; ///< Used to indicate whether a direct transmission is required. - bool mLinkSecurity : 1; ///< Indicates whether or not link security is enabled. - uint8_t mPriority : 2; ///< Identifies the message priority level (lower value is higher priority). - bool mInPriorityQ : 1; ///< Indicates whether the message is queued in normal or priority queue. - bool mTxSuccess : 1; ///< Indicates whether the direct tx of the message was successful. + uint8_t mType : 2; ///< Identifies the type of message. + uint8_t mSubType : 4; ///< Identifies the message sub type. + bool mDirectTx : 1; ///< Used to indicate whether a direct transmission is required. + bool mLinkSecurity : 1; ///< Indicates whether or not link security is enabled. + uint8_t mPriority : 2; ///< Identifies the message priority level (lower value is higher priority). + bool mInPriorityQ : 1; ///< Indicates whether the message is queued in normal or priority queue. + bool mTxSuccess : 1; ///< Indicates whether the direct tx of the message was successful. }; /** @@ -174,7 +174,7 @@ private: enum { - kBufferDataSize = kBufferSize - sizeof(struct otMessage), + kBufferDataSize = kBufferSize - sizeof(struct otMessage), kHeadBufferDataSize = kBufferDataSize - sizeof(struct MessageInfo), }; @@ -183,7 +183,7 @@ private: struct { MessageInfo mInfo; - uint8_t mData[kHeadBufferDataSize]; + uint8_t mData[kHeadBufferDataSize]; } mHead; uint8_t mData[kBufferDataSize]; } mBuffer; @@ -193,7 +193,7 @@ private: * This class represents a message. * */ -class Message: public Buffer +class Message : public Buffer { friend class MessagePool; friend class MessageQueue; @@ -202,34 +202,34 @@ class Message: public Buffer public: enum { - kTypeIp6 = 0, ///< A full uncompressed IPv6 packet - kType6lowpan = 1, ///< A 6lowpan frame - kTypeMacDataPoll = 2, ///< A MAC data poll message - kTypeSupervision = 3, ///< A child supervision frame. + kTypeIp6 = 0, ///< A full uncompressed IPv6 packet + kType6lowpan = 1, ///< A 6lowpan frame + kTypeMacDataPoll = 2, ///< A MAC data poll message + kTypeSupervision = 3, ///< A child supervision frame. }; enum { - kSubTypeNone = 0, ///< None - kSubTypeMleAnnounce = 1, ///< MLE Announce - kSubTypeMleDiscoverRequest = 2, ///< MLE Discover Request - kSubTypeMleDiscoverResponse = 3, ///< MLE Discover Response - kSubTypeJoinerEntrust = 4, ///< Joiner Entrust - kSubTypeMplRetransmission = 5, ///< MPL next retransmission message - kSubTypeMleGeneral = 6, ///< General MLE - kSubTypeJoinerFinalizeResponse = 7, ///< Joiner Finalize Response - kSubTypeMleChildUpdateRequest = 8, ///< MLE Child Update Request - kSubTypeMleDataResponse = 9, ///< MLE Data Response + kSubTypeNone = 0, ///< None + kSubTypeMleAnnounce = 1, ///< MLE Announce + kSubTypeMleDiscoverRequest = 2, ///< MLE Discover Request + kSubTypeMleDiscoverResponse = 3, ///< MLE Discover Response + kSubTypeJoinerEntrust = 4, ///< Joiner Entrust + kSubTypeMplRetransmission = 5, ///< MPL next retransmission message + kSubTypeMleGeneral = 6, ///< General MLE + kSubTypeJoinerFinalizeResponse = 7, ///< Joiner Finalize Response + kSubTypeMleChildUpdateRequest = 8, ///< MLE Child Update Request + kSubTypeMleDataResponse = 9, ///< MLE Data Response }; enum { - kPriorityHigh = 0, ///< High priority level. - kPriorityMedium = 1, ///< Medium priority level. - kPriorityLow = 2, ///< Low priority level. - kPriorityVeryLow = 3, ///< Very low priority level. + kPriorityHigh = 0, ///< High priority level. + kPriorityMedium = 1, ///< Medium priority level. + kPriorityLow = 2, ///< Low priority level. + kPriorityVeryLow = 3, ///< Very low priority level. - kNumPriorities = 4, ///< Number of priority levels. + kNumPriorities = 4, ///< Number of priority levels. }; /** @@ -705,12 +705,12 @@ public: * @returns A pointer to the message queue or NULL if not in any message queue. * */ - MessageQueue *GetMessageQueue(void) const { + MessageQueue *GetMessageQueue(void) const + { return (!mBuffer.mHead.mInfo.mInPriorityQ) ? mBuffer.mHead.mInfo.mQueue.mMessage : NULL; } private: - /** * This method returns a pointer to the message pool to which this message belongs * @@ -749,7 +749,8 @@ private: * @returns A pointer to the priority queue or NULL if not in any priority queue. * */ - PriorityQueue *GetPriorityQueue(void) const { + PriorityQueue *GetPriorityQueue(void) const + { return (mBuffer.mHead.mInfo.mInPriorityQ) ? mBuffer.mHead.mInfo.mQueue.mPriority : NULL; } @@ -829,7 +830,6 @@ class MessageQueue : public otMessageQueue friend class PriorityQueue; public: - /** * This enumeration represents a position (head or tail) in the queue. This is used to specify where a new message * should be added in the queue. @@ -837,8 +837,8 @@ public: */ enum QueuePosition { - kQueuePositionHead, ///< Indicates the head (front) of the list. - kQueuePositionTail, ///< Indicates the tail (end) of the list. + kQueuePositionHead, ///< Indicates the head (front) of the list. + kQueuePositionTail, ///< Indicates the tail (end) of the list. }; /** @@ -899,7 +899,6 @@ public: void GetInfo(uint16_t &aMessageCount, uint16_t &aBufferCount) const; private: - /** * This method returns the tail of the list (last message in the list) * @@ -971,14 +970,14 @@ public: Message *GetHead(void) const; /** - * This method returns a pointer to the first message for a given priority level. - * - * @param[in] aPriority Priority level. - * - * @returns A pointer to the first message with given priority level or NULL if there is no messages with - * this priority level. - * - */ + * This method returns a pointer to the first message for a given priority level. + * + * @param[in] aPriority Priority level. + * + * @returns A pointer to the first message with given priority level or NULL if there is no messages with + * this priority level. + * + */ Message *GetHeadForPriority(uint8_t aPriority) const; /** @@ -1013,7 +1012,6 @@ public: void GetInfo(uint16_t &aMessageCount, uint16_t &aBufferCount) const; private: - /** * This method returns the tail of the list (last message in the list) * @@ -1048,7 +1046,8 @@ private: * * @returns Decreased/Moved back priority level */ - uint8_t PrevPriority(uint8_t aPriority) const { + uint8_t PrevPriority(uint8_t aPriority) const + { return (aPriority == 0) ? (Message::kNumPriorities - 1) : (aPriority - 1); } @@ -1064,26 +1063,24 @@ private: Message *FindFirstNonNullTail(uint8_t aStartPriorityLevel) const; private: - - Message *mTails[Message::kNumPriorities]; ///< Tail pointers associated with different priority levels. + Message *mTails[Message::kNumPriorities]; ///< Tail pointers associated with different priority levels. }; /** * This class represents a message pool * */ -class MessagePool: public InstanceLocator +class MessagePool : public InstanceLocator { friend class Message; friend class MessageQueue; friend class PriorityQueue; public: - /** - * This class represents an iterator for iterating through all queued message from this pool. - * - */ + * This class represents an iterator for iterating through all queued message from this pool. + * + */ class Iterator { friend class MessagePool; @@ -1092,7 +1089,10 @@ public: /** * This constructor initializes an empty iterator. */ - Iterator(void) : mMessage(NULL) { } + Iterator(void) + : mMessage(NULL) + { + } /** * This method returns the associated message with the iterator. @@ -1138,7 +1138,11 @@ public: * @returns A reference to current iterator. * */ - Iterator &GoToNext(void) { mMessage = Next(); return *this; } + Iterator &GoToNext(void) + { + mMessage = Next(); + return *this; + } /** * This method moves the current iterator to the previous message on the list. @@ -1146,10 +1150,17 @@ public: * @returns A reference to current iterator. * */ - Iterator &GoToPrev(void) { mMessage = Prev(); return *this; } + Iterator &GoToPrev(void) + { + mMessage = Prev(); + return *this; + } private: - Iterator(Message *aMessage) : mMessage(aMessage) { } + Iterator(Message *aMessage) + : mMessage(aMessage) + { + } Message *Next(void) const; Message *Prev(void) const; @@ -1200,12 +1211,12 @@ public: */ Iterator GetAllMessagesTail(void) const { return Iterator(mAllQueue.GetTail()); } - /** - * This method returns the number of free buffers. - * - * @returns The number of free buffers. - * - */ + /** + * This method returns the number of free buffers. + * + * @returns The number of free buffers. + * + */ #if OPENTHREAD_CONFIG_PLATFORM_MESSAGE_MANAGEMENT uint16_t GetFreeBufferCount(void) const; #else @@ -1218,15 +1229,15 @@ private: kDefaultMessagePriority = Message::kPriorityLow, }; - Buffer *NewBuffer(void); - void FreeBuffers(Buffer *aBuffer); - otError ReclaimBuffers(int aNumBuffers); + Buffer * NewBuffer(void); + void FreeBuffers(Buffer *aBuffer); + otError ReclaimBuffers(int aNumBuffers); PriorityQueue *GetAllMessagesQueue(void) { return &mAllQueue; } #if OPENTHREAD_CONFIG_PLATFORM_MESSAGE_MANAGEMENT == 0 uint16_t mNumFreeBuffers; Buffer mBuffers[kNumBuffers]; - Buffer *mFreeBuffers; + Buffer * mFreeBuffers; #endif PriorityQueue mAllQueue; @@ -1237,6 +1248,6 @@ private: * */ -} // namespace ot +} // namespace ot -#endif // MESSAGE_HPP_ +#endif // MESSAGE_HPP_ diff --git a/src/core/common/new.hpp b/src/core/common/new.hpp index ee2e3a47d..ab437b18b 100644 --- a/src/core/common/new.hpp +++ b/src/core/common/new.hpp @@ -40,6 +40,9 @@ #include -inline void *operator new(size_t, void *p) throw() { return p; } +inline void *operator new(size_t, void *p) throw() +{ + return p; +} -#endif // NEW_HPP_ +#endif // NEW_HPP_ diff --git a/src/core/common/notifier.cpp b/src/core/common/notifier.cpp index 6a4fa79eb..4e115d6b7 100644 --- a/src/core/common/notifier.cpp +++ b/src/core/common/notifier.cpp @@ -41,18 +41,18 @@ namespace ot { -Notifier::Callback::Callback(Handler aHandler, void *aOwner): - OwnerLocator(aOwner), - mHandler(aHandler), - mNext(this) +Notifier::Callback::Callback(Handler aHandler, void *aOwner) + : OwnerLocator(aOwner) + , mHandler(aHandler) + , mNext(this) { } -Notifier::Notifier(Instance &aInstance): - InstanceLocator(aInstance), - mFlags(0), - mTask(aInstance, &Notifier::HandleStateChanged, this), - mCallbacks(NULL) +Notifier::Notifier(Instance &aInstance) + : InstanceLocator(aInstance) + , mFlags(0) + , mTask(aInstance, &Notifier::HandleStateChanged, this) + , mCallbacks(NULL) { for (unsigned int i = 0; i < kMaxExternalHandlers; i++) { @@ -68,7 +68,7 @@ otError Notifier::RegisterCallback(Callback &aCallback) VerifyOrExit(aCallback.mNext == &aCallback, error = OT_ERROR_ALREADY); aCallback.mNext = mCallbacks; - mCallbacks = &aCallback; + mCallbacks = &aCallback; exit: return error; @@ -99,7 +99,7 @@ exit: otError Notifier::RegisterCallback(otStateChangedCallback aCallback, void *aContext) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; ExternalCallback *unusedCallback = NULL; VerifyOrExit(aCallback != NULL); @@ -197,10 +197,10 @@ exit: void Notifier::LogChangedFlags(uint32_t aFlags) const { uint32_t flags = aFlags; - char stringBuffer[kFlagsStringBufferSize]; - char *buf = stringBuffer; - int len = sizeof(stringBuffer) - 1; - int charsWritten; + char stringBuffer[kFlagsStringBufferSize]; + char * buf = stringBuffer; + int len = sizeof(stringBuffer) - 1; + int charsWritten; for (uint8_t bit = 0; bit < 32; bit++) { @@ -342,4 +342,4 @@ const char *Notifier::FlagToString(uint32_t aFlag) const #endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MAC == 1) -} // namespace ot +} // namespace ot diff --git a/src/core/common/notifier.hpp b/src/core/common/notifier.hpp index e23904e23..e9b4b1f00 100644 --- a/src/core/common/notifier.hpp +++ b/src/core/common/notifier.hpp @@ -36,8 +36,8 @@ #include "openthread-core-config.h" -#include "utils/wrap_stdint.h" #include "utils/wrap_stdbool.h" +#include "utils/wrap_stdint.h" #include #include @@ -63,15 +63,14 @@ namespace ot { * It can be used to register callbacks to be notified of state or configuration changes within OpenThread. * */ -class Notifier: public InstanceLocator +class Notifier : public InstanceLocator { public: - /** * This class defines a callback instance that can be registered with the `Notifier`. * */ - class Callback: public OwnerLocator + class Callback : public OwnerLocator { friend class Notifier; @@ -96,7 +95,7 @@ public: Callback(Handler aHandler, void *aOwner); private: - Handler mHandler; + Handler mHandler; Callback *mNext; }; @@ -170,25 +169,25 @@ public: private: enum { - kMaxExternalHandlers = OPENTHREAD_CONFIG_MAX_STATECHANGE_HANDLERS, + kMaxExternalHandlers = OPENTHREAD_CONFIG_MAX_STATECHANGE_HANDLERS, kFlagsStringBufferSize = 128, }; struct ExternalCallback { otStateChangedCallback mHandler; - void *mContext; + void * mContext; }; static void HandleStateChanged(Tasklet &aTasklet); - void HandleStateChanged(void); + void HandleStateChanged(void); - void LogChangedFlags(uint32_t aFlags) const; + void LogChangedFlags(uint32_t aFlags) const; const char *FlagToString(uint32_t aFlag) const; - uint32_t mFlags; - Tasklet mTask; - Callback *mCallbacks; + uint32_t mFlags; + Tasklet mTask; + Callback * mCallbacks; ExternalCallback mExternalCallbacks[kMaxExternalHandlers]; }; @@ -197,6 +196,6 @@ private: * */ -} // namespace ot +} // namespace ot -#endif // NOTIFIER_HPP_ +#endif // NOTIFIER_HPP_ diff --git a/src/core/common/owner-locator.hpp b/src/core/common/owner-locator.hpp index b9263def7..7d193e5c2 100644 --- a/src/core/common/owner-locator.hpp +++ b/src/core/common/owner-locator.hpp @@ -44,8 +44,7 @@ namespace ot { #if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES -template -OwnerType &OwnerLocator::GetOwner(void) +template OwnerType &OwnerLocator::GetOwner(void) { // This method uses the `Instance` template method `Get` // to get to the given `Type` from the single OpenThread @@ -62,6 +61,6 @@ OwnerType &OwnerLocator::GetOwner(void) #endif -} // namespace ot +} // namespace ot -#endif // OWNER_LOCATOR_HPP_ +#endif // OWNER_LOCATOR_HPP_ diff --git a/src/core/common/settings.hpp b/src/core/common/settings.hpp index db42760fd..c0b809e4b 100644 --- a/src/core/common/settings.hpp +++ b/src/core/common/settings.hpp @@ -69,12 +69,12 @@ namespace Settings { */ enum { - kKeyActiveDataset = 0x0001, ///< Active Operational Dataset - kKeyPendingDataset = 0x0002, ///< Pending Operational Dataset - kKeyNetworkInfo = 0x0003, ///< Thread network information - kKeyParentInfo = 0x0004, ///< Parent information - kKeyChildInfo = 0x0005, ///< Child information - kKeyThreadAutoStart = 0x0006, ///< Auto-start information + kKeyActiveDataset = 0x0001, ///< Active Operational Dataset + kKeyPendingDataset = 0x0002, ///< Pending Operational Dataset + kKeyNetworkInfo = 0x0003, ///< Thread network information + kKeyParentInfo = 0x0004, ///< Parent information + kKeyChildInfo = 0x0005, ///< Child information + kKeyThreadAutoStart = 0x0006, ///< Auto-start information }; /** @@ -83,15 +83,15 @@ enum */ struct NetworkInfo { - uint8_t mRole; ///< Current Thread role. - uint8_t mDeviceMode; ///< Device mode setting. - uint16_t mRloc16; ///< RLOC16 - uint32_t mKeySequence; ///< Key Sequence - uint32_t mMleFrameCounter; ///< MLE Frame Counter - uint32_t mMacFrameCounter; ///< MAC Frame Counter - uint32_t mPreviousPartitionId; ///< PartitionId - Mac::ExtAddress mExtAddress; ///< Extended Address - uint8_t mMlIid[OT_IP6_IID_SIZE]; ///< IID from ML-EID + uint8_t mRole; ///< Current Thread role. + uint8_t mDeviceMode; ///< Device mode setting. + uint16_t mRloc16; ///< RLOC16 + uint32_t mKeySequence; ///< Key Sequence + uint32_t mMleFrameCounter; ///< MLE Frame Counter + uint32_t mMacFrameCounter; ///< MAC Frame Counter + uint32_t mPreviousPartitionId; ///< PartitionId + Mac::ExtAddress mExtAddress; ///< Extended Address + uint8_t mMlIid[OT_IP6_IID_SIZE]; ///< IID from ML-EID }; /** @@ -100,7 +100,7 @@ struct NetworkInfo */ struct ParentInfo { - Mac::ExtAddress mExtAddress; ///< Extended Address + Mac::ExtAddress mExtAddress; ///< Extended Address }; /** @@ -109,13 +109,13 @@ struct ParentInfo */ struct ChildInfo { - Mac::ExtAddress mExtAddress; ///< Extended Address - uint32_t mTimeout; ///< Timeout - uint16_t mRloc16; ///< RLOC16 - uint8_t mMode; ///< The MLE device mode + Mac::ExtAddress mExtAddress; ///< Extended Address + uint32_t mTimeout; ///< Timeout + uint16_t mRloc16; ///< RLOC16 + uint8_t mMode; ///< The MLE device mode }; -} // namespace Settings -} // namespace ot +} // namespace Settings +} // namespace ot -#endif // SETTINGS_HPP_ +#endif // SETTINGS_HPP_ diff --git a/src/core/common/tasklet.cpp b/src/core/common/tasklet.cpp index b0c152180..1e61e0921 100644 --- a/src/core/common/tasklet.cpp +++ b/src/core/common/tasklet.cpp @@ -42,11 +42,11 @@ namespace ot { -Tasklet::Tasklet(Instance &aInstance, Handler aHandler, void *aOwner): - InstanceLocator(aInstance), - OwnerLocator(aOwner), - mHandler(aHandler), - mNext(NULL) +Tasklet::Tasklet(Instance &aInstance, Handler aHandler, void *aOwner) + : InstanceLocator(aInstance) + , OwnerLocator(aOwner) + , mHandler(aHandler) + , mNext(NULL) { } @@ -55,9 +55,9 @@ otError Tasklet::Post(void) return GetInstance().GetTaskletScheduler().Post(*this); } -TaskletScheduler::TaskletScheduler(void): - mHead(NULL), - mTail(NULL) +TaskletScheduler::TaskletScheduler(void) + : mHead(NULL) + , mTail(NULL) { } @@ -78,7 +78,7 @@ otError TaskletScheduler::Post(Tasklet &aTasklet) else { mTail->mNext = &aTasklet; - mTail = &aTasklet; + mTail = &aTasklet; } exit: @@ -126,4 +126,4 @@ void TaskletScheduler::ProcessQueuedTasklets(void) } } -} // namespace ot +} // namespace ot diff --git a/src/core/common/tasklet.hpp b/src/core/common/tasklet.hpp index 5faa910cc..a9b96faab 100644 --- a/src/core/common/tasklet.hpp +++ b/src/core/common/tasklet.hpp @@ -60,7 +60,7 @@ class TaskletScheduler; * This class is used to represent a tasklet. * */ -class Tasklet: public InstanceLocator, public OwnerLocator +class Tasklet : public InstanceLocator, public OwnerLocator { friend class TaskletScheduler; @@ -92,8 +92,8 @@ public: private: void RunTask(void) { mHandler(*this); } - Handler mHandler; - Tasklet *mNext; + Handler mHandler; + Tasklet *mNext; }; /** @@ -145,6 +145,6 @@ private: * */ -} // namespace ot +} // namespace ot -#endif // TASKLET_HPP_ +#endif // TASKLET_HPP_ diff --git a/src/core/common/timer.cpp b/src/core/common/timer.cpp index 8cdfe5c96..d4a64c7b2 100644 --- a/src/core/common/timer.cpp +++ b/src/core/common/timer.cpp @@ -42,12 +42,8 @@ namespace ot { -const TimerScheduler::AlarmApi TimerMilliScheduler::sAlarmMilliApi = -{ - &otPlatAlarmMilliStartAt, - &otPlatAlarmMilliStop, - &otPlatAlarmMilliGetNow -}; +const TimerScheduler::AlarmApi TimerMilliScheduler::sAlarmMilliApi = {&otPlatAlarmMilliStartAt, &otPlatAlarmMilliStop, + &otPlatAlarmMilliGetNow}; bool Timer::DoesFireBefore(const Timer &aSecondTimer, uint32_t aNow) { @@ -96,7 +92,7 @@ void TimerScheduler::Add(Timer &aTimer, const AlarmApi &aAlarmApi) if (mHead == NULL) { - mHead = &aTimer; + mHead = &aTimer; aTimer.mNext = NULL; SetAlarm(aAlarmApi); } @@ -112,12 +108,12 @@ void TimerScheduler::Add(Timer &aTimer, const AlarmApi &aAlarmApi) if (prev) { aTimer.mNext = cur; - prev->mNext = &aTimer; + prev->mNext = &aTimer; } else { aTimer.mNext = mHead; - mHead = &aTimer; + mHead = &aTimer; SetAlarm(aAlarmApi); } @@ -129,7 +125,7 @@ void TimerScheduler::Add(Timer &aTimer, const AlarmApi &aAlarmApi) if (cur == NULL) { - prev->mNext = &aTimer; + prev->mNext = &aTimer; aTimer.mNext = NULL; } } @@ -170,7 +166,7 @@ void TimerScheduler::SetAlarm(const AlarmApi &aAlarmApi) } else { - uint32_t now = aAlarmApi.AlarmGetNow(); + uint32_t now = aAlarmApi.AlarmGetNow(); uint32_t remaining = IsStrictlyBefore(now, mHead->mFireTime) ? (mHead->mFireTime - now) : 0; aAlarmApi.AlarmStartAt(&GetInstance(), now, remaining); @@ -223,12 +219,8 @@ exit: } #if OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_TIMER -const TimerScheduler::AlarmApi TimerMicroScheduler::sAlarmMicroApi = -{ - &otPlatAlarmMicroStartAt, - &otPlatAlarmMicroStop, - &otPlatAlarmMicroGetNow -}; +const TimerScheduler::AlarmApi TimerMicroScheduler::sAlarmMicroApi = {&otPlatAlarmMicroStartAt, &otPlatAlarmMicroStop, + &otPlatAlarmMicroGetNow}; void TimerMicro::StartAt(uint32_t aT0, uint32_t aDt) { @@ -259,4 +251,4 @@ exit: } #endif // OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_TIMER -} // namespace ot +} // namespace ot diff --git a/src/core/common/timer.hpp b/src/core/common/timer.hpp index 9300089e5..568e6a9fc 100644 --- a/src/core/common/timer.hpp +++ b/src/core/common/timer.hpp @@ -65,15 +65,14 @@ class TimerMilliScheduler; * This class implements a timer. * */ -class Timer: public InstanceLocator, public OwnerLocator +class Timer : public InstanceLocator, public OwnerLocator { friend class TimerScheduler; public: - enum { - kMaxDt = (1UL << 31) - 1, //< Maximum permitted value for parameter `aDt` in `Start` and `StartAt` method. + kMaxDt = (1UL << 31) - 1, //< Maximum permitted value for parameter `aDt` in `Start` and `StartAt` method. }; /** @@ -92,12 +91,13 @@ public: * @param[in] aOwner A pointer to owner of the `Timer` object. * */ - Timer(Instance &aInstance, Handler aHandler, void *aOwner): - InstanceLocator(aInstance), - OwnerLocator(aOwner), - mHandler(aHandler), - mFireTime(0), - mNext(this) { + Timer(Instance &aInstance, Handler aHandler, void *aOwner) + : InstanceLocator(aInstance) + , OwnerLocator(aOwner) + , mHandler(aHandler) + , mFireTime(0) + , mNext(this) + { } /** @@ -132,16 +132,16 @@ protected: void Fired(void) { mHandler(*this); } - Handler mHandler; - uint32_t mFireTime; - Timer *mNext; + Handler mHandler; + uint32_t mFireTime; + Timer * mNext; }; /** * This class implements the millisecond timer. * */ -class TimerMilli: public Timer +class TimerMilli : public Timer { public: /** @@ -152,8 +152,9 @@ public: * @param[in] aOwner A pointer to the owner of the `TimerMilli` object. * */ - TimerMilli(Instance &aInstance, Handler aHandler, void *aOwner): - Timer(aInstance, aHandler, aOwner) { + TimerMilli(Instance &aInstance, Handler aHandler, void *aOwner) + : Timer(aInstance, aHandler, aOwner) + { } /** @@ -215,12 +216,11 @@ private: TimerMilliScheduler &GetTimerMilliScheduler(void) const; }; - /** * This class implements the base timer scheduler. * */ -class TimerScheduler: public InstanceLocator +class TimerScheduler : public InstanceLocator { friend class Timer; @@ -242,9 +242,10 @@ protected: * @param[in] aInstance A reference to the instance object. * */ - TimerScheduler(Instance &aInstance): - InstanceLocator(aInstance), - mHead(NULL) { + TimerScheduler(Instance &aInstance) + : InstanceLocator(aInstance) + , mHead(NULL) + { } /** @@ -303,7 +304,7 @@ protected: * This class implements the millisecond timer scheduler. * */ -class TimerMilliScheduler: public TimerScheduler +class TimerMilliScheduler : public TimerScheduler { public: /** @@ -312,8 +313,9 @@ public: * @param[in] aInstance A reference to the instance object. * */ - TimerMilliScheduler(Instance &aInstance): - TimerScheduler(aInstance) { + TimerMilliScheduler(Instance &aInstance) + : TimerScheduler(aInstance) + { } /** @@ -349,7 +351,7 @@ class TimerMicroScheduler; * This class implements the microsecond timer. * */ -class TimerMicro: public Timer +class TimerMicro : public Timer { public: /** @@ -360,8 +362,9 @@ public: * @param[in] aOwner A pointer to owner of the `TimerMicro` object. * */ - TimerMicro(Instance &aInstance, Handler aHandler, void *aOwner): - Timer(aInstance, aHandler, aOwner) { + TimerMicro(Instance &aInstance, Handler aHandler, void *aOwner) + : Timer(aInstance, aHandler, aOwner) + { } /** @@ -411,7 +414,7 @@ private: * This class implements the microsecond timer scheduler. * */ -class TimerMicroScheduler: public TimerScheduler +class TimerMicroScheduler : public TimerScheduler { public: /** @@ -420,8 +423,9 @@ public: * @param[in] aInstance A reference to the instance object. * */ - TimerMicroScheduler(Instance &aInstance): - TimerScheduler(aInstance) { + TimerMicroScheduler(Instance &aInstance) + : TimerScheduler(aInstance) + { } /** @@ -456,6 +460,6 @@ private: * */ -} // namespace ot +} // namespace ot -#endif // TIMER_HPP_ +#endif // TIMER_HPP_ diff --git a/src/core/common/tlvs.cpp b/src/core/common/tlvs.cpp index fb38ca927..49ac45419 100644 --- a/src/core/common/tlvs.cpp +++ b/src/core/common/tlvs.cpp @@ -40,7 +40,7 @@ namespace ot { otError Tlv::Get(const Message &aMessage, uint8_t aType, uint16_t aMaxLength, Tlv &aTlv) { - otError error = OT_ERROR_NOT_FOUND; + otError error = OT_ERROR_NOT_FOUND; uint16_t offset; SuccessOrExit(error = GetOffset(aMessage, aType, offset)); @@ -59,10 +59,10 @@ exit: otError Tlv::GetOffset(const Message &aMessage, uint8_t aType, uint16_t &aOffset) { - otError error = OT_ERROR_NOT_FOUND; + otError error = OT_ERROR_NOT_FOUND; uint16_t offset = aMessage.GetOffset(); - uint16_t end = aMessage.GetLength(); - Tlv tlv; + uint16_t end = aMessage.GetLength(); + Tlv tlv; while (offset + sizeof(tlv) <= end) { @@ -99,10 +99,10 @@ exit: otError Tlv::GetValueOffset(const Message &aMessage, uint8_t aType, uint16_t &aOffset, uint16_t &aLength) { - otError error = OT_ERROR_NOT_FOUND; + otError error = OT_ERROR_NOT_FOUND; uint16_t offset = aMessage.GetOffset(); - uint16_t end = aMessage.GetLength(); - Tlv tlv; + uint16_t end = aMessage.GetLength(); + Tlv tlv; while (offset + sizeof(tlv) <= end) { @@ -136,4 +136,4 @@ exit: return error; } -} // namespace ot +} // namespace ot diff --git a/src/core/common/tlvs.hpp b/src/core/common/tlvs.hpp index 32351c380..264edd2e2 100644 --- a/src/core/common/tlvs.hpp +++ b/src/core/common/tlvs.hpp @@ -60,9 +60,11 @@ public: * Default constructor. * */ - Tlv(void): - mType(0), - mLength(0) {} + Tlv(void) + : mType(0) + , mLength(0) + { + } /** * This method returns the Type value. @@ -126,9 +128,7 @@ public: * @returns A pointer to the next TLV. * */ - Tlv *GetNext(void) { - return reinterpret_cast(reinterpret_cast(this) + sizeof(*this) + mLength); - } + Tlv *GetNext(void) { return reinterpret_cast(reinterpret_cast(this) + sizeof(*this) + mLength); } /** * This method returns a pointer to the next TLV. @@ -136,7 +136,8 @@ public: * @returns A pointer to the next TLV. * */ - const Tlv *GetNext(void) const { + const Tlv *GetNext(void) const + { return reinterpret_cast(reinterpret_cast(this) + sizeof(*this) + mLength); } @@ -197,7 +198,7 @@ private: } OT_TOOL_PACKED_END; OT_TOOL_PACKED_BEGIN -class ExtendedTlv: public Tlv +class ExtendedTlv : public Tlv { public: /** @@ -212,12 +213,16 @@ public: * @param[in] aLength The Length value. * */ - void SetLength(uint16_t aLength) { Tlv::SetLength(kExtendedLength); mLength = HostSwap16(aLength); } + void SetLength(uint16_t aLength) + { + Tlv::SetLength(kExtendedLength); + mLength = HostSwap16(aLength); + } private: uint16_t mLength; } OT_TOOL_PACKED_END; -} // namespace ot +} // namespace ot -#endif // TLVS_HPP_ +#endif // TLVS_HPP_ diff --git a/src/core/common/trickle_timer.cpp b/src/core/common/trickle_timer.cpp index 9f1c33dfe..37d516b13 100644 --- a/src/core/common/trickle_timer.cpp +++ b/src/core/common/trickle_timer.cpp @@ -40,26 +40,28 @@ namespace ot { -TrickleTimer::TrickleTimer( - Instance &aInstance, +TrickleTimer::TrickleTimer(Instance &aInstance, #ifdef ENABLE_TRICKLE_TIMER_SUPPRESSION_SUPPORT - uint32_t aRedundancyConstant, + uint32_t aRedundancyConstant, #endif - Handler aTransmitHandler, Handler aIntervalExpiredHandler, void *aOwner) - : - TimerMilli(aInstance, HandleTimerFired, aOwner), + Handler aTransmitHandler, + Handler aIntervalExpiredHandler, + void * aOwner) + : TimerMilli(aInstance, HandleTimerFired, aOwner) + , #ifdef ENABLE_TRICKLE_TIMER_SUPPRESSION_SUPPORT - k(aRedundancyConstant), - c(0), + k(aRedundancyConstant) + , c(0) + , #endif - Imin(0), - Imax(0), - mMode(kModeNormal), - I(0), - t(0), - mPhase(kPhaseDormant), - mTransmitHandler(aTransmitHandler), - mIntervalExpiredHandler(aIntervalExpiredHandler) + Imin(0) + , Imax(0) + , mMode(kModeNormal) + , I(0) + , t(0) + , mPhase(kPhaseDormant) + , mTransmitHandler(aTransmitHandler) + , mIntervalExpiredHandler(aIntervalExpiredHandler) { } @@ -73,8 +75,8 @@ void TrickleTimer::Start(uint32_t aIntervalMin, uint32_t aIntervalMax, Mode aMod assert(!IsRunning()); // Set the interval limits and mode - Imin = aIntervalMin; - Imax = aIntervalMax; + Imin = aIntervalMin; + Imax = aIntervalMax; mMode = aMode; // Initialize I to [Imin, Imax] @@ -123,7 +125,7 @@ void TrickleTimer::IndicateInconsistent(void) void TrickleTimer::StartNewInterval(void) { - // Reset the counter and timer phase +// Reset the counter and timer phase #ifdef ENABLE_TRICKLE_TIMER_SUPPRESSION_SUPPORT c = 0; @@ -163,8 +165,8 @@ void TrickleTimer::HandleTimerFired(Timer &aTimer) void TrickleTimer::HandleTimerFired(void) { - Phase curPhase = mPhase; - bool shouldContinue = true; + Phase curPhase = mPhase; + bool shouldContinue = true; // Default the current state to Dormant mPhase = kPhaseDormant; @@ -174,7 +176,7 @@ void TrickleTimer::HandleTimerFired(void) // We have just reached time 't' case kPhaseTransmit: { - // Are we not using redundancy or is the counter still less than it? + // Are we not using redundancy or is the counter still less than it? #ifdef ENABLE_TRICKLE_TIMER_SUPPRESSION_SUPPORT if (k == 0 || c < k) #endif @@ -214,7 +216,10 @@ void TrickleTimer::HandleTimerFired(void) // Double 'I' to get the new interval length uint32_t newI = I == 0 ? 1 : I << 1; - if (newI > Imax) { newI = Imax; } + if (newI > Imax) + { + newI = Imax; + } I = newI; @@ -235,4 +240,4 @@ void TrickleTimer::HandleTimerFired(void) } } -} // namespace ot +} // namespace ot diff --git a/src/core/common/trickle_timer.hpp b/src/core/common/trickle_timer.hpp index e475ab909..df52faf37 100644 --- a/src/core/common/trickle_timer.hpp +++ b/src/core/common/trickle_timer.hpp @@ -54,18 +54,16 @@ namespace ot { * This class implements a trickle timer. * */ -class TrickleTimer: public TimerMilli +class TrickleTimer : public TimerMilli { public: - /** * Represents the modes of operation for the TrickleTimer */ - typedef enum Mode - { - kModeNormal = 0, ///< Runs the normal trickle logic. - kModePlainTimer = 1, ///< Runs a normal timer between Imin and Imax. - kModeMPL = 2, ///< Runs the trickle logic modified for MPL. + typedef enum Mode { + kModeNormal = 0, ///< Runs the normal trickle logic. + kModePlainTimer = 1, ///< Runs a normal timer between Imin and Imax. + kModeMPL = 2, ///< Runs the trickle logic modified for MPL. } Mode; /** @@ -92,7 +90,9 @@ public: #ifdef ENABLE_TRICKLE_TIMER_SUPPRESSION_SUPPORT uint32_t aRedundancyConstant, #endif - Handler aTransmitHandler, Handler aIntervalExpiredHandler, void *aOwner); + Handler aTransmitHandler, + Handler aIntervalExpiredHandler, + void * aOwner); /** * This method indicates whether or not the trickle timer instance is running. @@ -150,19 +150,18 @@ private: void StartNewInterval(void); static void HandleTimerFired(Timer &aTimer); - void HandleTimerFired(void); + void HandleTimerFired(void); // Shadow base class method to ensure it is hidden. - void StartAt(void) { } + void StartAt(void) {} - typedef enum Phase - { + typedef enum Phase { ///< Indicates we are currently not running - kPhaseDormant = 1, + kPhaseDormant = 1, ///< Indicates that when the timer expires, it should evaluate for transmit callbacks - kPhaseTransmit = 2, + kPhaseTransmit = 2, ///< Indicates that when the timer expires, it should process interval expiration callbacks - kPhaseInterval = 3, + kPhaseInterval = 3, } Phase; #ifdef ENABLE_TRICKLE_TIMER_SUPPRESSION_SUPPORT @@ -198,6 +197,6 @@ private: * */ -} // namespace ot +} // namespace ot -#endif // TRICKLE_TIMER_HPP_ +#endif // TRICKLE_TIMER_HPP_ diff --git a/src/core/crypto/aes_ccm.cpp b/src/core/crypto/aes_ccm.cpp index 4bb58c316..73c163c98 100644 --- a/src/core/crypto/aes_ccm.cpp +++ b/src/core/crypto/aes_ccm.cpp @@ -45,15 +45,18 @@ otError AesCcm::SetKey(const uint8_t *aKey, uint16_t aKeyLength) return OT_ERROR_NONE; } -otError AesCcm::Init(uint32_t aHeaderLength, uint32_t aPlainTextLength, uint8_t aTagLength, - const void *aNonce, uint8_t aNonceLength) +otError AesCcm::Init(uint32_t aHeaderLength, + uint32_t aPlainTextLength, + uint8_t aTagLength, + const void *aNonce, + uint8_t aNonceLength) { - const uint8_t *nonceBytes = reinterpret_cast(aNonce); - otError error = OT_ERROR_NONE; - uint8_t blockLength = 0; - uint32_t len; - uint8_t L; - uint8_t i; + const uint8_t *nonceBytes = reinterpret_cast(aNonce); + otError error = OT_ERROR_NONE; + uint8_t blockLength = 0; + uint32_t len; + uint8_t L; + uint8_t i; // aTagLength must be even aTagLength &= ~1; @@ -99,8 +102,7 @@ otError AesCcm::Init(uint32_t aHeaderLength, uint32_t aPlainTextLength, uint8_t // setup initial block // write flags - mBlock[0] = (static_cast((aHeaderLength != 0) << 6) | - static_cast(((aTagLength - 2) >> 1) << 3) | + mBlock[0] = (static_cast((aHeaderLength != 0) << 6) | static_cast(((aTagLength - 2) >> 1) << 3) | static_cast(L - 1)); // write nonce @@ -154,14 +156,14 @@ otError AesCcm::Init(uint32_t aHeaderLength, uint32_t aPlainTextLength, uint8_t mCtr[i] = 0; } - mNonceLength = aNonceLength; - mHeaderLength = aHeaderLength; - mHeaderCur = 0; + mNonceLength = aNonceLength; + mHeaderLength = aHeaderLength; + mHeaderCur = 0; mPlainTextLength = aPlainTextLength; - mPlainTextCur = 0; - mBlockLength = blockLength; - mCtrLength = sizeof(mCtrPad); - mTagLength = aTagLength; + mPlainTextCur = 0; + mBlockLength = blockLength; + mCtrLength = sizeof(mCtrPad); + mTagLength = aTagLength; exit: return error; @@ -201,9 +203,9 @@ void AesCcm::Header(const void *aHeader, uint32_t aHeaderLength) void AesCcm::Payload(void *plaintext, void *ciphertext, uint32_t len, bool aEncrypt) { - uint8_t *plaintextBytes = reinterpret_cast(plaintext); + uint8_t *plaintextBytes = reinterpret_cast(plaintext); uint8_t *ciphertextBytes = reinterpret_cast(ciphertext); - uint8_t byte; + uint8_t byte; assert(mPlainTextCur + len <= mPlainTextLength); @@ -225,12 +227,12 @@ void AesCcm::Payload(void *plaintext, void *ciphertext, uint32_t len, bool aEncr if (aEncrypt) { - byte = plaintextBytes[i]; + byte = plaintextBytes[i]; ciphertextBytes[i] = byte ^ mCtrPad[mCtrLength++]; } else { - byte = ciphertextBytes[i] ^ mCtrPad[mCtrLength++]; + byte = ciphertextBytes[i] ^ mCtrPad[mCtrLength++]; plaintextBytes[i] = byte; } @@ -282,5 +284,5 @@ void AesCcm::Finalize(void *tag, uint8_t *aTagLength) } } -} // namespace Crypto -} // namespace ot +} // namespace Crypto +} // namespace ot diff --git a/src/core/crypto/aes_ccm.hpp b/src/core/crypto/aes_ccm.hpp index 1fb093235..30142e04e 100644 --- a/src/core/crypto/aes_ccm.hpp +++ b/src/core/crypto/aes_ccm.hpp @@ -81,8 +81,11 @@ public: * @retval OT_ERROR_INVALID_ARGS Initialization failed. * */ - otError Init(uint32_t aHeaderLength, uint32_t aPlainTextLength, uint8_t aTagLength, - const void *aNonce, uint8_t aNonceLength); + otError Init(uint32_t aHeaderLength, + uint32_t aPlainTextLength, + uint8_t aTagLength, + const void *aNonce, + uint8_t aNonceLength); /** * This method processes the header. @@ -119,18 +122,18 @@ private: kTagLengthMin = 4, }; - AesEcb mEcb; - uint8_t mBlock[AesEcb::kBlockSize]; - uint8_t mCtr[AesEcb::kBlockSize]; - uint8_t mCtrPad[AesEcb::kBlockSize]; - uint8_t mNonceLength; + AesEcb mEcb; + uint8_t mBlock[AesEcb::kBlockSize]; + uint8_t mCtr[AesEcb::kBlockSize]; + uint8_t mCtrPad[AesEcb::kBlockSize]; + uint8_t mNonceLength; uint32_t mHeaderLength; uint32_t mHeaderCur; uint32_t mPlainTextLength; uint32_t mPlainTextCur; uint16_t mBlockLength; uint16_t mCtrLength; - uint8_t mTagLength; + uint8_t mTagLength; }; /** @@ -138,7 +141,7 @@ private: * */ -} // namespace Crypto -} // namespace ot +} // namespace Crypto +} // namespace ot -#endif // AES_CCM_HPP_ +#endif // AES_CCM_HPP_ diff --git a/src/core/crypto/aes_ecb.cpp b/src/core/crypto/aes_ecb.cpp index 7f3c4b487..2c252a05f 100644 --- a/src/core/crypto/aes_ecb.cpp +++ b/src/core/crypto/aes_ecb.cpp @@ -56,5 +56,5 @@ AesEcb::~AesEcb() mbedtls_aes_free(&mContext); } -} // namespace Crypto -} // namespace ot +} // namespace Crypto +} // namespace ot diff --git a/src/core/crypto/aes_ecb.hpp b/src/core/crypto/aes_ecb.hpp index 058d08438..1d86eccd0 100644 --- a/src/core/crypto/aes_ecb.hpp +++ b/src/core/crypto/aes_ecb.hpp @@ -57,7 +57,7 @@ class AesEcb public: enum { - kBlockSize = 16, ///< AES-128 block size (bytes). + kBlockSize = 16, ///< AES-128 block size (bytes). }; /** @@ -99,7 +99,7 @@ private: * */ -} // namespace Crypto -} // namespace ot +} // namespace Crypto +} // namespace ot -#endif // AES_ECB_HPP_ +#endif // AES_ECB_HPP_ diff --git a/src/core/crypto/heap.cpp b/src/core/crypto/heap.cpp index 29aed49d0..2538dad62 100644 --- a/src/core/crypto/heap.cpp +++ b/src/core/crypto/heap.cpp @@ -59,9 +59,9 @@ Heap::Heap(void) void *Heap::CAlloc(size_t aCount, size_t aSize) { - void *ret = NULL; - Block *prev = NULL; - Block *curr = NULL; + void * ret = NULL; + Block * prev = NULL; + Block * curr = NULL; uint16_t size = static_cast(aCount * aSize); VerifyOrExit(size); @@ -115,9 +115,7 @@ void Heap::BlockInsert(Block &aPrev, Block &aBlock) { Block *prev = &aPrev; - for (Block *block = &BlockNext(*prev); - block->GetSize() < aBlock.GetSize(); - block = &BlockNext(*block)) + for (Block *block = &BlockNext(*prev); block->GetSize() < aBlock.GetSize(); block = &BlockNext(*block)) { prev = block; } @@ -166,7 +164,8 @@ void Heap::Free(void *aPointer) { if (right.GetSize() > left->GetSize()) { - for (const uint16_t offset = BlockOffset(right); prev->GetNext() != offset; prev = &BlockNext(*prev)); + for (const uint16_t offset = BlockOffset(right); prev->GetNext() != offset; prev = &BlockNext(*prev)) + ; } else { @@ -192,7 +191,7 @@ void Heap::Free(void *aPointer) { Block &prev = BlockPrev(right); prev.SetNext(right.GetNext()); - block.SetSize(block.GetSize() + right.GetSize() + sizeof(Block)); + block.SetSize(block.GetSize() + right.GetSize() + sizeof(Block)); BlockInsert(prev, block); } else @@ -202,6 +201,5 @@ void Heap::Free(void *aPointer) } } -} // namespace Crypto -} // namespace ot - +} // namespace Crypto +} // namespace ot diff --git a/src/core/crypto/heap.hpp b/src/core/crypto/heap.hpp index 2279c40dd..f268ce3b4 100644 --- a/src/core/crypto/heap.hpp +++ b/src/core/crypto/heap.hpp @@ -44,7 +44,6 @@ namespace ot { namespace Crypto { - /** * This class represents a memory block. * @@ -71,9 +70,7 @@ public: * @returns Size of this block. * */ - uint16_t GetSize(void) const { - return mSize; - } + uint16_t GetSize(void) const { return mSize; } /** * This method updates the size of this block. @@ -81,9 +78,7 @@ public: * @param[in] aSize Size of this block in bytes. * */ - void SetSize(uint16_t aSize) { - mSize = aSize; - } + void SetSize(uint16_t aSize) { mSize = aSize; } /** * This method returns the offset of the free block after this block. @@ -95,7 +90,8 @@ public: * @retval 0 This block is not free. * */ - uint16_t GetNext(void) const { + uint16_t GetNext(void) const + { return *reinterpret_cast(reinterpret_cast(this) + sizeof(mSize) + mSize); } @@ -107,7 +103,8 @@ public: * @param[in] aNext Offset of the next free block in bytes. * */ - void SetNext(uint16_t aNext) { + void SetNext(uint16_t aNext) + { *reinterpret_cast(reinterpret_cast(this) + sizeof(mSize) + mSize) = aNext; } @@ -117,9 +114,7 @@ public: * @retval Pointer to the user memory. The pointer address is aligned to sizeof(long). * */ - void *GetPointer(void) { - return &mMemory; - } + void *GetPointer(void) { return &mMemory; } /** * This method returns the offset of the free block after the left neighbor block. @@ -127,9 +122,7 @@ public: * @returns Offset in bytes. * */ - uint16_t GetLeftNext(void) const { - return *(&mSize - 1); - } + uint16_t GetLeftNext(void) const { return *(&mSize - 1); } /** * This method returns whether the left neighbor block is a free block. @@ -138,9 +131,7 @@ public: * @retval false The left neighbor block is not free. * */ - bool IsLeftFree(void) const { - return GetLeftNext() != 0; - } + bool IsLeftFree(void) const { return GetLeftNext() != 0; } /** * This method returns whether the current block is a free block. @@ -149,9 +140,7 @@ public: * @retval false The block is not free. * */ - bool IsFree(void) const { - return mSize != kGuardBlockSize && GetNext() != 0; - } + bool IsFree(void) const { return mSize != kGuardBlockSize && GetNext() != 0; } private: enum @@ -166,7 +155,7 @@ private: * structure is equal to size of block metadata, i.e. sizeof(mSize) + sizeof(mNext) * */ - uint8_t mMemory[sizeof(uint16_t)]; + uint8_t mMemory[sizeof(uint16_t)]; }; /** @@ -217,7 +206,8 @@ public: * This method returns whether the heap is clean. * */ - bool IsClean(void) { + bool IsClean(void) + { const Block &super = BlockSuper(); const Block &first = BlockRight(super); return super.GetNext() == BlockOffset(first) && first.GetSize() == kFirstBlockSize; @@ -227,26 +217,23 @@ public: * This method returns the capacity of this heap. * */ - size_t GetCapacity(void) const { - return kFirstBlockSize; - } + size_t GetCapacity(void) const { return kFirstBlockSize; } private: enum { #if OPENTHREAD_ENABLE_DTLS - kMemorySize = OPENTHREAD_CONFIG_MBEDTLS_HEAP_SIZE, ///< Size of memory buffer (bytes). + kMemorySize = OPENTHREAD_CONFIG_MBEDTLS_HEAP_SIZE, ///< Size of memory buffer (bytes). #else - kMemorySize = OPENTHREAD_CONFIG_MBEDTLS_HEAP_SIZE_NO_DTLS, ///< Size of memory buffer (bytes). + kMemorySize = OPENTHREAD_CONFIG_MBEDTLS_HEAP_SIZE_NO_DTLS, ///< Size of memory buffer (bytes). #endif - kAlignSize = sizeof(long), ///< The alignment size. - kBlockRemainderSize = kAlignSize - sizeof(uint16_t) * 2, ///< Block unit remainder size. - kSuperBlockSize = kAlignSize - sizeof(Block), ///< Super block size. - kFirstBlockSize = kMemorySize - kAlignSize * 3 + - kBlockRemainderSize, ///< First block size. - kSuperBlockOffset = kAlignSize - sizeof(uint16_t), ///< Offset of the super block. - kFirstBlockOffset = kAlignSize * 2 - sizeof(uint16_t), ///< Offset of the first block. - kGuardBlockOffset = kMemorySize - sizeof(uint16_t), ///< Offset of the guard block. + kAlignSize = sizeof(long), ///< The alignment size. + kBlockRemainderSize = kAlignSize - sizeof(uint16_t) * 2, ///< Block unit remainder size. + kSuperBlockSize = kAlignSize - sizeof(Block), ///< Super block size. + kFirstBlockSize = kMemorySize - kAlignSize * 3 + kBlockRemainderSize, ///< First block size. + kSuperBlockOffset = kAlignSize - sizeof(uint16_t), ///< Offset of the super block. + kFirstBlockOffset = kAlignSize * 2 - sizeof(uint16_t), ///< Offset of the first block. + kGuardBlockOffset = kMemorySize - sizeof(uint16_t), ///< Offset of the guard block. }; /** @@ -257,9 +244,7 @@ private: * @returns A reference to the block. * */ - Block &BlockAt(uint16_t aOffset) { - return *reinterpret_cast(&mMemory.m16[aOffset / 2]); - } + Block &BlockAt(uint16_t aOffset) { return *reinterpret_cast(&mMemory.m16[aOffset / 2]); } /** * This method returns the block of @p aPointer. @@ -269,7 +254,8 @@ private: * @returns A reference to the block. * */ - Block &BlockOf(void *aPointer) { + Block &BlockOf(void *aPointer) + { uint16_t offset = static_cast(reinterpret_cast(aPointer) - mMemory.m8); offset -= sizeof(uint16_t); return BlockAt(offset); @@ -281,9 +267,7 @@ private: * @returns Reference to the super block. * */ - Block &BlockSuper(void) { - return BlockAt(kSuperBlockOffset); - } + Block &BlockSuper(void) { return BlockAt(kSuperBlockOffset); } /** * This method returns the free block after @p aBlock in the free block list. @@ -293,9 +277,7 @@ private: * @returns Reference to the free block after this block. * */ - Block &BlockNext(const Block &aBlock) { - return BlockAt(aBlock.GetNext()); - } + Block &BlockNext(const Block &aBlock) { return BlockAt(aBlock.GetNext()); } /** * This method returns the block on the right side of @p aBlock. @@ -305,9 +287,7 @@ private: * @returns Reference to the block on the right side. * */ - Block &BlockRight(const Block &aBlock) { - return BlockAt(BlockOffset(aBlock) + sizeof(Block) + aBlock.GetSize()); - } + Block &BlockRight(const Block &aBlock) { return BlockAt(BlockOffset(aBlock) + sizeof(Block) + aBlock.GetSize()); } /** * This method returns the free block before @p aBlock in the free block list. @@ -323,9 +303,7 @@ private: * @param[in] aBlock A reference to the block. * */ - bool IsLeftFree(const Block &aBlock) { - return (BlockOffset(aBlock) != kFirstBlockOffset && aBlock.IsLeftFree()); - } + bool IsLeftFree(const Block &aBlock) { return (BlockOffset(aBlock) != kFirstBlockOffset && aBlock.IsLeftFree()); } /** * This method returns the offset of @p aBlock. @@ -335,7 +313,8 @@ private: * @returns Offset in bytes of @p aBlock. * */ - uint16_t BlockOffset(const Block &aBlock) { + uint16_t BlockOffset(const Block &aBlock) + { return static_cast(reinterpret_cast(&aBlock) - mMemory.m8); } @@ -353,13 +332,13 @@ private: union { // Make sure memory is long aligned. - long mLong[kMemorySize / sizeof(long)]; - uint8_t m8[kMemorySize]; + long mLong[kMemorySize / sizeof(long)]; + uint8_t m8[kMemorySize]; uint16_t m16[kMemorySize / sizeof(uint16_t)]; } mMemory; }; -} // namespace Crypto -} // namespace ot +} // namespace Crypto +} // namespace ot #endif // OT_HEAP_HPP_ diff --git a/src/core/crypto/hmac_sha256.cpp b/src/core/crypto/hmac_sha256.cpp index f2c81bdd8..17358b548 100644 --- a/src/core/crypto/hmac_sha256.cpp +++ b/src/core/crypto/hmac_sha256.cpp @@ -64,5 +64,5 @@ void HmacSha256::Finish(uint8_t aHash[kHashSize]) mbedtls_md_hmac_finish(&mContext, aHash); } -} // namespace Crypto -} // namespace ot +} // namespace Crypto +} // namespace ot diff --git a/src/core/crypto/hmac_sha256.hpp b/src/core/crypto/hmac_sha256.hpp index 7d8ed8646..f9e2185b4 100644 --- a/src/core/crypto/hmac_sha256.hpp +++ b/src/core/crypto/hmac_sha256.hpp @@ -59,7 +59,7 @@ class HmacSha256 public: enum { - kHashSize = 32, ///< SHA-256 hash size (bytes) + kHashSize = 32, ///< SHA-256 hash size (bytes) }; /** @@ -109,7 +109,7 @@ private: * */ -} // namespace Crypto -} // namespace ot +} // namespace Crypto +} // namespace ot -#endif // HMAC_SHA256_HPP_ +#endif // HMAC_SHA256_HPP_ diff --git a/src/core/crypto/mbedtls.cpp b/src/core/crypto/mbedtls.cpp index 21f40be53..8db43c5b5 100644 --- a/src/core/crypto/mbedtls.cpp +++ b/src/core/crypto/mbedtls.cpp @@ -58,7 +58,7 @@ MbedTls::MbedTls(void) mbedtls_platform_set_calloc_free(CAlloc, Free); } -} // namespace Crypto -} // namespace ot +} // namespace Crypto +} // namespace ot #endif // #if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES diff --git a/src/core/crypto/mbedtls.hpp b/src/core/crypto/mbedtls.hpp index 8535aa235..3cb33f4fd 100644 --- a/src/core/crypto/mbedtls.hpp +++ b/src/core/crypto/mbedtls.hpp @@ -67,9 +67,9 @@ public: * */ -} // namespace Crypto -} // namespace ot +} // namespace Crypto +} // namespace ot #endif // #if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES -#endif // OT_MBEDTLS_HPP_ +#endif // OT_MBEDTLS_HPP_ diff --git a/src/core/crypto/pbkdf2_cmac.cpp b/src/core/crypto/pbkdf2_cmac.cpp index 8ad97510c..205fd727a 100644 --- a/src/core/crypto/pbkdf2_cmac.cpp +++ b/src/core/crypto/pbkdf2_cmac.cpp @@ -40,21 +40,23 @@ #if OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD -void otPbkdf2Cmac( - const uint8_t *aPassword, uint16_t aPasswordLen, - const uint8_t *aSalt, uint16_t aSaltLen, - uint32_t aIterationCounter, uint16_t aKeyLen, - uint8_t *aKey) +void otPbkdf2Cmac(const uint8_t *aPassword, + uint16_t aPasswordLen, + const uint8_t *aSalt, + uint16_t aSaltLen, + uint32_t aIterationCounter, + uint16_t aKeyLen, + uint8_t * aKey) { const size_t kBlockSize = MBEDTLS_CIPHER_BLKSIZE_MAX; - uint8_t prfInput[OT_PBKDF2_SALT_MAX_LEN + 4]; // Salt || INT(), for U1 calculation - long prfOne[kBlockSize / sizeof(long)]; - long prfTwo[kBlockSize / sizeof(long)]; - long keyBlock[kBlockSize / sizeof(long)]; - uint32_t blockCounter = 0; - uint8_t *key = aKey; - uint16_t keyLen = aKeyLen; - uint16_t useLen = 0; + uint8_t prfInput[OT_PBKDF2_SALT_MAX_LEN + 4]; // Salt || INT(), for U1 calculation + long prfOne[kBlockSize / sizeof(long)]; + long prfTwo[kBlockSize / sizeof(long)]; + long keyBlock[kBlockSize / sizeof(long)]; + uint32_t blockCounter = 0; + uint8_t * key = aKey; + uint16_t keyLen = aKeyLen; + uint16_t useLen = 0; memcpy(prfInput, aSalt, aSaltLen); assert(aIterationCounter % 2 == 0); @@ -73,8 +75,8 @@ void otPbkdf2Cmac( reinterpret_cast(keyBlock)); // Calculate U_2 - mbedtls_aes_cmac_prf_128(aPassword, aPasswordLen, reinterpret_cast(keyBlock), - kBlockSize, reinterpret_cast(prfOne)); + mbedtls_aes_cmac_prf_128(aPassword, aPasswordLen, reinterpret_cast(keyBlock), kBlockSize, + reinterpret_cast(prfOne)); for (uint32_t j = 0; j < kBlockSize / sizeof(long); ++j) { @@ -84,11 +86,11 @@ void otPbkdf2Cmac( for (uint32_t i = 1; i < aIterationCounter; ++i) { // Calculate U_{2 * i - 1} - mbedtls_aes_cmac_prf_128(aPassword, aPasswordLen, reinterpret_cast(prfOne), - kBlockSize, reinterpret_cast(prfTwo)); + mbedtls_aes_cmac_prf_128(aPassword, aPasswordLen, reinterpret_cast(prfOne), kBlockSize, + reinterpret_cast(prfTwo)); // Calculate U_{2 * i} - mbedtls_aes_cmac_prf_128(aPassword, aPasswordLen, reinterpret_cast(prfTwo), - kBlockSize, reinterpret_cast(prfOne)); + mbedtls_aes_cmac_prf_128(aPassword, aPasswordLen, reinterpret_cast(prfTwo), kBlockSize, + reinterpret_cast(prfOne)); for (uint32_t j = 0; j < kBlockSize / sizeof(long); ++j) { diff --git a/src/core/crypto/pbkdf2_cmac.h b/src/core/crypto/pbkdf2_cmac.h index 0d59ac133..cbf73ee1c 100644 --- a/src/core/crypto/pbkdf2_cmac.h +++ b/src/core/crypto/pbkdf2_cmac.h @@ -44,7 +44,7 @@ extern "C" { #endif -#define OT_PBKDF2_SALT_MAX_LEN 30 // salt prefix (6) + extended panid (8) + network name (16) +#define OT_PBKDF2_SALT_MAX_LEN 30 // salt prefix (6) + extended panid (8) + network name (16) /** * This method perform PKCS#5 PBKDF2 using CMAC (AES-CMAC-PRF-128). @@ -58,14 +58,16 @@ extern "C" { * @param[out] aKey A pointer to the generated key. * */ -void otPbkdf2Cmac( - const uint8_t *aPassword, uint16_t aPasswordLen, - const uint8_t *aSalt, uint16_t aSaltLen, - uint32_t aIterationCounter, uint16_t aKeyLen, - uint8_t *aKey); +void otPbkdf2Cmac(const uint8_t *aPassword, + uint16_t aPasswordLen, + const uint8_t *aSalt, + uint16_t aSaltLen, + uint32_t aIterationCounter, + uint16_t aKeyLen, + uint8_t * aKey); #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // PBKDF2_CMAC_H_ +#endif // PBKDF2_CMAC_H_ diff --git a/src/core/crypto/sha256.cpp b/src/core/crypto/sha256.cpp index a61f780a9..7941190fd 100644 --- a/src/core/crypto/sha256.cpp +++ b/src/core/crypto/sha256.cpp @@ -61,5 +61,5 @@ void Sha256::Finish(uint8_t aHash[kHashSize]) mbedtls_sha256_finish(&mContext, aHash); } -} // namespace Crypto -} // namespace ot +} // namespace Crypto +} // namespace ot diff --git a/src/core/crypto/sha256.hpp b/src/core/crypto/sha256.hpp index 6431dd74a..a8681db4f 100644 --- a/src/core/crypto/sha256.hpp +++ b/src/core/crypto/sha256.hpp @@ -59,7 +59,7 @@ class Sha256 public: enum { - kHashSize = 32, ///< SHA-256 hash size (bytes) + kHashSize = 32, ///< SHA-256 hash size (bytes) }; /** @@ -106,7 +106,7 @@ private: * */ -} // namespace Crypto -} // namespace ot +} // namespace Crypto +} // namespace ot -#endif // SHA256_HPP_ +#endif // SHA256_HPP_ diff --git a/src/core/mac/mac.cpp b/src/core/mac/mac.cpp index 22be25cab..800cf5b6d 100644 --- a/src/core/mac/mac.cpp +++ b/src/core/mac/mac.cpp @@ -57,70 +57,72 @@ using ot::Encoding::BigEndian::HostSwap64; namespace ot { namespace Mac { -static const uint8_t sMode2Key[] = -{ - 0x78, 0x58, 0x16, 0x86, 0xfd, 0xb4, 0x58, 0x0f, 0xb0, 0x92, 0x54, 0x6a, 0xec, 0xbd, 0x15, 0x66 -}; +static const uint8_t sMode2Key[] = {0x78, 0x58, 0x16, 0x86, 0xfd, 0xb4, 0x58, 0x0f, + 0xb0, 0x92, 0x54, 0x6a, 0xec, 0xbd, 0x15, 0x66}; -static const otExtAddress sMode2ExtAddress = -{ - { 0x35, 0x06, 0xfe, 0xb8, 0x23, 0xd4, 0x87, 0x12 }, +static const otExtAddress sMode2ExtAddress = { + {0x35, 0x06, 0xfe, 0xb8, 0x23, 0xd4, 0x87, 0x12}, }; static const uint8_t sExtendedPanidInit[] = {0xde, 0xad, 0x00, 0xbe, 0xef, 0x00, 0xca, 0xfe}; -static const char sNetworkNameInit[] = "OpenThread"; +static const char sNetworkNameInit[] = "OpenThread"; #ifdef _WIN32 -const uint32_t kMinBackoffSum = kMinBackoff + (kUnitBackoffPeriod *OT_RADIO_SYMBOL_TIME * (1 << kMinBE)) / 1000; -const uint32_t kMaxBackoffSum = kMinBackoff + (kUnitBackoffPeriod *OT_RADIO_SYMBOL_TIME * (1 << kMaxBE)) / 1000; +const uint32_t kMinBackoffSum = kMinBackoff + (kUnitBackoffPeriod * OT_RADIO_SYMBOL_TIME * (1 << kMinBE)) / 1000; +const uint32_t kMaxBackoffSum = kMinBackoff + (kUnitBackoffPeriod * OT_RADIO_SYMBOL_TIME * (1 << kMaxBE)) / 1000; static_assert(kMinBackoffSum > 0, "The min backoff value should be greater than zero!"); #endif -Mac::Mac(Instance &aInstance): - InstanceLocator(aInstance), - mOperation(kOperationIdle), - mPendingActiveScan(false), - mPendingEnergyScan(false), - mPendingTransmitBeacon(false), - mPendingTransmitData(false), - mPendingTransmitOobFrame(false), - mPendingWaitingForData(false), - mRxOnWhenIdle(false), - mBeaconsEnabled(false), +Mac::Mac(Instance &aInstance) + : InstanceLocator(aInstance) + , mOperation(kOperationIdle) + , mPendingActiveScan(false) + , mPendingEnergyScan(false) + , mPendingTransmitBeacon(false) + , mPendingTransmitData(false) + , mPendingTransmitOobFrame(false) + , mPendingWaitingForData(false) + , mRxOnWhenIdle(false) + , mBeaconsEnabled(false) + , #if OPENTHREAD_CONFIG_STAY_AWAKE_BETWEEN_FRAGMENTS - mDelaySleep(false), + mDelaySleep(false) + , #endif - mOperationTask(aInstance, &Mac::PerformOperation, this), - mMacTimer(aInstance, &Mac::HandleMacTimer, this), - mBackoffTimer(aInstance, &Mac::HandleBackoffTimer, this), - mReceiveTimer(aInstance, &Mac::HandleReceiveTimer, this), - mShortAddress(kShortAddrInvalid), - mPanId(kPanIdBroadcast), - mChannel(OPENTHREAD_CONFIG_DEFAULT_CHANNEL), - mSendHead(NULL), - mSendTail(NULL), - mReceiveHead(NULL), - mReceiveTail(NULL), - mBeaconSequence(static_cast(otPlatRandomGet())), - mDataSequence(static_cast(otPlatRandomGet())), - mCsmaAttempts(0), - mTransmitAttempts(0), - mScanChannels(0xff), - mScanDuration(0), - mScanChannel(OT_RADIO_CHANNEL_MIN), - mEnergyScanCurrentMaxRssi(kInvalidRssiValue), - mScanContext(NULL), - mActiveScanHandler(NULL), // Initialize `mActiveScanHandler` and `mEnergyScanHandler` union - mPcapCallback(NULL), - mPcapCallbackContext(NULL), + mOperationTask(aInstance, &Mac::PerformOperation, this) + , mMacTimer(aInstance, &Mac::HandleMacTimer, this) + , mBackoffTimer(aInstance, &Mac::HandleBackoffTimer, this) + , mReceiveTimer(aInstance, &Mac::HandleReceiveTimer, this) + , mShortAddress(kShortAddrInvalid) + , mPanId(kPanIdBroadcast) + , mChannel(OPENTHREAD_CONFIG_DEFAULT_CHANNEL) + , mSendHead(NULL) + , mSendTail(NULL) + , mReceiveHead(NULL) + , mReceiveTail(NULL) + , mBeaconSequence(static_cast(otPlatRandomGet())) + , mDataSequence(static_cast(otPlatRandomGet())) + , mCsmaAttempts(0) + , mTransmitAttempts(0) + , mScanChannels(0xff) + , mScanDuration(0) + , mScanChannel(OT_RADIO_CHANNEL_MIN) + , mEnergyScanCurrentMaxRssi(kInvalidRssiValue) + , mScanContext(NULL) + , mActiveScanHandler(NULL) + , // Initialize `mActiveScanHandler` and `mEnergyScanHandler` union + mPcapCallback(NULL) + , mPcapCallbackContext(NULL) + , #if OPENTHREAD_ENABLE_MAC_FILTER - mFilter(), -#endif // OPENTHREAD_ENABLE_MAC_FILTER - mTxFrame(static_cast(otPlatRadioGetTransmitBuffer(&aInstance))), - mOobFrame(NULL), - mKeyIdMode2FrameCounter(0), - mCcaSuccessRateTracker(), - mCcaSampleCount(0) + mFilter() + , +#endif // OPENTHREAD_ENABLE_MAC_FILTER + mTxFrame(static_cast(otPlatRadioGetTransmitBuffer(&aInstance))) + , mOobFrame(NULL) + , mKeyIdMode2FrameCounter(0) + , mCcaSuccessRateTracker() + , mCcaSampleCount(0) { GenerateExtAddress(&mExtAddress); @@ -169,10 +171,10 @@ exit: void Mac::Scan(Operation aScanOperation, uint32_t aScanChannels, uint16_t aScanDuration, void *aContext) { - mScanContext = aContext; + mScanContext = aContext; mScanDuration = aScanDuration; mScanChannels = (aScanChannels == 0) ? static_cast(kScanChannelsAll) : aScanChannels; - mScanChannel = OT_RADIO_CHANNEL_MIN - 1; + mScanChannel = OT_RADIO_CHANNEL_MIN - 1; StartOperation(aScanOperation); } @@ -188,18 +190,18 @@ bool Mac::IsEnergyScanInProgress(void) bool Mac::IsInTransmitState(void) { - return (mOperation == kOperationTransmitData) || - (mOperation == kOperationTransmitBeacon) || (mOperation == kOperationTransmitOutOfBandFrame); + return (mOperation == kOperationTransmitData) || (mOperation == kOperationTransmitBeacon) || + (mOperation == kOperationTransmitOutOfBandFrame); } otError Mac::ConvertBeaconToActiveScanResult(Frame *aBeaconFrame, otActiveScanResult &aResult) { - otError error = OT_ERROR_NONE; - Address address; - Beacon *beacon = NULL; + otError error = OT_ERROR_NONE; + Address address; + Beacon * beacon = NULL; BeaconPayload *beaconPayload = NULL; - uint8_t payloadLength; - char stringBuffer[BeaconPayload::kInfoStringSize]; + uint8_t payloadLength; + char stringBuffer[BeaconPayload::kInfoStringSize]; memset(&aResult, 0, sizeof(otActiveScanResult)); @@ -212,19 +214,19 @@ otError Mac::ConvertBeaconToActiveScanResult(Frame *aBeaconFrame, otActiveScanRe aBeaconFrame->GetSrcPanId(aResult.mPanId); aResult.mChannel = aBeaconFrame->GetChannel(); - aResult.mRssi = aBeaconFrame->GetRssi(); - aResult.mLqi = aBeaconFrame->GetLqi(); + aResult.mRssi = aBeaconFrame->GetRssi(); + aResult.mLqi = aBeaconFrame->GetLqi(); payloadLength = aBeaconFrame->GetPayloadLength(); - beacon = reinterpret_cast(aBeaconFrame->GetPayload()); + beacon = reinterpret_cast(aBeaconFrame->GetPayload()); beaconPayload = reinterpret_cast(beacon->GetPayload()); if ((payloadLength >= (sizeof(*beacon) + sizeof(*beaconPayload))) && beacon->IsValid() && beaconPayload->IsValid()) { - aResult.mVersion = beaconPayload->GetProtocolVersion(); + aResult.mVersion = beaconPayload->GetProtocolVersion(); aResult.mIsJoinable = beaconPayload->IsJoiningPermitted(); - aResult.mIsNative = beaconPayload->IsNative(); + aResult.mIsNative = beaconPayload->IsNative(); memcpy(&aResult.mNetworkName, beaconPayload->GetNetworkName(), sizeof(aResult.mNetworkName)); memcpy(&aResult.mExtendedPanId, beaconPayload->GetExtendedPanId(), sizeof(aResult.mExtendedPanId)); } @@ -246,8 +248,7 @@ otError Mac::UpdateScanChannel(void) mScanChannel++; VerifyOrExit(mScanChannel <= OT_RADIO_CHANNEL_MAX, error = OT_ERROR_NOT_FOUND); - } - while ((mScanChannels & (1U << mScanChannel)) == 0); + } while ((mScanChannels & (1U << mScanChannel)) == 0); exit: return error; @@ -376,7 +377,7 @@ otError Mac::RegisterReceiver(Receiver &aReceiver) else { mReceiveTail->mNext = &aReceiver; - mReceiveTail = &aReceiver; + mReceiveTail = &aReceiver; } return OT_ERROR_NONE; @@ -494,7 +495,7 @@ otError Mac::SendFrameRequest(Sender &aSender) else { mSendTail->mNext = &aSender; - mSendTail = &aSender; + mSendTail = &aSender; } StartOperation(kOperationTransmitData); @@ -600,37 +601,37 @@ void Mac::PerformOperation(void) if (mPendingWaitingForData) { mPendingWaitingForData = false; - mOperation = kOperationWaitingForData; + mOperation = kOperationWaitingForData; RadioReceive(mChannel); } else if (mPendingTransmitOobFrame) { mPendingTransmitOobFrame = false; - mOperation = kOperationTransmitOutOfBandFrame; + mOperation = kOperationTransmitOutOfBandFrame; StartCsmaBackoff(); } else if (mPendingActiveScan) { mPendingActiveScan = false; - mOperation = kOperationActiveScan; + mOperation = kOperationActiveScan; PerformActiveScan(); } else if (mPendingEnergyScan) { mPendingEnergyScan = false; - mOperation = kOperationEnergyScan; + mOperation = kOperationEnergyScan; PerformEnergyScan(); } else if (mPendingTransmitBeacon) { mPendingTransmitBeacon = false; - mOperation = kOperationTransmitBeacon; + mOperation = kOperationTransmitBeacon; StartCsmaBackoff(); } else if (mPendingTransmitData) { mPendingTransmitData = false; - mOperation = kOperationTransmitData; + mOperation = kOperationTransmitData; StartCsmaBackoff(); } else @@ -697,12 +698,12 @@ void Mac::SendBeaconRequest(Frame &aFrame) void Mac::SendBeacon(Frame &aFrame) { - uint8_t numUnsecurePorts; - uint8_t beaconLength; - uint16_t fcf; - Beacon *beacon = NULL; + uint8_t numUnsecurePorts; + uint8_t beaconLength; + uint16_t fcf; + Beacon * beacon = NULL; BeaconPayload *beaconPayload = NULL; - char stringBuffer[BeaconPayload::kInfoStringSize]; + char stringBuffer[BeaconPayload::kInfoStringSize]; // initialize MAC header fcf = Frame::kFcfFrameBeacon | Frame::kFcfDstAddrNone | Frame::kFcfSrcAddrExt; @@ -748,16 +749,16 @@ void Mac::SendBeacon(Frame &aFrame) void Mac::ProcessTransmitSecurity(Frame &aFrame) { - KeyManager &keyManager = GetNetif().GetKeyManager(); - uint32_t frameCounter = 0; - uint8_t securityLevel; - uint8_t keyIdMode; - uint8_t nonce[kNonceSize]; - uint8_t tagLength; - Crypto::AesCcm aesCcm; - const uint8_t *key = NULL; + KeyManager & keyManager = GetNetif().GetKeyManager(); + uint32_t frameCounter = 0; + uint8_t securityLevel; + uint8_t keyIdMode; + uint8_t nonce[kNonceSize]; + uint8_t tagLength; + Crypto::AesCcm aesCcm; + const uint8_t * key = NULL; const ExtAddress *extAddress = NULL; - otError error; + otError error; if (aFrame.GetSecurityEnabled() == false) { @@ -769,7 +770,7 @@ void Mac::ProcessTransmitSecurity(Frame &aFrame) switch (keyIdMode) { case Frame::kKeyIdMode0: - key = keyManager.GetKek(); + key = keyManager.GetKek(); extAddress = &mExtAddress; if (!aFrame.IsARetransmission()) @@ -781,7 +782,7 @@ void Mac::ProcessTransmitSecurity(Frame &aFrame) break; case Frame::kKeyIdMode1: - key = keyManager.GetCurrentMacKey(); + key = keyManager.GetCurrentMacKey(); extAddress = &mExtAddress; // If the frame is marked as a retransmission, the `Mac::Sender` which @@ -802,7 +803,7 @@ void Mac::ProcessTransmitSecurity(Frame &aFrame) case Frame::kKeyIdMode2: { const uint8_t keySource[] = {0xff, 0xff, 0xff, 0xff}; - key = sMode2Key; + key = sMode2Key; mKeyIdMode2FrameCounter++; aFrame.SetFrameCounter(mKeyIdMode2FrameCounter); aFrame.SetKeySource(keySource); @@ -846,7 +847,7 @@ void Mac::StartCsmaBackoff(void) { uint32_t backoffExponent = kMinBE + mTransmitAttempts + mCsmaAttempts; uint32_t backoff; - bool shouldReceive; + bool shouldReceive; if (backoffExponent > kMaxBE) { @@ -890,7 +891,7 @@ void Mac::StartCsmaBackoff(void) #if OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_TIMER mBackoffTimer.Start(backoff); -#else // OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_TIMER +#else // OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_TIMER mBackoffTimer.Start(backoff / 1000UL); #endif // OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_TIMER } @@ -942,9 +943,9 @@ Frame *Mac::GetOperationFrame(void) void Mac::BeginTransmit(void) { - otError error = OT_ERROR_NONE; - bool applyTransmitSecurity = true; - Frame &sendFrame(*GetOperationFrame()); + otError error = OT_ERROR_NONE; + bool applyTransmitSecurity = true; + Frame & sendFrame(*GetOperationFrame()); #if OPENTHREAD_CONFIG_DISABLE_CCA_ON_LAST_ATTEMPT @@ -1048,8 +1049,7 @@ void Mac::HandleTransmitStarted(otRadioFrame *aFrame) } } -extern "C" void otPlatRadioTxDone(otInstance *aInstance, otRadioFrame *aFrame, otRadioFrame *aAckFrame, - otError aError) +extern "C" void otPlatRadioTxDone(otInstance *aInstance, otRadioFrame *aFrame, otRadioFrame *aAckFrame, otError aError) { Instance *instance = static_cast(aInstance); @@ -1073,11 +1073,11 @@ exit: void Mac::HandleTransmitDone(otRadioFrame *aFrame, otRadioFrame *aAckFrame, otError aError) { - Frame &sendFrame = *static_cast(aFrame); - bool framePending = false; - bool ccaSuccess = true; - Address dstAddr; - bool ackRequested; + Frame & sendFrame = *static_cast(aFrame); + bool framePending = false; + bool ccaSuccess = true; + Address dstAddr; + bool ackRequested; Neighbor *neighbor; // Stop the ack timer. @@ -1095,7 +1095,7 @@ void Mac::HandleTransmitDone(otRadioFrame *aFrame, otRadioFrame *aAckFrame, otEr case OT_ERROR_CHANNEL_ACCESS_FAILURE: ccaSuccess = false; - // fall through + // fall through case OT_ERROR_NONE: case OT_ERROR_NO_ACK: @@ -1130,7 +1130,7 @@ void Mac::HandleTransmitDone(otRadioFrame *aFrame, otRadioFrame *aAckFrame, otEr mCsmaAttempts = 0; sendFrame.GetDstAddr(dstAddr); - neighbor = GetNetif().GetMle().GetNeighbor(dstAddr); + neighbor = GetNetif().GetMle().GetNeighbor(dstAddr); ackRequested = sendFrame.GetAckRequest(); #if OPENTHREAD_CONFIG_ENABLE_TX_ERROR_RATE_TRACKING @@ -1150,7 +1150,7 @@ void Mac::HandleTransmitDone(otRadioFrame *aFrame, otRadioFrame *aAckFrame, otEr case OT_ERROR_NO_ACK: frameTxSuccess = false; - // Fall through + // Fall through case OT_ERROR_NONE: neighbor->GetLinkInfo().AddFrameTxStatus(frameTxSuccess); @@ -1267,7 +1267,7 @@ void Mac::HandleTransmitDone(otRadioFrame *aFrame, otRadioFrame *aAckFrame, otEr mCounters.mTxData++; } - sender = mSendHead; + sender = mSendHead; mSendHead = mSendHead->mNext; if (mSendHead == NULL) @@ -1451,19 +1451,19 @@ void Mac::HandleReceiveTimer(void) otError Mac::ProcessReceiveSecurity(Frame &aFrame, const Address &aSrcAddr, Neighbor *aNeighbor) { - KeyManager &keyManager = GetNetif().GetKeyManager(); - otError error = OT_ERROR_NONE; - uint8_t securityLevel; - uint8_t keyIdMode; - uint32_t frameCounter; - uint8_t nonce[kNonceSize]; - uint8_t tag[Frame::kMaxMicSize]; - uint8_t tagLength; - uint8_t keyid; - uint32_t keySequence = 0; - const uint8_t *macKey; + KeyManager & keyManager = GetNetif().GetKeyManager(); + otError error = OT_ERROR_NONE; + uint8_t securityLevel; + uint8_t keyIdMode; + uint32_t frameCounter; + uint8_t nonce[kNonceSize]; + uint8_t tag[Frame::kMaxMicSize]; + uint8_t tagLength; + uint8_t keyid; + uint32_t keySequence = 0; + const uint8_t * macKey; const ExtAddress *extAddress; - Crypto::AesCcm aesCcm; + Crypto::AesCcm aesCcm; aFrame.SetSecurityValid(false); @@ -1495,19 +1495,19 @@ otError Mac::ProcessReceiveSecurity(Frame &aFrame, const Address &aSrcAddr, Neig { // same key index keySequence = keyManager.GetCurrentKeySequence(); - macKey = keyManager.GetCurrentMacKey(); + macKey = keyManager.GetCurrentMacKey(); } else if (keyid == ((keyManager.GetCurrentKeySequence() - 1) & 0x7f)) { // previous key index keySequence = keyManager.GetCurrentKeySequence() - 1; - macKey = keyManager.GetTemporaryMacKey(keySequence); + macKey = keyManager.GetTemporaryMacKey(keySequence); } else if (keyid == ((keyManager.GetCurrentKeySequence() + 1) & 0x7f)) { // next key index keySequence = keyManager.GetCurrentKeySequence() + 1; - macKey = keyManager.GetTemporaryMacKey(keySequence); + macKey = keyManager.GetTemporaryMacKey(keySequence); } else { @@ -1544,7 +1544,7 @@ otError Mac::ProcessReceiveSecurity(Frame &aFrame, const Address &aSrcAddr, Neig break; case Frame::kKeyIdMode2: - macKey = sMode2Key; + macKey = sMode2Key; extAddress = static_cast(&sMode2ExtAddress); break; @@ -1621,15 +1621,15 @@ exit: void Mac::HandleReceivedFrame(Frame *aFrame, otError aError) { - Address srcaddr; - Address dstaddr; - PanId panid; + Address srcaddr; + Address dstaddr; + PanId panid; Neighbor *neighbor; - bool receive = false; - otError error = aError; + bool receive = false; + otError error = aError; #if OPENTHREAD_ENABLE_MAC_FILTER int8_t rssi = OT_MAC_FILTER_FIXED_RSS_DISABLED; -#endif // OPENTHREAD_ENABLE_MAC_FILTER +#endif // OPENTHREAD_ENABLE_MAC_FILTER mCounters.mRxTotal++; @@ -1661,12 +1661,11 @@ void Mac::HandleReceivedFrame(Frame *aFrame, otError aError) case Address::kTypeShort: aFrame->GetDstPanId(panid); VerifyOrExit((panid == kShortAddrBroadcast || panid == mPanId) && - ((mRxOnWhenIdle && dstaddr.IsBroadcast()) || - dstaddr.GetShort() == mShortAddress), error = OT_ERROR_DESTINATION_ADDRESS_FILTERED); + ((mRxOnWhenIdle && dstaddr.IsBroadcast()) || dstaddr.GetShort() == mShortAddress), + error = OT_ERROR_DESTINATION_ADDRESS_FILTERED); // Allow multicasts from neighbor routers if FFD - if (neighbor == NULL && dstaddr.IsBroadcast() && - (GetNetif().GetMle().GetDeviceMode() & Mle::ModeTlv::kModeFFD)) + if (neighbor == NULL && dstaddr.IsBroadcast() && (GetNetif().GetMle().GetDeviceMode() & Mle::ModeTlv::kModeFFD)) { neighbor = GetNetif().GetMle().GetRxOnlyNeighborRouter(srcaddr); } @@ -1696,7 +1695,7 @@ void Mac::HandleReceivedFrame(Frame *aFrame, otError aError) srcaddr.SetExtended(neighbor->GetExtAddress()); - // fall through + // fall through case Address::kTypeExtended: @@ -1717,7 +1716,7 @@ void Mac::HandleReceivedFrame(Frame *aFrame, otError aError) aFrame->mRssi = rssi; } -#endif // OPENTHREAD_ENABLE_MAC_FILTER +#endif // OPENTHREAD_ENABLE_MAC_FILTER break; } @@ -1747,7 +1746,7 @@ void Mac::HandleReceivedFrame(Frame *aFrame, otError aError) neighbor->GetLinkInfo().Clear(); } -#endif // OPENTHREAD_ENABLE_MAC_FILTER +#endif // OPENTHREAD_ENABLE_MAC_FILTER neighbor->GetLinkInfo().AddRss(GetNoiseFloor(), aFrame->mRssi); @@ -1782,7 +1781,7 @@ void Mac::HandleReceivedFrame(Frame *aFrame, otError aError) ExitNow(); } - // Fall-through + // Fall-through case kOperationEnergyScan: @@ -1923,7 +1922,7 @@ otError Mac::HandleMacCommand(Frame &aFrame) #if OPENTHREAD_CONFIG_ENABLE_BEACON_RSP_WHEN_JOINABLE || IsBeaconJoinable() #endif // OPENTHREAD_CONFIG_ENABLE_BEACON_RSP_WHEN_JOINABLE - ) + ) { StartOperation(kOperationTransmitBeacon); } @@ -1945,7 +1944,7 @@ exit: void Mac::SetPcapCallback(otLinkPcapCallback aPcapCallback, void *aCallbackContext) { - mPcapCallback = aPcapCallback; + mPcapCallback = aPcapCallback; mPcapCallbackContext = aCallbackContext; } @@ -2007,7 +2006,7 @@ int8_t Mac::GetNoiseFloor(void) bool Mac::IsBeaconJoinable(void) { uint8_t numUnsecurePorts; - bool joinable = false; + bool joinable = false; GetNetif().GetIp6Filter().GetUnsecurePorts(numUnsecurePorts); @@ -2062,5 +2061,5 @@ const char *Mac::OperationToString(Operation aOperation) return retval; } -} // namespace Mac -} // namespace ot +} // namespace Mac +} // namespace ot diff --git a/src/core/mac/mac.hpp b/src/core/mac/mac.hpp index f7c2d0c00..d00ffc8e1 100644 --- a/src/core/mac/mac.hpp +++ b/src/core/mac/mac.hpp @@ -41,8 +41,8 @@ #include "common/locator.hpp" #include "common/tasklet.hpp" #include "common/timer.hpp" -#include "mac/mac_frame.hpp" #include "mac/mac_filter.hpp" +#include "mac/mac_frame.hpp" #include "thread/key_manager.hpp" #include "thread/link_quality.hpp" #include "thread/network_diagnostic_tlvs.hpp" @@ -50,7 +50,9 @@ namespace ot { -namespace Mle { class MleRouter; } +namespace Mle { +class MleRouter; +} /** * @addtogroup core-mac @@ -70,26 +72,26 @@ namespace Mac { */ enum { - kMinBE = 3, ///< macMinBE (IEEE 802.15.4-2006) - kMaxBE = 5, ///< macMaxBE (IEEE 802.15.4-2006) - kMaxCSMABackoffs = 4, ///< macMaxCSMABackoffs (IEEE 802.15.4-2006) - kUnitBackoffPeriod = 20, ///< Number of symbols (IEEE 802.15.4-2006) + kMinBE = 3, ///< macMinBE (IEEE 802.15.4-2006) + kMaxBE = 5, ///< macMaxBE (IEEE 802.15.4-2006) + kMaxCSMABackoffs = 4, ///< macMaxCSMABackoffs (IEEE 802.15.4-2006) + kUnitBackoffPeriod = 20, ///< Number of symbols (IEEE 802.15.4-2006) - kMinBackoff = 1, ///< Minimum backoff (milliseconds). + kMinBackoff = 1, ///< Minimum backoff (milliseconds). - kAckTimeout = 16, ///< Timeout for waiting on an ACK (milliseconds). - kDataPollTimeout = 100, ///< Timeout for receiving Data Frame (milliseconds). - kSleepDelay = 300, ///< Max sleep delay when frame is pending (milliseconds). - kNonceSize = 13, ///< Size of IEEE 802.15.4 Nonce (bytes). + kAckTimeout = 16, ///< Timeout for waiting on an ACK (milliseconds). + kDataPollTimeout = 100, ///< Timeout for receiving Data Frame (milliseconds). + kSleepDelay = 300, ///< Max sleep delay when frame is pending (milliseconds). + kNonceSize = 13, ///< Size of IEEE 802.15.4 Nonce (bytes). - kScanChannelsAll = OT_CHANNEL_ALL, ///< All channels. - kScanDurationDefault = 300, ///< Default interval between channels (milliseconds). + kScanChannelsAll = OT_CHANNEL_ALL, ///< All channels. + kScanDurationDefault = 300, ///< Default interval between channels (milliseconds). /** * Maximum number of MAC layer tx attempts for an outbound direct frame. * */ - kDirectFrameMacTxAttempts = OPENTHREAD_CONFIG_MAX_TX_ATTEMPTS_DIRECT, + kDirectFrameMacTxAttempts = OPENTHREAD_CONFIG_MAX_TX_ATTEMPTS_DIRECT, /** * Maximum number of MAC layer tx attempts for an outbound indirect frame (for a sleepy child) after receiving @@ -103,7 +105,7 @@ enum * This class implements a MAC receiver client. * */ -class Receiver: public OwnerLocator +class Receiver : public OwnerLocator { friend class Mac; @@ -134,32 +136,35 @@ public: * @param[in] aOwner A pointer to owner of this object. * */ - Receiver(ReceiveFrameHandler aReceiveFrameHandler, DataPollTimeoutHandler aPollTimeoutHandler, void *aOwner): - OwnerLocator(aOwner), - mReceiveFrameHandler(aReceiveFrameHandler), - mPollTimeoutHandler(aPollTimeoutHandler), - mNext(NULL) { + Receiver(ReceiveFrameHandler aReceiveFrameHandler, DataPollTimeoutHandler aPollTimeoutHandler, void *aOwner) + : OwnerLocator(aOwner) + , mReceiveFrameHandler(aReceiveFrameHandler) + , mPollTimeoutHandler(aPollTimeoutHandler) + , mNext(NULL) + { } private: void HandleReceivedFrame(Frame &aFrame) { mReceiveFrameHandler(*this, aFrame); } - void HandleDataPollTimeout(void) { - if (mPollTimeoutHandler != NULL) { + void HandleDataPollTimeout(void) + { + if (mPollTimeoutHandler != NULL) + { mPollTimeoutHandler(*this); } } - ReceiveFrameHandler mReceiveFrameHandler; + ReceiveFrameHandler mReceiveFrameHandler; DataPollTimeoutHandler mPollTimeoutHandler; - Receiver *mNext; + Receiver * mNext; }; /** * This class implements a MAC sender client. * */ -class Sender: public OwnerLocator +class Sender : public OwnerLocator { friend class Mac; @@ -172,7 +177,7 @@ public: * @param[in] aFrame A reference to the MAC frame buffer. * */ - typedef otError(*FrameRequestHandler)(Sender &aSender, Frame &aFrame); + typedef otError (*FrameRequestHandler)(Sender &aSender, Frame &aFrame); /** * This function pointer is called when the MAC is done sending the frame. @@ -192,27 +197,28 @@ public: * @param[in] aOwner A pointer to owner of this object. * */ - Sender(FrameRequestHandler aFrameRequestHandler, SentFrameHandler aSentFrameHandler, void *aOwner): - OwnerLocator(aOwner), - mFrameRequestHandler(aFrameRequestHandler), - mSentFrameHandler(aSentFrameHandler), - mNext(NULL) { + Sender(FrameRequestHandler aFrameRequestHandler, SentFrameHandler aSentFrameHandler, void *aOwner) + : OwnerLocator(aOwner) + , mFrameRequestHandler(aFrameRequestHandler) + , mSentFrameHandler(aSentFrameHandler) + , mNext(NULL) + { } private: otError HandleFrameRequest(Frame &aFrame) { return mFrameRequestHandler(*this, aFrame); } - void HandleSentFrame(Frame &aFrame, otError aError) { mSentFrameHandler(*this, aFrame, aError); } + void HandleSentFrame(Frame &aFrame, otError aError) { mSentFrameHandler(*this, aFrame, aError); } FrameRequestHandler mFrameRequestHandler; - SentFrameHandler mSentFrameHandler; - Sender *mNext; + SentFrameHandler mSentFrameHandler; + Sender * mNext; }; /** * This class implements the IEEE 802.15.4 MAC. * */ -class Mac: public InstanceLocator +class Mac : public InstanceLocator { public: /** @@ -482,7 +488,7 @@ public: * */ Filter &GetFilter(void) { return mFilter; } -#endif // OPENTHREAD_ENABLE_MAC_FILTER +#endif // OPENTHREAD_ENABLE_MAC_FILTER /** * This method is called to handle a received frame. @@ -539,8 +545,8 @@ public: /** * This method registers a callback to provide received raw IEEE 802.15.4 frames. * - * @param[in] aPcapCallback A pointer to a function that is called when receiving an IEEE 802.15.4 link frame or - * NULL to disable the callback. + * @param[in] aPcapCallback A pointer to a function that is called when receiving an IEEE 802.15.4 link frame + * or NULL to disable the callback. * @param[in] aCallbackContext A pointer to application-specific context. * */ @@ -638,16 +644,16 @@ public: private: enum { - kInvalidRssiValue = 127, + kInvalidRssiValue = 127, kMaxCcaSampleCount = OPENTHREAD_CONFIG_CCA_FAILURE_RATE_AVERAGING_WINDOW, - /** - * Interval between RSSI samples when performing Energy Scan. - * - * `mBackoffTimer` is used for adding delay between RSSI samples. If microsecond timer is supported, 128 usec - * time between samples is used, otherwise with a millisecond timer the minimum value of 1 msec is used. - * - */ + /** + * Interval between RSSI samples when performing Energy Scan. + * + * `mBackoffTimer` is used for adding delay between RSSI samples. If microsecond timer is supported, 128 usec + * time between samples is used, otherwise with a millisecond timer the minimum value of 1 msec is used. + * + */ #if OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_TIMER kEnergyScanRssiSampleInterval = 128, #else @@ -666,36 +672,36 @@ private: kOperationTransmitOutOfBandFrame, }; - void GenerateNonce(const ExtAddress &aAddress, uint32_t aFrameCounter, uint8_t aSecurityLevel, uint8_t *aNonce); - void ProcessTransmitSecurity(Frame &aFrame); + void GenerateNonce(const ExtAddress &aAddress, uint32_t aFrameCounter, uint8_t aSecurityLevel, uint8_t *aNonce); + void ProcessTransmitSecurity(Frame &aFrame); otError ProcessReceiveSecurity(Frame &aFrame, const Address &aSrcAddr, Neighbor *aNeighbor); - void UpdateIdleMode(void); - void StartOperation(Operation aOperation); - void FinishOperation(void); - void SendBeaconRequest(Frame &aFrame); - void SendBeacon(Frame &aFrame); - void StartBackoff(void); - void BeginTransmit(void); + void UpdateIdleMode(void); + void StartOperation(Operation aOperation); + void FinishOperation(void); + void SendBeaconRequest(Frame &aFrame); + void SendBeacon(Frame &aFrame); + void StartBackoff(void); + void BeginTransmit(void); otError HandleMacCommand(Frame &aFrame); - Frame *GetOperationFrame(void); + Frame * GetOperationFrame(void); static void HandleMacTimer(Timer &aTimer); - void HandleMacTimer(void); + void HandleMacTimer(void); static void HandleBackoffTimer(Timer &aTimer); - void HandleBackoffTimer(void); + void HandleBackoffTimer(void); static void HandleReceiveTimer(Timer &aTimer); - void HandleReceiveTimer(void); + void HandleReceiveTimer(void); static void PerformOperation(Tasklet &aTasklet); - void PerformOperation(void); + void PerformOperation(void); void StartCsmaBackoff(void); - void Scan(Operation aScanOperation, uint32_t aScanChannels, uint16_t aScanDuration, void *aContext); + void Scan(Operation aScanOperation, uint32_t aScanChannels, uint16_t aScanDuration, void *aContext); otError UpdateScanChannel(void); - void PerformActiveScan(void); - void PerformEnergyScan(void); - void ReportEnergyScanResult(int8_t aRssi); - void SampleRssi(void); + void PerformActiveScan(void); + void PerformEnergyScan(void); + void ReportEnergyScanResult(int8_t aRssi); + void SampleRssi(void); otError RadioTransmit(Frame *aSendFrame); otError RadioReceive(uint8_t aChannel); @@ -705,16 +711,16 @@ private: Operation mOperation; - bool mPendingActiveScan : 1; - bool mPendingEnergyScan : 1; - bool mPendingTransmitBeacon : 1; - bool mPendingTransmitData : 1; + bool mPendingActiveScan : 1; + bool mPendingEnergyScan : 1; + bool mPendingTransmitBeacon : 1; + bool mPendingTransmitData : 1; bool mPendingTransmitOobFrame : 1; - bool mPendingWaitingForData : 1; - bool mRxOnWhenIdle : 1; - bool mBeaconsEnabled : 1; + bool mPendingWaitingForData : 1; + bool mRxOnWhenIdle : 1; + bool mBeaconsEnabled : 1; #if OPENTHREAD_CONFIG_STAY_AWAKE_BETWEEN_FRAGMENTS - bool mDelaySleep : 1; + bool mDelaySleep : 1; #endif Tasklet mOperationTask; @@ -727,15 +733,15 @@ private: #endif TimerMilli mReceiveTimer; - ExtAddress mExtAddress; + ExtAddress mExtAddress; ShortAddress mShortAddress; - PanId mPanId; - uint8_t mChannel; + PanId mPanId; + uint8_t mChannel; - otNetworkName mNetworkName; + otNetworkName mNetworkName; otExtendedPanId mExtendedPanId; - Sender *mSendHead, *mSendTail; + Sender * mSendHead, *mSendTail; Receiver *mReceiveHead, *mReceiveTail; uint8_t mBeaconSequence; @@ -745,9 +751,9 @@ private: uint32_t mScanChannels; uint16_t mScanDuration; - uint8_t mScanChannel; - int8_t mEnergyScanCurrentMaxRssi; - void *mScanContext; + uint8_t mScanChannel; + int8_t mEnergyScanCurrentMaxRssi; + void * mScanContext; union { ActiveScanHandler mActiveScanHandler; @@ -755,20 +761,20 @@ private: }; otLinkPcapCallback mPcapCallback; - void *mPcapCallbackContext; + void * mPcapCallbackContext; #if OPENTHREAD_ENABLE_MAC_FILTER Filter mFilter; -#endif // OPENTHREAD_ENABLE_MAC_FILTER +#endif // OPENTHREAD_ENABLE_MAC_FILTER Frame *mTxFrame; Frame *mOobFrame; otMacCounters mCounters; - uint32_t mKeyIdMode2FrameCounter; + uint32_t mKeyIdMode2FrameCounter; SuccessRateTracker mCcaSuccessRateTracker; - uint16_t mCcaSampleCount; + uint16_t mCcaSampleCount; }; /** @@ -776,7 +782,7 @@ private: * */ -} // namespace Mac -} // namespace ot +} // namespace Mac +} // namespace ot -#endif // MAC_HPP_ +#endif // MAC_HPP_ diff --git a/src/core/mac/mac_filter.cpp b/src/core/mac/mac_filter.cpp index a8a9a1c1e..48232b2df 100644 --- a/src/core/mac/mac_filter.cpp +++ b/src/core/mac/mac_filter.cpp @@ -43,16 +43,16 @@ namespace ot { namespace Mac { -Filter::Filter(void) : - mAddressMode(OT_MAC_FILTER_ADDRESS_MODE_DISABLED), - mRssIn(OT_MAC_FILTER_FIXED_RSS_DISABLED) +Filter::Filter(void) + : mAddressMode(OT_MAC_FILTER_ADDRESS_MODE_DISABLED) + , mRssIn(OT_MAC_FILTER_FIXED_RSS_DISABLED) { for (int i = 0; i < GetMaxEntries(); i++) { memset(&mEntries[i], 0, sizeof(Entry)); mEntries[i].mFiltered = false; - mEntries[i].mRssIn = OT_MAC_FILTER_FIXED_RSS_DISABLED; + mEntries[i].mRssIn = OT_MAC_FILTER_FIXED_RSS_DISABLED; } } @@ -93,9 +93,8 @@ otError Filter::SetAddressMode(otMacFilterAddressMode aMode) { otError error = OT_ERROR_NONE; - VerifyOrExit(aMode == OT_MAC_FILTER_ADDRESS_MODE_DISABLED || - aMode == OT_MAC_FILTER_ADDRESS_MODE_WHITELIST || - aMode == OT_MAC_FILTER_ADDRESS_MODE_BLACKLIST, + VerifyOrExit(aMode == OT_MAC_FILTER_ADDRESS_MODE_DISABLED || aMode == OT_MAC_FILTER_ADDRESS_MODE_WHITELIST || + aMode == OT_MAC_FILTER_ADDRESS_MODE_BLACKLIST, error = OT_ERROR_INVALID_ARGS); mAddressMode = aMode; @@ -107,7 +106,7 @@ exit: otError Filter::AddAddress(const ExtAddress &aExtAddress) { otError error = OT_ERROR_NONE; - Entry *entry = FindEntry(aExtAddress); + Entry * entry = FindEntry(aExtAddress); if (entry == NULL) { @@ -129,7 +128,7 @@ exit: otError Filter::RemoveAddress(const ExtAddress &aExtAddress) { otError error = OT_ERROR_NONE; - Entry *entry = FindEntry(aExtAddress); + Entry * entry = FindEntry(aExtAddress); if (entry == NULL || !entry->mFiltered) { @@ -153,13 +152,13 @@ void Filter::ClearAddresses(void) otError Filter::GetNextAddress(otMacFilterIterator &aIterator, Entry &aEntry) { otError error = OT_ERROR_NOT_FOUND; - uint8_t i = *reinterpret_cast(&aIterator); + uint8_t i = *reinterpret_cast(&aIterator); for (; i < GetMaxEntries(); i++) { if (mEntries[i].mFiltered) { - aEntry = mEntries[i]; + aEntry = mEntries[i]; aIterator = *reinterpret_cast(&(++i)); ExitNow(error = OT_ERROR_NONE); } @@ -169,7 +168,6 @@ exit: return error; } - otError Filter::AddRssIn(const ExtAddress *aExtAddress, int8_t aRss) { otError error = OT_ERROR_NONE; @@ -229,13 +227,13 @@ void Filter::ClearRssIn(void) otError Filter::GetNextRssIn(otMacFilterIterator &aIterator, Entry &aEntry) { otError error = OT_ERROR_NOT_FOUND; - uint8_t i = *reinterpret_cast(&aIterator); + uint8_t i = *reinterpret_cast(&aIterator); for (; i < GetMaxEntries(); i++) { if (mEntries[i].mRssIn != OT_MAC_FILTER_FIXED_RSS_DISABLED) { - aEntry = mEntries[i]; + aEntry = mEntries[i]; aIterator = *reinterpret_cast(&(++i)); ExitNow(error = OT_ERROR_NONE); } @@ -246,7 +244,7 @@ otError Filter::GetNextRssIn(otMacFilterIterator &aIterator, Entry &aEntry) { memset(&aEntry.mExtAddress, 0xff, OT_EXT_ADDRESS_SIZE); aEntry.mRssIn = mRssIn; - aIterator = *reinterpret_cast(&(++i)); + aIterator = *reinterpret_cast(&(++i)); ExitNow(error = OT_ERROR_NONE); } @@ -283,7 +281,7 @@ exit: return error; } -} // namespace Mac -} // namespace ot +} // namespace Mac +} // namespace ot -#endif // OPENTHREAD_ENABLE_MAC_FILTER +#endif // OPENTHREAD_ENABLE_MAC_FILTER diff --git a/src/core/mac/mac_filter.hpp b/src/core/mac/mac_filter.hpp index 8589a04d3..e6bcd00e4 100644 --- a/src/core/mac/mac_filter.hpp +++ b/src/core/mac/mac_filter.hpp @@ -209,9 +209,9 @@ private: Entry *FindAvailEntry(void); Entry *FindEntry(const ExtAddress &aExtAddress); - Entry mEntries[kMaxEntries]; + Entry mEntries[kMaxEntries]; otMacFilterAddressMode mAddressMode; - int8_t mRssIn; + int8_t mRssIn; }; /** @@ -219,9 +219,9 @@ private: * */ -} // namespace Mac -} // namespace ot +} // namespace Mac +} // namespace ot -#endif // OPENTHREAD_ENABLE_MAC_FILTER +#endif // OPENTHREAD_ENABLE_MAC_FILTER -#endif // MAC_FILTER_HPP_ +#endif // MAC_FILTER_HPP_ diff --git a/src/core/mac/mac_frame.cpp b/src/core/mac/mac_frame.cpp index d5c124e9b..43b98820a 100644 --- a/src/core/mac/mac_frame.cpp +++ b/src/core/mac/mac_frame.cpp @@ -83,9 +83,9 @@ const char *Address::ToString(char *aBuf, uint16_t aSize) const break; case kTypeExtended: - snprintf(aBuf, aSize, "%02x%02x%02x%02x%02x%02x%02x%02x", - GetExtended().m8[0], GetExtended().m8[1], GetExtended().m8[2], GetExtended().m8[3], - GetExtended().m8[4], GetExtended().m8[5], GetExtended().m8[6], GetExtended().m8[7]); + snprintf(aBuf, aSize, "%02x%02x%02x%02x%02x%02x%02x%02x", GetExtended().m8[0], GetExtended().m8[1], + GetExtended().m8[2], GetExtended().m8[3], GetExtended().m8[4], GetExtended().m8[5], + GetExtended().m8[6], GetExtended().m8[7]); break; } @@ -94,8 +94,8 @@ const char *Address::ToString(char *aBuf, uint16_t aSize) const otError Frame::InitMacHeader(uint16_t aFcf, uint8_t aSecurityControl) { - uint8_t *bytes = GetPsdu(); - uint8_t length = 0; + uint8_t *bytes = GetPsdu(); + uint8_t length = 0; // Frame Control Field Encoding::LittleEndian::WriteUint16(aFcf, bytes); @@ -198,7 +198,7 @@ uint16_t Frame::GetFrameControlField(void) const otError Frame::ValidatePsdu(void) const { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint8_t offset = FindPayloadIndex(); VerifyOrExit(offset != kInvalidIndex, error = OT_ERROR_PARSE); @@ -308,8 +308,8 @@ otError Frame::SetDstAddr(ShortAddress aShortAddress) otError Frame::SetDstAddr(const ExtAddress &aExtAddress) { - uint8_t index = FindDstAddrIndex(); - uint8_t *buf = GetPsdu() + index; + uint8_t index = FindDstAddrIndex(); + uint8_t *buf = GetPsdu() + index; assert((GetFrameControlField() & kFcfDstAddrMask) == kFcfDstAddrExt); assert(index != kInvalidIndex); @@ -346,11 +346,11 @@ otError Frame::SetDstAddr(const Address &aAddress) uint8_t Frame::FindSrcPanIdIndex(void) const { - uint8_t index = 0; - uint16_t fcf = GetFrameControlField(); + uint8_t index = 0; + uint16_t fcf = GetFrameControlField(); - VerifyOrExit((fcf & kFcfDstAddrMask) != kFcfDstAddrNone || - (fcf & kFcfSrcAddrMask) != kFcfSrcAddrNone, index = kInvalidIndex); + VerifyOrExit((fcf & kFcfDstAddrMask) != kFcfDstAddrNone || (fcf & kFcfSrcAddrMask) != kFcfSrcAddrNone, + index = kInvalidIndex); // Frame Control Field and Sequence Number index += kFcfSize + kDsnSize; @@ -400,8 +400,8 @@ exit: uint8_t Frame::FindSrcAddrIndex(void) const { - uint8_t index = 0; - uint16_t fcf = GetFrameControlField(); + uint8_t index = 0; + uint16_t fcf = GetFrameControlField(); // Frame Control Field and Sequence Number index += kFcfSize + kDsnSize; @@ -429,9 +429,9 @@ uint8_t Frame::FindSrcAddrIndex(void) const otError Frame::GetSrcAddr(Address &address) const { - otError error = OT_ERROR_NONE; - uint8_t index = FindSrcAddrIndex(); - uint16_t fcf = GetFrameControlField(); + otError error = OT_ERROR_NONE; + uint8_t index = FindSrcAddrIndex(); + uint16_t fcf = GetFrameControlField(); VerifyOrExit(index != kInvalidIndex, error = OT_ERROR_PARSE); @@ -468,8 +468,8 @@ otError Frame::SetSrcAddr(ShortAddress aShortAddress) otError Frame::SetSrcAddr(const ExtAddress &aExtAddress) { - uint8_t index = FindSrcAddrIndex(); - uint8_t *buf = GetPsdu() + index; + uint8_t index = FindSrcAddrIndex(); + uint8_t *buf = GetPsdu() + index; assert((GetFrameControlField() & kFcfSrcAddrMask) == kFcfSrcAddrExt); assert(index != kInvalidIndex); @@ -506,8 +506,8 @@ otError Frame::SetSrcAddr(const Address &aAddress) uint8_t Frame::FindSecurityHeaderIndex(void) const { - uint8_t index = 0; - uint16_t fcf = GetFrameControlField(); + uint8_t index = 0; + uint16_t fcf = GetFrameControlField(); VerifyOrExit((fcf & kFcfSecurityEnabled) != 0, index = kInvalidIndex); @@ -610,8 +610,8 @@ otError Frame::SetFrameCounter(uint32_t aFrameCounter) const uint8_t *Frame::GetKeySource(void) const { - uint8_t index = FindSecurityHeaderIndex(); - const uint8_t *buf = GetPsdu() + index; + uint8_t index = FindSecurityHeaderIndex(); + const uint8_t *buf = GetPsdu() + index; assert(index != kInvalidIndex); @@ -649,9 +649,9 @@ uint8_t Frame::GetKeySourceLength(uint8_t aKeyIdMode) void Frame::SetKeySource(const uint8_t *aKeySource) { - uint8_t keySourceLength; - uint8_t index = FindSecurityHeaderIndex(); - uint8_t *buf = GetPsdu() + index; + uint8_t keySourceLength; + uint8_t index = FindSecurityHeaderIndex(); + uint8_t *buf = GetPsdu() + index; assert(index != kInvalidIndex); @@ -664,10 +664,10 @@ void Frame::SetKeySource(const uint8_t *aKeySource) otError Frame::GetKeyId(uint8_t &aKeyId) const { - otError error = OT_ERROR_NONE; - uint8_t keySourceLength; - uint8_t index = FindSecurityHeaderIndex(); - const uint8_t *buf = GetPsdu() + index; + otError error = OT_ERROR_NONE; + uint8_t keySourceLength; + uint8_t index = FindSecurityHeaderIndex(); + const uint8_t *buf = GetPsdu() + index; VerifyOrExit(index != kInvalidIndex); @@ -683,9 +683,9 @@ exit: otError Frame::SetKeyId(uint8_t aKeyId) { - uint8_t keySourceLength; - uint8_t index = FindSecurityHeaderIndex(); - uint8_t *buf = GetPsdu() + index; + uint8_t keySourceLength; + uint8_t index = FindSecurityHeaderIndex(); + uint8_t *buf = GetPsdu() + index; assert(index != kInvalidIndex); @@ -726,8 +726,8 @@ exit: bool Frame::IsDataRequestCommand(void) const { - bool isDataRequest = false; - uint8_t commandId = 0; + bool isDataRequest = false; + uint8_t commandId = 0; VerifyOrExit(GetType() == kFcfFrameMacCmd); SuccessOrExit(GetCommandId(commandId)); @@ -745,7 +745,7 @@ uint8_t Frame::GetHeaderLength(void) const uint8_t Frame::GetFooterLength(void) const { uint8_t footerLength = 0; - uint8_t index = FindSecurityHeaderIndex(); + uint8_t index = FindSecurityHeaderIndex(); VerifyOrExit(index != kInvalidIndex); @@ -797,7 +797,7 @@ otError Frame::SetPayloadLength(uint8_t aLength) uint8_t Frame::FindPayloadIndex(void) const { - uint8_t index = 0; + uint8_t index = 0; uint16_t fcf; // Frame Control @@ -892,12 +892,11 @@ uint8_t Frame::FindPayloadIndex(void) const exit: return index; - } uint8_t *Frame::GetPayload(void) { - uint8_t index = FindPayloadIndex(); + uint8_t index = FindPayloadIndex(); uint8_t *payload = GetPsdu() + index; VerifyOrExit(index != kInvalidIndex, payload = NULL); @@ -908,7 +907,7 @@ exit: const uint8_t *Frame::GetPayload(void) const { - uint8_t index = FindPayloadIndex(); + uint8_t index = FindPayloadIndex(); const uint8_t *payload = GetPsdu() + index; VerifyOrExit(index != kInvalidIndex, payload = NULL); @@ -929,12 +928,12 @@ const uint8_t *Frame::GetFooter(void) const const char *Frame::ToInfoString(char *aBuf, uint16_t aSize) const { - uint8_t type, commandId; - Address src, dst; + uint8_t type, commandId; + Address src, dst; const char *typeStr; - char stringBuffer[10]; - char srcStringBuffer[Address::kAddressStringSize]; - char dstStringBuffer[Address::kAddressStringSize]; + char stringBuffer[10]; + char srcStringBuffer[Address::kAddressStringSize]; + char dstStringBuffer[Address::kAddressStringSize]; type = GetType(); @@ -1004,6 +1003,5 @@ const char *BeaconPayload::ToInfoString(char *aBuf, uint16_t aSize) return aBuf; } -} // namespace Mac -} // namespace ot - +} // namespace Mac +} // namespace ot diff --git a/src/core/mac/mac_frame.hpp b/src/core/mac/mac_frame.hpp index b25325e02..4da99e460 100644 --- a/src/core/mac/mac_frame.hpp +++ b/src/core/mac/mac_frame.hpp @@ -47,7 +47,9 @@ namespace ot { -namespace Ip6 { class Address; } +namespace Ip6 { +class Address; +} namespace Mac { @@ -61,8 +63,8 @@ namespace Mac { enum { kShortAddrBroadcast = 0xffff, - kShortAddrInvalid = 0xfffe, - kPanIdBroadcast = 0xffff, + kShortAddrInvalid = 0xfffe, + kPanIdBroadcast = 0xffff, }; /** @@ -82,7 +84,7 @@ typedef otShortAddress ShortAddress; * */ OT_TOOL_PACKED_BEGIN -class ExtAddress: public otExtAddress +class ExtAddress : public otExtAddress { public: /** @@ -100,11 +102,14 @@ public: * @param[in] aLocal TRUE if group address, FALSE otherwise. * */ - void SetGroup(bool aGroup) { - if (aGroup) { + void SetGroup(bool aGroup) + { + if (aGroup) + { m8[0] |= kGroupFlag; } - else { + else + { m8[0] &= ~kGroupFlag; } } @@ -113,9 +118,7 @@ public: * This method toggles the Group bit. * */ - void ToggleGroup(void) { - m8[0] ^= kGroupFlag; - } + void ToggleGroup(void) { m8[0] ^= kGroupFlag; } /** * This method indicates whether or not the Local bit is set. @@ -132,11 +135,14 @@ public: * @param[in] aLocal TRUE if locally administered, FALSE otherwise. * */ - void SetLocal(bool aLocal) { - if (aLocal) { + void SetLocal(bool aLocal) + { + if (aLocal) + { m8[0] |= kLocalFlag; } - else { + else + { m8[0] &= ~kLocalFlag; } } @@ -145,9 +151,7 @@ public: * This method toggles the Local bit. * */ - void ToggleLocal(void) { - m8[0] ^= kLocalFlag; - } + void ToggleLocal(void) { m8[0] ^= kLocalFlag; } /** * This method evaluates whether or not the Extended Addresses match. @@ -188,7 +192,7 @@ class Address public: enum { - kAddressStringSize = 18, ///< Max chars needed for a string representation of address (@sa ToString()). + kAddressStringSize = 18, ///< Max chars needed for a string representation of address (@sa ToString()). }; /** @@ -197,16 +201,19 @@ public: */ enum Type { - kTypeNone, ///< No address. - kTypeShort, ///< IEEE 802.15.4 Short Address. - kTypeExtended, ///< IEEE 802.15.4 Extended Address. + kTypeNone, ///< No address. + kTypeShort, ///< IEEE 802.15.4 Short Address. + kTypeExtended, ///< IEEE 802.15.4 Extended Address. }; /** * This constructor initializes an Address. * */ - Address(void): mType(kTypeNone) { } + Address(void) + : mType(kTypeNone) + { + } /** * This method gets the address type (Short Address, Extended Address, or none). @@ -286,7 +293,11 @@ public: * @param[in] aShortAddress A Short Address * */ - void SetShort(ShortAddress aShortAddress) { mShared.mShortAddress = aShortAddress; mType = kTypeShort; } + void SetShort(ShortAddress aShortAddress) + { + mShared.mShortAddress = aShortAddress; + mType = kTypeShort; + } /** * This method sets the address with an Extended Address. @@ -296,7 +307,11 @@ public: * @param[in] aExtAddress An Extended Address * */ - void SetExtended(const ExtAddress &aExtAddress) { mShared.mExtAddress = aExtAddress; mType = kTypeExtended; } + void SetExtended(const ExtAddress &aExtAddress) + { + mShared.mExtAddress = aExtAddress; + mType = kTypeExtended; + } /** * This method sets the address with an Extended Address given as byte array. @@ -341,90 +356,90 @@ public: private: union { - ShortAddress mShortAddress; ///< The IEEE 802.15.4 Short Address. - ExtAddress mExtAddress; ///< The IEEE 802.15.4 Extended Address. + ShortAddress mShortAddress; ///< The IEEE 802.15.4 Short Address. + ExtAddress mExtAddress; ///< The IEEE 802.15.4 Extended Address. } mShared; - Type mType; ///< The address type (Short, Extended, or none). + Type mType; ///< The address type (Short, Extended, or none). }; /** * This class implements IEEE 802.15.4 MAC frame generation and parsing. * */ -class Frame: public otRadioFrame +class Frame : public otRadioFrame { public: enum { - kMTU = 127, - kFcfSize = sizeof(uint16_t), - kDsnSize = sizeof(uint8_t), - kSecurityControlSize = sizeof(uint8_t), - kFrameCounterSize = sizeof(uint32_t), - kCommandIdSize = sizeof(uint8_t), - kFcsSize = sizeof(uint16_t), + kMTU = 127, + kFcfSize = sizeof(uint16_t), + kDsnSize = sizeof(uint8_t), + kSecurityControlSize = sizeof(uint8_t), + kFrameCounterSize = sizeof(uint32_t), + kCommandIdSize = sizeof(uint8_t), + kFcsSize = sizeof(uint16_t), - kFcfFrameBeacon = 0 << 0, - kFcfFrameData = 1 << 0, - kFcfFrameAck = 2 << 0, - kFcfFrameMacCmd = 3 << 0, - kFcfFrameTypeMask = 7 << 0, - kFcfSecurityEnabled = 1 << 3, - kFcfFramePending = 1 << 4, - kFcfAckRequest = 1 << 5, - kFcfPanidCompression = 1 << 6, - kFcfDstAddrNone = 0 << 10, - kFcfDstAddrShort = 2 << 10, - kFcfDstAddrExt = 3 << 10, - kFcfDstAddrMask = 3 << 10, - kFcfFrameVersion2006 = 1 << 12, - kFcfFrameVersionMask = 3 << 13, - kFcfSrcAddrNone = 0 << 14, - kFcfSrcAddrShort = 2 << 14, - kFcfSrcAddrExt = 3 << 14, - kFcfSrcAddrMask = 3 << 14, + kFcfFrameBeacon = 0 << 0, + kFcfFrameData = 1 << 0, + kFcfFrameAck = 2 << 0, + kFcfFrameMacCmd = 3 << 0, + kFcfFrameTypeMask = 7 << 0, + kFcfSecurityEnabled = 1 << 3, + kFcfFramePending = 1 << 4, + kFcfAckRequest = 1 << 5, + kFcfPanidCompression = 1 << 6, + kFcfDstAddrNone = 0 << 10, + kFcfDstAddrShort = 2 << 10, + kFcfDstAddrExt = 3 << 10, + kFcfDstAddrMask = 3 << 10, + kFcfFrameVersion2006 = 1 << 12, + kFcfFrameVersionMask = 3 << 13, + kFcfSrcAddrNone = 0 << 14, + kFcfSrcAddrShort = 2 << 14, + kFcfSrcAddrExt = 3 << 14, + kFcfSrcAddrMask = 3 << 14, - kSecNone = 0 << 0, - kSecMic32 = 1 << 0, - kSecMic64 = 2 << 0, - kSecMic128 = 3 << 0, - kSecEnc = 4 << 0, - kSecEncMic32 = 5 << 0, - kSecEncMic64 = 6 << 0, - kSecEncMic128 = 7 << 0, - kSecLevelMask = 7 << 0, + kSecNone = 0 << 0, + kSecMic32 = 1 << 0, + kSecMic64 = 2 << 0, + kSecMic128 = 3 << 0, + kSecEnc = 4 << 0, + kSecEncMic32 = 5 << 0, + kSecEncMic64 = 6 << 0, + kSecEncMic128 = 7 << 0, + kSecLevelMask = 7 << 0, - kMic0Size = 0, - kMic32Size = 32 / CHAR_BIT, - kMic64Size = 64 / CHAR_BIT, - kMic128Size = 128 / CHAR_BIT, - kMaxMicSize = kMic128Size, + kMic0Size = 0, + kMic32Size = 32 / CHAR_BIT, + kMic64Size = 64 / CHAR_BIT, + kMic128Size = 128 / CHAR_BIT, + kMaxMicSize = kMic128Size, - kKeyIdMode0 = 0 << 3, - kKeyIdMode1 = 1 << 3, - kKeyIdMode2 = 2 << 3, - kKeyIdMode3 = 3 << 3, - kKeyIdModeMask = 3 << 3, + kKeyIdMode0 = 0 << 3, + kKeyIdMode1 = 1 << 3, + kKeyIdMode2 = 2 << 3, + kKeyIdMode3 = 3 << 3, + kKeyIdModeMask = 3 << 3, - kKeySourceSizeMode0 = 0, - kKeySourceSizeMode1 = 0, - kKeySourceSizeMode2 = 4, - kKeySourceSizeMode3 = 8, + kKeySourceSizeMode0 = 0, + kKeySourceSizeMode1 = 0, + kKeySourceSizeMode2 = 4, + kKeySourceSizeMode3 = 8, - kKeyIndexSize = sizeof(uint8_t), + kKeyIndexSize = sizeof(uint8_t), - kMacCmdAssociationRequest = 1, - kMacCmdAssociationResponse = 2, - kMacCmdDisassociationNotification = 3, - kMacCmdDataRequest = 4, - kMacCmdPanidConflictNotification = 5, - kMacCmdOrphanNotification = 6, - kMacCmdBeaconRequest = 7, - kMacCmdCoordinatorRealignment = 8, - kMacCmdGtsRequest = 9, + kMacCmdAssociationRequest = 1, + kMacCmdAssociationResponse = 2, + kMacCmdDisassociationNotification = 3, + kMacCmdDataRequest = 4, + kMacCmdPanidConflictNotification = 5, + kMacCmdOrphanNotification = 6, + kMacCmdBeaconRequest = 7, + kMacCmdCoordinatorRealignment = 8, + kMacCmdGtsRequest = 9, - kInfoStringSize = 110, ///< Max chars needed for the info string representation (@sa ToInfoString()). + kInfoStringSize = 110, ///< Max chars needed for the info string representation (@sa ToInfoString()). }; /** @@ -755,7 +770,11 @@ public: * @retval OT_ERROR_NONE Successfully set the MAC Frame Length. * */ - otError SetLength(uint8_t aLength) { SetPsduLength(aLength); return OT_ERROR_NONE; } + otError SetLength(uint8_t aLength) + { + SetPsduLength(aLength); + return OT_ERROR_NONE; + } /** * This method returns the MAC header size. @@ -990,20 +1009,19 @@ public: private: enum { - kInvalidIndex = 0xff, + kInvalidIndex = 0xff, kSequenceIndex = kFcfSize, }; uint16_t GetFrameControlField(void) const; - uint8_t FindDstPanIdIndex(void) const; - uint8_t FindDstAddrIndex(void) const; - uint8_t FindSrcPanIdIndex(void) const; - uint8_t FindSrcAddrIndex(void) const; - uint8_t FindSecurityHeaderIndex(void) const; - uint8_t FindPayloadIndex(void) const; + uint8_t FindDstPanIdIndex(void) const; + uint8_t FindDstAddrIndex(void) const; + uint8_t FindSrcPanIdIndex(void) const; + uint8_t FindSrcAddrIndex(void) const; + uint8_t FindSecurityHeaderIndex(void) const; + uint8_t FindPayloadIndex(void) const; static uint8_t GetKeySourceLength(uint8_t aKeyIdMode); - }; OT_TOOL_PACKED_BEGIN @@ -1012,16 +1030,17 @@ class Beacon public: enum { - kSuperFrameSpec = 0x0fff, ///< Superframe Specification value. + kSuperFrameSpec = 0x0fff, ///< Superframe Specification value. }; /** * This method initializes the Beacon message. * */ - void Init(void) { - mSuperframeSpec = ot::Encoding::LittleEndian::HostSwap16(kSuperFrameSpec); - mGtsSpec = 0; + void Init(void) + { + mSuperframeSpec = ot::Encoding::LittleEndian::HostSwap16(kSuperFrameSpec); + mGtsSpec = 0; mPendingAddressSpec = 0; } @@ -1032,9 +1051,10 @@ public: * @retval FALSE if the beacon does not appear to be a valid Thread Beacon message. * */ - bool IsValid(void) { - return (mSuperframeSpec == ot::Encoding::LittleEndian::HostSwap16(kSuperFrameSpec)) && - (mGtsSpec == 0) && (mPendingAddressSpec == 0); + bool IsValid(void) + { + return (mSuperframeSpec == ot::Encoding::LittleEndian::HostSwap16(kSuperFrameSpec)) && (mGtsSpec == 0) && + (mPendingAddressSpec == 0); } /** @@ -1061,28 +1081,29 @@ class BeaconPayload public: enum { - kProtocolId = 3, ///< Thread Protocol ID. - kNetworkNameSize = 16, ///< Size of Thread Network Name (bytes). - kExtPanIdSize = 8, ///< Size of Thread Extended PAN ID. - kInfoStringSize = 92, ///< Max chars for the info string (@sa ToInfoString()). + kProtocolId = 3, ///< Thread Protocol ID. + kNetworkNameSize = 16, ///< Size of Thread Network Name (bytes). + kExtPanIdSize = 8, ///< Size of Thread Extended PAN ID. + kInfoStringSize = 92, ///< Max chars for the info string (@sa ToInfoString()). }; enum { - kProtocolVersion = 2, ///< Thread Protocol version. - kVersionOffset = 4, ///< Version field bit offset. - kVersionMask = 0xf << kVersionOffset, ///< Version field mask. - kNativeFlag = 1 << 3, ///< Native Commissioner flag. - kJoiningFlag = 1 << 0, ///< Joining Permitted flag. + kProtocolVersion = 2, ///< Thread Protocol version. + kVersionOffset = 4, ///< Version field bit offset. + kVersionMask = 0xf << kVersionOffset, ///< Version field mask. + kNativeFlag = 1 << 3, ///< Native Commissioner flag. + kJoiningFlag = 1 << 0, ///< Joining Permitted flag. }; /** * This method initializes the Beacon Payload. * */ - void Init(void) { + void Init(void) + { mProtocolId = kProtocolId; - mFlags = kProtocolVersion << kVersionOffset; + mFlags = kProtocolVersion << kVersionOffset; } /** @@ -1092,9 +1113,7 @@ public: * @retval FALSE if the beacon does not appear to be a valid Thread Beacon Payload. * */ - bool IsValid(void) { - return (mProtocolId == kProtocolId); - } + bool IsValid(void) { return (mProtocolId == kProtocolId); } /** * This method returns the Protocol ID value. @@ -1152,12 +1171,13 @@ public: * This method sets the Joining Permitted flag. * */ - void SetJoiningPermitted(void) { + void SetJoiningPermitted(void) + { mFlags |= kJoiningFlag; #if OPENTHREAD_CONFIG_JOIN_BEACON_VERSION != kProtocolVersion mFlags &= ~kVersionMask; - mFlags |= OPENTHREAD_CONFIG_JOIN_BEACON_VERSION << kVersionOffset; + mFlags |= OPENTHREAD_CONFIG_JOIN_BEACON_VERSION << kVersionOffset; #endif } @@ -1175,7 +1195,8 @@ public: * @param[in] aNetworkName A pointer to the Network Name. * */ - void SetNetworkName(const char *aNetworkName) { + void SetNetworkName(const char *aNetworkName) + { size_t length = strnlen(aNetworkName, sizeof(mNetworkName)); memset(mNetworkName, 0, sizeof(mNetworkName)); memcpy(mNetworkName, aNetworkName, length); @@ -1209,10 +1230,10 @@ public: const char *ToInfoString(char *aBuf, uint16_t aSize); private: - uint8_t mProtocolId; - uint8_t mFlags; - char mNetworkName[kNetworkNameSize]; - uint8_t mExtendedPanId[kExtPanIdSize]; + uint8_t mProtocolId; + uint8_t mFlags; + char mNetworkName[kNetworkNameSize]; + uint8_t mExtendedPanId[kExtPanIdSize]; } OT_TOOL_PACKED_END; /** @@ -1220,7 +1241,7 @@ private: * */ -} // namespace Mac -} // namespace ot +} // namespace Mac +} // namespace ot -#endif // MAC_FRAME_HPP_ +#endif // MAC_FRAME_HPP_ diff --git a/src/core/meshcop/announce_begin_client.cpp b/src/core/meshcop/announce_begin_client.cpp index eb5d6acc2..1380345fe 100644 --- a/src/core/meshcop/announce_begin_client.cpp +++ b/src/core/meshcop/announce_begin_client.cpp @@ -51,28 +51,29 @@ namespace ot { -AnnounceBeginClient::AnnounceBeginClient(Instance &aInstance): - InstanceLocator(aInstance) +AnnounceBeginClient::AnnounceBeginClient(Instance &aInstance) + : InstanceLocator(aInstance) { } -otError AnnounceBeginClient::SendRequest(uint32_t aChannelMask, uint8_t aCount, uint16_t aPeriod, +otError AnnounceBeginClient::SendRequest(uint32_t aChannelMask, + uint8_t aCount, + uint16_t aPeriod, const Ip6::Address &aAddress) { - otError error = OT_ERROR_NONE; - Coap::Header header; + otError error = OT_ERROR_NONE; + Coap::Header header; MeshCoP::CommissionerSessionIdTlv sessionId; - MeshCoP::ChannelMask0Tlv channelMask; - MeshCoP::CountTlv count; - MeshCoP::PeriodTlv period; + MeshCoP::ChannelMask0Tlv channelMask; + MeshCoP::CountTlv count; + MeshCoP::PeriodTlv period; Ip6::MessageInfo messageInfo; - Message *message = NULL; + Message * message = NULL; VerifyOrExit(GetNetif().GetCommissioner().IsActive(), error = OT_ERROR_INVALID_STATE); - header.Init(aAddress.IsMulticast() ? OT_COAP_TYPE_NON_CONFIRMABLE : OT_COAP_TYPE_CONFIRMABLE, - OT_COAP_CODE_POST); + header.Init(aAddress.IsMulticast() ? OT_COAP_TYPE_NON_CONFIRMABLE : OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); header.SetToken(Coap::Header::kDefaultTokenLength); header.AppendUriPathOptions(OT_URI_PATH_ANNOUNCE_BEGIN); header.SetPayloadMarker(); @@ -115,7 +116,6 @@ exit: return error; } -} // namespace ot +} // namespace ot #endif // OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD - diff --git a/src/core/meshcop/announce_begin_client.hpp b/src/core/meshcop/announce_begin_client.hpp index 26b2e4a89..4662c91fe 100644 --- a/src/core/meshcop/announce_begin_client.hpp +++ b/src/core/meshcop/announce_begin_client.hpp @@ -36,8 +36,8 @@ #include "openthread-core-config.h" -#include "common/locator.hpp" #include "coap/coap.hpp" +#include "common/locator.hpp" #include "net/ip6_address.hpp" #include "net/udp6.hpp" @@ -47,7 +47,7 @@ namespace ot { * This class implements handling Announce Begin Requests. * */ -class AnnounceBeginClient: public InstanceLocator +class AnnounceBeginClient : public InstanceLocator { public: /** @@ -74,6 +74,6 @@ public: * @} */ -} // namespace ot +} // namespace ot -#endif // ANNOUNCE_BEGIN_CLIENT_HPP_ +#endif // ANNOUNCE_BEGIN_CLIENT_HPP_ diff --git a/src/core/meshcop/commissioner.cpp b/src/core/meshcop/commissioner.cpp index 50e4d25e5..f11243d11 100644 --- a/src/core/meshcop/commissioner.cpp +++ b/src/core/meshcop/commissioner.cpp @@ -61,21 +61,21 @@ using ot::Encoding::BigEndian::HostSwap64; namespace ot { namespace MeshCoP { -Commissioner::Commissioner(Instance &aInstance): - InstanceLocator(aInstance), - mState(OT_COMMISSIONER_STATE_DISABLED), - mJoinerPort(0), - mJoinerRloc(0), - mJoinerExpirationTimer(aInstance, HandleJoinerExpirationTimer, this), - mTimer(aInstance, HandleTimer, this), - mSessionId(0), - mTransmitAttempts(0), - mRelayReceive(OT_URI_PATH_RELAY_RX, &Commissioner::HandleRelayReceive, this), - mDatasetChanged(OT_URI_PATH_DATASET_CHANGED, &Commissioner::HandleDatasetChanged, this), - mJoinerFinalize(OT_URI_PATH_JOINER_FINALIZE, &Commissioner::HandleJoinerFinalize, this), - mAnnounceBegin(aInstance), - mEnergyScan(aInstance), - mPanIdQuery(aInstance) +Commissioner::Commissioner(Instance &aInstance) + : InstanceLocator(aInstance) + , mState(OT_COMMISSIONER_STATE_DISABLED) + , mJoinerPort(0) + , mJoinerRloc(0) + , mJoinerExpirationTimer(aInstance, HandleJoinerExpirationTimer, this) + , mTimer(aInstance, HandleTimer, this) + , mSessionId(0) + , mTransmitAttempts(0) + , mRelayReceive(OT_URI_PATH_RELAY_RX, &Commissioner::HandleRelayReceive, this) + , mDatasetChanged(OT_URI_PATH_DATASET_CHANGED, &Commissioner::HandleDatasetChanged, this) + , mJoinerFinalize(OT_URI_PATH_JOINER_FINALIZE, &Commissioner::HandleJoinerFinalize, this) + , mAnnounceBegin(aInstance) + , mEnergyScan(aInstance) + , mPanIdQuery(aInstance) { memset(mJoiners, 0, sizeof(mJoiners)); } @@ -106,7 +106,7 @@ otError Commissioner::Start(void) SuccessOrExit(error = GetNetif().GetCoapSecure().Start(OPENTHREAD_CONFIG_JOINER_UDP_PORT, SendRelayTransmit, this)); - mState = OT_COMMISSIONER_STATE_PETITION; + mState = OT_COMMISSIONER_STATE_PETITION; mTransmitAttempts = 0; SendPetition(); @@ -141,17 +141,17 @@ exit: otError Commissioner::SendCommissionerSet(void) { - otError error; + otError error; otCommissioningDataset dataset; - SteeringDataTlv steeringData; - Mac::ExtAddress joinerId; + SteeringDataTlv steeringData; + Mac::ExtAddress joinerId; VerifyOrExit(mState == OT_COMMISSIONER_STATE_ACTIVE, error = OT_ERROR_INVALID_STATE); memset(&dataset, 0, sizeof(dataset)); // session id - dataset.mSessionId = mSessionId; + dataset.mSessionId = mSessionId; dataset.mIsSessionIdSet = true; // compute bloom filter @@ -179,7 +179,7 @@ otError Commissioner::SendCommissionerSet(void) // set bloom filter memcpy(dataset.mSteeringData.m8, steeringData.GetValue(), steeringData.GetLength()); dataset.mSteeringData.mLength = steeringData.GetLength(); - dataset.mIsSteeringDataSet = true; + dataset.mIsSteeringDataSet = true; SuccessOrExit(error = SendMgmtCommissionerSetRequest(dataset, NULL, 0)); @@ -207,7 +207,7 @@ otError Commissioner::AddJoiner(const Mac::ExtAddress *aEui64, const char *aPSKd (aEui64 ? HostSwap64(*reinterpret_cast(aEui64)) : 0), aPSKd); VerifyOrExit(strlen(aPSKd) <= Dtls::kPskMaxLength, error = OT_ERROR_INVALID_ARGS); - RemoveJoiner(aEui64, 0); // remove immediately + RemoveJoiner(aEui64, 0); // remove immediately for (size_t i = 0; i < sizeof(mJoiners) / sizeof(mJoiners[0]); i++) { @@ -227,7 +227,7 @@ otError Commissioner::AddJoiner(const Mac::ExtAddress *aEui64, const char *aPSKd } (void)strlcpy(mJoiners[i].mPsk, aPSKd, sizeof(mJoiners[i].mPsk)); - mJoiners[i].mValid = true; + mJoiners[i].mValid = true; mJoiners[i].mExpirationTime = TimerMilli::GetNow() + TimerMilli::SecToMsec(aTimeout); UpdateJoinerExpirationTimer(); @@ -351,7 +351,7 @@ void Commissioner::HandleJoinerExpirationTimer(void) if (static_cast(now - mJoiners[i].mExpirationTime) >= 0) { otLogDebgMeshCoP(GetInstance(), "removing joiner due to timeout or successfully joined"); - RemoveJoiner(&mJoiners[i].mEui64, 0); // remove immediately + RemoveJoiner(&mJoiners[i].mEui64, 0); // remove immediately } } @@ -360,7 +360,7 @@ void Commissioner::HandleJoinerExpirationTimer(void) void Commissioner::UpdateJoinerExpirationTimer(void) { - uint32_t now = TimerMilli::GetNow(); + uint32_t now = TimerMilli::GetNow(); uint32_t nextTimeout = 0xffffffff; // Check if timer should be set for next Joiner. @@ -391,15 +391,14 @@ void Commissioner::UpdateJoinerExpirationTimer(void) } } -otError Commissioner::SendMgmtCommissionerGetRequest(const uint8_t *aTlvs, - uint8_t aLength) +otError Commissioner::SendMgmtCommissionerGetRequest(const uint8_t *aTlvs, uint8_t aLength) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Coap::Header header; - Message *message; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Coap::Header header; + Message * message; Ip6::MessageInfo messageInfo; - MeshCoP::Tlv tlv; + MeshCoP::Tlv tlv; header.Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); header.SetToken(Coap::Header::kDefaultTokenLength); @@ -438,16 +437,21 @@ exit: return error; } -void Commissioner::HandleMgmtCommissionerGetResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError aResult) +void Commissioner::HandleMgmtCommissionerGetResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aResult) { static_cast(aContext)->HandleMgmtCommissisonerGetResponse( static_cast(aHeader), static_cast(aMessage), static_cast(aMessageInfo), aResult); } -void Commissioner::HandleMgmtCommissisonerGetResponse(Coap::Header *aHeader, Message *aMessage, - const Ip6::MessageInfo *aMessageInfo, otError aResult) +void Commissioner::HandleMgmtCommissisonerGetResponse(Coap::Header * aHeader, + Message * aMessage, + const Ip6::MessageInfo *aMessageInfo, + otError aResult) { OT_UNUSED_VARIABLE(aMessage); OT_UNUSED_VARIABLE(aMessageInfo); @@ -460,12 +464,13 @@ exit: } otError Commissioner::SendMgmtCommissionerSetRequest(const otCommissioningDataset &aDataset, - const uint8_t *aTlvs, uint8_t aLength) + const uint8_t * aTlvs, + uint8_t aLength) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Coap::Header header; - Message *message; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Coap::Header header; + Message * message; Ip6::MessageInfo messageInfo; header.Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); @@ -537,16 +542,21 @@ exit: return error; } -void Commissioner::HandleMgmtCommissionerSetResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError aResult) +void Commissioner::HandleMgmtCommissionerSetResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aResult) { static_cast(aContext)->HandleMgmtCommissisonerSetResponse( static_cast(aHeader), static_cast(aMessage), static_cast(aMessageInfo), aResult); } -void Commissioner::HandleMgmtCommissisonerSetResponse(Coap::Header *aHeader, Message *aMessage, - const Ip6::MessageInfo *aMessageInfo, otError aResult) +void Commissioner::HandleMgmtCommissisonerSetResponse(Coap::Header * aHeader, + Message * aMessage, + const Ip6::MessageInfo *aMessageInfo, + otError aResult) { OT_UNUSED_VARIABLE(aMessage); OT_UNUSED_VARIABLE(aMessageInfo); @@ -560,11 +570,11 @@ exit: otError Commissioner::SendPetition(void) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Coap::Header header; - Message *message = NULL; - Ip6::MessageInfo messageInfo; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Coap::Header header; + Message * message = NULL; + Ip6::MessageInfo messageInfo; CommissionerIdTlv commissionerId; mTransmitAttempts++; @@ -584,8 +594,8 @@ otError Commissioner::SendPetition(void) netif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); messageInfo.SetPeerPort(kCoapUdpPort); messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo, - Commissioner::HandleLeaderPetitionResponse, this)); + SuccessOrExit( + error = netif.GetCoap().SendMessage(*message, messageInfo, Commissioner::HandleLeaderPetitionResponse, this)); otLogInfoMeshCoP(GetInstance(), "sent petition"); @@ -599,23 +609,27 @@ exit: return error; } -void Commissioner::HandleLeaderPetitionResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError aResult) +void Commissioner::HandleLeaderPetitionResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aResult) { static_cast(aContext)->HandleLeaderPetitionResponse( static_cast(aHeader), static_cast(aMessage), static_cast(aMessageInfo), aResult); - } -void Commissioner::HandleLeaderPetitionResponse(Coap::Header *aHeader, Message *aMessage, - const Ip6::MessageInfo *aMessageInfo, otError aResult) +void Commissioner::HandleLeaderPetitionResponse(Coap::Header * aHeader, + Message * aMessage, + const Ip6::MessageInfo *aMessageInfo, + otError aResult) { - (void) aMessageInfo; + (void)aMessageInfo; - StateTlv state; + StateTlv state; CommissionerSessionIdTlv sessionId; - bool retransmit = false; + bool retransmit = false; VerifyOrExit(mState == OT_COMMISSIONER_STATE_PETITION, mState = OT_COMMISSIONER_STATE_DISABLED); VerifyOrExit(aResult == OT_ERROR_NONE && aHeader->GetCode() == OT_COAP_CODE_CHANGED, retransmit = true); @@ -656,12 +670,12 @@ exit: otError Commissioner::SendKeepAlive(void) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Coap::Header header; - Message *message = NULL; - Ip6::MessageInfo messageInfo; - StateTlv state; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Coap::Header header; + Message * message = NULL; + Ip6::MessageInfo messageInfo; + StateTlv state; CommissionerSessionIdTlv sessionId; header.Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); @@ -682,8 +696,8 @@ otError Commissioner::SendKeepAlive(void) messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); netif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo, - Commissioner::HandleLeaderKeepAliveResponse, this)); + SuccessOrExit( + error = netif.GetCoap().SendMessage(*message, messageInfo, Commissioner::HandleLeaderKeepAliveResponse, this)); otLogInfoMeshCoP(GetInstance(), "sent keep alive"); @@ -697,18 +711,23 @@ exit: return error; } -void Commissioner::HandleLeaderKeepAliveResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError aResult) +void Commissioner::HandleLeaderKeepAliveResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aResult) { static_cast(aContext)->HandleLeaderKeepAliveResponse( static_cast(aHeader), static_cast(aMessage), static_cast(aMessageInfo), aResult); } -void Commissioner::HandleLeaderKeepAliveResponse(Coap::Header *aHeader, Message *aMessage, - const Ip6::MessageInfo *aMessageInfo, otError aResult) +void Commissioner::HandleLeaderKeepAliveResponse(Coap::Header * aHeader, + Message * aMessage, + const Ip6::MessageInfo *aMessageInfo, + otError aResult) { - (void) aMessageInfo; + (void)aMessageInfo; StateTlv state; @@ -733,31 +752,32 @@ exit: } } -void Commissioner::HandleRelayReceive(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void Commissioner::HandleRelayReceive(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleRelayReceive( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleRelayReceive(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void Commissioner::HandleRelayReceive(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - otError error; - JoinerUdpPortTlv joinerPort; - JoinerIidTlv joinerIid; + ThreadNetif & netif = GetNetif(); + otError error; + JoinerUdpPortTlv joinerPort; + JoinerIidTlv joinerIid; JoinerRouterLocatorTlv joinerRloc; - Ip6::MessageInfo joinerMessageInfo; - uint16_t offset; - uint16_t length; - bool enableJoiner = false; - Mac::ExtAddress joinerId; + Ip6::MessageInfo joinerMessageInfo; + uint16_t offset; + uint16_t length; + bool enableJoiner = false; + Mac::ExtAddress joinerId; VerifyOrExit(mState == OT_COMMISSIONER_STATE_ACTIVE, error = OT_ERROR_INVALID_STATE); - VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_NON_CONFIRMABLE && - aHeader.GetCode() == OT_COAP_CODE_POST); + VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_NON_CONFIRMABLE && aHeader.GetCode() == OT_COAP_CODE_POST); SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kJoinerUdpPort, sizeof(joinerPort), joinerPort)); VerifyOrExit(joinerPort.IsValid(), error = OT_ERROR_PARSE); @@ -787,7 +807,6 @@ void Commissioner::HandleRelayReceive(Coap::Header &aHeader, Message &aMessage, if (mJoiners[i].mAny || !memcmp(&joinerId, mJoinerIid, sizeof(joinerId))) { - error = netif.GetCoapSecure().SetPsk(reinterpret_cast(mJoiners[i].mPsk), static_cast(strlen(mJoiners[i].mPsk))); SuccessOrExit(error); @@ -826,18 +845,19 @@ exit: return; } -void Commissioner::HandleDatasetChanged(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void Commissioner::HandleDatasetChanged(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleDatasetChanged( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleDatasetChanged(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void Commissioner::HandleDatasetChanged(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && - aHeader.GetCode() == OT_COAP_CODE_POST); + VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && aHeader.GetCode() == OT_COAP_CODE_POST); otLogInfoMeshCoP(GetInstance(), "received dataset changed"); OT_UNUSED_VARIABLE(aMessage); @@ -850,18 +870,20 @@ exit: return; } -void Commissioner::HandleJoinerFinalize(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void Commissioner::HandleJoinerFinalize(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleJoinerFinalize( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleJoinerFinalize(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void Commissioner::HandleJoinerFinalize(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { OT_UNUSED_VARIABLE(aMessageInfo); - StateTlv::State state = StateTlv::kAccept; + StateTlv::State state = StateTlv::kAccept; ProvisioningUrlTlv provisioningUrl; otLogInfoMeshCoP(GetInstance(), "received joiner finalize"); @@ -889,16 +911,15 @@ exit: SendJoinFinalizeResponse(aHeader, state); } - void Commissioner::SendJoinFinalizeResponse(const Coap::Header &aRequestHeader, StateTlv::State aState) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Coap::Header responseHeader; - Ip6::MessageInfo joinerMessageInfo; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Coap::Header responseHeader; + Ip6::MessageInfo joinerMessageInfo; MeshCoP::StateTlv stateTlv; - Message *message; - Mac::ExtAddress extAddr; + Message * message; + Mac::ExtAddress extAddr; responseHeader.SetDefaultResponseHeader(aRequestHeader); responseHeader.SetPayloadMarker(); @@ -928,7 +949,7 @@ void Commissioner::SendJoinFinalizeResponse(const Coap::Header &aRequestHeader, memcpy(extAddr.m8, mJoinerIid, sizeof(extAddr.m8)); extAddr.SetLocal(!extAddr.IsLocal()); - RemoveJoiner(&extAddr, kRemoveJoinerDelay); // remove after kRemoveJoinerDelay (seconds) + RemoveJoiner(&extAddr, kRemoveJoinerDelay); // remove after kRemoveJoinerDelay (seconds) otLogInfoMeshCoP(GetInstance(), "sent joiner finalize response"); @@ -947,16 +968,16 @@ otError Commissioner::SendRelayTransmit(void *aContext, Message &aMessage, const otError Commissioner::SendRelayTransmit(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Coap::Header header; - JoinerUdpPortTlv udpPort; - JoinerIidTlv iid; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Coap::Header header; + JoinerUdpPortTlv udpPort; + JoinerIidTlv iid; JoinerRouterLocatorTlv rloc; - ExtendedTlv tlv; - Message *message; - uint16_t offset; - Ip6::MessageInfo messageInfo; + ExtendedTlv tlv; + Message * message; + uint16_t offset; + Ip6::MessageInfo messageInfo; OT_UNUSED_VARIABLE(aMessageInfo); @@ -1012,16 +1033,19 @@ exit: return error; } -otError Commissioner::GeneratePSKc(const char *aPassPhrase, const char *aNetworkName, const uint8_t *aExtPanId, - uint8_t *aPSKc) +otError Commissioner::GeneratePSKc(const char * aPassPhrase, + const char * aNetworkName, + const uint8_t *aExtPanId, + uint8_t * aPSKc) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; const char *saltPrefix = "Thread"; - uint8_t salt[OT_PBKDF2_SALT_MAX_LEN]; - uint16_t saltLen = 0; + uint8_t salt[OT_PBKDF2_SALT_MAX_LEN]; + uint16_t saltLen = 0; VerifyOrExit((strlen(aPassPhrase) >= OT_COMMISSIONING_PASSPHRASE_MIN_SIZE) && - (strlen(aPassPhrase) <= OT_COMMISSIONING_PASSPHRASE_MAX_SIZE), error = OT_ERROR_INVALID_ARGS); + (strlen(aPassPhrase) <= OT_COMMISSIONING_PASSPHRASE_MAX_SIZE), + error = OT_ERROR_INVALID_ARGS); memset(salt, 0, sizeof(salt)); memcpy(salt, saltPrefix, strlen(saltPrefix)); @@ -1040,7 +1064,7 @@ exit: return error; } -} // namespace MeshCoP -} // namespace ot +} // namespace MeshCoP +} // namespace ot #endif // OPENTHREAD_FTD && OPENTHREAD_ENABLE_COMMISSIONER diff --git a/src/core/meshcop/commissioner.hpp b/src/core/meshcop/commissioner.hpp index 2ff2af6eb..c4ba33818 100644 --- a/src/core/meshcop/commissioner.hpp +++ b/src/core/meshcop/commissioner.hpp @@ -56,7 +56,7 @@ class ThreadNetif; namespace MeshCoP { -class Commissioner: public InstanceLocator +class Commissioner : public InstanceLocator { public: /** @@ -167,7 +167,7 @@ public: /** * This method sends MGMT_COMMISSIONER_SET. - * + * * @param[in] aDataset A reference to Commissioning Data. * @param[in] aTlvs A pointer to user specific Commissioning Data TLVs. * @param[in] aLength The length of user specific TLVs in bytes. @@ -177,7 +177,8 @@ public: * */ otError SendMgmtCommissionerSetRequest(const otCommissioningDataset &aDataset, - const uint8_t *aTlvs, uint8_t aLength); + const uint8_t * aTlvs, + uint8_t aLength); /** * This static method generates PSKc. @@ -193,8 +194,10 @@ public: * @retval OT_ERROR_INVALID_ARGS If the length of passphrase is out of range. * */ - static otError GeneratePSKc(const char *aPassPhrase, const char *aNetworkName, const uint8_t *aExtPanId, - uint8_t *aPSKc); + static otError GeneratePSKc(const char * aPassPhrase, + const char * aNetworkName, + const uint8_t *aExtPanId, + uint8_t * aPSKc); /** * This method returns a reference to the AnnounceBeginClient instance. @@ -223,57 +226,83 @@ public: private: enum { - kPetitionAttemptDelay = 5, ///< COMM_PET_ATTEMPT_DELAY (seconds) - kPetitionRetryCount = 2, ///< COMM_PET_RETRY_COUNT - kPetitionRetryDelay = 1, ///< COMM_PET_RETRY_DELAY (seconds) - kKeepAliveTimeout = 50, ///< TIMEOUT_COMM_PET (seconds) - kRemoveJoinerDelay = 20, ///< Delay to remove successfully joined joiner + kPetitionAttemptDelay = 5, ///< COMM_PET_ATTEMPT_DELAY (seconds) + kPetitionRetryCount = 2, ///< COMM_PET_RETRY_COUNT + kPetitionRetryDelay = 1, ///< COMM_PET_RETRY_DELAY (seconds) + kKeepAliveTimeout = 50, ///< TIMEOUT_COMM_PET (seconds) + kRemoveJoinerDelay = 20, ///< Delay to remove successfully joined joiner }; void AddCoapResources(void); void RemoveCoapResources(void); static void HandleTimer(Timer &aTimer); - void HandleTimer(void); + void HandleTimer(void); static void HandleJoinerExpirationTimer(Timer &aTimer); - void HandleJoinerExpirationTimer(void); + void HandleJoinerExpirationTimer(void); void UpdateJoinerExpirationTimer(void); - static void HandleMgmtCommissionerSetResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError aResult); - void HandleMgmtCommissisonerSetResponse(Coap::Header *aHeader, Message *aMessage, - const Ip6::MessageInfo *aMessageInfo, otError aResult); - static void HandleMgmtCommissionerGetResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError aResult); - void HandleMgmtCommissisonerGetResponse(Coap::Header *aHeader, Message *aMessage, - const Ip6::MessageInfo *aMessageInfo, otError aResult); - static void HandleLeaderPetitionResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError aResult); - void HandleLeaderPetitionResponse(Coap::Header *aHeader, Message *aMessage, - const Ip6::MessageInfo *aMessageInfo, otError aResult); - static void HandleLeaderKeepAliveResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError aResult); - void HandleLeaderKeepAliveResponse(Coap::Header *aHeader, Message *aMessage, - const Ip6::MessageInfo *aMessageInfo, otError aResult); + static void HandleMgmtCommissionerSetResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aResult); + void HandleMgmtCommissisonerSetResponse(Coap::Header * aHeader, + Message * aMessage, + const Ip6::MessageInfo *aMessageInfo, + otError aResult); + static void HandleMgmtCommissionerGetResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aResult); + void HandleMgmtCommissisonerGetResponse(Coap::Header * aHeader, + Message * aMessage, + const Ip6::MessageInfo *aMessageInfo, + otError aResult); + static void HandleLeaderPetitionResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aResult); + void HandleLeaderPetitionResponse(Coap::Header * aHeader, + Message * aMessage, + const Ip6::MessageInfo *aMessageInfo, + otError aResult); + static void HandleLeaderKeepAliveResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aResult); + void HandleLeaderKeepAliveResponse(Coap::Header * aHeader, + Message * aMessage, + const Ip6::MessageInfo *aMessageInfo, + otError aResult); - static void HandleRelayReceive(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleRelayReceive(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleRelayReceive(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleRelayReceive(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - static void HandleDatasetChanged(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleDatasetChanged(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleDatasetChanged(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleDatasetChanged(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - static void HandleJoinerFinalize(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleJoinerFinalize(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleJoinerFinalize(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleJoinerFinalize(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); void SendJoinFinalizeResponse(const Coap::Header &aRequestHeader, StateTlv::State aState); static otError SendRelayTransmit(void *aContext, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - otError SendRelayTransmit(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + otError SendRelayTransmit(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); otError SendCommissionerSet(void); otError SendPetition(void); @@ -284,36 +313,36 @@ private: struct Joiner { Mac::ExtAddress mEui64; - uint32_t mExpirationTime; - char mPsk[Dtls::kPskMaxLength + 1]; - bool mValid : 1; - bool mAny : 1; + uint32_t mExpirationTime; + char mPsk[Dtls::kPskMaxLength + 1]; + bool mValid : 1; + bool mAny : 1; }; Joiner mJoiners[OPENTHREAD_CONFIG_MAX_JOINER_ENTRIES]; union { - uint8_t mJoinerIid[8]; + uint8_t mJoinerIid[8]; uint64_t mJoinerIid64; }; - uint16_t mJoinerPort; - uint16_t mJoinerRloc; + uint16_t mJoinerPort; + uint16_t mJoinerRloc; TimerMilli mJoinerExpirationTimer; TimerMilli mTimer; - uint16_t mSessionId; - uint8_t mTransmitAttempts; + uint16_t mSessionId; + uint8_t mTransmitAttempts; Coap::Resource mRelayReceive; Coap::Resource mDatasetChanged; Coap::Resource mJoinerFinalize; AnnounceBeginClient mAnnounceBegin; - EnergyScanClient mEnergyScan; - PanIdQueryClient mPanIdQuery; + EnergyScanClient mEnergyScan; + PanIdQueryClient mPanIdQuery; }; -} // namespace MeshCoP -} // namespace ot +} // namespace MeshCoP +} // namespace ot -#endif // COMMISSIONER_HPP_ +#endif // COMMISSIONER_HPP_ diff --git a/src/core/meshcop/dataset.cpp b/src/core/meshcop/dataset.cpp index 523696b5a..4e8d9f676 100644 --- a/src/core/meshcop/dataset.cpp +++ b/src/core/meshcop/dataset.cpp @@ -48,10 +48,10 @@ namespace ot { namespace MeshCoP { -Dataset::Dataset(const Tlv::Type aType) : - mUpdateTime(0), - mLength(0), - mType(aType) +Dataset::Dataset(const Tlv::Type aType) + : mUpdateTime(0) + , mLength(0) + , mType(aType) { memset(mTlvs, 0, sizeof(mTlvs)); } @@ -63,8 +63,8 @@ void Dataset::Clear(void) Tlv *Dataset::Get(Tlv::Type aType) { - Tlv *cur = reinterpret_cast(mTlvs); - Tlv *end = reinterpret_cast(mTlvs + mLength); + Tlv *cur = reinterpret_cast(mTlvs); + Tlv *end = reinterpret_cast(mTlvs + mLength); Tlv *rval = NULL; while (cur < end) @@ -83,8 +83,8 @@ exit: const Tlv *Dataset::Get(Tlv::Type aType) const { - const Tlv *cur = reinterpret_cast(mTlvs); - const Tlv *end = reinterpret_cast(mTlvs + mLength); + const Tlv *cur = reinterpret_cast(mTlvs); + const Tlv *end = reinterpret_cast(mTlvs + mLength); const Tlv *rval = NULL; while (cur < end) @@ -112,42 +112,41 @@ void Dataset::Get(otOperationalDataset &aDataset) const { switch (cur->GetType()) { - case Tlv::kActiveTimestamp: { - const ActiveTimestampTlv *tlv = static_cast(cur); - aDataset.mActiveTimestamp = tlv->GetSeconds(); + const ActiveTimestampTlv *tlv = static_cast(cur); + aDataset.mActiveTimestamp = tlv->GetSeconds(); aDataset.mIsActiveTimestampSet = true; break; } case Tlv::kChannel: { - const ChannelTlv *tlv = static_cast(cur); - aDataset.mChannel = tlv->GetChannel(); + const ChannelTlv *tlv = static_cast(cur); + aDataset.mChannel = tlv->GetChannel(); aDataset.mIsChannelSet = true; break; } case Tlv::kChannelMask: { - uint8_t length = cur->GetLength(); - const uint8_t *entry = reinterpret_cast(cur) + sizeof(Tlv); - const uint8_t *entryEnd = entry + length; + uint8_t length = cur->GetLength(); + const uint8_t *entry = reinterpret_cast(cur) + sizeof(Tlv); + const uint8_t *entryEnd = entry + length; while (entry < entryEnd) { if (reinterpret_cast(entry)->GetChannelPage() == 0) { - uint8_t i = sizeof(ChannelMaskEntry); - aDataset.mChannelMaskPage0 = static_cast(entry[i] | (entry[i + 1] << 8) | + uint8_t i = sizeof(ChannelMaskEntry); + aDataset.mChannelMaskPage0 = static_cast(entry[i] | (entry[i + 1] << 8) | (entry[i + 2] << 16) | (entry[i + 3] << 24)); aDataset.mIsChannelMaskPage0Set = true; break; } - entry += (reinterpret_cast(entry)->GetMaskLength() + - sizeof(ChannelMaskEntry)); + entry += + (reinterpret_cast(entry)->GetMaskLength() + sizeof(ChannelMaskEntry)); } break; @@ -156,8 +155,8 @@ void Dataset::Get(otOperationalDataset &aDataset) const case Tlv::kDelayTimer: { const DelayTimerTlv *tlv = static_cast(cur); - aDataset.mDelay = tlv->GetDelayTimer(); - aDataset.mIsDelaySet = true; + aDataset.mDelay = tlv->GetDelayTimer(); + aDataset.mIsDelaySet = true; break; } @@ -180,8 +179,8 @@ void Dataset::Get(otOperationalDataset &aDataset) const case Tlv::kNetworkMasterKey: { const NetworkMasterKeyTlv *tlv = static_cast(cur); - aDataset.mMasterKey = tlv->GetNetworkMasterKey(); - aDataset.mIsMasterKeySet = true; + aDataset.mMasterKey = tlv->GetNetworkMasterKey(); + aDataset.mIsMasterKeySet = true; break; } @@ -190,22 +189,22 @@ void Dataset::Get(otOperationalDataset &aDataset) const const NetworkNameTlv *tlv = static_cast(cur); memcpy(aDataset.mNetworkName.m8, tlv->GetNetworkName(), tlv->GetLength()); aDataset.mNetworkName.m8[tlv->GetLength()] = '\0'; - aDataset.mIsNetworkNameSet = true; + aDataset.mIsNetworkNameSet = true; break; } case Tlv::kPanId: { const PanIdTlv *panid = static_cast(cur); - aDataset.mPanId = panid->GetPanId(); - aDataset.mIsPanIdSet = true; + aDataset.mPanId = panid->GetPanId(); + aDataset.mIsPanIdSet = true; break; } case Tlv::kPendingTimestamp: { - const PendingTimestampTlv *tlv = static_cast(cur); - aDataset.mPendingTimestamp = tlv->GetSeconds(); + const PendingTimestampTlv *tlv = static_cast(cur); + aDataset.mPendingTimestamp = tlv->GetSeconds(); aDataset.mIsPendingTimestampSet = true; break; } @@ -220,10 +219,10 @@ void Dataset::Get(otOperationalDataset &aDataset) const case Tlv::kSecurityPolicy: { - const SecurityPolicyTlv *tlv = static_cast(cur); + const SecurityPolicyTlv *tlv = static_cast(cur); aDataset.mSecurityPolicy.mRotationTime = tlv->GetRotationTime(); - aDataset.mSecurityPolicy.mFlags = tlv->GetFlags(); - aDataset.mIsSecurityPolicySet = true; + aDataset.mSecurityPolicy.mFlags = tlv->GetFlags(); + aDataset.mIsSecurityPolicySet = true; break; } @@ -256,7 +255,7 @@ otError Dataset::Set(const Dataset &aDataset) #if OPENTHREAD_FTD otError Dataset::Set(const otOperationalDataset &aDataset) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; MeshCoP::ActiveTimestampTlv activeTimestampTlv; VerifyOrExit(aDataset.mIsActiveTimestampSet, error = OT_ERROR_INVALID_ARGS); @@ -365,7 +364,7 @@ otError Dataset::Set(const otOperationalDataset &aDataset) exit: return error; } -#endif // OPENTHREAD_FTD +#endif // OPENTHREAD_FTD const Timestamp *Dataset::GetTimestamp(void) const { @@ -408,9 +407,9 @@ void Dataset::SetTimestamp(const Timestamp &aTimestamp) otError Dataset::Set(const Tlv &aTlv) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint16_t bytesAvailable = sizeof(mTlvs) - mLength; - Tlv *old = Get(aTlv.GetType()); + Tlv * old = Get(aTlv.GetType()); if (old != NULL) { @@ -461,11 +460,11 @@ exit: otError Dataset::AppendMleDatasetTlv(Message &aMessage) const { - otError error = OT_ERROR_NONE; - Mle::Tlv tlv; + otError error = OT_ERROR_NONE; + Mle::Tlv tlv; Mle::Tlv::Type type; - const Tlv *cur = reinterpret_cast(mTlvs); - const Tlv *end = reinterpret_cast(mTlvs + mLength); + const Tlv * cur = reinterpret_cast(mTlvs); + const Tlv * end = reinterpret_cast(mTlvs + mLength); VerifyOrExit(mLength > 0); @@ -483,7 +482,7 @@ otError Dataset::AppendMleDatasetTlv(Message &aMessage) const } else if (cur->GetType() == Tlv::kDelayTimer) { - uint32_t elapsed = TimerMilli::GetNow() - mUpdateTime; + uint32_t elapsed = TimerMilli::GetNow() - mUpdateTime; DelayTimerTlv delayTimer; memcpy(&delayTimer, cur, sizeof(delayTimer)); @@ -535,12 +534,12 @@ void Dataset::Remove(uint8_t *aStart, uint8_t aLength) otError Dataset::ApplyConfiguration(Instance &aInstance) const { - ThreadNetif &netif = aInstance.GetThreadNetif(); - Notifier ¬ifier = aInstance.GetNotifier(); - Mac::Mac &mac = netif.GetMac(); - otError error = OT_ERROR_NONE; - const Tlv *cur = reinterpret_cast(mTlvs); - const Tlv *end = reinterpret_cast(mTlvs + mLength); + ThreadNetif &netif = aInstance.GetThreadNetif(); + Notifier & notifier = aInstance.GetNotifier(); + Mac::Mac & mac = netif.GetMac(); + otError error = OT_ERROR_NONE; + const Tlv * cur = reinterpret_cast(mTlvs); + const Tlv * end = reinterpret_cast(mTlvs + mLength); while (cur < end) { @@ -556,8 +555,7 @@ otError Dataset::ApplyConfiguration(Instance &aInstance) const if (error != OT_ERROR_NONE) { - otLogWarnMeshCoP(aInstance, - "DatasetManager::ApplyConfiguration() Failed to set channel to %d (%s)", + otLogWarnMeshCoP(aInstance, "DatasetManager::ApplyConfiguration() Failed to set channel to %d (%s)", channel, otThreadErrorToString(error)); ExitNow(); } @@ -597,7 +595,7 @@ otError Dataset::ApplyConfiguration(Instance &aInstance) const case Tlv::kNetworkName: { const NetworkNameTlv *name = static_cast(cur); - otNetworkName networkName; + otNetworkName networkName; memcpy(networkName.m8, name->GetNetworkName(), name->GetLength()); networkName.m8[name->GetLength()] = '\0'; @@ -664,5 +662,5 @@ otError Dataset::ConvertToActive(void) return OT_ERROR_NONE; } -} // namespace MeshCoP -} // namespace ot +} // namespace MeshCoP +} // namespace ot diff --git a/src/core/meshcop/dataset.hpp b/src/core/meshcop/dataset.hpp index 31d952c90..9c21620a2 100644 --- a/src/core/meshcop/dataset.hpp +++ b/src/core/meshcop/dataset.hpp @@ -51,7 +51,7 @@ class Dataset public: enum { - kMaxSize = 256, ///< Maximum size of MeshCoP Dataset (bytes) + kMaxSize = 256, ///< Maximum size of MeshCoP Dataset (bytes) kMaxValueSize = 16, /// < Maximum size of each Dataset TLV value (bytes) }; @@ -220,13 +220,13 @@ private: void Remove(uint8_t *aStart, uint8_t aLength); - uint8_t mTlvs[kMaxSize]; ///< The Dataset buffer - uint32_t mUpdateTime; ///< Local time last updated - uint16_t mLength; ///< The number of valid bytes in @var mTlvs - Tlv::Type mType; ///< Active or Pending + uint8_t mTlvs[kMaxSize]; ///< The Dataset buffer + uint32_t mUpdateTime; ///< Local time last updated + uint16_t mLength; ///< The number of valid bytes in @var mTlvs + Tlv::Type mType; ///< Active or Pending }; -} // namespace MeshCoP -} // namespace ot +} // namespace MeshCoP +} // namespace ot -#endif // MESHCOP_DATASET_HPP_ +#endif // MESHCOP_DATASET_HPP_ diff --git a/src/core/meshcop/dataset_local.cpp b/src/core/meshcop/dataset_local.cpp index a35312324..bae25c40e 100644 --- a/src/core/meshcop/dataset_local.cpp +++ b/src/core/meshcop/dataset_local.cpp @@ -41,8 +41,8 @@ #include #include "common/code_utils.hpp" -#include "common/logging.hpp" #include "common/instance.hpp" +#include "common/logging.hpp" #include "common/settings.hpp" #include "meshcop/dataset.hpp" #include "meshcop/meshcop_tlvs.hpp" @@ -51,10 +51,10 @@ namespace ot { namespace MeshCoP { -DatasetLocal::DatasetLocal(Instance &aInstance, const Tlv::Type aType) : - InstanceLocator(aInstance), - mUpdateTime(0), - mType(aType) +DatasetLocal::DatasetLocal(Instance &aInstance, const Tlv::Type aType) + : InstanceLocator(aInstance) + , mUpdateTime(0) + , mType(aType) { } @@ -66,11 +66,11 @@ void DatasetLocal::Clear(void) otError DatasetLocal::Get(Dataset &aDataset) const { DelayTimerTlv *delayTimer; - uint32_t elapsed; - otError error; + uint32_t elapsed; + otError error; aDataset.mLength = sizeof(aDataset.mTlvs); - error = otPlatSettingsGet(&GetInstance(), GetSettingsKey(), 0, aDataset.mTlvs, &aDataset.mLength); + error = otPlatSettingsGet(&GetInstance(), GetSettingsKey(), 0, aDataset.mTlvs, &aDataset.mLength); VerifyOrExit(error == OT_ERROR_NONE, aDataset.mLength = 0); delayTimer = static_cast(aDataset.Get(Tlv::kDelayTimer)); @@ -103,7 +103,7 @@ otError DatasetLocal::Get(otOperationalDataset &aDataset) const memset(&aDataset, 0, sizeof(aDataset)); dataset.mLength = sizeof(dataset.mTlvs); - error = otPlatSettingsGet(&GetInstance(), GetSettingsKey(), 0, dataset.mTlvs, &dataset.mLength); + error = otPlatSettingsGet(&GetInstance(), GetSettingsKey(), 0, dataset.mTlvs, &dataset.mLength); SuccessOrExit(error); cur = reinterpret_cast(dataset.mTlvs); @@ -113,42 +113,41 @@ otError DatasetLocal::Get(otOperationalDataset &aDataset) const { switch (cur->GetType()) { - case Tlv::kActiveTimestamp: { - const ActiveTimestampTlv *tlv = static_cast(cur); - aDataset.mActiveTimestamp = tlv->GetSeconds(); + const ActiveTimestampTlv *tlv = static_cast(cur); + aDataset.mActiveTimestamp = tlv->GetSeconds(); aDataset.mIsActiveTimestampSet = true; break; } case Tlv::kChannel: { - const ChannelTlv *tlv = static_cast(cur); - aDataset.mChannel = tlv->GetChannel(); + const ChannelTlv *tlv = static_cast(cur); + aDataset.mChannel = tlv->GetChannel(); aDataset.mIsChannelSet = true; break; } case Tlv::kChannelMask: { - uint8_t tlvLength = cur->GetLength(); - const uint8_t *entry = reinterpret_cast(cur) + sizeof(Tlv); - const uint8_t *entryEnd = entry + tlvLength; + uint8_t tlvLength = cur->GetLength(); + const uint8_t *entry = reinterpret_cast(cur) + sizeof(Tlv); + const uint8_t *entryEnd = entry + tlvLength; while (entry < entryEnd) { if (reinterpret_cast(entry)->GetChannelPage() == 0) { - uint8_t i = sizeof(ChannelMaskEntry); - aDataset.mChannelMaskPage0 = static_cast(entry[i] | (entry[i + 1] << 8) | + uint8_t i = sizeof(ChannelMaskEntry); + aDataset.mChannelMaskPage0 = static_cast(entry[i] | (entry[i + 1] << 8) | (entry[i + 2] << 16) | (entry[i + 3] << 24)); aDataset.mIsChannelMaskPage0Set = true; break; } - entry += (reinterpret_cast(entry)->GetMaskLength() + - sizeof(ChannelMaskEntry)); + entry += + (reinterpret_cast(entry)->GetMaskLength() + sizeof(ChannelMaskEntry)); } break; @@ -157,8 +156,8 @@ otError DatasetLocal::Get(otOperationalDataset &aDataset) const case Tlv::kDelayTimer: { const DelayTimerTlv *tlv = static_cast(cur); - aDataset.mDelay = tlv->GetDelayTimer(); - aDataset.mIsDelaySet = true; + aDataset.mDelay = tlv->GetDelayTimer(); + aDataset.mIsDelaySet = true; break; } @@ -181,15 +180,15 @@ otError DatasetLocal::Get(otOperationalDataset &aDataset) const case Tlv::kNetworkMasterKey: { const NetworkMasterKeyTlv *tlv = static_cast(cur); - aDataset.mMasterKey = tlv->GetNetworkMasterKey(); - aDataset.mIsMasterKeySet = true; + aDataset.mMasterKey = tlv->GetNetworkMasterKey(); + aDataset.mIsMasterKeySet = true; break; } case Tlv::kNetworkName: { - const NetworkNameTlv *tlv = static_cast(cur); - uint8_t length = tlv->GetLength(); + const NetworkNameTlv *tlv = static_cast(cur); + uint8_t length = tlv->GetLength(); if (length > sizeof(aDataset.mNetworkName) - 1) { @@ -198,22 +197,22 @@ otError DatasetLocal::Get(otOperationalDataset &aDataset) const memcpy(aDataset.mNetworkName.m8, tlv->GetNetworkName(), length); aDataset.mNetworkName.m8[length] = '\0'; - aDataset.mIsNetworkNameSet = true; + aDataset.mIsNetworkNameSet = true; break; } case Tlv::kPanId: { const PanIdTlv *panid = static_cast(cur); - aDataset.mPanId = panid->GetPanId(); - aDataset.mIsPanIdSet = true; + aDataset.mPanId = panid->GetPanId(); + aDataset.mIsPanIdSet = true; break; } case Tlv::kPendingTimestamp: { - const PendingTimestampTlv *tlv = static_cast(cur); - aDataset.mPendingTimestamp = tlv->GetSeconds(); + const PendingTimestampTlv *tlv = static_cast(cur); + aDataset.mPendingTimestamp = tlv->GetSeconds(); aDataset.mIsPendingTimestampSet = true; break; } @@ -228,10 +227,10 @@ otError DatasetLocal::Get(otOperationalDataset &aDataset) const case Tlv::kSecurityPolicy: { - const SecurityPolicyTlv *tlv = static_cast(cur); + const SecurityPolicyTlv *tlv = static_cast(cur); aDataset.mSecurityPolicy.mRotationTime = tlv->GetRotationTime(); - aDataset.mSecurityPolicy.mFlags = tlv->GetFlags(); - aDataset.mIsSecurityPolicySet = true; + aDataset.mSecurityPolicy.mFlags = tlv->GetFlags(); + aDataset.mIsSecurityPolicySet = true; break; } @@ -252,8 +251,8 @@ exit: otError DatasetLocal::Set(const otOperationalDataset &aDataset) { - otError error = OT_ERROR_NONE; - Dataset dataset(mType); + otError error = OT_ERROR_NONE; + Dataset dataset(mType); MeshCoP::ActiveTimestampTlv activeTimestampTlv; VerifyOrExit(aDataset.mIsActiveTimestampSet, error = OT_ERROR_INVALID_ARGS); @@ -372,7 +371,7 @@ exit: return error; } -#endif // OPENTHREAD_FTD +#endif // OPENTHREAD_FTD otError DatasetLocal::Set(const Dataset &aDataset) { @@ -423,8 +422,8 @@ uint16_t DatasetLocal::GetSettingsKey(void) const int DatasetLocal::Compare(const Timestamp *aCompareTimestamp) { const Timestamp *thisTimestamp; - Dataset dataset(mType); - int rval = 1; + Dataset dataset(mType); + int rval = 1; SuccessOrExit(Get(dataset)); @@ -451,5 +450,5 @@ exit: return rval; } -} // namespace MeshCoP -} // namespace ot +} // namespace MeshCoP +} // namespace ot diff --git a/src/core/meshcop/dataset_local.hpp b/src/core/meshcop/dataset_local.hpp index 0b6bd7c0f..aa7965538 100644 --- a/src/core/meshcop/dataset_local.hpp +++ b/src/core/meshcop/dataset_local.hpp @@ -44,7 +44,7 @@ namespace ot { namespace MeshCoP { -class DatasetLocal: public InstanceLocator +class DatasetLocal : public InstanceLocator { public: /** @@ -133,13 +133,13 @@ public: private: uint16_t GetSettingsKey(void) const; - void SetTimestamp(const Dataset &aDataset); + void SetTimestamp(const Dataset &aDataset); - uint32_t mUpdateTime; ///< Local time last updated - Tlv::Type mType; ///< Active or Pending + uint32_t mUpdateTime; ///< Local time last updated + Tlv::Type mType; ///< Active or Pending }; -} // namespace MeshCoP -} // namespace ot +} // namespace MeshCoP +} // namespace ot -#endif // MESHCOP_DATASET_LOCAL_HPP_ +#endif // MESHCOP_DATASET_LOCAL_HPP_ diff --git a/src/core/meshcop/dataset_manager.cpp b/src/core/meshcop/dataset_manager.cpp index 55d1cedfb..41269f3eb 100644 --- a/src/core/meshcop/dataset_manager.cpp +++ b/src/core/meshcop/dataset_manager.cpp @@ -52,8 +52,11 @@ namespace ot { namespace MeshCoP { -DatasetManager::DatasetManager(Instance &aInstance, const Tlv::Type aType, const char *aUriGet, - const char *aUriSet, Timer::Handler aTimerHandler) +DatasetManager::DatasetManager(Instance & aInstance, + const Tlv::Type aType, + const char * aUriGet, + const char * aUriSet, + Timer::Handler aTimerHandler) : InstanceLocator(aInstance) , mLocal(aInstance, aType) , mTimestampValid(false) @@ -72,7 +75,7 @@ const Timestamp *DatasetManager::GetTimestamp(void) const int DatasetManager::Compare(const Timestamp &aTimestamp) const { const Timestamp *timestamp = GetTimestamp(); - int rval = 1; + int rval = 1; if (timestamp) { @@ -102,8 +105,8 @@ const Tlv *DatasetManager::GetTlv(Tlv::Type aType) const otError DatasetManager::Restore(void) { - otError error; - Dataset dataset(mLocal.GetType()); + otError error; + Dataset dataset(mLocal.GetType()); const Timestamp *timestamp; mTimer.Stop(); @@ -114,7 +117,7 @@ otError DatasetManager::Restore(void) if (timestamp != NULL) { - mTimestamp = *timestamp; + mTimestamp = *timestamp; mTimestampValid = true; if (mLocal.GetType() == Tlv::kActiveTimestamp) @@ -155,13 +158,13 @@ void DatasetManager::HandleDetach(void) void DatasetManager::Set(const Dataset &aDataset) { const Timestamp *timestamp; - int compare; + int compare; timestamp = aDataset.GetTimestamp(); if (timestamp != NULL) { - mTimestamp = *timestamp; + mTimestamp = *timestamp; mTimestampValid = true; if (mLocal.GetType() == Tlv::kActiveTimestamp) @@ -200,12 +203,11 @@ void DatasetManager::HandleTimer(void) if (mLocal.GetType() == Tlv::kActiveTimestamp) { - const ActiveTimestampTlv *tlv = static_cast(netif.GetPendingDataset().GetTlv( - Tlv::kActiveTimestamp)); + const ActiveTimestampTlv *tlv = + static_cast(netif.GetPendingDataset().GetTlv(Tlv::kActiveTimestamp)); const Timestamp *pendingActiveTimestamp = static_cast(tlv); - if (pendingActiveTimestamp != NULL && - mLocal.Compare(pendingActiveTimestamp) >= 0) + if (pendingActiveTimestamp != NULL && mLocal.Compare(pendingActiveTimestamp) >= 0) { // stop registration attempts during dataset transition ExitNow(); @@ -221,12 +223,12 @@ exit: otError DatasetManager::Register(void) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Coap::Header header; - Message *message; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Coap::Header header; + Message * message; Ip6::MessageInfo messageInfo; - Dataset dataset(mLocal.GetType()); + Dataset dataset(mLocal.GetType()); header.Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); header.SetToken(Coap::Header::kDefaultTokenLength); @@ -255,13 +257,14 @@ exit: return error; } -void DatasetManager::Get(const Coap::Header &aHeader, const Message &aMessage, +void DatasetManager::Get(const Coap::Header & aHeader, + const Message & aMessage, const Ip6::MessageInfo &aMessageInfo) const { - Tlv tlv; + Tlv tlv; uint16_t offset = aMessage.GetOffset(); - uint8_t tlvs[Dataset::kMaxSize]; - uint8_t length = 0; + uint8_t tlvs[Dataset::kMaxSize]; + uint8_t length = 0; while (offset < aMessage.GetLength()) { @@ -299,14 +302,16 @@ void DatasetManager::Get(const Coap::Header &aHeader, const Message &aMessage, SendGetResponse(aHeader, aMessageInfo, tlvs, length); } -void DatasetManager::SendGetResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, - uint8_t *aTlvs, uint8_t aLength) const +void DatasetManager::SendGetResponse(const Coap::Header & aRequestHeader, + const Ip6::MessageInfo &aMessageInfo, + uint8_t * aTlvs, + uint8_t aLength) const { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Coap::Header responseHeader; - Message *message; - Dataset dataset(mLocal.GetType()); + Message * message; + Dataset dataset(mLocal.GetType()); mLocal.Get(dataset); @@ -369,7 +374,10 @@ exit: } ActiveDataset::ActiveDataset(Instance &aInstance) - : DatasetManager(aInstance, Tlv::kActiveTimestamp, OT_URI_PATH_ACTIVE_GET, OT_URI_PATH_ACTIVE_SET, + : DatasetManager(aInstance, + Tlv::kActiveTimestamp, + OT_URI_PATH_ACTIVE_GET, + OT_URI_PATH_ACTIVE_SET, &ActiveDataset::HandleTimer) , mResourceGet(OT_URI_PATH_ACTIVE_GET, &ActiveDataset::HandleGet, this) #if OPENTHREAD_FTD @@ -389,8 +397,7 @@ void ActiveDataset::Set(const Dataset &aDataset) DatasetManager::Set(aDataset); } -otError ActiveDataset::Set(const Timestamp &aTimestamp, const Message &aMessage, - uint16_t aOffset, uint8_t aLength) +otError ActiveDataset::Set(const Timestamp &aTimestamp, const Message &aMessage, uint16_t aOffset, uint8_t aLength) { otError error = OT_ERROR_NONE; Dataset dataset(mLocal.GetType()); @@ -403,12 +410,14 @@ exit: return error; } -void ActiveDataset::HandleGet(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void ActiveDataset::HandleGet(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleGet( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleGet(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void ActiveDataset::HandleGet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) const @@ -422,7 +431,10 @@ void ActiveDataset::HandleTimer(Timer &aTimer) } PendingDataset::PendingDataset(Instance &aInstance) - : DatasetManager(aInstance, Tlv::kPendingTimestamp, OT_URI_PATH_PENDING_GET, OT_URI_PATH_PENDING_SET, + : DatasetManager(aInstance, + Tlv::kPendingTimestamp, + OT_URI_PATH_PENDING_GET, + OT_URI_PATH_PENDING_SET, &PendingDataset::HandleTimer) , mDelayTimer(aInstance, &PendingDataset::HandleDelayTimer, this) , mResourceGet(OT_URI_PATH_PENDING_GET, &PendingDataset::HandleGet, this) @@ -444,8 +456,7 @@ void PendingDataset::ClearNetwork(void) Restore(); } -otError PendingDataset::Set(const Timestamp &aTimestamp, const Message &aMessage, - uint16_t aOffset, uint8_t aLength) +otError PendingDataset::Set(const Timestamp &aTimestamp, const Message &aMessage, uint16_t aOffset, uint8_t aLength) { otError error = OT_ERROR_NONE; Dataset dataset(mLocal.GetType()); @@ -462,7 +473,7 @@ exit: void PendingDataset::StartDelayTimer(void) { DelayTimerTlv *delayTimer; - Dataset dataset(mLocal.GetType()); + Dataset dataset(mLocal.GetType()); mLocal.Get(dataset); @@ -491,7 +502,7 @@ void PendingDataset::HandleDelayTimer(Timer &aTimer) void PendingDataset::HandleDelayTimer(void) { DelayTimerTlv *delayTimer; - Dataset dataset(mLocal.GetType()); + Dataset dataset(mLocal.GetType()); mLocal.Get(dataset); @@ -500,7 +511,7 @@ void PendingDataset::HandleDelayTimer(void) if ((delayTimer = static_cast(dataset.Get(Tlv::kDelayTimer))) != NULL) { uint32_t elapsed = mDelayTimer.GetFireTime() - dataset.GetUpdateTime(); - uint32_t delay = delayTimer->GetDelayTimer(); + uint32_t delay = delayTimer->GetDelayTimer(); if (elapsed < delay) { @@ -520,12 +531,14 @@ exit: return; } -void PendingDataset::HandleGet(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void PendingDataset::HandleGet(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleGet( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleGet(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void PendingDataset::HandleGet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) const @@ -538,5 +551,5 @@ void PendingDataset::HandleTimer(Timer &aTimer) aTimer.GetOwner().HandleTimer(); } -} // namespace MeshCoP -} // namespace ot +} // namespace MeshCoP +} // namespace ot diff --git a/src/core/meshcop/dataset_manager.hpp b/src/core/meshcop/dataset_manager.hpp index b6920b690..69488d293 100644 --- a/src/core/meshcop/dataset_manager.hpp +++ b/src/core/meshcop/dataset_manager.hpp @@ -52,7 +52,7 @@ class ThreadNetif; namespace MeshCoP { -class DatasetManager: public InstanceLocator +class DatasetManager : public InstanceLocator { public: /** @@ -140,7 +140,6 @@ public: void HandleDetach(void); protected: - /** * This constructor initializes the object. * @@ -151,7 +150,10 @@ protected: * @param[in] aTimerHandler The registration timer handler. * */ - DatasetManager(Instance &aInstance, const Tlv::Type aType, const char *aUriGet, const char *aUriSet, + DatasetManager(Instance & aInstance, + const Tlv::Type aType, + const char * aUriGet, + const char * aUriSet, TimerMilli::Handler aTimerHandler); /** @@ -207,16 +209,18 @@ protected: void HandleTimer(void); DatasetLocal mLocal; - Timestamp mTimestamp; - bool mTimestampValid : 1; + Timestamp mTimestamp; + bool mTimestampValid : 1; private: static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo); - void HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); otError Register(void); - void SendGetResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, - uint8_t *aTlvs, uint8_t aLength) const; + void SendGetResponse(const Coap::Header & aRequestHeader, + const Ip6::MessageInfo &aMessageInfo, + uint8_t * aTlvs, + uint8_t aLength) const; TimerMilli mTimer; @@ -272,11 +276,13 @@ protected: otError Set(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); private: - void SendSetResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, StateTlv::State aState); + void SendSetResponse(const Coap::Header & aRequestHeader, + const Ip6::MessageInfo &aMessageInfo, + StateTlv::State aState); #endif }; -class ActiveDataset: public DatasetManager +class ActiveDataset : public DatasetManager { public: /** @@ -350,16 +356,20 @@ public: private: static void HandleTimer(Timer &aTimer); - void HandleTimer(void) { DatasetManager::HandleTimer(); } + void HandleTimer(void) { DatasetManager::HandleTimer(); } - static void HandleGet(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleGet(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleGet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) const; + void HandleGet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) const; #if OPENTHREAD_FTD - static void HandleSet(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleSet(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleSet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleSet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); bool IsTlvInitialized(Tlv::Type aType); #endif @@ -371,7 +381,7 @@ private: #endif }; -class PendingDataset: public DatasetManager +class PendingDataset : public DatasetManager { public: /** @@ -450,19 +460,23 @@ private: void StartDelayTimer(void); static void HandleTimer(Timer &aTimer); - void HandleTimer(void) { DatasetManager::HandleTimer(); } + void HandleTimer(void) { DatasetManager::HandleTimer(); } static void HandleDelayTimer(Timer &aTimer); - void HandleDelayTimer(void); + void HandleDelayTimer(void); - static void HandleGet(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleGet(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleGet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) const; + void HandleGet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) const; #if OPENTHREAD_FTD - static void HandleSet(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleSet(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleSet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleSet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); #endif TimerMilli mDelayTimer; @@ -474,7 +488,7 @@ private: #endif }; -} // namespace MeshCoP -} // namespace ot +} // namespace MeshCoP +} // namespace ot -#endif // MESHCOP_DATASET_MANAGER_HPP_ +#endif // MESHCOP_DATASET_MANAGER_HPP_ diff --git a/src/core/meshcop/dataset_manager_ftd.cpp b/src/core/meshcop/dataset_manager_ftd.cpp index 7efea4df8..8eb39b4e1 100644 --- a/src/core/meshcop/dataset_manager_ftd.cpp +++ b/src/core/meshcop/dataset_manager_ftd.cpp @@ -37,8 +37,8 @@ #include -#include #include +#include #include "coap/coap_header.hpp" #include "common/code_utils.hpp" @@ -48,9 +48,9 @@ #include "common/timer.hpp" #include "meshcop/dataset.hpp" #include "meshcop/dataset_manager.hpp" +#include "meshcop/leader.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" -#include "meshcop/leader.hpp" #include "thread/thread_netif.hpp" #include "thread/thread_tlvs.hpp" #include "thread/thread_uri_paths.hpp" @@ -61,7 +61,7 @@ namespace MeshCoP { otError DatasetManager::Set(const otOperationalDataset &aDataset) { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; SuccessOrExit(error = mLocal.Set(aDataset)); @@ -92,24 +92,24 @@ exit: otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - Tlv tlv; - Timestamp *timestamp; - uint16_t offset = aMessage.GetOffset(); - Tlv::Type type; - bool isUpdateFromCommissioner = false; - bool doesAffectConnectivity = false; - bool doesAffectMasterKey = false; - StateTlv::State state = StateTlv::kAccept; - Dataset dataset(mLocal.GetType()); + ThreadNetif & netif = GetNetif(); + Tlv tlv; + Timestamp * timestamp; + uint16_t offset = aMessage.GetOffset(); + Tlv::Type type; + bool isUpdateFromCommissioner = false; + bool doesAffectConnectivity = false; + bool doesAffectMasterKey = false; + StateTlv::State state = StateTlv::kAccept; + Dataset dataset(mLocal.GetType()); - ActiveTimestampTlv activeTimestamp; - PendingTimestampTlv pendingTimestamp; - ChannelTlv channel; + ActiveTimestampTlv activeTimestamp; + PendingTimestampTlv pendingTimestamp; + ChannelTlv channel; CommissionerSessionIdTlv sessionId; - MeshLocalPrefixTlv meshLocalPrefix; - NetworkMasterKeyTlv masterKey; - PanIdTlv panId; + MeshLocalPrefixTlv meshLocalPrefix; + NetworkMasterKeyTlv masterKey; + PanIdTlv panId; mLocal.Get(dataset); @@ -150,18 +150,16 @@ otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6: } // verify the request includes a timestamp that is ahead of the locally stored value - timestamp = (type == Tlv::kActiveTimestamp) ? - static_cast(&activeTimestamp) : - static_cast(&pendingTimestamp); + timestamp = (type == Tlv::kActiveTimestamp) ? static_cast(&activeTimestamp) + : static_cast(&pendingTimestamp); VerifyOrExit(mLocal.Compare(timestamp) > 0, state = StateTlv::kReject); // check channel if (Tlv::GetTlv(aMessage, Tlv::kChannel, sizeof(channel), channel) == OT_ERROR_NONE) { - VerifyOrExit(channel.IsValid() && - channel.GetChannel() >= OT_RADIO_CHANNEL_MIN && - channel.GetChannel() <= OT_RADIO_CHANNEL_MAX, + VerifyOrExit(channel.IsValid() && channel.GetChannel() >= OT_RADIO_CHANNEL_MIN && + channel.GetChannel() <= OT_RADIO_CHANNEL_MAX, state = StateTlv::kReject); if (channel.GetChannel() != netif.GetMac().GetChannel()) @@ -171,8 +169,7 @@ otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6: } // check PAN ID - if (Tlv::GetTlv(aMessage, Tlv::kPanId, sizeof(panId), panId) == OT_ERROR_NONE && - panId.IsValid() && + if (Tlv::GetTlv(aMessage, Tlv::kPanId, sizeof(panId), panId) == OT_ERROR_NONE && panId.IsValid() && panId.GetPanId() != netif.GetMac().GetPanId()) { doesAffectConnectivity = true; @@ -181,8 +178,7 @@ otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6: // check mesh local prefix if (Tlv::GetTlv(aMessage, Tlv::kMeshLocalPrefix, sizeof(meshLocalPrefix), meshLocalPrefix) == OT_ERROR_NONE && meshLocalPrefix.IsValid() && - memcmp(meshLocalPrefix.GetMeshLocalPrefix(), netif.GetMle().GetMeshLocalPrefix(), - meshLocalPrefix.GetLength())) + memcmp(meshLocalPrefix.GetMeshLocalPrefix(), netif.GetMle().GetMeshLocalPrefix(), meshLocalPrefix.GetLength())) { doesAffectConnectivity = true; } @@ -193,7 +189,7 @@ otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6: memcmp(&masterKey.GetNetworkMasterKey(), &netif.GetKeyManager().GetMasterKey(), OT_MASTER_KEY_SIZE)) { doesAffectConnectivity = true; - doesAffectMasterKey = true; + doesAffectMasterKey = true; } // check active timestamp rollback @@ -215,12 +211,11 @@ otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6: isUpdateFromCommissioner = true; - localId = static_cast(netif.GetNetworkDataLeader().GetCommissioningDataSubTlv( - Tlv::kCommissionerSessionId)); + localId = static_cast( + netif.GetNetworkDataLeader().GetCommissioningDataSubTlv(Tlv::kCommissionerSessionId)); - VerifyOrExit(sessionId.IsValid() && - localId != NULL && - localId->GetCommissionerSessionId() == sessionId.GetCommissionerSessionId(), + VerifyOrExit(sessionId.IsValid() && localId != NULL && + localId->GetCommissionerSessionId() == sessionId.GetCommissionerSessionId(), state = StateTlv::kReject); } @@ -266,7 +261,7 @@ otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6: OT_TOOL_PACKED_BEGIN struct { - Tlv tlv; + Tlv tlv; uint8_t value[Dataset::kMaxValueSize]; } OT_TOOL_PACKED_END data; @@ -293,7 +288,7 @@ otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6: } } - // fall through + // fall through default: dataset.Set(data.tlv); @@ -316,14 +311,14 @@ otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6: if (!isUpdateFromCommissioner) { BorderAgentLocatorTlv *borderAgentLocator; - Ip6::Address destination; + Ip6::Address destination; - borderAgentLocator = static_cast(netif.GetNetworkDataLeader().GetCommissioningDataSubTlv( - Tlv::kBorderAgentLocator)); + borderAgentLocator = static_cast( + netif.GetNetworkDataLeader().GetCommissioningDataSubTlv(Tlv::kBorderAgentLocator)); VerifyOrExit(borderAgentLocator != NULL); memset(&destination, 0, sizeof(destination)); - destination = netif.GetMle().GetMeshLocal16(); + destination = netif.GetMle().GetMeshLocal16(); destination.mFields.m16[7] = HostSwap16(borderAgentLocator->GetBorderAgentLocator()); netif.GetLeader().SendDatasetChanged(destination); @@ -341,10 +336,10 @@ exit: otError DatasetManager::SendSetRequest(const otOperationalDataset &aDataset, const uint8_t *aTlvs, uint8_t aLength) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Coap::Header header; - Message *message; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Coap::Header header; + Message * message; Ip6::MessageInfo messageInfo; header.Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); @@ -358,9 +353,9 @@ otError DatasetManager::SendSetRequest(const otOperationalDataset &aDataset, con if (netif.GetCommissioner().IsActive()) { - const uint8_t *cur = aTlvs; - const uint8_t *end = aTlvs + aLength; - bool hasSessionId = false; + const uint8_t *cur = aTlvs; + const uint8_t *end = aTlvs + aLength; + bool hasSessionId = false; while (cur < end) { @@ -499,12 +494,12 @@ exit: otError DatasetManager::SendGetRequest(const uint8_t *aTlvTypes, uint8_t aLength, const otIp6Address *aAddress) const { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Coap::Header header; - Message *message; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Coap::Header header; + Message * message; Ip6::MessageInfo messageInfo; - Tlv tlv; + Tlv tlv; header.Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); header.SetToken(Coap::Header::kDefaultTokenLength); @@ -550,14 +545,15 @@ exit: return error; } -void DatasetManager::SendSetResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, - StateTlv::State aState) +void DatasetManager::SendSetResponse(const Coap::Header & aRequestHeader, + const Ip6::MessageInfo &aMessageInfo, + StateTlv::State aState) { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Coap::Header responseHeader; - Message *message; - StateTlv state; + Message * message; + StateTlv state; responseHeader.SetDefaultResponseHeader(aRequestHeader); responseHeader.SetPayloadMarker(); @@ -588,8 +584,8 @@ otError ActiveDataset::Set(const otOperationalDataset &aDataset) otError ActiveDataset::GenerateLocal(void) { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Dataset dataset(mLocal.GetType()); + otError error = OT_ERROR_NONE; + Dataset dataset(mLocal.GetType()); VerifyOrExit(netif.GetMle().IsAttached(), error = OT_ERROR_INVALID_STATE); @@ -708,12 +704,14 @@ void ActiveDataset::StopLeader(void) GetNetif().GetCoap().RemoveResource(mResourceSet); } -void ActiveDataset::HandleSet(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void ActiveDataset::HandleSet(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleSet( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleSet(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void ActiveDataset::HandleSet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) @@ -747,12 +745,14 @@ void PendingDataset::StopLeader(void) GetNetif().GetCoap().RemoveResource(mResourceSet); } -void PendingDataset::HandleSet(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void PendingDataset::HandleSet(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleSet( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleSet(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void PendingDataset::HandleSet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) @@ -766,9 +766,9 @@ exit: void PendingDataset::ApplyActiveDataset(const Timestamp &aTimestamp, Message &aMessage) { - ThreadNetif &netif = GetNetif(); - uint16_t offset = aMessage.GetOffset(); - Dataset dataset(mLocal.GetType()); + ThreadNetif & netif = GetNetif(); + uint16_t offset = aMessage.GetOffset(); + Dataset dataset(mLocal.GetType()); DelayTimerTlv delayTimer; VerifyOrExit(netif.GetMle().IsAttached()); @@ -778,7 +778,7 @@ void PendingDataset::ApplyActiveDataset(const Timestamp &aTimestamp, Message &aM OT_TOOL_PACKED_BEGIN struct { - Tlv tlv; + Tlv tlv; uint8_t value[Dataset::kMaxValueSize]; } OT_TOOL_PACKED_END data; @@ -804,7 +804,7 @@ exit: return; } -} // namespace MeshCoP -} // namespace ot +} // namespace MeshCoP +} // namespace ot #endif // OPENTHREAD_FTD diff --git a/src/core/meshcop/dtls.cpp b/src/core/meshcop/dtls.cpp index cbd2140f4..97afbc826 100644 --- a/src/core/meshcop/dtls.cpp +++ b/src/core/meshcop/dtls.cpp @@ -53,23 +53,23 @@ namespace ot { namespace MeshCoP { -Dtls::Dtls(Instance &aInstance): - InstanceLocator(aInstance), - mPskLength(0), - mStarted(false), - mTimer(aInstance, &Dtls::HandleTimer, this), - mTimerIntermediate(0), - mTimerSet(false), - mReceiveMessage(NULL), - mReceiveOffset(0), - mReceiveLength(0), - mConnectedHandler(NULL), - mReceiveHandler(NULL), - mSendHandler(NULL), - mContext(NULL), - mClient(false), - mMessageSubType(Message::kSubTypeNone), - mMessageDefaultSubType(Message::kSubTypeNone) +Dtls::Dtls(Instance &aInstance) + : InstanceLocator(aInstance) + , mPskLength(0) + , mStarted(false) + , mTimer(aInstance, &Dtls::HandleTimer, this) + , mTimerIntermediate(0) + , mTimerSet(false) + , mReceiveMessage(NULL) + , mReceiveOffset(0) + , mReceiveLength(0) + , mConnectedHandler(NULL) + , mReceiveHandler(NULL) + , mSendHandler(NULL) + , mContext(NULL) + , mClient(false) + , mMessageSubType(Message::kSubTypeNone) + , mMessageDefaultSubType(Message::kSubTypeNone) { memset(mPsk, 0, sizeof(mPsk)); memset(&mEntropy, 0, sizeof(mEntropy)); @@ -83,7 +83,7 @@ Dtls::Dtls(Instance &aInstance): int Dtls::HandleMbedtlsEntropyPoll(void *aData, unsigned char *aOutput, size_t aInLen, size_t *aOutLen) { otError error; - int rval = 0; + int rval = 0; OT_UNUSED_VARIABLE(aData); @@ -105,27 +105,30 @@ exit: return rval; } -otError Dtls::Start(bool aClient, ConnectedHandler aConnectedHandler, ReceiveHandler aReceiveHandler, - SendHandler aSendHandler, void *aContext) +otError Dtls::Start(bool aClient, + ConnectedHandler aConnectedHandler, + ReceiveHandler aReceiveHandler, + SendHandler aSendHandler, + void * aContext) { static const int ciphersuites[2] = {0xC0FF, 0}; // EC-JPAKE cipher suite - otExtAddress eui64; - int rval; + otExtAddress eui64; + int rval; mConnectedHandler = aConnectedHandler; - mReceiveHandler = aReceiveHandler; - mSendHandler = aSendHandler; - mContext = aContext; - mClient = aClient; - mReceiveMessage = NULL; - mMessageSubType = Message::kSubTypeNone; + mReceiveHandler = aReceiveHandler; + mSendHandler = aSendHandler; + mContext = aContext; + mClient = aClient; + mReceiveMessage = NULL; + mMessageSubType = Message::kSubTypeNone; mbedtls_ssl_init(&mSsl); mbedtls_ssl_config_init(&mConf); mbedtls_ctr_drbg_init(&mCtrDrbg); mbedtls_entropy_init(&mEntropy); - rval = mbedtls_entropy_add_source(&mEntropy, &Dtls::HandleMbedtlsEntropyPoll, NULL, - MBEDTLS_ENTROPY_MIN_PLATFORM, MBEDTLS_ENTROPY_SOURCE_STRONG); + rval = mbedtls_entropy_add_source(&mEntropy, &Dtls::HandleMbedtlsEntropyPoll, NULL, MBEDTLS_ENTROPY_MIN_PLATFORM, + MBEDTLS_ENTROPY_SOURCE_STRONG); VerifyOrExit(rval == 0); // mbedTLS's debug level is almost the same as OpenThread's @@ -256,8 +259,8 @@ exit: otError Dtls::Receive(Message &aMessage, uint16_t aOffset, uint16_t aLength) { mReceiveMessage = &aMessage; - mReceiveOffset = aOffset; - mReceiveLength = aLength; + mReceiveOffset = aOffset; + mReceiveLength = aLength; Process(); @@ -272,7 +275,7 @@ int Dtls::HandleMbedtlsTransmit(void *aContext, const unsigned char *aBuf, size_ int Dtls::HandleMbedtlsTransmit(const unsigned char *aBuf, size_t aLength) { otError error; - int rval = 0; + int rval = 0; otLogInfoMeshCoP(GetInstance(), "Dtls::HandleMbedtlsTransmit"); @@ -378,17 +381,24 @@ void Dtls::HandleMbedtlsSetTimer(uint32_t aIntermediate, uint32_t aFinish) } } -int Dtls::HandleMbedtlsExportKeys(void *aContext, const unsigned char *aMasterSecret, const unsigned char *aKeyBlock, - size_t aMacLength, size_t aKeyLength, size_t aIvLength) +int Dtls::HandleMbedtlsExportKeys(void * aContext, + const unsigned char *aMasterSecret, + const unsigned char *aKeyBlock, + size_t aMacLength, + size_t aKeyLength, + size_t aIvLength) { - return static_cast(aContext)->HandleMbedtlsExportKeys(aMasterSecret, aKeyBlock, - aMacLength, aKeyLength, aIvLength); + return static_cast(aContext)->HandleMbedtlsExportKeys(aMasterSecret, aKeyBlock, aMacLength, aKeyLength, + aIvLength); } -int Dtls::HandleMbedtlsExportKeys(const unsigned char *aMasterSecret, const unsigned char *aKeyBlock, - size_t aMacLength, size_t aKeyLength, size_t aIvLength) +int Dtls::HandleMbedtlsExportKeys(const unsigned char *aMasterSecret, + const unsigned char *aKeyBlock, + size_t aMacLength, + size_t aKeyLength, + size_t aIvLength) { - uint8_t kek[Crypto::Sha256::kHashSize]; + uint8_t kek[Crypto::Sha256::kHashSize]; Crypto::Sha256 sha256; sha256.Start(); @@ -416,8 +426,8 @@ void Dtls::HandleTimer(void) void Dtls::Process(void) { uint8_t buf[MBEDTLS_SSL_MAX_CONTENT_LEN]; - bool shouldClose = false; - int rval; + bool shouldClose = false; + int rval; while (mStarted) { @@ -544,7 +554,7 @@ void Dtls::HandleMbedtlsDebug(void *ctx, int level, const char *, int, const cha } } -} // namespace MeshCoP -} // namespace ot +} // namespace MeshCoP +} // namespace ot #endif // OPENTHREAD_ENABLE_DTLS diff --git a/src/core/meshcop/dtls.hpp b/src/core/meshcop/dtls.hpp index 0afb7fed5..de41efab5 100644 --- a/src/core/meshcop/dtls.hpp +++ b/src/core/meshcop/dtls.hpp @@ -38,12 +38,12 @@ #include -#include +#include +#include #include #include -#include #include -#include +#include #include #include "common/locator.hpp" @@ -58,12 +58,12 @@ class ThreadNetif; namespace MeshCoP { -class Dtls: public InstanceLocator +class Dtls : public InstanceLocator { public: enum { - kPskMaxLength = 32, + kPskMaxLength = 32, kApplicationDataMaxLength = 128, }; @@ -103,7 +103,7 @@ public: * @param[in] aMessageSubtype A message sub type information for the sender. * */ - typedef otError(*SendHandler)(void *aContext, const uint8_t *aBuf, uint16_t aLength, uint8_t aMessageSubType); + typedef otError (*SendHandler)(void *aContext, const uint8_t *aBuf, uint16_t aLength, uint8_t aMessageSubType); /** * This method starts the DTLS service. @@ -117,8 +117,11 @@ public: * @retval OT_ERROR_NONE Successfully started the DTLS service. * */ - otError Start(bool aClient, ConnectedHandler aConnectedHandler, ReceiveHandler aReceiveHandler, - SendHandler aSendHandler, void *aContext); + otError Start(bool aClient, + ConnectedHandler aConnectedHandler, + ReceiveHandler aReceiveHandler, + SendHandler aSendHandler, + void * aContext); /** * This method stops the DTLS service. @@ -212,25 +215,31 @@ private: static void HandleMbedtlsDebug(void *ctx, int level, const char *file, int line, const char *str); static int HandleMbedtlsGetTimer(void *aContext); - int HandleMbedtlsGetTimer(void); + int HandleMbedtlsGetTimer(void); static void HandleMbedtlsSetTimer(void *aContext, uint32_t aIntermediate, uint32_t aFinish); - void HandleMbedtlsSetTimer(uint32_t aIntermediate, uint32_t aFinish); + void HandleMbedtlsSetTimer(uint32_t aIntermediate, uint32_t aFinish); static int HandleMbedtlsReceive(void *aContext, unsigned char *aBuf, size_t aLength); - int HandleMbedtlsReceive(unsigned char *aBuf, size_t aLength); + int HandleMbedtlsReceive(unsigned char *aBuf, size_t aLength); static int HandleMbedtlsTransmit(void *aContext, const unsigned char *aBuf, size_t aLength); - int HandleMbedtlsTransmit(const unsigned char *aBuf, size_t aLength); + int HandleMbedtlsTransmit(const unsigned char *aBuf, size_t aLength); - static int HandleMbedtlsExportKeys(void *aContext, const unsigned char *aMasterSecret, + static int HandleMbedtlsExportKeys(void * aContext, + const unsigned char *aMasterSecret, const unsigned char *aKeyBlock, - size_t aMacLength, size_t aKeyLength, size_t aIvLength); - int HandleMbedtlsExportKeys(const unsigned char *aMasterSecret, const unsigned char *aKeyBlock, - size_t aMacLength, size_t aKeyLength, size_t aIvLength); + size_t aMacLength, + size_t aKeyLength, + size_t aIvLength); + int HandleMbedtlsExportKeys(const unsigned char *aMasterSecret, + const unsigned char *aKeyBlock, + size_t aMacLength, + size_t aKeyLength, + size_t aIvLength); static void HandleTimer(Timer &aTimer); - void HandleTimer(void); + void HandleTimer(void); static int HandleMbedtlsEntropyPoll(void *aData, unsigned char *aOutput, size_t aInLen, size_t *aOutLen); @@ -240,32 +249,32 @@ private: uint8_t mPsk[kPskMaxLength]; uint8_t mPskLength; - mbedtls_entropy_context mEntropy; + mbedtls_entropy_context mEntropy; mbedtls_ctr_drbg_context mCtrDrbg; - mbedtls_ssl_context mSsl; - mbedtls_ssl_config mConf; - mbedtls_ssl_cookie_ctx mCookieCtx; - bool mStarted; + mbedtls_ssl_context mSsl; + mbedtls_ssl_config mConf; + mbedtls_ssl_cookie_ctx mCookieCtx; + bool mStarted; TimerMilli mTimer; - uint32_t mTimerIntermediate; - bool mTimerSet; + uint32_t mTimerIntermediate; + bool mTimerSet; Message *mReceiveMessage; uint16_t mReceiveOffset; uint16_t mReceiveLength; ConnectedHandler mConnectedHandler; - ReceiveHandler mReceiveHandler; - SendHandler mSendHandler; - void *mContext; - bool mClient; + ReceiveHandler mReceiveHandler; + SendHandler mSendHandler; + void * mContext; + bool mClient; uint8_t mMessageSubType; uint8_t mMessageDefaultSubType; }; -} // namespace MeshCoP -} // namespace ot +} // namespace MeshCoP +} // namespace ot -#endif // DTLS_HPP_ +#endif // DTLS_HPP_ diff --git a/src/core/meshcop/energy_scan_client.cpp b/src/core/meshcop/energy_scan_client.cpp index 48bd14257..b50848f6f 100644 --- a/src/core/meshcop/energy_scan_client.cpp +++ b/src/core/meshcop/energy_scan_client.cpp @@ -41,7 +41,6 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/encoding.hpp" -#include "coap/coap_header.hpp" #include "common/logging.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" @@ -55,40 +54,42 @@ using ot::Encoding::BigEndian::HostSwap32; namespace ot { -EnergyScanClient::EnergyScanClient(Instance &aInstance) : - InstanceLocator(aInstance), - mEnergyScan(OT_URI_PATH_ENERGY_REPORT, &EnergyScanClient::HandleReport, this) +EnergyScanClient::EnergyScanClient(Instance &aInstance) + : InstanceLocator(aInstance) + , mEnergyScan(OT_URI_PATH_ENERGY_REPORT, &EnergyScanClient::HandleReport, this) { - mContext = NULL; + mContext = NULL; mCallback = NULL; GetNetif().GetCoap().AddResource(mEnergyScan); } -otError EnergyScanClient::SendQuery(uint32_t aChannelMask, uint8_t aCount, uint16_t aPeriod, - uint16_t aScanDuration, const Ip6::Address &aAddress, - otCommissionerEnergyReportCallback aCallback, void *aContext) +otError EnergyScanClient::SendQuery(uint32_t aChannelMask, + uint8_t aCount, + uint16_t aPeriod, + uint16_t aScanDuration, + const Ip6::Address & aAddress, + otCommissionerEnergyReportCallback aCallback, + void * aContext) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Coap::Header header; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Coap::Header header; MeshCoP::CommissionerSessionIdTlv sessionId; - MeshCoP::ChannelMask0Tlv channelMask; - MeshCoP::CountTlv count; - MeshCoP::PeriodTlv period; - MeshCoP::ScanDurationTlv scanDuration; - Ip6::MessageInfo messageInfo; - Message *message = NULL; + MeshCoP::ChannelMask0Tlv channelMask; + MeshCoP::CountTlv count; + MeshCoP::PeriodTlv period; + MeshCoP::ScanDurationTlv scanDuration; + Ip6::MessageInfo messageInfo; + Message * message = NULL; VerifyOrExit(netif.GetCommissioner().IsActive(), error = OT_ERROR_INVALID_STATE); - header.Init(aAddress.IsMulticast() ? OT_COAP_TYPE_NON_CONFIRMABLE : OT_COAP_TYPE_CONFIRMABLE, - OT_COAP_CODE_POST); + header.Init(aAddress.IsMulticast() ? OT_COAP_TYPE_NON_CONFIRMABLE : OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); header.SetToken(Coap::Header::kDefaultTokenLength); header.AppendUriPathOptions(OT_URI_PATH_ENERGY_SCAN); header.SetPayloadMarker(); - VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(netif.GetCoap(), header)) != NULL, - error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(netif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); sessionId.Init(); sessionId.SetCommissionerSessionId(netif.GetCommissioner().GetSessionId()); @@ -119,7 +120,7 @@ otError EnergyScanClient::SendQuery(uint32_t aChannelMask, uint8_t aCount, uint1 otLogInfoMeshCoP(GetInstance(), "sent energy scan query"); mCallback = aCallback; - mContext = aContext; + mContext = aContext; exit: @@ -131,29 +132,30 @@ exit: return error; } -void EnergyScanClient::HandleReport(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void EnergyScanClient::HandleReport(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleReport( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleReport(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void EnergyScanClient::HandleReport(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); + ThreadNetif & netif = GetNetif(); MeshCoP::ChannelMask0Tlv channelMask; - Ip6::MessageInfo responseInfo(aMessageInfo); + Ip6::MessageInfo responseInfo(aMessageInfo); OT_TOOL_PACKED_BEGIN struct { MeshCoP::EnergyListTlv tlv; - uint8_t list[OPENTHREAD_CONFIG_MAX_ENERGY_RESULTS]; + uint8_t list[OPENTHREAD_CONFIG_MAX_ENERGY_RESULTS]; } OT_TOOL_PACKED_END energyList; - VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && - aHeader.GetCode() == OT_COAP_CODE_POST); + VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && aHeader.GetCode() == OT_COAP_CODE_POST); otLogInfoMeshCoP(GetInstance(), "received energy scan report"); @@ -176,7 +178,6 @@ exit: return; } -} // namespace ot +} // namespace ot #endif // OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD - diff --git a/src/core/meshcop/energy_scan_client.hpp b/src/core/meshcop/energy_scan_client.hpp index af93fce5c..321e3bbf2 100644 --- a/src/core/meshcop/energy_scan_client.hpp +++ b/src/core/meshcop/energy_scan_client.hpp @@ -51,7 +51,7 @@ class ThreadNetif; * This class implements handling PANID Query Requests. * */ -class EnergyScanClient: public InstanceLocator +class EnergyScanClient : public InstanceLocator { public: /** @@ -75,16 +75,23 @@ public: * @retval OT_ERROR_NO_BUFS Insufficient buffers to generate an Energy Scan Query message. * */ - otError SendQuery(uint32_t aChannelMask, uint8_t aCount, uint16_t aPeriod, uint16_t aScanDuration, - const Ip6::Address &aAddress, otCommissionerEnergyReportCallback aCallback, void *aContext); + otError SendQuery(uint32_t aChannelMask, + uint8_t aCount, + uint16_t aPeriod, + uint16_t aScanDuration, + const Ip6::Address & aAddress, + otCommissionerEnergyReportCallback aCallback, + void * aContext); private: - static void HandleReport(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleReport(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleReport(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleReport(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); otCommissionerEnergyReportCallback mCallback; - void *mContext; + void * mContext; Coap::Resource mEnergyScan; }; @@ -93,6 +100,6 @@ private: * @} */ -} // namespace ot +} // namespace ot -#endif // ENERGY_SCAN_CLIENT_HPP_ +#endif // ENERGY_SCAN_CLIENT_HPP_ diff --git a/src/core/meshcop/joiner.cpp b/src/core/meshcop/joiner.cpp index ea08e713c..62ce6aff5 100644 --- a/src/core/meshcop/joiner.cpp +++ b/src/core/meshcop/joiner.cpp @@ -60,19 +60,19 @@ using ot::Encoding::BigEndian::HostSwap64; namespace ot { namespace MeshCoP { -Joiner::Joiner(Instance &aInstance): - InstanceLocator(aInstance), - mState(OT_JOINER_STATE_IDLE), - mCallback(NULL), - mContext(NULL), - mCcitt(0), - mAnsi(0), - mVendorName(NULL), - mVendorModel(NULL), - mVendorSwVersion(NULL), - mVendorData(NULL), - mTimer(aInstance, &Joiner::HandleTimer, this), - mJoinerEntrust(OT_URI_PATH_JOINER_ENTRUST, &Joiner::HandleJoinerEntrust, this) +Joiner::Joiner(Instance &aInstance) + : InstanceLocator(aInstance) + , mState(OT_JOINER_STATE_IDLE) + , mCallback(NULL) + , mContext(NULL) + , mCcitt(0) + , mAnsi(0) + , mVendorName(NULL) + , mVendorModel(NULL) + , mVendorSwVersion(NULL) + , mVendorData(NULL) + , mTimer(aInstance, &Joiner::HandleTimer, this) + , mJoinerEntrust(OT_URI_PATH_JOINER_ENTRUST, &Joiner::HandleJoinerEntrust, this) { memset(mJoinerRouters, 0, sizeof(mJoinerRouters)); GetNetif().GetCoap().AddResource(mJoinerEntrust); @@ -84,15 +84,20 @@ void Joiner::GetJoinerId(Mac::ExtAddress &aJoinerId) const ComputeJoinerId(aJoinerId, aJoinerId); } -otError Joiner::Start(const char *aPSKd, const char *aProvisioningUrl, - const char *aVendorName, const char *aVendorModel, const char *aVendorSwVersion, - const char *aVendorData, otJoinerCallback aCallback, void *aContext) +otError Joiner::Start(const char * aPSKd, + const char * aProvisioningUrl, + const char * aVendorName, + const char * aVendorModel, + const char * aVendorSwVersion, + const char * aVendorData, + otJoinerCallback aCallback, + void * aContext) { - ThreadNetif &netif = GetNetif(); - otError error; + ThreadNetif & netif = GetNetif(); + otError error; Mac::ExtAddress joinerId; - Crc16 ccitt(Crc16::kCcitt); - Crc16 ansi(Crc16::kAnsi); + Crc16 ccitt(Crc16::kCcitt); + Crc16 ansi(Crc16::kAnsi); VerifyOrExit(mState == OT_JOINER_STATE_IDLE, error = OT_ERROR_BUSY); @@ -110,7 +115,7 @@ otError Joiner::Start(const char *aPSKd, const char *aProvisioningUrl, } mCcitt = ccitt.Get(); - mAnsi = ansi.Get(); + mAnsi = ansi.Get(); error = netif.GetCoapSecure().Start(OPENTHREAD_CONFIG_JOINER_UDP_PORT); SuccessOrExit(error); @@ -124,16 +129,16 @@ otError Joiner::Start(const char *aPSKd, const char *aProvisioningUrl, memset(mJoinerRouters, 0, sizeof(mJoinerRouters)); - SuccessOrExit(error = netif.GetMle().Discover(0, netif.GetMac().GetPanId(), true, false, HandleDiscoverResult, - this)); + SuccessOrExit(error = + netif.GetMle().Discover(0, netif.GetMac().GetPanId(), true, false, HandleDiscoverResult, this)); - mVendorName = aVendorName; - mVendorModel = aVendorModel; + mVendorName = aVendorName; + mVendorModel = aVendorModel; mVendorSwVersion = aVendorSwVersion; - mVendorData = aVendorData; - mCallback = aCallback; - mContext = aContext; - mState = OT_JOINER_STATE_DISCOVER; + mVendorData = aVendorData; + mCallback = aCallback; + mContext = aContext; + mState = OT_JOINER_STATE_DISCOVER; exit: return error; @@ -162,8 +167,8 @@ void Joiner::Close(void) void Joiner::Complete(otError aError) { ThreadNetif &netif = GetNetif(); - mState = OT_JOINER_STATE_IDLE; - otError error = OT_ERROR_NOT_FOUND; + mState = OT_JOINER_STATE_IDLE; + otError error = OT_ERROR_NOT_FOUND; GetNotifier().SetFlags(OT_CHANGED_JOINER_STATE); netif.GetCoapSecure().Disconnect(); @@ -177,7 +182,7 @@ void Joiner::Complete(otError aError) { netif.GetCoapSecure().Stop(); otJoinerCallback callback = mCallback; - mCallback = NULL; + mCallback = NULL; callback(aError, mContext); } } @@ -222,9 +227,9 @@ void Joiner::HandleDiscoverResult(otActiveScanResult *aResult) } joinerRouter.mJoinerUdpPort = aResult->mJoinerUdpPort; - joinerRouter.mPanId = aResult->mPanId; - joinerRouter.mChannel = aResult->mChannel; - joinerRouter.mExtAddr = static_cast(aResult->mExtAddress); + joinerRouter.mPanId = aResult->mPanId; + joinerRouter.mChannel = aResult->mChannel; + joinerRouter.mExtAddr = static_cast(aResult->mExtAddress); AddJoinerRouter(joinerRouter); } else @@ -267,8 +272,8 @@ void Joiner::AddJoinerRouter(JoinerRouter &aJoinerRouter) otError Joiner::TryNextJoin() { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NOT_FOUND; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NOT_FOUND; JoinerRouter *joinerRouter = &mJoinerRouters[0]; for (size_t i = 1; i < OPENTHREAD_CONFIG_MAX_JOINER_ROUTER_ENTRIES; i++) @@ -291,12 +296,12 @@ otError Joiner::TryNextJoin() messageInfo.GetPeerAddr().mFields.m16[0] = HostSwap16(0xfe80); messageInfo.GetPeerAddr().SetIid(joinerRouter->mExtAddr); - messageInfo.mPeerPort = joinerRouter->mJoinerUdpPort; + messageInfo.mPeerPort = joinerRouter->mJoinerUdpPort; messageInfo.mInterfaceId = OT_NETIF_INTERFACE_ID_THREAD; netif.GetCoapSecure().Connect(messageInfo, Joiner::HandleSecureCoapClientConnect, this); mState = OT_JOINER_STATE_CONNECT; - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; } else { @@ -336,14 +341,14 @@ void Joiner::HandleSecureCoapClientConnect(bool aConnected) void Joiner::SendJoinerFinalize(void) { - ThreadNetif &netif = GetNetif(); - Coap::Header header; - otError error = OT_ERROR_NONE; - Message *message = NULL; - StateTlv stateTlv; - VendorNameTlv vendorNameTlv; - VendorModelTlv vendorModelTlv; - VendorSwVersionTlv vendorSwVersionTlv; + ThreadNetif & netif = GetNetif(); + Coap::Header header; + otError error = OT_ERROR_NONE; + Message * message = NULL; + StateTlv stateTlv; + VendorNameTlv vendorNameTlv; + VendorModelTlv vendorModelTlv; + VendorSwVersionTlv vendorSwVersionTlv; VendorStackVersionTlv vendorStackVersionTlv; header.Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); @@ -409,24 +414,27 @@ exit: } } -void Joiner::HandleJoinerFinalizeResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError aResult) +void Joiner::HandleJoinerFinalizeResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aResult) { static_cast(aContext)->HandleJoinerFinalizeResponse( static_cast(aHeader), static_cast(aMessage), static_cast(aMessageInfo), aResult); } -void Joiner::HandleJoinerFinalizeResponse(Coap::Header *aHeader, Message *aMessage, - const Ip6::MessageInfo *aMessageInfo, otError aResult) +void Joiner::HandleJoinerFinalizeResponse(Coap::Header * aHeader, + Message * aMessage, + const Ip6::MessageInfo *aMessageInfo, + otError aResult) { - (void) aMessageInfo; + (void)aMessageInfo; StateTlv state; - VerifyOrExit(mState == OT_JOINER_STATE_CONNECTED && - aResult == OT_ERROR_NONE && - aHeader->GetType() == OT_COAP_TYPE_ACKNOWLEDGMENT && - aHeader->GetCode() == OT_COAP_CODE_CHANGED); + VerifyOrExit(mState == OT_JOINER_STATE_CONNECTED && aResult == OT_ERROR_NONE && + aHeader->GetType() == OT_COAP_TYPE_ACKNOWLEDGMENT && aHeader->GetCode() == OT_COAP_CODE_CHANGED); SuccessOrExit(Tlv::GetTlv(*aMessage, Tlv::kState, sizeof(state), state)); VerifyOrExit(state.IsValid()); @@ -447,28 +455,30 @@ exit: Close(); } -void Joiner::HandleJoinerEntrust(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void Joiner::HandleJoinerEntrust(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleJoinerEntrust( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleJoinerEntrust(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void Joiner::HandleJoinerEntrust(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - otError error; - NetworkMasterKeyTlv masterKey; - MeshLocalPrefixTlv meshLocalPrefix; - ExtendedPanIdTlv extendedPanId; - NetworkNameTlv networkName; - ActiveTimestampTlv activeTimestamp; + ThreadNetif & netif = GetNetif(); + otError error; + NetworkMasterKeyTlv masterKey; + MeshLocalPrefixTlv meshLocalPrefix; + ExtendedPanIdTlv extendedPanId; + NetworkNameTlv networkName; + ActiveTimestampTlv activeTimestamp; NetworkKeySequenceTlv networkKeySeq; - VerifyOrExit(mState == OT_JOINER_STATE_ENTRUST && - aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && - aHeader.GetCode() == OT_COAP_CODE_POST, error = OT_ERROR_DROP); + VerifyOrExit(mState == OT_JOINER_STATE_ENTRUST && aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && + aHeader.GetCode() == OT_COAP_CODE_POST, + error = OT_ERROR_DROP); otLogInfoMeshCoP(GetInstance(), "Received joiner entrust"); otLogCertMeshCoP(GetInstance(), "[THCI] direction=recv | type=JOIN_ENT.ntf"); @@ -515,18 +525,16 @@ exit: if (error != OT_ERROR_NONE) { - otLogWarnMeshCoP(GetInstance(), "Error while processing joiner entrust: %s", - otThreadErrorToString(error)); + otLogWarnMeshCoP(GetInstance(), "Error while processing joiner entrust: %s", otThreadErrorToString(error)); } } -void Joiner::SendJoinerEntrustResponse(const Coap::Header &aRequestHeader, - const Ip6::MessageInfo &aRequestInfo) +void Joiner::SendJoinerEntrustResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aRequestInfo) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Message *message; - Coap::Header responseHeader; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Message * message; + Coap::Header responseHeader; Ip6::MessageInfo responseInfo(aRequestInfo); responseHeader.SetDefaultResponseHeader(aRequestHeader); @@ -560,7 +568,7 @@ void Joiner::HandleTimer(Timer &aTimer) void Joiner::HandleTimer(void) { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; switch (mState) { @@ -584,13 +592,12 @@ void Joiner::HandleTimer(void) error = OT_ERROR_NONE; break; - } Complete(error); } -} // namespace MeshCoP -} // namespace ot +} // namespace MeshCoP +} // namespace ot #endif // OPENTHREAD_ENABLE_JOINER diff --git a/src/core/meshcop/joiner.hpp b/src/core/meshcop/joiner.hpp index f3034fd45..1cb47d117 100644 --- a/src/core/meshcop/joiner.hpp +++ b/src/core/meshcop/joiner.hpp @@ -54,7 +54,7 @@ class ThreadNetif; namespace MeshCoP { -class Joiner: public InstanceLocator +class Joiner : public InstanceLocator { public: /** @@ -80,10 +80,14 @@ public: * @retval OT_ERROR_NONE Successfully started the Joiner service. * */ - otError Start(const char *aPSKd, const char *aProvisioningUrl, - const char *aVendorName, const char *aVendorModel, - const char *aVendorSwVersion, const char *aVendorData, - otJoinerCallback aCallback, void *aContext); + otError Start(const char * aPSKd, + const char * aProvisioningUrl, + const char * aVendorName, + const char * aVendorModel, + const char * aVendorSwVersion, + const char * aVendorData, + otJoinerCallback aCallback, + void * aContext); /** * This method stops the Joiner service. @@ -125,42 +129,49 @@ private: struct JoinerRouter { Mac::ExtAddress mExtAddr; - uint16_t mPriority; - uint16_t mPanId; - uint16_t mJoinerUdpPort; - uint8_t mChannel; + uint16_t mPriority; + uint16_t mPanId; + uint16_t mJoinerUdpPort; + uint8_t mChannel; }; static void HandleDiscoverResult(otActiveScanResult *aResult, void *aContext); - void HandleDiscoverResult(otActiveScanResult *aResult); + void HandleDiscoverResult(otActiveScanResult *aResult); static void HandleTimer(Timer &aTimer); - void HandleTimer(void); + void HandleTimer(void); void Close(void); void Complete(otError aError); - void AddJoinerRouter(JoinerRouter &aJoinerRouter); + void AddJoinerRouter(JoinerRouter &aJoinerRouter); otError TryNextJoin(); static void HandleSecureCoapClientConnect(bool aConnected, void *aContext); - void HandleSecureCoapClientConnect(bool aConnected); + void HandleSecureCoapClientConnect(bool aConnected); - void SendJoinerFinalize(void); - static void HandleJoinerFinalizeResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError aResult); - void HandleJoinerFinalizeResponse(Coap::Header *aHeader, Message *aMessage, - const Ip6::MessageInfo *aMessageInfo, otError aResult); + void SendJoinerFinalize(void); + static void HandleJoinerFinalizeResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aResult); + void HandleJoinerFinalizeResponse(Coap::Header * aHeader, + Message * aMessage, + const Ip6::MessageInfo *aMessageInfo, + otError aResult); - static void HandleJoinerEntrust(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleJoinerEntrust(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleJoinerEntrust(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - void SendJoinerEntrustResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aRequestInfo); + void HandleJoinerEntrust(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void SendJoinerEntrustResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aRequestInfo); otJoinerState mState; otJoinerCallback mCallback; - void *mContext; + void * mContext; uint16_t mCcitt; uint16_t mAnsi; @@ -172,11 +183,11 @@ private: const char *mVendorSwVersion; const char *mVendorData; - TimerMilli mTimer; + TimerMilli mTimer; Coap::Resource mJoinerEntrust; }; -} // namespace MeshCoP -} // namespace ot +} // namespace MeshCoP +} // namespace ot -#endif // JOINER_HPP_ +#endif // JOINER_HPP_ diff --git a/src/core/meshcop/joiner_router.cpp b/src/core/meshcop/joiner_router.cpp index fe29d84e4..7a34b6228 100644 --- a/src/core/meshcop/joiner_router.cpp +++ b/src/core/meshcop/joiner_router.cpp @@ -56,15 +56,15 @@ using ot::Encoding::BigEndian::HostSwap64; namespace ot { namespace MeshCoP { -JoinerRouter::JoinerRouter(Instance &aInstance): - InstanceLocator(aInstance), - mSocket(aInstance.GetThreadNetif().GetIp6().GetUdp()), - mRelayTransmit(OT_URI_PATH_RELAY_TX, &JoinerRouter::HandleRelayTransmit, this), - mTimer(aInstance, &JoinerRouter::HandleTimer, this), - mNotifierCallback(&JoinerRouter::HandleStateChanged, this), - mJoinerUdpPort(0), - mIsJoinerPortConfigured(false), - mExpectJoinEntRsp(false) +JoinerRouter::JoinerRouter(Instance &aInstance) + : InstanceLocator(aInstance) + , mSocket(aInstance.GetThreadNetif().GetIp6().GetUdp()) + , mRelayTransmit(OT_URI_PATH_RELAY_TX, &JoinerRouter::HandleRelayTransmit, this) + , mTimer(aInstance, &JoinerRouter::HandleTimer, this) + , mNotifierCallback(&JoinerRouter::HandleStateChanged, this) + , mJoinerUdpPort(0) + , mIsJoinerPortConfigured(false) + , mExpectJoinEntRsp(false) { mSocket.GetSockName().mPort = OPENTHREAD_CONFIG_JOINER_UDP_PORT; GetNetif().GetCoap().AddResource(mRelayTransmit); @@ -107,11 +107,11 @@ exit: otError JoinerRouter::GetBorderAgentRloc(uint16_t &aRloc) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; BorderAgentLocatorTlv *borderAgentLocator; - borderAgentLocator = static_cast(GetNetif().GetNetworkDataLeader().GetCommissioningDataSubTlv( - Tlv::kBorderAgentLocator)); + borderAgentLocator = static_cast( + GetNetif().GetNetworkDataLeader().GetCommissioningDataSubTlv(Tlv::kBorderAgentLocator)); VerifyOrExit(borderAgentLocator != NULL, error = OT_ERROR_NOT_FOUND); aRloc = borderAgentLocator->GetBorderAgentLocator(); @@ -122,13 +122,13 @@ exit: uint16_t JoinerRouter::GetJoinerUdpPort(void) { - uint16_t rval = OPENTHREAD_CONFIG_JOINER_UDP_PORT; + uint16_t rval = OPENTHREAD_CONFIG_JOINER_UDP_PORT; JoinerUdpPortTlv *joinerUdpPort; VerifyOrExit(!mIsJoinerPortConfigured, rval = mJoinerUdpPort); - joinerUdpPort = static_cast(GetNetif().GetNetworkDataLeader().GetCommissioningDataSubTlv( - Tlv::kJoinerUdpPort)); + joinerUdpPort = static_cast( + GetNetif().GetNetworkDataLeader().GetCommissioningDataSubTlv(Tlv::kJoinerUdpPort)); VerifyOrExit(joinerUdpPort != NULL); rval = joinerUdpPort->GetUdpPort(); @@ -139,7 +139,7 @@ exit: otError JoinerRouter::SetJoinerUdpPort(uint16_t aJoinerUdpPort) { - mJoinerUdpPort = aJoinerUdpPort; + mJoinerUdpPort = aJoinerUdpPort; mIsJoinerPortConfigured = true; HandleStateChanged(OT_CHANGED_THREAD_NETDATA); @@ -154,16 +154,16 @@ void JoinerRouter::HandleUdpReceive(void *aContext, otMessage *aMessage, const o void JoinerRouter::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - otError error; - Message *message = NULL; - Coap::Header header; - Ip6::MessageInfo messageInfo; - JoinerUdpPortTlv udpPort; - JoinerIidTlv iid; + ThreadNetif & netif = GetNetif(); + otError error; + Message * message = NULL; + Coap::Header header; + Ip6::MessageInfo messageInfo; + JoinerUdpPortTlv udpPort; + JoinerIidTlv iid; JoinerRouterLocatorTlv rloc; - ExtendedTlv tlv; - uint16_t borderAgentRloc; + ExtendedTlv tlv; + uint16_t borderAgentRloc; otLogInfoMeshCoP(GetInstance(), "JoinerRouter::HandleUdpReceive"); @@ -195,7 +195,7 @@ void JoinerRouter::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &a while (aMessage.GetOffset() < aMessage.GetLength()) { uint16_t length = aMessage.GetLength() - aMessage.GetOffset(); - uint8_t tmp[16]; + uint8_t tmp[16]; if (length >= sizeof(tmp)) { @@ -225,27 +225,29 @@ exit: } } -void JoinerRouter::HandleRelayTransmit(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void JoinerRouter::HandleRelayTransmit(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleRelayTransmit( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleRelayTransmit(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void JoinerRouter::HandleRelayTransmit(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - otError error; - JoinerUdpPortTlv joinerPort; - JoinerIidTlv joinerIid; + otError error; + JoinerUdpPortTlv joinerPort; + JoinerIidTlv joinerIid; JoinerRouterKekTlv kek; - uint16_t offset; - uint16_t length; - Message *message = NULL; - Ip6::MessageInfo messageInfo; + uint16_t offset; + uint16_t length; + Message * message = NULL; + Ip6::MessageInfo messageInfo; - VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_NON_CONFIRMABLE && - aHeader.GetCode() == OT_COAP_CODE_POST, error = OT_ERROR_DROP); + VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_NON_CONFIRMABLE && aHeader.GetCode() == OT_COAP_CODE_POST, + error = OT_ERROR_DROP); otLogInfoMeshCoP(GetInstance(), "Received relay transmit"); @@ -264,7 +266,7 @@ void JoinerRouter::HandleRelayTransmit(Coap::Header &aHeader, Message &aMessage, while (length) { uint16_t copyLength = length; - uint8_t tmp[16]; + uint8_t tmp[16]; if (copyLength >= sizeof(tmp)) { @@ -303,22 +305,20 @@ exit: } } - -otError JoinerRouter::DelaySendingJoinerEntrust(const Ip6::MessageInfo &aMessageInfo, - const JoinerRouterKekTlv &aKek) +otError JoinerRouter::DelaySendingJoinerEntrust(const Ip6::MessageInfo &aMessageInfo, const JoinerRouterKekTlv &aKek) { - ThreadNetif &netif = GetNetif(); - otError error; - Message *message = NULL; - Coap::Header header; + ThreadNetif & netif = GetNetif(); + otError error; + Message * message = NULL; + Coap::Header header; Ip6::MessageInfo messageInfo; - NetworkMasterKeyTlv masterKey; - MeshLocalPrefixTlv meshLocalPrefix; - ExtendedPanIdTlv extendedPanId; - NetworkNameTlv networkName; + NetworkMasterKeyTlv masterKey; + MeshLocalPrefixTlv meshLocalPrefix; + ExtendedPanIdTlv extendedPanId; + NetworkNameTlv networkName; NetworkKeySequenceTlv networkKeySequence; - const Tlv *tlv; + const Tlv * tlv; DelayedJoinEntHeader delayedMessage; @@ -427,11 +427,11 @@ void JoinerRouter::HandleTimer(void) void JoinerRouter::SendDelayedJoinerEntrust(void) { - ThreadNetif &netif = GetNetif(); + ThreadNetif & netif = GetNetif(); DelayedJoinEntHeader delayedJoinEnt; - Message *message = mDelayedJoinEnts.GetHead(); - uint32_t now = TimerMilli::GetNow(); - Ip6::MessageInfo messageInfo; + Message * message = mDelayedJoinEnts.GetHead(); + uint32_t now = TimerMilli::GetNow(); + Ip6::MessageInfo messageInfo; VerifyOrExit(message != NULL); VerifyOrExit(!mTimer.IsRunning()); @@ -442,7 +442,6 @@ void JoinerRouter::SendDelayedJoinerEntrust(void) VerifyOrExit(!mExpectJoinEntRsp || memcmp(netif.GetKeyManager().GetKek(), delayedJoinEnt.GetKek(), KeyManager::kMaxKeyLength) == 0); - if (delayedJoinEnt.IsLater(now)) { mTimer.Start(delayedJoinEnt.GetSendTime() - now); @@ -468,19 +467,19 @@ void JoinerRouter::SendDelayedJoinerEntrust(void) } exit: - return ; + return; } otError JoinerRouter::SendJoinerEntrust(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { ThreadNetif &netif = GetNetif(); - otError error; + otError error; netif.GetCoap().AbortTransaction(&JoinerRouter::HandleJoinerEntrustResponse, this); otLogInfoMeshCoP(GetInstance(), "Sending JOIN_ENT.ntf"); - SuccessOrExit(error = netif.GetCoap().SendMessage(aMessage, aMessageInfo, - &JoinerRouter::HandleJoinerEntrustResponse, this)); + SuccessOrExit( + error = netif.GetCoap().SendMessage(aMessage, aMessageInfo, &JoinerRouter::HandleJoinerEntrustResponse, this)); otLogInfoMeshCoP(GetInstance(), "Sent joiner entrust length = %d", aMessage.GetLength()); otLogCertMeshCoP(GetInstance(), "[THCI] direction=send | type=JOIN_ENT.ntf"); @@ -491,17 +490,21 @@ exit: return error; } -void JoinerRouter::HandleJoinerEntrustResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError aResult) +void JoinerRouter::HandleJoinerEntrustResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aResult) { - static_cast(aContext)->HandleJoinerEntrustResponse(static_cast(aHeader), - static_cast(aMessage), - static_cast(aMessageInfo), - aResult); + static_cast(aContext)->HandleJoinerEntrustResponse( + static_cast(aHeader), static_cast(aMessage), + static_cast(aMessageInfo), aResult); } -void JoinerRouter::HandleJoinerEntrustResponse(Coap::Header *aHeader, Message *aMessage, - const Ip6::MessageInfo *aMessageInfo, otError aResult) +void JoinerRouter::HandleJoinerEntrustResponse(Coap::Header * aHeader, + Message * aMessage, + const Ip6::MessageInfo *aMessageInfo, + otError aResult) { OT_UNUSED_VARIABLE(aMessageInfo); @@ -516,11 +519,10 @@ void JoinerRouter::HandleJoinerEntrustResponse(Coap::Header *aHeader, Message *a otLogCertMeshCoP(GetInstance(), "[THCI] direction=recv | type=JOIN_ENT.rsp"); exit: - return ; + return; } -} // namespace Dtls -} // namespace ot +} // namespace MeshCoP +} // namespace ot #endif // OPENTHREAD_FTD - diff --git a/src/core/meshcop/joiner_router.hpp b/src/core/meshcop/joiner_router.hpp index 041340188..c2d64cfa6 100644 --- a/src/core/meshcop/joiner_router.hpp +++ b/src/core/meshcop/joiner_router.hpp @@ -55,7 +55,7 @@ class ThreadNetif; namespace MeshCoP { -class JoinerRouter: public InstanceLocator +class JoinerRouter : public InstanceLocator { public: /** @@ -87,29 +87,36 @@ public: private: enum { - kDelayJoinEnt = 50, ///< milliseconds + kDelayJoinEnt = 50, ///< milliseconds }; static void HandleStateChanged(Notifier::Callback &aCallback, uint32_t aFlags); - void HandleStateChanged(uint32_t aFlags); + void HandleStateChanged(uint32_t aFlags); static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo); - void HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - static void HandleRelayTransmit(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleRelayTransmit(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleRelayTransmit(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleRelayTransmit(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - static void HandleJoinerEntrustResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError result); - void HandleJoinerEntrustResponse(Coap::Header *aHeader, Message *aMessage, - const Ip6::MessageInfo *aMessageInfo, otError result); + static void HandleJoinerEntrustResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError result); + void HandleJoinerEntrustResponse(Coap::Header * aHeader, + Message * aMessage, + const Ip6::MessageInfo *aMessageInfo, + otError result); static void HandleTimer(Timer &aTimer); - void HandleTimer(void); + void HandleTimer(void); otError DelaySendingJoinerEntrust(const Ip6::MessageInfo &aMessageInfo, const JoinerRouterKekTlv &aKek); - void SendDelayedJoinerEntrust(void); + void SendDelayedJoinerEntrust(void); otError SendJoinerEntrust(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); otError GetBorderAgentRloc(uint16_t &aRloc); @@ -117,7 +124,7 @@ private: Ip6::UdpSocket mSocket; Coap::Resource mRelayTransmit; - TimerMilli mTimer; + TimerMilli mTimer; MessageQueue mDelayedJoinEnts; Notifier::Callback mNotifierCallback; @@ -148,8 +155,9 @@ public: * @param[in] aDestination IPv6 address of the message destination. * */ - DelayedJoinEntHeader(uint32_t aSendTime, Ip6::MessageInfo &aMessageInfo, const uint8_t *aKek) { - mSendTime = aSendTime; + DelayedJoinEntHeader(uint32_t aSendTime, Ip6::MessageInfo &aMessageInfo, const uint8_t *aKek) + { + mSendTime = aSendTime; mMessageInfo = aMessageInfo; memcpy(&mKek, aKek, sizeof(mKek)); } @@ -163,9 +171,7 @@ public: * @retval OT_ERROR_NO_BUFS Insufficient available buffers to grow the message. * */ - otError AppendTo(Message &aMessage) { - return aMessage.Append(this, sizeof(*this)); - } + otError AppendTo(Message &aMessage) { return aMessage.Append(this, sizeof(*this)); } /** * This method reads delayed response header from the message. @@ -175,7 +181,8 @@ public: * @returns The number of bytes read. * */ - uint16_t ReadFrom(Message &aMessage) { + uint16_t ReadFrom(Message &aMessage) + { return aMessage.Read(aMessage.GetLength() - sizeof(*this), sizeof(*this), this); } @@ -187,7 +194,8 @@ public: * @retval OT_ERROR_NONE Successfully removed the header. * */ - static otError RemoveFrom(Message &aMessage) { + static otError RemoveFrom(Message &aMessage) + { return aMessage.SetLength(aMessage.GetLength() - sizeof(DelayedJoinEntHeader)); } @@ -236,13 +244,12 @@ public: bool IsLater(uint32_t aTime) { return (static_cast(aTime - mSendTime) < 0); } private: - Ip6::MessageInfo mMessageInfo; ///< Message info of the message to send. - uint32_t mSendTime; ///< Time when the message shall be sent. - uint8_t mKek[KeyManager::kMaxKeyLength]; ///< KEK used by MAC layer to encode this message. + Ip6::MessageInfo mMessageInfo; ///< Message info of the message to send. + uint32_t mSendTime; ///< Time when the message shall be sent. + uint8_t mKek[KeyManager::kMaxKeyLength]; ///< KEK used by MAC layer to encode this message. }; +} // namespace MeshCoP +} // namespace ot -} // namespace MeshCoP -} // namespace ot - -#endif // JOINER_ROUTER_HPP_ +#endif // JOINER_ROUTER_HPP_ diff --git a/src/core/meshcop/leader.cpp b/src/core/meshcop/leader.cpp index 5fd899ea5..beb86612b 100644 --- a/src/core/meshcop/leader.cpp +++ b/src/core/meshcop/leader.cpp @@ -55,31 +55,33 @@ namespace ot { namespace MeshCoP { -Leader::Leader(Instance &aInstance): - InstanceLocator(aInstance), - mPetition(OT_URI_PATH_LEADER_PETITION, Leader::HandlePetition, this), - mKeepAlive(OT_URI_PATH_LEADER_KEEP_ALIVE, Leader::HandleKeepAlive, this), - mTimer(aInstance, HandleTimer, this), - mDelayTimerMinimal(DelayTimerTlv::kDelayTimerMinimal), - mSessionId(0xffff) +Leader::Leader(Instance &aInstance) + : InstanceLocator(aInstance) + , mPetition(OT_URI_PATH_LEADER_PETITION, Leader::HandlePetition, this) + , mKeepAlive(OT_URI_PATH_LEADER_KEEP_ALIVE, Leader::HandleKeepAlive, this) + , mTimer(aInstance, HandleTimer, this) + , mDelayTimerMinimal(DelayTimerTlv::kDelayTimerMinimal) + , mSessionId(0xffff) { GetNetif().GetCoap().AddResource(mPetition); GetNetif().GetCoap().AddResource(mKeepAlive); } -void Leader::HandlePetition(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void Leader::HandlePetition(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandlePetition( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandlePetition(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void Leader::HandlePetition(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { CommissioningData data; CommissionerIdTlv commissionerId; - StateTlv::State state = StateTlv::kReject; + StateTlv::State state = StateTlv::kReject; otLogInfoMeshCoP(GetInstance(), "received petition"); @@ -88,8 +90,8 @@ void Leader::HandlePetition(Coap::Header &aHeader, Message &aMessage, const Ip6: if (mTimer.IsRunning()) { - VerifyOrExit(!strncmp(commissionerId.GetCommissionerId(), mCommissionerId.GetCommissionerId(), - sizeof(mCommissionerId))); + VerifyOrExit( + !strncmp(commissionerId.GetCommissionerId(), mCommissionerId.GetCommissionerId(), sizeof(mCommissionerId))); ResignCommissioner(); } @@ -104,8 +106,8 @@ void Leader::HandlePetition(Coap::Header &aHeader, Message &aMessage, const Ip6: data.mSteeringData.SetLength(1); data.mSteeringData.Clear(); - SuccessOrExit(GetNetif().GetNetworkDataLeader().SetCommissioningData(reinterpret_cast(&data), - data.GetLength())); + SuccessOrExit( + GetNetif().GetNetworkDataLeader().SetCommissioningData(reinterpret_cast(&data), data.GetLength())); mCommissionerId = commissionerId; @@ -117,15 +119,16 @@ exit: SendPetitionResponse(aHeader, aMessageInfo, state); } -otError Leader::SendPetitionResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, - StateTlv::State aState) +otError Leader::SendPetitionResponse(const Coap::Header & aRequestHeader, + const Ip6::MessageInfo &aMessageInfo, + StateTlv::State aState) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Coap::Header responseHeader; - StateTlv state; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Coap::Header responseHeader; + StateTlv state; CommissionerSessionIdTlv sessionId; - Message *message; + Message * message; responseHeader.SetDefaultResponseHeader(aRequestHeader); responseHeader.SetPayloadMarker(); @@ -163,19 +166,21 @@ exit: return error; } -void Leader::HandleKeepAlive(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void Leader::HandleKeepAlive(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleKeepAlive( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleKeepAlive(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void Leader::HandleKeepAlive(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - StateTlv state; + StateTlv state; CommissionerSessionIdTlv sessionId; - StateTlv::State responseState; + StateTlv::State responseState; otLogInfoMeshCoP(GetInstance(), "received keep alive"); @@ -206,14 +211,15 @@ exit: return; } -otError Leader::SendKeepAliveResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, - StateTlv::State aState) +otError Leader::SendKeepAliveResponse(const Coap::Header & aRequestHeader, + const Ip6::MessageInfo &aMessageInfo, + StateTlv::State aState) { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Coap::Header responseHeader; - StateTlv state; - Message *message; + StateTlv state; + Message * message; responseHeader.SetDefaultResponseHeader(aRequestHeader); responseHeader.SetPayloadMarker(); @@ -240,11 +246,11 @@ exit: otError Leader::SendDatasetChanged(const Ip6::Address &aAddress) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Coap::Header header; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Coap::Header header; Ip6::MessageInfo messageInfo; - Message *message; + Message * message; header.Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); header.SetToken(Coap::Header::kDefaultTokenLength); @@ -319,8 +325,7 @@ void Leader::ResignCommissioner(void) otLogInfoMeshCoP(GetInstance(), "commissioner inactive"); } -} // namespace MeshCoP -} // namespace ot +} // namespace MeshCoP +} // namespace ot #endif // OPENTHREAD_FTD - diff --git a/src/core/meshcop/leader.hpp b/src/core/meshcop/leader.hpp index 74c3ae866..4855ad65c 100644 --- a/src/core/meshcop/leader.hpp +++ b/src/core/meshcop/leader.hpp @@ -50,18 +50,18 @@ OT_TOOL_PACKED_BEGIN class CommissioningData { public: - uint8_t GetLength(void) const { - return sizeof(Tlv) + mBorderAgentLocator.GetLength() + - sizeof(Tlv) + mCommissionerSessionId.GetLength() + + uint8_t GetLength(void) const + { + return sizeof(Tlv) + mBorderAgentLocator.GetLength() + sizeof(Tlv) + mCommissionerSessionId.GetLength() + sizeof(Tlv) + mSteeringData.GetLength(); } - BorderAgentLocatorTlv mBorderAgentLocator; + BorderAgentLocatorTlv mBorderAgentLocator; CommissionerSessionIdTlv mCommissionerSessionId; - SteeringDataTlv mSteeringData; + SteeringDataTlv mSteeringData; } OT_TOOL_PACKED_END; -class Leader: public InstanceLocator +class Leader : public InstanceLocator { public: /** @@ -115,19 +115,25 @@ private: }; static void HandleTimer(Timer &aTimer); - void HandleTimer(void); + void HandleTimer(void); - static void HandlePetition(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandlePetition(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandlePetition(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - otError SendPetitionResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, - StateTlv::State aState); + void HandlePetition(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + otError SendPetitionResponse(const Coap::Header & aRequestHeader, + const Ip6::MessageInfo &aMessageInfo, + StateTlv::State aState); - static void HandleKeepAlive(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleKeepAlive(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleKeepAlive(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - otError SendKeepAliveResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, - StateTlv::State aState); + void HandleKeepAlive(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + otError SendKeepAliveResponse(const Coap::Header & aRequestHeader, + const Ip6::MessageInfo &aMessageInfo, + StateTlv::State aState); static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo); @@ -135,15 +141,15 @@ private: Coap::Resource mPetition; Coap::Resource mKeepAlive; - TimerMilli mTimer; + TimerMilli mTimer; uint32_t mDelayTimerMinimal; CommissionerIdTlv mCommissionerId; - uint16_t mSessionId; + uint16_t mSessionId; }; -} // namespace MeshCoP -} // namespace ot +} // namespace MeshCoP +} // namespace ot -#endif // MESHCOP_LEADER_HPP_ +#endif // MESHCOP_LEADER_HPP_ diff --git a/src/core/meshcop/meshcop.cpp b/src/core/meshcop/meshcop.cpp index 0f3d2e35e..f37d9a137 100644 --- a/src/core/meshcop/meshcop.cpp +++ b/src/core/meshcop/meshcop.cpp @@ -40,7 +40,7 @@ namespace MeshCoP { void ComputeJoinerId(const Mac::ExtAddress &aEui64, Mac::ExtAddress &aJoinerId) { Crypto::Sha256 sha256; - uint8_t hash[Crypto::Sha256::kHashSize]; + uint8_t hash[Crypto::Sha256::kHashSize]; sha256.Start(); sha256.Update(aEui64.m8, sizeof(aEui64)); @@ -50,5 +50,5 @@ void ComputeJoinerId(const Mac::ExtAddress &aEui64, Mac::ExtAddress &aJoinerId) aJoinerId.SetLocal(true); } -} // namespace MeshCoP -} // namespace ot +} // namespace MeshCoP +} // namespace ot diff --git a/src/core/meshcop/meshcop.hpp b/src/core/meshcop/meshcop.hpp index 0655b93b8..d7bcf4fe5 100644 --- a/src/core/meshcop/meshcop.hpp +++ b/src/core/meshcop/meshcop.hpp @@ -67,8 +67,8 @@ inline Message *NewMeshCoPMessage(Coap::CoapBase &aCoap, const Coap::Header &aHe */ void ComputeJoinerId(const Mac::ExtAddress &aEui64, Mac::ExtAddress &aJoinerId); -} // namespace MeshCoP +} // namespace MeshCoP -} // namespace ot +} // namespace ot -#endif // MESHCOP_HPP_ +#endif // MESHCOP_HPP_ diff --git a/src/core/meshcop/meshcop_tlvs.cpp b/src/core/meshcop/meshcop_tlvs.cpp index 642c42e54..515b1aa08 100644 --- a/src/core/meshcop/meshcop_tlvs.cpp +++ b/src/core/meshcop/meshcop_tlvs.cpp @@ -68,5 +68,5 @@ void SteeringDataTlv::ComputeBloomFilter(const otExtAddress &aJoinerId) SetBit(ansi.Get() % GetNumBits()); } -} // namespace MeshCoP -} // namespace ot +} // namespace MeshCoP +} // namespace ot diff --git a/src/core/meshcop/meshcop_tlvs.hpp b/src/core/meshcop/meshcop_tlvs.hpp index ff2e75b64..6889116be 100644 --- a/src/core/meshcop/meshcop_tlvs.hpp +++ b/src/core/meshcop/meshcop_tlvs.hpp @@ -47,9 +47,9 @@ #include "common/tlvs.hpp" #include "meshcop/timestamp.hpp" -using ot::Encoding::Reverse32; using ot::Encoding::BigEndian::HostSwap16; using ot::Encoding::BigEndian::HostSwap32; +using ot::Encoding::Reverse32; namespace ot { namespace MeshCoP { @@ -68,42 +68,42 @@ public: */ enum Type { - kChannel = OT_MESHCOP_TLV_CHANNEL, ///< Channel TLV - kPanId = OT_MESHCOP_TLV_PANID, ///< PAN ID TLV - kExtendedPanId = OT_MESHCOP_TLV_EXTPANID, ///< Extended PAN ID TLV - kNetworkName = OT_MESHCOP_TLV_NETWORKNAME, ///< Newtork Name TLV - kPSKc = OT_MESHCOP_TLV_PSKC, ///< PSKc TLV - kNetworkMasterKey = OT_MESHCOP_TLV_MASTERKEY, ///< Network Master Key TLV - kNetworkKeySequence = OT_MESHCOP_TLV_NETWORK_KEY_SEQUENCE, ///< Network Key Sequence TLV - kMeshLocalPrefix = OT_MESHCOP_TLV_MESHLOCALPREFIX, ///< Mesh Local Prefix TLV - kSteeringData = OT_MESHCOP_TLV_STEERING_DATA, ///< Steering Data TLV - kBorderAgentLocator = OT_MESHCOP_TLV_BORDER_AGENT_RLOC, ///< Border Agent Locator TLV - kCommissionerId = OT_MESHCOP_TLV_COMMISSIONER_ID, ///< Commissioner ID TLV - kCommissionerSessionId = OT_MESHCOP_TLV_COMM_SESSION_ID, ///< Commissioner Session ID TLV - kSecurityPolicy = OT_MESHCOP_TLV_SECURITYPOLICY, ///< Security Policy TLV - kGet = OT_MESHCOP_TLV_GET, ///< Get TLV - kActiveTimestamp = OT_MESHCOP_TLV_ACTIVETIMESTAMP, ///< Active Timestamp TLV - kState = OT_MESHCOP_TLV_STATE, ///< State TLV - kJoinerDtlsEncapsulation = OT_MESHCOP_TLV_JOINER_DTLS, ///< Joiner DTLS Encapsulation TLV - kJoinerUdpPort = OT_MESHCOP_TLV_JOINER_UDP_PORT, ///< Joiner UDP Port TLV - kJoinerIid = OT_MESHCOP_TLV_JOINER_IID, ///< Joiner IID TLV - kJoinerRouterLocator = OT_MESHCOP_TLV_JOINER_RLOC, ///< Joiner Router Locator TLV - kJoinerRouterKek = OT_MESHCOP_TLV_JOINER_ROUTER_KEK, ///< Joiner Router KEK TLV - kProvisioningUrl = OT_MESHCOP_TLV_PROVISIONING_URL, ///< Provisioning URL TLV - kVendorName = OT_MESHCOP_TLV_VENDOR_NAME_TLV, ///< meshcop Vendor Name TLV - kVendorModel = OT_MESHCOP_TLV_VENDOR_MODEL_TLV, ///< meshcop Vendor Model TLV - kVendorSwVersion = OT_MESHCOP_TLV_VENDOR_SW_VERSION_TLV, ///< meshcop Vendor SW Version TLV - kVendorData = OT_MESHCOP_TLV_VENDOR_DATA_TLV, ///< meshcop Vendor Data TLV - kVendorStackVersion = OT_MESHCOP_TLV_VENDOR_STACK_VERSION_TLV, ///< meshcop Vendor Stack Version TLV - kPendingTimestamp = OT_MESHCOP_TLV_PENDINGTIMESTAMP, ///< Pending Timestamp TLV - kDelayTimer = OT_MESHCOP_TLV_DELAYTIMER, ///< Delay Timer TLV - kChannelMask = OT_MESHCOP_TLV_CHANNELMASK, ///< Channel Mask TLV - kCount = OT_MESHCOP_TLV_COUNT, ///< Count TLV - kPeriod = OT_MESHCOP_TLV_PERIOD, ///< Period TLV - kScanDuration = OT_MESHCOP_TLV_SCAN_DURATION, ///< Scan Duration TLV - kEnergyList = OT_MESHCOP_TLV_ENERGY_LIST, ///< Energy List TLV - kDiscoveryRequest = OT_MESHCOP_TLV_DISCOVERYREQUEST, ///< Discovery Request TLV - kDiscoveryResponse = OT_MESHCOP_TLV_DISCOVERYRESPONSE, ///< Discovery Response TLV + kChannel = OT_MESHCOP_TLV_CHANNEL, ///< Channel TLV + kPanId = OT_MESHCOP_TLV_PANID, ///< PAN ID TLV + kExtendedPanId = OT_MESHCOP_TLV_EXTPANID, ///< Extended PAN ID TLV + kNetworkName = OT_MESHCOP_TLV_NETWORKNAME, ///< Newtork Name TLV + kPSKc = OT_MESHCOP_TLV_PSKC, ///< PSKc TLV + kNetworkMasterKey = OT_MESHCOP_TLV_MASTERKEY, ///< Network Master Key TLV + kNetworkKeySequence = OT_MESHCOP_TLV_NETWORK_KEY_SEQUENCE, ///< Network Key Sequence TLV + kMeshLocalPrefix = OT_MESHCOP_TLV_MESHLOCALPREFIX, ///< Mesh Local Prefix TLV + kSteeringData = OT_MESHCOP_TLV_STEERING_DATA, ///< Steering Data TLV + kBorderAgentLocator = OT_MESHCOP_TLV_BORDER_AGENT_RLOC, ///< Border Agent Locator TLV + kCommissionerId = OT_MESHCOP_TLV_COMMISSIONER_ID, ///< Commissioner ID TLV + kCommissionerSessionId = OT_MESHCOP_TLV_COMM_SESSION_ID, ///< Commissioner Session ID TLV + kSecurityPolicy = OT_MESHCOP_TLV_SECURITYPOLICY, ///< Security Policy TLV + kGet = OT_MESHCOP_TLV_GET, ///< Get TLV + kActiveTimestamp = OT_MESHCOP_TLV_ACTIVETIMESTAMP, ///< Active Timestamp TLV + kState = OT_MESHCOP_TLV_STATE, ///< State TLV + kJoinerDtlsEncapsulation = OT_MESHCOP_TLV_JOINER_DTLS, ///< Joiner DTLS Encapsulation TLV + kJoinerUdpPort = OT_MESHCOP_TLV_JOINER_UDP_PORT, ///< Joiner UDP Port TLV + kJoinerIid = OT_MESHCOP_TLV_JOINER_IID, ///< Joiner IID TLV + kJoinerRouterLocator = OT_MESHCOP_TLV_JOINER_RLOC, ///< Joiner Router Locator TLV + kJoinerRouterKek = OT_MESHCOP_TLV_JOINER_ROUTER_KEK, ///< Joiner Router KEK TLV + kProvisioningUrl = OT_MESHCOP_TLV_PROVISIONING_URL, ///< Provisioning URL TLV + kVendorName = OT_MESHCOP_TLV_VENDOR_NAME_TLV, ///< meshcop Vendor Name TLV + kVendorModel = OT_MESHCOP_TLV_VENDOR_MODEL_TLV, ///< meshcop Vendor Model TLV + kVendorSwVersion = OT_MESHCOP_TLV_VENDOR_SW_VERSION_TLV, ///< meshcop Vendor SW Version TLV + kVendorData = OT_MESHCOP_TLV_VENDOR_DATA_TLV, ///< meshcop Vendor Data TLV + kVendorStackVersion = OT_MESHCOP_TLV_VENDOR_STACK_VERSION_TLV, ///< meshcop Vendor Stack Version TLV + kPendingTimestamp = OT_MESHCOP_TLV_PENDINGTIMESTAMP, ///< Pending Timestamp TLV + kDelayTimer = OT_MESHCOP_TLV_DELAYTIMER, ///< Delay Timer TLV + kChannelMask = OT_MESHCOP_TLV_CHANNELMASK, ///< Channel Mask TLV + kCount = OT_MESHCOP_TLV_COUNT, ///< Count TLV + kPeriod = OT_MESHCOP_TLV_PERIOD, ///< Period TLV + kScanDuration = OT_MESHCOP_TLV_SCAN_DURATION, ///< Scan Duration TLV + kEnergyList = OT_MESHCOP_TLV_ENERGY_LIST, ///< Energy List TLV + kDiscoveryRequest = OT_MESHCOP_TLV_DISCOVERYREQUEST, ///< Discovery Request TLV + kDiscoveryResponse = OT_MESHCOP_TLV_DISCOVERYRESPONSE, ///< Discovery Response TLV }; /** @@ -128,13 +128,9 @@ public: * @returns A pointer to the next TLV. * */ - Tlv *GetNext(void) { - return static_cast(ot::Tlv::GetNext()); - } + Tlv *GetNext(void) { return static_cast(ot::Tlv::GetNext()); } - const Tlv *GetNext(void) const { - return static_cast(ot::Tlv::GetNext()); - } + const Tlv *GetNext(void) const { return static_cast(ot::Tlv::GetNext()); } /** * This static method reads the requested TLV out of @p aMessage. @@ -148,7 +144,8 @@ public: * @retval OT_ERROR_NOT_FOUND Could not find the TLV with Type @p aType. * */ - static otError GetTlv(const Message &aMessage, Type aType, uint16_t aMaxLength, Tlv &aTlv) { + static otError GetTlv(const Message &aMessage, Type aType, uint16_t aMaxLength, Tlv &aTlv) + { return ot::Tlv::Get(aMessage, static_cast(aType), aMaxLength, aTlv); } @@ -164,7 +161,8 @@ public: * @retval OT_ERROR_NOT_FOUND Could not find the TLV with Type @p aType. * */ - static otError GetValueOffset(const Message &aMessage, Type aType, uint16_t &aOffset, uint16_t &aLength) { + static otError GetValueOffset(const Message &aMessage, Type aType, uint16_t &aOffset, uint16_t &aLength) + { return ot::Tlv::GetValueOffset(aMessage, static_cast(aType), aOffset, aLength); } @@ -175,14 +173,18 @@ public: * */ OT_TOOL_PACKED_BEGIN -class ChannelTlv: public Tlv +class ChannelTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kChannel); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kChannel); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -226,7 +228,7 @@ public: void SetChannel(uint16_t aChannel) { mChannel = HostSwap16(aChannel); } private: - uint8_t mChannelPage; + uint8_t mChannelPage; uint16_t mChannel; } OT_TOOL_PACKED_END; @@ -235,14 +237,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class PanIdTlv: public Tlv +class PanIdTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kPanId); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kPanId); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -278,14 +284,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ExtendedPanIdTlv: public Tlv +class ExtendedPanIdTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kExtendedPanId); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kExtendedPanId); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -310,9 +320,7 @@ public: * @param[in] aExtendedPanId A pointer to the Extended PAN ID value. * */ - void SetExtendedPanId(const uint8_t *aExtendedPanId) { - memcpy(mExtendedPanId, aExtendedPanId, OT_EXT_PAN_ID_SIZE); - } + void SetExtendedPanId(const uint8_t *aExtendedPanId) { memcpy(mExtendedPanId, aExtendedPanId, OT_EXT_PAN_ID_SIZE); } private: uint8_t mExtendedPanId[OT_EXT_PAN_ID_SIZE]; @@ -323,14 +331,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class NetworkNameTlv: public Tlv +class NetworkNameTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kNetworkName); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kNetworkName); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -355,7 +367,8 @@ public: * @param[in] aNetworkName A pointer to the Network Name value. * */ - void SetNetworkName(const char *aNetworkName) { + void SetNetworkName(const char *aNetworkName) + { size_t length = strnlen(aNetworkName, sizeof(mNetworkName)); memcpy(mNetworkName, aNetworkName, length); SetLength(static_cast(length)); @@ -370,14 +383,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class PSKcTlv: public Tlv +class PSKcTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kPSKc); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kPSKc); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -402,9 +419,7 @@ public: * @param[in] aPSKc A pointer to the PSKc value. * */ - void SetPSKc(const uint8_t *aPSKc) { - memcpy(mPSKc, aPSKc, sizeof(mPSKc)); - } + void SetPSKc(const uint8_t *aPSKc) { memcpy(mPSKc, aPSKc, sizeof(mPSKc)); } private: uint8_t mPSKc[16]; @@ -415,14 +430,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class NetworkMasterKeyTlv: public Tlv +class NetworkMasterKeyTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kNetworkMasterKey); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kNetworkMasterKey); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -447,9 +466,7 @@ public: * @param[in] aNetworkMasterKey A pointer to the Network Master Key value. * */ - void SetNetworkMasterKey(const otMasterKey &aNetworkMasterKey) { - mNetworkMasterKey = aNetworkMasterKey; - } + void SetNetworkMasterKey(const otMasterKey &aNetworkMasterKey) { mNetworkMasterKey = aNetworkMasterKey; } private: otMasterKey mNetworkMasterKey; @@ -460,14 +477,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class NetworkKeySequenceTlv: public Tlv +class NetworkKeySequenceTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kNetworkKeySequence); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kNetworkKeySequence); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -503,14 +524,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class MeshLocalPrefixTlv: public Tlv +class MeshLocalPrefixTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kMeshLocalPrefix); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kMeshLocalPrefix); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -535,7 +560,8 @@ public: * @param[in] aMeshLocalPrefix A pointer to the Mesh Local Prefix value. * */ - void SetMeshLocalPrefix(const uint8_t *aMeshLocalPrefix) { + void SetMeshLocalPrefix(const uint8_t *aMeshLocalPrefix) + { memcpy(mMeshLocalPrefix, aMeshLocalPrefix, sizeof(mMeshLocalPrefix)); } @@ -548,14 +574,19 @@ private: * */ OT_TOOL_PACKED_BEGIN -class SteeringDataTlv: public Tlv +class SteeringDataTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kSteeringData); SetLength(sizeof(*this) - sizeof(Tlv)); Clear(); } + void Init(void) + { + SetType(kSteeringData); + SetLength(sizeof(*this) - sizeof(Tlv)); + Clear(); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -585,11 +616,14 @@ public: * @retval FALSE If the SteeringData doesn't allow any Joiner. * */ - bool DoesAllowAny(void) { + bool DoesAllowAny(void) + { bool rval = true; - for (uint8_t i = 0; i < GetLength(); i++) { - if (mSteeringData[i] != 0xff) { + for (uint8_t i = 0; i < GetLength(); i++) + { + if (mSteeringData[i] != 0xff) + { rval = false; break; } @@ -659,14 +693,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class BorderAgentLocatorTlv: public Tlv +class BorderAgentLocatorTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kBorderAgentLocator); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kBorderAgentLocator); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -702,14 +740,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class CommissionerIdTlv: public Tlv +class CommissionerIdTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kCommissionerId); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kCommissionerId); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -734,7 +776,8 @@ public: * @param[in] aCommissionerId A pointer to the Commissioner ID value. * */ - void SetCommissionerId(const char *aCommissionerId) { + void SetCommissionerId(const char *aCommissionerId) + { size_t length = strnlen(aCommissionerId, sizeof(mCommissionerId)); memcpy(mCommissionerId, aCommissionerId, length); SetLength(static_cast(length)); @@ -754,14 +797,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class CommissionerSessionIdTlv: public Tlv +class CommissionerSessionIdTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kCommissionerSessionId); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kCommissionerSessionId); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -797,14 +844,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class SecurityPolicyTlv: public Tlv +class SecurityPolicyTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kSecurityPolicy); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kSecurityPolicy); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -833,11 +884,11 @@ public: enum { - kObtainMasterKeyFlag = OT_SECURITY_POLICY_OBTAIN_MASTER_KEY, ///< Obtaining the Master Key - kNativeCommissioningFlag = OT_SECURITY_POLICY_NATIVE_COMMISSIONING, ///< Native Commissioning - kRoutersFlag = OT_SECURITY_POLICY_ROUTERS, ///< Routers enabled - kExternalCommissionerFlag = OT_SECURITY_POLICY_EXTERNAL_COMMISSIONER, ///< External Commissioner allowed - kBeaconsFlag = OT_SECURITY_POLICY_BEACONS, ///< Beacons enabled + kObtainMasterKeyFlag = OT_SECURITY_POLICY_OBTAIN_MASTER_KEY, ///< Obtaining the Master Key + kNativeCommissioningFlag = OT_SECURITY_POLICY_NATIVE_COMMISSIONING, ///< Native Commissioning + kRoutersFlag = OT_SECURITY_POLICY_ROUTERS, ///< Routers enabled + kExternalCommissionerFlag = OT_SECURITY_POLICY_EXTERNAL_COMMISSIONER, ///< External Commissioner allowed + kBeaconsFlag = OT_SECURITY_POLICY_BEACONS, ///< Beacons enabled }; /** @@ -858,7 +909,7 @@ public: private: uint16_t mRotationTime; - uint8_t mFlags; + uint8_t mFlags; } OT_TOOL_PACKED_END; /** @@ -873,7 +924,12 @@ public: * This method initializes the TLV. * */ - void Init(void) { SetType(kActiveTimestamp); SetLength(sizeof(*this) - sizeof(Tlv)); Timestamp::Init(); } + void Init(void) + { + SetType(kActiveTimestamp); + SetLength(sizeof(*this) - sizeof(Tlv)); + Timestamp::Init(); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -890,14 +946,18 @@ public: * */ OT_TOOL_PACKED_BEGIN -class StateTlv: public Tlv +class StateTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kState); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kState); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -914,9 +974,9 @@ public: */ enum State { - kReject = -1, ///< Reject - kPending = 0, ///< Pending - kAccept = 1, ///< Accept + kReject = -1, ///< Reject + kPending = 0, ///< Pending + kAccept = 1, ///< Accept }; /** @@ -944,14 +1004,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class JoinerUdpPortTlv: public Tlv +class JoinerUdpPortTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kJoinerUdpPort); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kJoinerUdpPort); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -987,14 +1051,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class JoinerIidTlv: public Tlv +class JoinerIidTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kJoinerIid); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kJoinerIid); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1030,14 +1098,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class JoinerRouterLocatorTlv: public Tlv +class JoinerRouterLocatorTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kJoinerRouterLocator); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kJoinerRouterLocator); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1073,14 +1145,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class JoinerRouterKekTlv: public Tlv +class JoinerRouterKekTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kJoinerRouterKek); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kJoinerRouterKek); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1123,7 +1199,12 @@ public: * This method initializes the TLV. * */ - void Init(void) { SetType(kPendingTimestamp); SetLength(sizeof(*this) - sizeof(Tlv)); Timestamp::Init(); } + void Init(void) + { + SetType(kPendingTimestamp); + SetLength(sizeof(*this) - sizeof(Tlv)); + Timestamp::Init(); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1140,14 +1221,18 @@ public: * */ OT_TOOL_PACKED_BEGIN -class DelayTimerTlv: public Tlv +class DelayTimerTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kDelayTimer); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kDelayTimer); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1176,9 +1261,9 @@ public: enum { - kMaxDelayTimer = 259200, ///< maximum delay timer value for a Pending Dataset in seconds - kDelayTimerMinimal = 30000, ///< Minimum Delay Timer value for a Pending Operational Dataset (ms) - kDelayTimerDefault = 300000, ///< Default Delay Timer value for a Pending Operational Dataset (ms) + kMaxDelayTimer = 259200, ///< maximum delay timer value for a Pending Dataset in seconds + kDelayTimerMinimal = 30000, ///< Minimum Delay Timer value for a Pending Operational Dataset (ms) + kDelayTimerDefault = 300000, ///< Default Delay Timer value for a Pending Operational Dataset (ms) }; private: @@ -1231,7 +1316,8 @@ public: * @param[in] aChannel The channel in ChannelMask to clear. * */ - void ClearChannel(uint8_t aChannel) { + void ClearChannel(uint8_t aChannel) + { uint8_t *mask = reinterpret_cast(this) + sizeof(*this); mask[aChannel / 8] &= ~(0x80 >> (aChannel % 8)); } @@ -1242,7 +1328,8 @@ public: * @param[in] aChannel The channel in ChannelMask to set. * */ - void SetChannel(uint8_t aChannel) { + void SetChannel(uint8_t aChannel) + { uint8_t *mask = reinterpret_cast(this) + sizeof(*this); mask[aChannel / 8] |= 0x80 >> (aChannel % 8); } @@ -1253,7 +1340,8 @@ public: * @param[in] aChannel The channel in ChannelMask to get. * */ - bool IsChannelSet(uint8_t aChannel) const { + bool IsChannelSet(uint8_t aChannel) const + { const uint8_t *mask = reinterpret_cast(this) + sizeof(*this); return (aChannel < (mMaskLength * 8)) ? ((mask[aChannel / 8] & (0x80 >> (aChannel % 8))) != 0) : false; } @@ -1268,14 +1356,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ChannelMaskTlv: public Tlv +class ChannelMaskTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kChannelMask); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kChannelMask); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1292,14 +1384,15 @@ public: * */ OT_TOOL_PACKED_BEGIN -class ChannelMask0Tlv: public ChannelMaskTlv, public ChannelMaskEntry +class ChannelMask0Tlv : public ChannelMaskTlv, public ChannelMaskEntry { public: /** * This method initializes the TLV. * */ - void Init(void) { + void Init(void) + { SetType(kChannelMask); SetLength(sizeof(*this) - sizeof(Tlv)); SetChannelPage(0); @@ -1313,11 +1406,9 @@ public: * @retval FALSE If the TLV does not appear to be well-formed. * */ - bool IsValid(void) const { - return - GetLength() == sizeof(*this) - sizeof(Tlv) && - GetChannelPage() == 0 && - GetMaskLength() == sizeof(mMask); + bool IsValid(void) const + { + return GetLength() == sizeof(*this) - sizeof(Tlv) && GetChannelPage() == 0 && GetMaskLength() == sizeof(mMask); } /** @@ -1345,14 +1436,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class CountTlv: public Tlv +class CountTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kCount); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kCount); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1388,14 +1483,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class PeriodTlv: public Tlv +class PeriodTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kPeriod); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kPeriod); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1431,14 +1530,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ScanDurationTlv: public Tlv +class ScanDurationTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kScanDuration); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kScanDuration); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1474,14 +1577,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class EnergyListTlv: public Tlv +class EnergyListTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kEnergyList); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kEnergyList); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1498,14 +1605,18 @@ public: * */ OT_TOOL_PACKED_BEGIN -class ProvisioningUrlTlv: public Tlv +class ProvisioningUrlTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kProvisioningUrl); SetLength(0); } + void Init(void) + { + SetType(kProvisioningUrl); + SetLength(0); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1530,18 +1641,20 @@ public: * @param[in] aProvisioningUrl A pointer to the Provisioning URL value. * */ - otError SetProvisioningUrl(const char *aProvisioningUrl) { + otError SetProvisioningUrl(const char *aProvisioningUrl) + { otError error = OT_ERROR_NONE; - size_t len = aProvisioningUrl ? strnlen(aProvisioningUrl, kMaxLength + 1) : 0; + size_t len = aProvisioningUrl ? strnlen(aProvisioningUrl, kMaxLength + 1) : 0; VerifyOrExit(len <= kMaxLength, error = OT_ERROR_INVALID_ARGS); SetLength(static_cast(len)); - if (len > 0) { + if (len > 0) + { memcpy(mProvisioningUrl, aProvisioningUrl, len); } -exit: + exit: return error; } @@ -1559,14 +1672,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class VendorNameTlv: public Tlv +class VendorNameTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kVendorName); SetLength(0); } + void Init(void) + { + SetType(kVendorName); + SetLength(0); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1591,18 +1708,20 @@ public: * @param[in] aVendorName A pointer to the Vendor Name value. * */ - otError SetVendorName(const char *aVendorName) { + otError SetVendorName(const char *aVendorName) + { otError error = OT_ERROR_NONE; - size_t len = (aVendorName == NULL) ? 0 : strnlen(aVendorName, sizeof(mVendorName) + 1); + size_t len = (aVendorName == NULL) ? 0 : strnlen(aVendorName, sizeof(mVendorName) + 1); VerifyOrExit(len <= sizeof(mVendorName), error = OT_ERROR_INVALID_ARGS); SetLength(static_cast(len)); - if (len > 0) { + if (len > 0) + { memcpy(mVendorName, aVendorName, len); } -exit: + exit: return error; } @@ -1620,14 +1739,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class VendorModelTlv: public Tlv +class VendorModelTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kVendorModel); SetLength(0); } + void Init(void) + { + SetType(kVendorModel); + SetLength(0); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1652,18 +1775,20 @@ public: * @param[in] aVendorModel A pointer to the Vendor Model value. * */ - otError SetVendorModel(const char *aVendorModel) { + otError SetVendorModel(const char *aVendorModel) + { otError error = OT_ERROR_NONE; - size_t len = (aVendorModel == NULL) ? 0 : strnlen(aVendorModel, sizeof(mVendorModel) + 1); + size_t len = (aVendorModel == NULL) ? 0 : strnlen(aVendorModel, sizeof(mVendorModel) + 1); VerifyOrExit(len <= sizeof(mVendorModel), error = OT_ERROR_INVALID_ARGS); SetLength(static_cast(len)); - if (len > 0) { + if (len > 0) + { memcpy(mVendorModel, aVendorModel, len); } -exit: + exit: return error; } @@ -1681,14 +1806,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class VendorSwVersionTlv: public Tlv +class VendorSwVersionTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kVendorSwVersion); SetLength(0); } + void Init(void) + { + SetType(kVendorSwVersion); + SetLength(0); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1713,18 +1842,20 @@ public: * @param[in] aVendorSwVersion A pointer to the Vendor SW Version value. * */ - otError SetVendorSwVersion(const char *aVendorSwVersion) { + otError SetVendorSwVersion(const char *aVendorSwVersion) + { otError error = OT_ERROR_NONE; - size_t len = (aVendorSwVersion == NULL) ? 0 : strnlen(aVendorSwVersion, sizeof(mVendorSwVersion) + 1); + size_t len = (aVendorSwVersion == NULL) ? 0 : strnlen(aVendorSwVersion, sizeof(mVendorSwVersion) + 1); VerifyOrExit(len <= sizeof(mVendorSwVersion), error = OT_ERROR_INVALID_ARGS); SetLength(static_cast(len)); - if (len > 0) { + if (len > 0) + { memcpy(mVendorSwVersion, aVendorSwVersion, len); } -exit: + exit: return error; } @@ -1742,14 +1873,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class VendorDataTlv: public Tlv +class VendorDataTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kVendorData); SetLength(0); } + void Init(void) + { + SetType(kVendorData); + SetLength(0); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1774,18 +1909,20 @@ public: * @param[in] aVendorData A pointer to the Vendor Data value. * */ - otError SetVendorData(const char *aVendorData) { + otError SetVendorData(const char *aVendorData) + { otError error = OT_ERROR_NONE; - size_t len = (aVendorData == NULL) ? 0 : strnlen(aVendorData, sizeof(mVendorData) + 1); + size_t len = (aVendorData == NULL) ? 0 : strnlen(aVendorData, sizeof(mVendorData) + 1); VerifyOrExit(len <= sizeof(mVendorData), error = OT_ERROR_INVALID_ARGS); SetLength(static_cast(len)); - if (len > 0) { + if (len > 0) + { memcpy(mVendorData, aVendorData, len); } -exit: + exit: return error; } @@ -1803,22 +1940,28 @@ private: * */ OT_TOOL_PACKED_BEGIN -class VendorStackVersionTlv: public Tlv +class VendorStackVersionTlv : public Tlv { public: /** * Default constructor. * */ - VendorStackVersionTlv(void) : - mBuildRevision(0), - mMinorMajor(0) {} + VendorStackVersionTlv(void) + : mBuildRevision(0) + , mMinorMajor(0) + { + } /** * This method initializes the TLV. * */ - void Init(void) { SetType(kVendorStackVersion); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kVendorStackVersion); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1835,8 +1978,10 @@ public: * @returns The Vendor Stack Vendor OUI value. * */ - uint32_t GetOui(void) const { - return (static_cast(mOui[0]) << 16) | (static_cast(mOui[1]) << 8) | static_cast(mOui[2]); + uint32_t GetOui(void) const + { + return (static_cast(mOui[0]) << 16) | (static_cast(mOui[1]) << 8) | + static_cast(mOui[2]); } /** @@ -1845,7 +1990,8 @@ public: * @param[in] aOui The Vendor Stack Vendor OUI value. * */ - void SetOui(uint32_t aOui) { + void SetOui(uint32_t aOui) + { mOui[0] = (aOui >> 16) & 0xff; mOui[1] = (aOui >> 8) & 0xff; mOui[2] = aOui & 0xff; @@ -1865,9 +2011,10 @@ public: * @param[in] aBuild The Build value. * */ - void SetBuild(uint16_t aBuild) { - mBuildRevision = HostSwap16((HostSwap16(mBuildRevision) & ~kBuildMask) | - ((aBuild << kBuildOffset) & kBuildMask)); + void SetBuild(uint16_t aBuild) + { + mBuildRevision = + HostSwap16((HostSwap16(mBuildRevision) & ~kBuildMask) | ((aBuild << kBuildOffset) & kBuildMask)); } /** @@ -1884,7 +2031,8 @@ public: * @param[in] aRevision The Revision value. * */ - void SetRevision(uint8_t aRevision) { + void SetRevision(uint8_t aRevision) + { mBuildRevision = HostSwap16((HostSwap16(mBuildRevision) & ~kRevMask) | ((aRevision << kRevOffset) & kRevMask)); } @@ -1902,7 +2050,8 @@ public: * @param[in] aMinor The Minor value. * */ - void SetMinor(uint8_t aMinor) { + void SetMinor(uint8_t aMinor) + { mMinorMajor = (mMinorMajor & ~kMinorMask) | ((aMinor << kMinorOffset) & kMinorMask); } @@ -1920,7 +2069,8 @@ public: * @param[in] aMajor The Major value. * */ - void SetMajor(uint8_t aMajor) { + void SetMajor(uint8_t aMajor) + { mMinorMajor = (mMinorMajor & ~kMajorMask) | ((aMajor << kMajorOffset) & kMajorMask); } @@ -1930,18 +2080,18 @@ private: enum { kBuildOffset = 4, - kBuildMask = 0xfff << kBuildOffset, - kRevOffset = 0, - kRevMask = 0xf << kBuildOffset, + kBuildMask = 0xfff << kBuildOffset, + kRevOffset = 0, + kRevMask = 0xf << kBuildOffset, }; uint16_t mBuildRevision; enum { kMinorOffset = 4, - kMinorMask = 0xf << kMinorOffset, + kMinorMask = 0xf << kMinorOffset, kMajorOffset = 0, - kMajorMask = 0xf << kMajorOffset, + kMajorMask = 0xf << kMajorOffset, }; uint8_t mMinorMajor; } OT_TOOL_PACKED_END; @@ -1951,14 +2101,20 @@ private: * */ OT_TOOL_PACKED_BEGIN -class DiscoveryRequestTlv: public Tlv +class DiscoveryRequestTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kDiscoveryRequest); SetLength(sizeof(*this) - sizeof(Tlv)); mFlags = 0; mReserved = 0; } + void Init(void) + { + SetType(kDiscoveryRequest); + SetLength(sizeof(*this) - sizeof(Tlv)); + mFlags = 0; + mReserved = 0; + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1983,7 +2139,8 @@ public: * @param[in] aVersion The Version value. * */ - void SetVersion(uint8_t aVersion) { + void SetVersion(uint8_t aVersion) + { mFlags = (mFlags & ~kVersionMask) | ((aVersion << kVersionOffset) & kVersionMask); } @@ -2002,11 +2159,14 @@ public: * @param[in] aJoiner TRUE if set, FALSE otherwise. * */ - void SetJoiner(bool aJoiner) { - if (aJoiner) { + void SetJoiner(bool aJoiner) + { + if (aJoiner) + { mFlags |= kJoinerMask; } - else { + else + { mFlags &= ~kJoinerMask; } } @@ -2015,9 +2175,9 @@ private: enum { kVersionOffset = 4, - kVersionMask = 0xf << kVersionOffset, - kJoinerOffset = 3, - kJoinerMask = 1 << kJoinerOffset, + kVersionMask = 0xf << kVersionOffset, + kJoinerOffset = 3, + kJoinerMask = 1 << kJoinerOffset, }; uint8_t mFlags; uint8_t mReserved; @@ -2028,14 +2188,20 @@ private: * */ OT_TOOL_PACKED_BEGIN -class DiscoveryResponseTlv: public Tlv +class DiscoveryResponseTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kDiscoveryResponse); SetLength(sizeof(*this) - sizeof(Tlv)); mFlags = 0; mReserved = 0; } + void Init(void) + { + SetType(kDiscoveryResponse); + SetLength(sizeof(*this) - sizeof(Tlv)); + mFlags = 0; + mReserved = 0; + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -2060,7 +2226,8 @@ public: * @param[in] aVersion The Version value. * */ - void SetVersion(uint8_t aVersion) { + void SetVersion(uint8_t aVersion) + { mFlags = (mFlags & ~kVersionMask) | ((aVersion << kVersionOffset) & kVersionMask); } @@ -2079,11 +2246,14 @@ public: * @param[in] aNativeCommissioner TRUE if set, FALSE otherwise. * */ - void SetNativeCommissioner(bool aNativeCommissioner) { - if (aNativeCommissioner) { + void SetNativeCommissioner(bool aNativeCommissioner) + { + if (aNativeCommissioner) + { mFlags |= kNativeMask; } - else { + else + { mFlags &= ~kNativeMask; } } @@ -2092,16 +2262,16 @@ private: enum { kVersionOffset = 4, - kVersionMask = 0xf << kVersionOffset, - kNativeOffset = 3, - kNativeMask = 1 << kNativeOffset, + kVersionMask = 0xf << kVersionOffset, + kNativeOffset = 3, + kNativeMask = 1 << kNativeOffset, }; uint8_t mFlags; uint8_t mReserved; } OT_TOOL_PACKED_END; -} // namespace MeshCoP +} // namespace MeshCoP -} // namespace ot +} // namespace ot -#endif // MESHCOP_TLVS_HPP_ +#endif // MESHCOP_TLVS_HPP_ diff --git a/src/core/meshcop/panid_query_client.cpp b/src/core/meshcop/panid_query_client.cpp index 7e6678a14..2ae4867dc 100644 --- a/src/core/meshcop/panid_query_client.cpp +++ b/src/core/meshcop/panid_query_client.cpp @@ -51,37 +51,38 @@ namespace ot { -PanIdQueryClient::PanIdQueryClient(Instance &aInstance) : - InstanceLocator(aInstance), - mCallback(NULL), - mContext(NULL), - mPanIdQuery(OT_URI_PATH_PANID_CONFLICT, &PanIdQueryClient::HandleConflict, this) +PanIdQueryClient::PanIdQueryClient(Instance &aInstance) + : InstanceLocator(aInstance) + , mCallback(NULL) + , mContext(NULL) + , mPanIdQuery(OT_URI_PATH_PANID_CONFLICT, &PanIdQueryClient::HandleConflict, this) { GetNetif().GetCoap().AddResource(mPanIdQuery); } -otError PanIdQueryClient::SendQuery(uint16_t aPanId, uint32_t aChannelMask, const Ip6::Address &aAddress, - otCommissionerPanIdConflictCallback aCallback, void *aContext) +otError PanIdQueryClient::SendQuery(uint16_t aPanId, + uint32_t aChannelMask, + const Ip6::Address & aAddress, + otCommissionerPanIdConflictCallback aCallback, + void * aContext) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Coap::Header header; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Coap::Header header; MeshCoP::CommissionerSessionIdTlv sessionId; - MeshCoP::ChannelMask0Tlv channelMask; - MeshCoP::PanIdTlv panId; - Ip6::MessageInfo messageInfo; - Message *message = NULL; + MeshCoP::ChannelMask0Tlv channelMask; + MeshCoP::PanIdTlv panId; + Ip6::MessageInfo messageInfo; + Message * message = NULL; VerifyOrExit(netif.GetCommissioner().IsActive(), error = OT_ERROR_INVALID_STATE); - header.Init(aAddress.IsMulticast() ? OT_COAP_TYPE_NON_CONFIRMABLE : OT_COAP_TYPE_CONFIRMABLE, - OT_COAP_CODE_POST); + header.Init(aAddress.IsMulticast() ? OT_COAP_TYPE_NON_CONFIRMABLE : OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); header.SetToken(Coap::Header::kDefaultTokenLength); header.AppendUriPathOptions(OT_URI_PATH_PANID_QUERY); header.SetPayloadMarker(); - VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(netif.GetCoap(), header)) != NULL, - error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(netif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); sessionId.Init(); sessionId.SetCommissionerSessionId(netif.GetCommissioner().GetSessionId()); @@ -104,7 +105,7 @@ otError PanIdQueryClient::SendQuery(uint16_t aPanId, uint32_t aChannelMask, cons otLogInfoMeshCoP(GetInstance(), "sent panid query"); mCallback = aCallback; - mContext = aContext; + mContext = aContext; exit: @@ -116,23 +117,24 @@ exit: return error; } -void PanIdQueryClient::HandleConflict(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void PanIdQueryClient::HandleConflict(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleConflict( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleConflict(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void PanIdQueryClient::HandleConflict(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - MeshCoP::PanIdTlv panId; + ThreadNetif & netif = GetNetif(); + MeshCoP::PanIdTlv panId; MeshCoP::ChannelMask0Tlv channelMask; - Ip6::MessageInfo responseInfo(aMessageInfo); + Ip6::MessageInfo responseInfo(aMessageInfo); - VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && - aHeader.GetCode() == OT_COAP_CODE_POST); + VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && aHeader.GetCode() == OT_COAP_CODE_POST); otLogInfoMeshCoP(GetInstance(), "received panid conflict"); @@ -155,7 +157,6 @@ exit: return; } -} // namespace ot +} // namespace ot #endif // OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD - diff --git a/src/core/meshcop/panid_query_client.hpp b/src/core/meshcop/panid_query_client.hpp index bd0de7bb7..7151a515f 100644 --- a/src/core/meshcop/panid_query_client.hpp +++ b/src/core/meshcop/panid_query_client.hpp @@ -51,7 +51,7 @@ class ThreadNetif; * This class implements handling PANID Query Requests. * */ -class PanIdQueryClient: public InstanceLocator +class PanIdQueryClient : public InstanceLocator { public: /** @@ -73,16 +73,21 @@ public: * @retval OT_ERROR_NO_BUFS Insufficient buffers to generate a PAN ID Query message. * */ - otError SendQuery(uint16_t aPanId, uint32_t aChannelMask, const Ip6::Address &aAddress, - otCommissionerPanIdConflictCallback aCallback, void *aContext); + otError SendQuery(uint16_t aPanId, + uint32_t aChannelMask, + const Ip6::Address & aAddress, + otCommissionerPanIdConflictCallback aCallback, + void * aContext); private: - static void HandleConflict(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleConflict(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleConflict(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleConflict(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); otCommissionerPanIdConflictCallback mCallback; - void *mContext; + void * mContext; Coap::Resource mPanIdQuery; }; @@ -91,6 +96,6 @@ private: * @} */ -} // namespace ot +} // namespace ot -#endif // PANID_QUERY_CLIENT_HPP_ +#endif // PANID_QUERY_CLIENT_HPP_ diff --git a/src/core/meshcop/timestamp.cpp b/src/core/meshcop/timestamp.cpp index 65de2d59c..7a0aed501 100644 --- a/src/core/meshcop/timestamp.cpp +++ b/src/core/meshcop/timestamp.cpp @@ -42,11 +42,11 @@ namespace MeshCoP { int Timestamp::Compare(const Timestamp &aCompare) const { - uint64_t thisSeconds = GetSeconds(); + uint64_t thisSeconds = GetSeconds(); uint64_t compareSeconds = aCompare.GetSeconds(); - uint16_t thisTicks = GetTicks(); - uint16_t compareTicks = aCompare.GetTicks(); - int rval; + uint16_t thisTicks = GetTicks(); + uint16_t compareTicks = aCompare.GetTicks(); + int rval; if (compareSeconds > thisSeconds) { @@ -72,5 +72,5 @@ int Timestamp::Compare(const Timestamp &aCompare) const return rval; } -} // namespace MeshCoP -} // namespace ot +} // namespace MeshCoP +} // namespace ot diff --git a/src/core/meshcop/timestamp.hpp b/src/core/meshcop/timestamp.hpp index a76c2ea1e..4e9258f5b 100644 --- a/src/core/meshcop/timestamp.hpp +++ b/src/core/meshcop/timestamp.hpp @@ -60,7 +60,11 @@ public: * This method initializes the Timestamp * */ - void Init(void) { memset(mSeconds, 0, sizeof(mSeconds)); mTicks = 0; } + void Init(void) + { + memset(mSeconds, 0, sizeof(mSeconds)); + mTicks = 0; + } /** * This method compares this timestamp to another. @@ -80,10 +84,12 @@ public: * @returns The Seconds value. * */ - uint64_t GetSeconds(void) const { + uint64_t GetSeconds(void) const + { uint64_t seconds = 0; - for (size_t i = 0; i < sizeof(mSeconds); i++) { + for (size_t i = 0; i < sizeof(mSeconds); i++) + { seconds = (seconds << 8) | mSeconds[i]; } @@ -96,8 +102,10 @@ public: * @param[in] aSeconds The Seconds value. * */ - void SetSeconds(uint64_t aSeconds) { - for (size_t i = 0; i < sizeof(mSeconds); i++, aSeconds >>= 8) { + void SetSeconds(uint64_t aSeconds) + { + for (size_t i = 0; i < sizeof(mSeconds); i++, aSeconds >>= 8) + { mSeconds[sizeof(mSeconds) - 1 - i] = aSeconds & 0xff; } } @@ -116,7 +124,8 @@ public: * @param[in] aTicks The Ticks value. * */ - void SetTicks(uint16_t aTicks) { + void SetTicks(uint16_t aTicks) + { mTicks = HostSwap16((HostSwap16(mTicks) & ~kTicksMask) | ((aTicks << kTicksOffset) & kTicksMask)); } @@ -134,9 +143,10 @@ public: * @param[in] aAuthoritative The Authoritative value. * */ - void SetAuthoritative(bool aAuthoritative) { - mTicks = HostSwap16((HostSwap16(mTicks) & kTicksMask) | ((aAuthoritative << kAuthoritativeOffset) & - kAuthoritativeMask)); + void SetAuthoritative(bool aAuthoritative) + { + mTicks = HostSwap16((HostSwap16(mTicks) & kTicksMask) | + ((aAuthoritative << kAuthoritativeOffset) & kAuthoritativeMask)); } private: @@ -152,7 +162,7 @@ private: uint16_t mTicks; } OT_TOOL_PACKED_END; -} // namespace MeshCoP -} // namespace ot +} // namespace MeshCoP +} // namespace ot -#endif // MESHCOP_TIMESTAMP_HPP_ +#endif // MESHCOP_TIMESTAMP_HPP_ diff --git a/src/core/net/dhcp6.hpp b/src/core/net/dhcp6.hpp index 243e78360..998f1ebc4 100644 --- a/src/core/net/dhcp6.hpp +++ b/src/core/net/dhcp6.hpp @@ -55,44 +55,41 @@ namespace Dhcp6 { * */ - /** * DHCPv6 constant * */ enum { - kDhcpClientPort = 546, - kDhcpServerPort = 547, - kTransactionIdSize = 3, + kDhcpClientPort = 546, + kDhcpServerPort = 547, + kTransactionIdSize = 3, kLinkLayerAddressLen = 8, - kHardwareTypeEui64 = 27, + kHardwareTypeEui64 = 27, }; /** * DHCPv6 Message Types * */ -typedef enum Type -{ - kTypeSolicit = 1, - kTypeAdvertise = 2, - kTypeRequest = 3, - kTypeConfirm = 4, - kTypeRenew = 5, - kTypeRebind = 6, - kTypeReply = 7, - kTypeRelease = 8, - kTypeDecline = 9, - kTypeReconfigure = 10, +typedef enum Type { + kTypeSolicit = 1, + kTypeAdvertise = 2, + kTypeRequest = 3, + kTypeConfirm = 4, + kTypeRenew = 5, + kTypeRebind = 6, + kTypeReply = 7, + kTypeRelease = 8, + kTypeDecline = 9, + kTypeReconfigure = 10, kTypeInformationRequest = 11, - kTypeRelayForward = 12, - kTypeRelayReply = 13, - kTypeLeaseQuery = 14, - kTypeLeaseQueryReply = 15, + kTypeRelayForward = 12, + kTypeRelayReply = 13, + kTypeLeaseQuery = 14, + kTypeLeaseQueryReply = 15, } Type; - /** * This class implements DHCPv6 header. * @@ -105,7 +102,11 @@ public: * This method initializes the DHCPv6 header to all zeros. * */ - void Init(void) { mType = 0; mTransactionId[0] = 0; } + void Init(void) + { + mType = 0; + mTransactionId[0] = 0; + } /** * This method returns the DHCPv6 message type. @@ -140,37 +141,36 @@ public: void SetTransactionId(uint8_t *aBuf) { memcpy(mTransactionId, aBuf, kTransactionIdSize); } private: - uint8_t mType; ///< Type - uint8_t mTransactionId[kTransactionIdSize]; ///< Transaction Id + uint8_t mType; ///< Type + uint8_t mTransactionId[kTransactionIdSize]; ///< Transaction Id } OT_TOOL_PACKED_END; /** * DHCPv6 Option Codes * */ -typedef enum Code -{ - kOptionClientIdentifier = 1, - kOptionServerIdentifier = 2, - kOptionIaNa = 3, - kOptionIaTa = 4, - kOptionIaAddress = 5, - kOptionRequestOption = 6, - kOptionPreference = 7, - kOptionElapsedTime = 8, - kOptionRelayMessage = 9, - kOptionAuthentication = 11, - kOptionServerUnicast = 12, - kOptionStatusCode = 13, - kOptionRapidCommit = 14, - kOptionUserClass = 15, - kOptionVendorClass = 16, +typedef enum Code { + kOptionClientIdentifier = 1, + kOptionServerIdentifier = 2, + kOptionIaNa = 3, + kOptionIaTa = 4, + kOptionIaAddress = 5, + kOptionRequestOption = 6, + kOptionPreference = 7, + kOptionElapsedTime = 8, + kOptionRelayMessage = 9, + kOptionAuthentication = 11, + kOptionServerUnicast = 12, + kOptionStatusCode = 13, + kOptionRapidCommit = 14, + kOptionUserClass = 15, + kOptionVendorClass = 16, kOptionVendorSpecificInformation = 17, - kOptionInterfaceId = 18, - kOptionReconfigureMessage = 19, - kOptionReconfigureAccept = 20, - kOptionLeaseQuery = 44, - kOptionClientData = 45, + kOptionInterfaceId = 18, + kOptionReconfigureMessage = 19, + kOptionReconfigureAccept = 20, + kOptionLeaseQuery = 44, + kOptionClientData = 45, kOptionClientLastTransactionTime = 46, } Code; @@ -186,7 +186,11 @@ public: * This method initializes the DHCPv6 option to all zeros. * */ - void Init(void) { mCode = 0; mLength = 0; } + void Init(void) + { + mCode = 0; + mLength = 0; + } /** * This method returns the DHCPv6 option code. @@ -221,30 +225,33 @@ public: void SetLength(uint16_t aLength) { mLength = HostSwap16(aLength); } private: - uint16_t mCode; ///< Code - uint16_t mLength; ///< Length + uint16_t mCode; ///< Code + uint16_t mLength; ///< Length } OT_TOOL_PACKED_END; /** * Duid Type * */ -typedef enum DuidType -{ +typedef enum DuidType { kDuidLLT = 1, - kDuidEN = 2, - kDuidLL = 3, + kDuidEN = 2, + kDuidLL = 3, } DuidType; OT_TOOL_PACKED_BEGIN -class ClientIdentifier: public Dhcp6Option +class ClientIdentifier : public Dhcp6Option { public: /** * This method initializes the DHCPv6 Option. * */ - void Init(void) { SetCode(kOptionClientIdentifier); SetLength(sizeof(*this) - sizeof(Dhcp6Option)); } + void Init(void) + { + SetCode(kOptionClientIdentifier); + SetLength(sizeof(*this) - sizeof(Dhcp6Option)); + } /** * This method returns the client Duid Type. @@ -292,23 +299,30 @@ public: * @param[in] aLinkLayerAddress The client LinkLayerAddress. * */ - void SetDuidLinkLayerAddress(const Mac::ExtAddress &aDuidLinkLayerAddress) { memcpy(mDuidLinkLayerAddress, &aDuidLinkLayerAddress, sizeof(Mac::ExtAddress)); } + void SetDuidLinkLayerAddress(const Mac::ExtAddress &aDuidLinkLayerAddress) + { + memcpy(mDuidLinkLayerAddress, &aDuidLinkLayerAddress, sizeof(Mac::ExtAddress)); + } private: - uint16_t mDuidType; ///< Duid Type - uint16_t mDuidHardwareType; ///< Duid HardwareType - uint8_t mDuidLinkLayerAddress[kLinkLayerAddressLen]; ///< Duid LinkLayerAddress + uint16_t mDuidType; ///< Duid Type + uint16_t mDuidHardwareType; ///< Duid HardwareType + uint8_t mDuidLinkLayerAddress[kLinkLayerAddressLen]; ///< Duid LinkLayerAddress } OT_TOOL_PACKED_END; OT_TOOL_PACKED_BEGIN -class ServerIdentifier: public Dhcp6Option +class ServerIdentifier : public Dhcp6Option { public: /** * This method initializes the DHCPv6 Option. * */ - void Init(void) { SetCode(kOptionServerIdentifier); SetLength(sizeof(*this) - sizeof(Dhcp6Option)); } + void Init(void) + { + SetCode(kOptionServerIdentifier); + SetLength(sizeof(*this) - sizeof(Dhcp6Option)); + } /** * This method returns the server Duid Type. @@ -356,23 +370,30 @@ public: * @param[in] aLinkLayerAddress The server LinkLayerAddress. * */ - void SetDuidLinkLayerAddress(const Mac::ExtAddress &aDuidLinkLayerAddress) { memcpy(mDuidLinkLayerAddress, &aDuidLinkLayerAddress, sizeof(Mac::ExtAddress)); } + void SetDuidLinkLayerAddress(const Mac::ExtAddress &aDuidLinkLayerAddress) + { + memcpy(mDuidLinkLayerAddress, &aDuidLinkLayerAddress, sizeof(Mac::ExtAddress)); + } private: - uint16_t mDuidType; ///< Duid Type - uint16_t mDuidHardwareType; ///< Duid HardwareType - uint8_t mDuidLinkLayerAddress[kLinkLayerAddressLen]; ///< Duid LinkLayerAddress + uint16_t mDuidType; ///< Duid Type + uint16_t mDuidHardwareType; ///< Duid HardwareType + uint8_t mDuidLinkLayerAddress[kLinkLayerAddressLen]; ///< Duid LinkLayerAddress } OT_TOOL_PACKED_END; OT_TOOL_PACKED_BEGIN -class IaNa: public Dhcp6Option +class IaNa : public Dhcp6Option { public: /** * This method initializes the DHCPv6 Option. * */ - void Init(void) { SetCode(kOptionIaNa); SetLength(sizeof(*this) - sizeof(Dhcp6Option)); } + void Init(void) + { + SetCode(kOptionIaNa); + SetLength(sizeof(*this) - sizeof(Dhcp6Option)); + } /** * This method returns client IAID. @@ -423,20 +444,24 @@ public: void SetT2(uint32_t aT2) { mT2 = HostSwap32(aT2); } private: - uint32_t mIaid; ///< IAID - uint32_t mT1; ///< T1 - uint32_t mT2; ///< T2 + uint32_t mIaid; ///< IAID + uint32_t mT1; ///< T1 + uint32_t mT2; ///< T2 } OT_TOOL_PACKED_END; OT_TOOL_PACKED_BEGIN -class IaAddress: public Dhcp6Option +class IaAddress : public Dhcp6Option { public: /** * This method initializes the DHCPv6 Option. * */ - void Init(void) { SetCode(kOptionIaAddress); SetLength(sizeof(*this) - sizeof(Dhcp6Option)); } + void Init(void) + { + SetCode(kOptionIaAddress); + SetLength(sizeof(*this) - sizeof(Dhcp6Option)); + } /** * This method returns the pointer to the IPv6 address. @@ -487,20 +512,24 @@ public: void SetValidLifetime(uint32_t aValidLifetime) { mValidLifetime = HostSwap32(aValidLifetime); } private: - otIp6Address mAddress; ///< IPv6 address - uint32_t mPreferredLifetime; ///< Preferred Lifetime - uint32_t mValidLifetime; ///< Valid Lifetime + otIp6Address mAddress; ///< IPv6 address + uint32_t mPreferredLifetime; ///< Preferred Lifetime + uint32_t mValidLifetime; ///< Valid Lifetime } OT_TOOL_PACKED_END; OT_TOOL_PACKED_BEGIN -class ElapsedTime: public Dhcp6Option +class ElapsedTime : public Dhcp6Option { public: /** * This method initializes the DHCPv6 Option. * */ - void Init(void) { SetCode(kOptionElapsedTime); SetLength(sizeof(*this) - sizeof(Dhcp6Option)); } + void Init(void) + { + SetCode(kOptionElapsedTime); + SetLength(sizeof(*this) - sizeof(Dhcp6Option)); + } /** * This method returns the elapsed time since solicit starts. @@ -519,36 +548,39 @@ public: void SetElapsedTime(uint16_t aElapsedTime) { mElapsedTime = HostSwap16(aElapsedTime); } private: - uint16_t mElapsedTime; ///< Elapsed time + uint16_t mElapsedTime; ///< Elapsed time } OT_TOOL_PACKED_END; /** * Status Code * */ -typedef enum Status -{ - kStatusSuccess = 0, - kStatusUnspecFail = 1, +typedef enum Status { + kStatusSuccess = 0, + kStatusUnspecFail = 1, kStatusNoAddrsAvail = 2, - kStatusNoBinding = 3, - kStatusNotOnLink = 4, + kStatusNoBinding = 3, + kStatusNotOnLink = 4, kStatusUseMulticast = 5, - kUnknownQueryType = 7, - kMalformedQuery = 8, - kNotConfigured = 9, - kNotAllowed = 10, + kUnknownQueryType = 7, + kMalformedQuery = 8, + kNotConfigured = 9, + kNotAllowed = 10, } Status; OT_TOOL_PACKED_BEGIN -class StatusCode: public Dhcp6Option +class StatusCode : public Dhcp6Option { public: /** * This method initializes the DHCPv6 Option. * */ - void Init(void) { SetCode(kOptionStatusCode); SetLength(sizeof(*this) - sizeof(Dhcp6Option)); } + void Init(void) + { + SetCode(kOptionStatusCode); + SetLength(sizeof(*this) - sizeof(Dhcp6Option)); + } /** * This method returns the status code. @@ -567,21 +599,25 @@ public: void SetStatusCode(Status aStatus) { mStatus = HostSwap16(static_cast(aStatus)); } private: - uint16_t mStatus; ///< Status Code + uint16_t mStatus; ///< Status Code } OT_TOOL_PACKED_END; OT_TOOL_PACKED_BEGIN -class RapidCommit: public Dhcp6Option +class RapidCommit : public Dhcp6Option { public: /** * This method initializes the DHCPv6 Option. * */ - void Init(void) { SetCode(kOptionRapidCommit); SetLength(sizeof(*this) - sizeof(Dhcp6Option)); } + void Init(void) + { + SetCode(kOptionRapidCommit); + SetLength(sizeof(*this) - sizeof(Dhcp6Option)); + } } OT_TOOL_PACKED_END; -} // namespace Dhcp6 -} // namespace ot +} // namespace Dhcp6 +} // namespace ot -#endif // DHCP6_HPP_ +#endif // DHCP6_HPP_ diff --git a/src/core/net/dhcp6_client.cpp b/src/core/net/dhcp6_client.cpp index b85f4d80b..6b9b1ca79 100644 --- a/src/core/net/dhcp6_client.cpp +++ b/src/core/net/dhcp6_client.cpp @@ -47,7 +47,6 @@ #include "net/dhcp6.hpp" #include "thread/thread_netif.hpp" - #if OPENTHREAD_ENABLE_DHCP6_CLIENT using ot::Encoding::BigEndian::HostSwap16; @@ -57,13 +56,13 @@ namespace ot { namespace Dhcp6 { -Dhcp6Client::Dhcp6Client(Instance &aInstance) : - InstanceLocator(aInstance), - mSocket(aInstance.GetThreadNetif().GetIp6().GetUdp()), - mTrickleTimer(aInstance, &Dhcp6Client::HandleTrickleTimer, NULL, this), - mStartTime(0), - mAddresses(NULL), - mNumAddresses(0) +Dhcp6Client::Dhcp6Client(Instance &aInstance) + : InstanceLocator(aInstance) + , mSocket(aInstance.GetThreadNetif().GetIp6().GetUdp()) + , mTrickleTimer(aInstance, &Dhcp6Client::HandleTrickleTimer, NULL, this) + , mStartTime(0) + , mAddresses(NULL) + , mNumAddresses(0) { memset(mIdentityAssociations, 0, sizeof(IdentityAssociation)); @@ -72,21 +71,23 @@ Dhcp6Client::Dhcp6Client(Instance &aInstance) : mIdentityAssociations[i].SetNext(&(mIdentityAssociations[i + 1])); } - mIdentityAssociationHead = NULL; + mIdentityAssociationHead = NULL; mIdentityAssociationAvail = &mIdentityAssociations[0]; } -void Dhcp6Client::UpdateAddresses(otInstance *aInstance, otDhcpAddress *aAddresses, uint32_t aNumAddresses, - void *aContext) +void Dhcp6Client::UpdateAddresses(otInstance * aInstance, + otDhcpAddress *aAddresses, + uint32_t aNumAddresses, + void * aContext) { OT_UNUSED_VARIABLE(aContext); - bool found = false; - bool newAgent = false; - otDhcpAddress *address = NULL; + bool found = false; + bool newAgent = false; + otDhcpAddress * address = NULL; otNetworkDataIterator iterator; - otBorderRouterConfig config; + otBorderRouterConfig config; - mAddresses = aAddresses; + mAddresses = aAddresses; mNumAddresses = aNumAddresses; // remove addresses directly if prefix not valid in network data @@ -99,7 +100,7 @@ void Dhcp6Client::UpdateAddresses(otInstance *aInstance, otDhcpAddress *aAddress continue; } - found = false; + found = false; iterator = OT_NETWORK_DATA_ITERATOR_INIT; while ((otNetDataGetNextOnMeshPrefix(aInstance, &iterator, &config)) == OT_ERROR_NONE) @@ -192,12 +193,12 @@ void Dhcp6Client::UpdateAddresses(otInstance *aInstance, otDhcpAddress *aAddress void Dhcp6Client::AddIdentityAssociation(uint16_t aRloc16, otIp6Prefix &aIp6Prefix) { - IdentityAssociation *identityAssociation = NULL; + IdentityAssociation *identityAssociation = NULL; IdentityAssociation *identityAssociationCursor = NULL; VerifyOrExit(mIdentityAssociationAvail); - identityAssociation = mIdentityAssociationAvail; + identityAssociation = mIdentityAssociationAvail; mIdentityAssociationAvail = mIdentityAssociationAvail->GetNext(); identityAssociation->SetPrefixAgentRloc(aRloc16); @@ -210,7 +211,9 @@ void Dhcp6Client::AddIdentityAssociation(uint16_t aRloc16, otIp6Prefix &aIp6Pref { // append the new identityassociation to the tail of used list for (identityAssociationCursor = mIdentityAssociationHead; identityAssociationCursor->GetNext(); - identityAssociationCursor = identityAssociationCursor->GetNext()) {} + identityAssociationCursor = identityAssociationCursor->GetNext()) + { + } identityAssociationCursor->SetNext(identityAssociation); } @@ -226,11 +229,11 @@ exit: void Dhcp6Client::RemoveIdentityAssociation(uint16_t aRloc16, otIp6Prefix &aIp6Prefix) { IdentityAssociation *prevIdentityAssociation = NULL; - IdentityAssociation *identityAssociation = NULL; + IdentityAssociation *identityAssociation = NULL; VerifyOrExit(mIdentityAssociationHead); - for (identityAssociation = mIdentityAssociationHead; identityAssociation; + for (identityAssociation = mIdentityAssociationHead; identityAssociation; prevIdentityAssociation = identityAssociation, identityAssociation = identityAssociation->GetNext()) { if (identityAssociation->GetPrefixAgentRloc() != aRloc16) @@ -285,9 +288,9 @@ otError Dhcp6Client::Stop(void) bool Dhcp6Client::ProcessNextIdentityAssociation() { - bool rval = false; + bool rval = false; IdentityAssociation *prevIdentityAssociation = NULL; - IdentityAssociation *identityAssociation = NULL; + IdentityAssociation *identityAssociation = NULL; VerifyOrExit(mIdentityAssociationHead); // not interrupt in-progress solicit @@ -295,7 +298,7 @@ bool Dhcp6Client::ProcessNextIdentityAssociation() mTrickleTimer.Stop(); - for (identityAssociation = mIdentityAssociationHead; identityAssociation; + for (identityAssociation = mIdentityAssociationHead; identityAssociation; prevIdentityAssociation = identityAssociation, identityAssociation = identityAssociation->GetNext()) { if (identityAssociation->GetStatus() != IdentityAssociation::kStatusSolicit) @@ -317,10 +320,8 @@ bool Dhcp6Client::ProcessNextIdentityAssociation() mIdentityAssociationHead = identityAssociation; } - mTrickleTimer.Start( - TimerMilli::SecToMsec(kTrickleTimerImin), - TimerMilli::SecToMsec(kTrickleTimerImax), - TrickleTimer::kModeNormal); + mTrickleTimer.Start(TimerMilli::SecToMsec(kTrickleTimerImin), TimerMilli::SecToMsec(kTrickleTimerImax), + TrickleTimer::kModeNormal); mTrickleTimer.IndicateInconsistent(); @@ -348,7 +349,7 @@ bool Dhcp6Client::HandleTrickleTimer(void) mStartTime = TimerMilli::GetNow(); mIdentityAssociationHead->SetStatus(IdentityAssociation::kStatusSoliciting); - // fall through + // fall through case IdentityAssociation::kStatusSoliciting: Solicit(mIdentityAssociationHead->GetPrefixAgentRloc()); @@ -374,9 +375,9 @@ exit: otError Dhcp6Client::Solicit(uint16_t aRloc16) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Message *message; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Message * message; Ip6::MessageInfo messageInfo; VerifyOrExit((message = mSocket.NewMessage(0)) != NULL, error = OT_ERROR_NO_BUFS); @@ -396,7 +397,7 @@ otError Dhcp6Client::Solicit(uint16_t aRloc16) messageInfo.GetPeerAddr().mFields.m16[6] = HostSwap16(0xfe00); messageInfo.GetPeerAddr().mFields.m16[7] = HostSwap16(aRloc16); messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); - messageInfo.mPeerPort = kDhcpServerPort; + messageInfo.mPeerPort = kDhcpServerPort; messageInfo.mInterfaceId = netif.GetInterfaceId(); SuccessOrExit(error = mSocket.SendTo(*message, messageInfo)); @@ -444,11 +445,11 @@ otError Dhcp6Client::AppendClientIdentifier(Message &aMessage) otError Dhcp6Client::AppendIaNa(Message &aMessage, uint16_t aRloc16) { - otError error = OT_ERROR_NONE; - uint8_t count = 0; - uint16_t length = 0; + otError error = OT_ERROR_NONE; + uint8_t count = 0; + uint16_t length = 0; IdentityAssociation *identityAssociation = NULL; - IaNa option; + IaNa option; VerifyOrExit(mIdentityAssociationHead, error = OT_ERROR_DROP); @@ -482,9 +483,9 @@ exit: otError Dhcp6Client::AppendIaAddress(Message &aMessage, uint16_t aRloc16) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; IdentityAssociation *identityAssociation = NULL; - IaAddress option; + IaAddress option; VerifyOrExit(mIdentityAssociationHead, error = OT_ERROR_DROP); @@ -588,12 +589,11 @@ exit: otError Dhcp6Client::ProcessServerIdentifier(Message &aMessage, uint16_t aOffset) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; ServerIdentifier option; VerifyOrExit(((aMessage.Read(aOffset, sizeof(option), &option) == sizeof(option)) && - (option.GetLength() == (sizeof(option) - sizeof(Dhcp6Option))) && - (option.GetDuidType() == kDuidLL) && + (option.GetLength() == (sizeof(option) - sizeof(Dhcp6Option))) && (option.GetDuidType() == kDuidLL) && (option.GetDuidHardwareType() == kHardwareTypeEui64)), error = OT_ERROR_PARSE); exit: @@ -602,24 +602,23 @@ exit: otError Dhcp6Client::ProcessClientIdentifier(Message &aMessage, uint16_t aOffset) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; ClientIdentifier option; - VerifyOrExit((((aMessage.Read(aOffset, sizeof(option), &option) == sizeof(option)) && - (option.GetLength() == (sizeof(option) - sizeof(Dhcp6Option))) && - (option.GetDuidType() == kDuidLL) && - (option.GetDuidHardwareType() == kHardwareTypeEui64)) && - (!memcmp(option.GetDuidLinkLayerAddress(), &GetNetif().GetMac().GetExtAddress(), - sizeof(Mac::ExtAddress)))), - error = OT_ERROR_PARSE); + VerifyOrExit( + (((aMessage.Read(aOffset, sizeof(option), &option) == sizeof(option)) && + (option.GetLength() == (sizeof(option) - sizeof(Dhcp6Option))) && (option.GetDuidType() == kDuidLL) && + (option.GetDuidHardwareType() == kHardwareTypeEui64)) && + (!memcmp(option.GetDuidLinkLayerAddress(), &GetNetif().GetMac().GetExtAddress(), sizeof(Mac::ExtAddress)))), + error = OT_ERROR_PARSE); exit: return error; } otError Dhcp6Client::ProcessIaNa(Message &aMessage, uint16_t aOffset) { - otError error = OT_ERROR_NONE; - IaNa option; + otError error = OT_ERROR_NONE; + IaNa option; uint16_t optionOffset; uint16_t length; @@ -654,7 +653,7 @@ exit: otError Dhcp6Client::ProcessStatusCode(Message &aMessage, uint16_t aOffset) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; StatusCode option; VerifyOrExit(((aMessage.Read(aOffset, sizeof(option), &option) == sizeof(option)) && @@ -668,10 +667,10 @@ exit: otError Dhcp6Client::ProcessIaAddress(Message &aMessage, uint16_t aOffset) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; IdentityAssociation *identityAssociation = NULL; - otDhcpAddress *address = NULL; - otIp6Prefix *prefix = NULL; + otDhcpAddress * address = NULL; + otIp6Prefix * prefix = NULL; IaAddress option; @@ -691,10 +690,10 @@ otError Dhcp6Client::ProcessIaAddress(Message &aMessage, uint16_t aOffset) if (otIp6PrefixMatch(&(address->mAddress.mAddress), option.GetAddress()) >= address->mAddress.mPrefixLength) { memcpy(address->mAddress.mAddress.mFields.m8, option.GetAddress()->mFields.m8, sizeof(otIp6Address)); - address->mPreferredLifetime = option.GetPreferredLifetime(); - address->mValidLifetime = option.GetValidLifetime(); + address->mPreferredLifetime = option.GetPreferredLifetime(); + address->mValidLifetime = option.GetValidLifetime(); address->mAddress.mPreferred = address->mPreferredLifetime != 0; - address->mAddress.mValid = address->mValidLifetime != 0; + address->mAddress.mValid = address->mValidLifetime != 0; otIp6AddUnicastAddress(&GetNetif().GetInstance(), &address->mAddress); break; } @@ -717,8 +716,7 @@ exit: return error; } -} // namespace Dhcp6 -} // namespace ot - -#endif //OPENTHREAD_ENABLE_DHCP6_CLIENT +} // namespace Dhcp6 +} // namespace ot +#endif // OPENTHREAD_ENABLE_DHCP6_CLIENT diff --git a/src/core/net/dhcp6_client.hpp b/src/core/net/dhcp6_client.hpp index ea822d9f6..cabe47a4e 100644 --- a/src/core/net/dhcp6_client.hpp +++ b/src/core/net/dhcp6_client.hpp @@ -50,7 +50,9 @@ namespace ot { class ThreadNetif; -namespace Mle { class MleRouter; } +namespace Mle { +class MleRouter; +} namespace Dhcp6 { @@ -64,7 +66,6 @@ namespace Dhcp6 { * */ - /** * Some constants * @@ -83,13 +84,11 @@ OT_TOOL_PACKED_BEGIN class IdentityAssociation { public: - /** * Status of IdentityAssociation * */ - typedef enum Status - { + typedef enum Status { kStatusInvalid, kStatusSolicit, kStatusSoliciting, @@ -159,18 +158,17 @@ public: void SetNext(IdentityAssociation *aNext) { mNext = aNext; } private: - uint8_t mStatus; ///< Status of IdentityAssocation - uint16_t mPrefixAgentRloc; ///< Rloc of Prefix Agent - otIp6Prefix mIp6Prefix; ///< Prefix - IdentityAssociation *mNext; ///< Pointer to next IdentityAssocation + uint8_t mStatus; ///< Status of IdentityAssocation + uint16_t mPrefixAgentRloc; ///< Rloc of Prefix Agent + otIp6Prefix mIp6Prefix; ///< Prefix + IdentityAssociation *mNext; ///< Pointer to next IdentityAssocation } OT_TOOL_PACKED_END; - /** * This class implements DHCPv6 Client. * */ -class Dhcp6Client: public InstanceLocator +class Dhcp6Client : public InstanceLocator { public: /** @@ -211,34 +209,34 @@ private: otError AppendRapidCommit(Message &aMessage); static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo); - void HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - void ProcessReply(Message &aMessage); + void ProcessReply(Message &aMessage); uint16_t FindOption(Message &aMessage, uint16_t aOffset, uint16_t aLength, Code aCode); - otError ProcessServerIdentifier(Message &aMessage, uint16_t aOffset); - otError ProcessClientIdentifier(Message &aMessage, uint16_t aOffset); - otError ProcessIaNa(Message &aMessage, uint16_t aOffset); - otError ProcessStatusCode(Message &aMessage, uint16_t aOffset); - otError ProcessIaAddress(Message &aMessage, uint16_t aOffset); + otError ProcessServerIdentifier(Message &aMessage, uint16_t aOffset); + otError ProcessClientIdentifier(Message &aMessage, uint16_t aOffset); + otError ProcessIaNa(Message &aMessage, uint16_t aOffset); + otError ProcessStatusCode(Message &aMessage, uint16_t aOffset); + otError ProcessIaAddress(Message &aMessage, uint16_t aOffset); static bool HandleTrickleTimer(TrickleTimer &aTrickleTimer); - bool HandleTrickleTimer(void); + bool HandleTrickleTimer(void); Ip6::UdpSocket mSocket; TrickleTimer mTrickleTimer; - uint8_t mTransactionId[kTransactionIdSize]; - uint32_t mStartTime; + uint8_t mTransactionId[kTransactionIdSize]; + uint32_t mStartTime; otDhcpAddress *mAddresses; - uint32_t mNumAddresses; + uint32_t mNumAddresses; - IdentityAssociation mIdentityAssociations[OPENTHREAD_CONFIG_NUM_DHCP_PREFIXES]; + IdentityAssociation mIdentityAssociations[OPENTHREAD_CONFIG_NUM_DHCP_PREFIXES]; IdentityAssociation *mIdentityAssociationHead; IdentityAssociation *mIdentityAssociationAvail; }; -} // namespace Dhcp6 -} // namespace ot +} // namespace Dhcp6 +} // namespace ot -# endif // DHCP6_CLIENT_HPP_ +#endif // DHCP6_CLIENT_HPP_ diff --git a/src/core/net/dhcp6_server.cpp b/src/core/net/dhcp6_server.cpp index b3c3135a3..e46a58ecc 100644 --- a/src/core/net/dhcp6_server.cpp +++ b/src/core/net/dhcp6_server.cpp @@ -52,9 +52,9 @@ using ot::Encoding::BigEndian::HostSwap32; namespace ot { namespace Dhcp6 { -Dhcp6Server::Dhcp6Server(Instance &aInstance): - InstanceLocator(aInstance), - mSocket(GetNetif().GetIp6().GetUdp()) +Dhcp6Server::Dhcp6Server(Instance &aInstance) + : InstanceLocator(aInstance) + , mSocket(GetNetif().GetIp6().GetUdp()) { for (uint8_t i = 0; i < OPENTHREAD_CONFIG_NUM_DHCP_PREFIXES; i++) { @@ -63,20 +63,20 @@ Dhcp6Server::Dhcp6Server(Instance &aInstance): } mPrefixAgentsCount = 0; - mPrefixAgentsMask = 0; + mPrefixAgentsMask = 0; } otError Dhcp6Server::UpdateService(void) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - bool found; - uint8_t i; - uint16_t rloc16 = netif.GetMle().GetRloc16(); - Ip6::Address *address = NULL; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + bool found; + uint8_t i; + uint16_t rloc16 = netif.GetMle().GetRloc16(); + Ip6::Address * address = NULL; otNetworkDataIterator iterator; - otBorderRouterConfig config; - Lowpan::Context lowpanContext; + otBorderRouterConfig config; + Lowpan::Context lowpanContext; // remove dhcp agent aloc and prefix delegation for (i = 0; i < OPENTHREAD_CONFIG_NUM_DHCP_PREFIXES; i++) @@ -88,7 +88,7 @@ otError Dhcp6Server::UpdateService(void) continue; } - address = &(mAgentsAloc[i].GetAddress()); + address = &(mAgentsAloc[i].GetAddress()); iterator = OT_NETWORK_DATA_ITERATOR_INIT; while (netif.GetNetworkDataLeader().GetNextOnMeshPrefix(&iterator, rloc16, &config) == OT_ERROR_NONE) @@ -156,14 +156,14 @@ otError Dhcp6Server::UpdateService(void) { address = &(mAgentsAloc[i].GetAddress()); memcpy(address, netif.GetMle().GetMeshLocalPrefix(), 8); - address->mFields.m16[4] = HostSwap16(0x0000); - address->mFields.m16[5] = HostSwap16(0x00ff); - address->mFields.m16[6] = HostSwap16(0xfe00); - address->mFields.m8[14] = Ip6::Address::kAloc16Mask; - address->mFields.m8[15] = lowpanContext.mContextId; + address->mFields.m16[4] = HostSwap16(0x0000); + address->mFields.m16[5] = HostSwap16(0x00ff); + address->mFields.m16[6] = HostSwap16(0xfe00); + address->mFields.m8[14] = Ip6::Address::kAloc16Mask; + address->mFields.m8[15] = lowpanContext.mContextId; mAgentsAloc[i].mPrefixLength = 128; - mAgentsAloc[i].mPreferred = true; - mAgentsAloc[i].mValid = true; + mAgentsAloc[i].mPreferred = true; + mAgentsAloc[i].mValid = true; netif.AddUnicastAddress(mAgentsAloc[i]); AddPrefixAgent(config.mPrefix); break; @@ -228,7 +228,7 @@ exit: otError Dhcp6Server::RemovePrefixAgent(const uint8_t *aIp6Address) { - otError error = OT_ERROR_NOT_FOUND; + otError error = OT_ERROR_NOT_FOUND; otIp6Prefix *prefix = NULL; for (uint8_t i = 0; i < OPENTHREAD_CONFIG_NUM_DHCP_PREFIXES; i++) @@ -240,7 +240,8 @@ otError Dhcp6Server::RemovePrefixAgent(const uint8_t *aIp6Address) continue; } - if (otIp6PrefixMatch(&(prefix->mPrefix), reinterpret_cast(aIp6Address)) >= prefix->mLength) + if (otIp6PrefixMatch(&(prefix->mPrefix), reinterpret_cast(aIp6Address)) >= + prefix->mLength) { memset(&(mPrefixAgents[i]), 0, sizeof(PrefixAgent)); mPrefixAgentsCount--; @@ -260,7 +261,7 @@ void Dhcp6Server::HandleUdpReceive(void *aContext, otMessage *aMessage, const ot void Dhcp6Server::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - Dhcp6Header header; + Dhcp6Header header; otIp6Address dst = aMessageInfo.mPeerAddr; VerifyOrExit(aMessage.Read(aMessage.GetOffset(), sizeof(header), &header) == sizeof(header)); @@ -277,11 +278,11 @@ exit: void Dhcp6Server::ProcessSolicit(Message &aMessage, otIp6Address &aDst, uint8_t *aTransactionId) { - IaNa iana; + IaNa iana; ClientIdentifier clientIdentifier; - uint16_t optionOffset; - uint16_t offset = aMessage.GetOffset(); - uint16_t length = aMessage.GetLength() - aMessage.GetOffset(); + uint16_t optionOffset; + uint16_t offset = aMessage.GetOffset(); + uint16_t length = aMessage.GetLength() - aMessage.GetOffset(); // Client Identifier (discard if not present) VerifyOrExit((optionOffset = FindOption(aMessage, offset, length, kOptionClientIdentifier)) > 0); @@ -335,8 +336,7 @@ otError Dhcp6Server::ProcessClientIdentifier(Message &aMessage, uint16_t aOffset VerifyOrExit(((aMessage.Read(aOffset, sizeof(aClient), &aClient) == sizeof(aClient)) && (aClient.GetLength() == (sizeof(aClient) - sizeof(Dhcp6Option))) && - (aClient.GetDuidType() == kDuidLL) && - (aClient.GetDuidHardwareType() == kHardwareTypeEui64)), + (aClient.GetDuidType() == kDuidLL) && (aClient.GetDuidHardwareType() == kHardwareTypeEui64)), error = OT_ERROR_PARSE); exit: return error; @@ -344,7 +344,7 @@ exit: otError Dhcp6Server::ProcessElapsedTime(Message &aMessage, uint16_t aOffset) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; ElapsedTime option; VerifyOrExit(((aMessage.Read(aOffset, sizeof(option), &option) == sizeof(option)) && @@ -356,7 +356,7 @@ exit: otError Dhcp6Server::ProcessIaNa(Message &aMessage, uint16_t aOffset, IaNa &aIaNa) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint16_t optionOffset; uint16_t length; @@ -384,9 +384,9 @@ exit: otError Dhcp6Server::ProcessIaAddress(Message &aMessage, uint16_t aOffset) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; otIp6Prefix *prefix = NULL; - IaAddress option; + IaAddress option; VerifyOrExit(((aMessage.Read(aOffset, sizeof(option), &option) == sizeof(option)) && option.GetLength() == (sizeof(option) - sizeof(Dhcp6Option))), @@ -415,9 +415,9 @@ exit: otError Dhcp6Server::SendReply(otIp6Address &aDst, uint8_t *aTransactionId, ClientIdentifier &aClient, IaNa &aIaNa) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Ip6::MessageInfo messageInfo; - Message *message; + Message * message; VerifyOrExit((message = mSocket.NewMessage(0)) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = AppendHeader(*message, aTransactionId)); @@ -460,7 +460,7 @@ otError Dhcp6Server::AppendClientIdentifier(Message &aMessage, ClientIdentifier otError Dhcp6Server::AppendServerIdentifier(Message &aMessage) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; ServerIdentifier option; option.Init(); @@ -475,7 +475,7 @@ exit: otError Dhcp6Server::AppendIaNa(Message &aMessage, IaNa &aIaNa) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint16_t length = 0; if (mPrefixAgentsMask) @@ -515,7 +515,7 @@ otError Dhcp6Server::AppendStatusCode(Message &aMessage, Status aStatus) otError Dhcp6Server::AppendIaAddress(Message &aMessage, ClientIdentifier &aClient) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; otIp6Prefix *prefix = NULL; // if specified, only apply specified prefixes @@ -530,7 +530,7 @@ otError Dhcp6Server::AppendIaAddress(Message &aMessage, ClientIdentifier &aClien } } } - else // if not specified, apply all configured prefixes + else // if not specified, apply all configured prefixes { for (uint8_t i = 0; i < OPENTHREAD_CONFIG_NUM_DHCP_PREFIXES; i++) { @@ -551,13 +551,13 @@ exit: otError Dhcp6Server::AddIaAddress(Message &aMessage, otIp6Prefix &aIp6Prefix, ClientIdentifier &aClient) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; IaAddress option; option.Init(); memcpy((option.GetAddress()->mFields.m8), &(aIp6Prefix.mPrefix), 8); - static_cast(option.GetAddress())->SetIid( - *reinterpret_cast(aClient.GetDuidLinkLayerAddress())); + static_cast(option.GetAddress()) + ->SetIid(*reinterpret_cast(aClient.GetDuidLinkLayerAddress())); option.SetPreferredLifetime(OT_DHCP6_DEFAULT_PREFERRED_LIFETIME); option.SetValidLifetime(OT_DHCP6_DEFAULT_VALID_LIFETIME); SuccessOrExit(error = aMessage.Append(&option, sizeof(option))); @@ -573,7 +573,7 @@ otError Dhcp6Server::AppendRapidCommit(Message &aMessage) return aMessage.Append(&option, sizeof(option)); } -} // namespace Dhcp6 -} // namespace ot +} // namespace Dhcp6 +} // namespace ot #endif // OPENTHREAD_ENABLE_DHCP6_SERVER diff --git a/src/core/net/dhcp6_server.hpp b/src/core/net/dhcp6_server.hpp index ce8c46ca3..cbd9f4c0f 100644 --- a/src/core/net/dhcp6_server.hpp +++ b/src/core/net/dhcp6_server.hpp @@ -39,8 +39,8 @@ #include #include "common/locator.hpp" -#include "mac/mac_frame.hpp" #include "mac/mac.hpp" +#include "mac/mac_frame.hpp" #include "net/dhcp6.hpp" #include "net/udp6.hpp" #include "thread/network_data_leader.hpp" @@ -48,7 +48,9 @@ namespace ot { class ThreadNetif; -namespace NetworkData { class Leader; } +namespace NetworkData { +class Leader; +} namespace Dhcp6 { @@ -62,15 +64,14 @@ namespace Dhcp6 { * */ - /** * DHCPv6 default constant * */ -#define OT_DHCP6_DEFAULT_IA_NA_T1 0xffffffffU -#define OT_DHCP6_DEFAULT_IA_NA_T2 0xffffffffU -#define OT_DHCP6_DEFAULT_PREFERRED_LIFETIME 0xffffffffU -#define OT_DHCP6_DEFAULT_VALID_LIFETIME 0xffffffffU +#define OT_DHCP6_DEFAULT_IA_NA_T1 0xffffffffU +#define OT_DHCP6_DEFAULT_IA_NA_T2 0xffffffffU +#define OT_DHCP6_DEFAULT_PREFERRED_LIFETIME 0xffffffffU +#define OT_DHCP6_DEFAULT_VALID_LIFETIME 0xffffffffU /** * This class implements prefix agent. @@ -81,7 +82,6 @@ OT_TOOL_PACKED_BEGIN class PrefixAgent { public: - /** * This method returns the reference to the IPv6 prefix. * @@ -99,10 +99,10 @@ public: void SetPrefix(otIp6Prefix &aIp6Prefix) { memcpy(&mIp6Prefix, &aIp6Prefix, sizeof(otIp6Prefix)); } private: - otIp6Prefix mIp6Prefix; ///< prefix + otIp6Prefix mIp6Prefix; ///< prefix } OT_TOOL_PACKED_END; -class Dhcp6Server: public InstanceLocator +class Dhcp6Server : public InstanceLocator { public: /** @@ -138,27 +138,27 @@ private: otError AddIaAddress(Message &aMessage, otIp6Prefix &aIp6Prefix, ClientIdentifier &aClient); static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo); - void HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); void ProcessSolicit(Message &aMessage, otIp6Address &aDst, uint8_t *aTransactionId); uint16_t FindOption(Message &aMessage, uint16_t aOffset, uint16_t aLength, Code aCode); - otError ProcessClientIdentifier(Message &aMessage, uint16_t aOffset, ClientIdentifier &aClient); - otError ProcessIaNa(Message &aMessage, uint16_t aOffset, IaNa &aIaNa); - otError ProcessIaAddress(Message &aMessage, uint16_t aOffset); - otError ProcessElapsedTime(Message &aMessage, uint16_t aOffset); + otError ProcessClientIdentifier(Message &aMessage, uint16_t aOffset, ClientIdentifier &aClient); + otError ProcessIaNa(Message &aMessage, uint16_t aOffset, IaNa &aIaNa); + otError ProcessIaAddress(Message &aMessage, uint16_t aOffset); + otError ProcessElapsedTime(Message &aMessage, uint16_t aOffset); otError SendReply(otIp6Address &aDst, uint8_t *aTransactionId, ClientIdentifier &aClientIdentifier, IaNa &aIaNa); Ip6::UdpSocket mSocket; Ip6::NetifUnicastAddress mAgentsAloc[OPENTHREAD_CONFIG_NUM_DHCP_PREFIXES]; - PrefixAgent mPrefixAgents[OPENTHREAD_CONFIG_NUM_DHCP_PREFIXES]; - uint8_t mPrefixAgentsMask; - uint8_t mPrefixAgentsCount; + PrefixAgent mPrefixAgents[OPENTHREAD_CONFIG_NUM_DHCP_PREFIXES]; + uint8_t mPrefixAgentsMask; + uint8_t mPrefixAgentsCount; }; -} // namespace Dhcp6 -} // namespace ot +} // namespace Dhcp6 +} // namespace ot -#endif // DHCP6_SERVER_HPP_ +#endif // DHCP6_SERVER_HPP_ diff --git a/src/core/net/dns_client.cpp b/src/core/net/dns_client.cpp index 0a1670dc3..051c09199 100644 --- a/src/core/net/dns_client.cpp +++ b/src/core/net/dns_client.cpp @@ -51,7 +51,7 @@ namespace Dns { otError Client::Start(void) { - otError error; + otError error; Ip6::SockAddr addr; SuccessOrExit(error = mSocket.Open(&Client::HandleUdpReceive, this)); @@ -63,15 +63,15 @@ exit: otError Client::Stop(void) { - Message *message = mPendingQueries.GetHead(); - Message *messageToRemove; + Message * message = mPendingQueries.GetHead(); + Message * messageToRemove; QueryMetadata queryMetadata; // Remove all pending queries. while (message != NULL) { messageToRemove = message; - message = message->GetNext(); + message = message->GetNext(); queryMetadata.ReadFrom(*messageToRemove); FinalizeDnsTransaction(*messageToRemove, queryMetadata, NULL, 0, OT_ERROR_ABORT); @@ -82,16 +82,15 @@ otError Client::Stop(void) otError Client::Query(const otDnsQuery *aQuery, otDnsResponseHandler aHandler, void *aContext) { - otError error; - QueryMetadata queryMetadata(aHandler, aContext); - Message *message = NULL; - Message *messageCopy = NULL; - Header header; - QuestionAaaa question; + otError error; + QueryMetadata queryMetadata(aHandler, aContext); + Message * message = NULL; + Message * messageCopy = NULL; + Header header; + QuestionAaaa question; const Ip6::MessageInfo *messageInfo; - VerifyOrExit(aQuery->mHostname != NULL && aQuery->mMessageInfo != NULL, - error = OT_ERROR_INVALID_ARGS); + VerifyOrExit(aQuery->mHostname != NULL && aQuery->mMessageInfo != NULL, error = OT_ERROR_INVALID_ARGS); header.SetMessageId(mMessageId++); header.SetType(Header::kTypeQuery); @@ -118,8 +117,7 @@ otError Client::Query(const otDnsQuery *aQuery, otDnsResponseHandler aHandler, v queryMetadata.mDestinationAddress = messageInfo->GetPeerAddr(); queryMetadata.mRetransmissionCount = 0; - VerifyOrExit((messageCopy = CopyAndEnqueueMessage(*message, queryMetadata)) != NULL, - error = OT_ERROR_NO_BUFS); + VerifyOrExit((messageCopy = CopyAndEnqueueMessage(*message, queryMetadata)) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = SendMessage(*message, *messageInfo)); exit: @@ -154,8 +152,8 @@ exit: Message *Client::CopyAndEnqueueMessage(const Message &aMessage, const QueryMetadata &aQueryMetadata) { - otError error = OT_ERROR_NONE; - uint32_t now = TimerMilli::GetNow(); + otError error = OT_ERROR_NONE; + uint32_t now = TimerMilli::GetNow(); Message *messageCopy = NULL; uint32_t nextTransmissionTime; @@ -214,7 +212,7 @@ otError Client::SendMessage(Message &aMessage, const Ip6::MessageInfo &aMessageI otError Client::SendCopy(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - otError error; + otError error; Message *messageCopy = NULL; // Create a message copy for lower layers. @@ -236,10 +234,10 @@ exit: otError Client::AppendCompressedHostname(Message &aMessage, const char *aHostname) { - otError error = OT_ERROR_NONE; - uint8_t index = 0; + otError error = OT_ERROR_NONE; + uint8_t index = 0; uint8_t labelPosition = 0; - uint8_t labelSize = 0; + uint8_t labelSize = 0; while (true) { @@ -251,7 +249,7 @@ otError Client::AppendCompressedHostname(Message &aMessage, const char *aHostnam SuccessOrExit(error = aMessage.Append(&aHostname[labelPosition], labelSize)); labelPosition += labelSize + 1; - labelSize = 0; + labelSize = 0; if (aHostname[index] == kLabelTerminator) { @@ -276,29 +274,27 @@ exit: otError Client::CompareQuestions(Message &aMessageResponse, Message &aMessageQuery, uint16_t &aOffset) { - otError error = OT_ERROR_NONE; - uint8_t bufQuery[kBufSize]; - uint8_t bufResponse[kBufSize]; + otError error = OT_ERROR_NONE; + uint8_t bufQuery[kBufSize]; + uint8_t bufResponse[kBufSize]; uint16_t read = 0; // Compare question section of the query with the response. - uint16_t length = aMessageQuery.GetLength() - aMessageQuery.GetOffset() - - sizeof(Header) - sizeof(QueryMetadata); + uint16_t length = aMessageQuery.GetLength() - aMessageQuery.GetOffset() - sizeof(Header) - sizeof(QueryMetadata); uint16_t offset = aMessageQuery.GetOffset() + sizeof(Header); while (length > 0) { - VerifyOrExit((read = aMessageQuery.Read(offset, - length < sizeof(bufQuery) ? length : sizeof(bufQuery), - bufQuery)) > 0, error = OT_ERROR_PARSE); - VerifyOrExit(aMessageResponse.Read(aOffset, read, bufResponse) == read, - error = OT_ERROR_PARSE); + VerifyOrExit( + (read = aMessageQuery.Read(offset, length < sizeof(bufQuery) ? length : sizeof(bufQuery), bufQuery)) > 0, + error = OT_ERROR_PARSE); + VerifyOrExit(aMessageResponse.Read(aOffset, read, bufResponse) == read, error = OT_ERROR_PARSE); VerifyOrExit(memcmp(bufResponse, bufQuery, read) == 0, error = OT_ERROR_NOT_FOUND); aOffset += read; - offset += read; - length -= read; + offset += read; + length -= read; } exit: @@ -307,17 +303,16 @@ exit: otError Client::SkipHostname(Message &aMessage, uint16_t &aOffset) { - otError error = OT_ERROR_NONE; - uint8_t buf[kBufSize]; + otError error = OT_ERROR_NONE; + uint8_t buf[kBufSize]; uint16_t index; - uint16_t read = 0; + uint16_t read = 0; uint16_t offset = aOffset; uint16_t length = aMessage.GetLength() - aOffset; while (length > 0) { - VerifyOrExit((read = aMessage.Read(offset, sizeof(buf), buf)) > 0, - error = OT_ERROR_PARSE); + VerifyOrExit((read = aMessage.Read(offset, sizeof(buf), buf)) > 0, error = OT_ERROR_PARSE); index = 0; @@ -370,16 +365,18 @@ exit: return message; } -void Client::FinalizeDnsTransaction(Message &aQuery, const QueryMetadata &aQueryMetadata, - otIp6Address *aAddress, uint32_t aTtl, - otError aResult) +void Client::FinalizeDnsTransaction(Message & aQuery, + const QueryMetadata &aQueryMetadata, + otIp6Address * aAddress, + uint32_t aTtl, + otError aResult) { DequeueMessage(aQuery); if (aQueryMetadata.mResponseHandler != NULL) { - aQueryMetadata.mResponseHandler(aQueryMetadata.mResponseContext, aQueryMetadata.mHostname, - aAddress, aTtl, aResult); + aQueryMetadata.mResponseHandler(aQueryMetadata.mResponseContext, aQueryMetadata.mHostname, aAddress, aTtl, + aResult); } } @@ -390,11 +387,11 @@ void Client::HandleRetransmissionTimer(Timer &aTimer) void Client::HandleRetransmissionTimer(void) { - uint32_t now = TimerMilli::GetNow(); - uint32_t nextDelta = 0xffffffff; - QueryMetadata queryMetadata; - Message *message = mPendingQueries.GetHead(); - Message *nextMessage = NULL; + uint32_t now = TimerMilli::GetNow(); + uint32_t nextDelta = 0xffffffff; + QueryMetadata queryMetadata; + Message * message = mPendingQueries.GetHead(); + Message * nextMessage = NULL; Ip6::MessageInfo messageInfo; while (message != NULL) @@ -453,12 +450,12 @@ void Client::HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessa void Client::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - otError error = OT_ERROR_NONE; - Header responseHeader; - QueryMetadata queryMetadata; + otError error = OT_ERROR_NONE; + Header responseHeader; + QueryMetadata queryMetadata; ResourceRecordAaaa record; - Message *message = NULL; - uint16_t offset; + Message * message = NULL; + uint16_t offset; // RFC1035 7.3. Resolver cannot rely that a response will come from the same address // which it sent the corresponding query to. @@ -466,8 +463,7 @@ void Client::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessag VerifyOrExit(aMessage.Read(aMessage.GetOffset(), sizeof(responseHeader), &responseHeader) == sizeof(responseHeader)); - VerifyOrExit(responseHeader.GetType() == Header::kTypeResponse && - responseHeader.GetQuestionCount() == 1 && + VerifyOrExit(responseHeader.GetType() == Header::kTypeResponse && responseHeader.GetQuestionCount() == 1 && responseHeader.IsTruncationFlagSet() == false); aMessage.MoveOffset(sizeof(responseHeader)); @@ -494,8 +490,7 @@ void Client::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessag } if (aMessage.Read(offset, sizeof(record), &record) != sizeof(record) || - record.GetType() != ResourceRecordAaaa::kType || - record.GetClass() != ResourceRecordAaaa::kClass) + record.GetType() != ResourceRecordAaaa::kType || record.GetClass() != ResourceRecordAaaa::kClass) { offset += sizeof(ResourceRecord) + record.GetLength(); @@ -520,7 +515,7 @@ exit: return; } -} // namespace Coap -} // namespace ot +} // namespace Dns +} // namespace ot #endif // OPENTHREAD_ENABLE_DNS_CLIENT diff --git a/src/core/net/dns_client.hpp b/src/core/net/dns_client.hpp index bb9559805..6313ce44d 100644 --- a/src/core/net/dns_client.hpp +++ b/src/core/net/dns_client.hpp @@ -71,7 +71,8 @@ public: * @param[in] aContext Context for the handler function. * */ - QueryMetadata(otDnsResponseHandler aHandler, void *aContext) { + QueryMetadata(otDnsResponseHandler aHandler, void *aContext) + { memset(this, 0, sizeof(*this)); mResponseHandler = aHandler; mResponseContext = aContext; @@ -86,9 +87,7 @@ public: * @retval OT_ERROR_NO_BUFS Insufficient available buffers to grow the message. * */ - otError AppendTo(Message &aMessage) const { - return aMessage.Append(this, sizeof(*this)); - }; + otError AppendTo(Message &aMessage) const { return aMessage.Append(this, sizeof(*this)); }; /** * This method reads request data from the message. @@ -98,7 +97,8 @@ public: * @returns The number of bytes read. * */ - uint16_t ReadFrom(const Message &aMessage) { + uint16_t ReadFrom(const Message &aMessage) + { return aMessage.Read(aMessage.GetLength() - sizeof(*this), sizeof(*this), this); }; @@ -110,7 +110,8 @@ public: * @returns The number of bytes updated. * */ - int UpdateIn(Message &aMessage) const { + int UpdateIn(Message &aMessage) const + { return aMessage.Write(aMessage.GetLength() - sizeof(*this), sizeof(*this), this); } @@ -135,14 +136,14 @@ public: bool IsLater(uint32_t aTime) const { return (static_cast(aTime - mTransmissionTime) < 0); }; private: - const char *mHostname; ///< A hostname to be find. - otDnsResponseHandler mResponseHandler; ///< A function pointer that is called on response reception. - void *mResponseContext; ///< A pointer to arbitrary context information. - uint32_t mTransmissionTime; ///< Time when the timer should shoot for this message. - Ip6::Address mSourceAddress; ///< IPv6 address of the message source. - Ip6::Address mDestinationAddress; ///< IPv6 address of the message destination. - uint16_t mDestinationPort; ///< UDP port of the message destination. - uint8_t mRetransmissionCount; ///< Number of retransmissions. + const char * mHostname; ///< A hostname to be find. + otDnsResponseHandler mResponseHandler; ///< A function pointer that is called on response reception. + void * mResponseContext; ///< A pointer to arbitrary context information. + uint32_t mTransmissionTime; ///< Time when the timer should shoot for this message. + Ip6::Address mSourceAddress; ///< IPv6 address of the message source. + Ip6::Address mDestinationAddress; ///< IPv6 address of the message destination. + uint16_t mDestinationPort; ///< UDP port of the message destination. + uint8_t mRetransmissionCount; ///< Number of retransmissions. } OT_TOOL_PACKED_END; /** @@ -158,11 +159,10 @@ public: * @param[in] aNetif A reference to the network interface that DNS client should be assigned to. * */ - Client(Ip6::Netif &aNetif): - mSocket(aNetif.GetIp6().GetUdp()), - mMessageId(0), - mRetransmissionTimer(aNetif.GetInstance(), &Client::HandleRetransmissionTimer, this) { - }; + Client(Ip6::Netif &aNetif) + : mSocket(aNetif.GetIp6().GetUdp()) + , mMessageId(0) + , mRetransmissionTimer(aNetif.GetInstance(), &Client::HandleRetransmissionTimer, this){}; /** * This method starts the DNS client. @@ -233,33 +233,35 @@ private: Message *NewMessage(const Header &aHeader); Message *CopyAndEnqueueMessage(const Message &aMessage, const QueryMetadata &aQueryMetadata); - void DequeueMessage(Message &aMessage); - otError SendMessage(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - otError SendCopy(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void DequeueMessage(Message &aMessage); + otError SendMessage(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + otError SendCopy(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); otError AppendCompressedHostname(Message &aMessage, const char *aHostname); otError CompareQuestions(Message &aMessageResponse, Message &aMessageQuery, uint16_t &aOffset); otError SkipHostname(Message &aMessage, uint16_t &aOffset); Message *FindRelatedQuery(const Header &aResponseHeader, QueryMetadata &aQueryMetadata); - void FinalizeDnsTransaction(Message &aQuery, const QueryMetadata &aQueryMetadata, - otIp6Address *aAddress, uint32_t aTtl, - otError aResult); + void FinalizeDnsTransaction(Message & aQuery, + const QueryMetadata &aQueryMetadata, + otIp6Address * aAddress, + uint32_t aTtl, + otError aResult); static void HandleRetransmissionTimer(Timer &aTimer); - void HandleRetransmissionTimer(void); + void HandleRetransmissionTimer(void); static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo); - void HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); Ip6::UdpSocket mSocket; - uint16_t mMessageId; + uint16_t mMessageId; MessageQueue mPendingQueries; - TimerMilli mRetransmissionTimer; + TimerMilli mRetransmissionTimer; }; -} // namespace Dns -} // namespace ot +} // namespace Dns +} // namespace ot -#endif // DNS_CLIENT_HPP_ +#endif // DNS_CLIENT_HPP_ diff --git a/src/core/net/dns_headers.hpp b/src/core/net/dns_headers.hpp index 5937d91a5..1b8a99b1a 100644 --- a/src/core/net/dns_headers.hpp +++ b/src/core/net/dns_headers.hpp @@ -74,7 +74,6 @@ OT_TOOL_PACKED_BEGIN class Header { public: - /** * Default constructor for DNS Header. * @@ -103,7 +102,7 @@ public: */ enum Type { - kTypeQuery = 0, + kTypeQuery = 0, kTypeResponse = 1, }; @@ -120,7 +119,8 @@ public: * @param[in] aType The type of the message. * */ - void SetType(Type aType) { + void SetType(Type aType) + { mFlags[0] &= ~kQrFlagMask; mFlags[0] |= static_cast(aType) << kQrFlagOffset; } @@ -151,7 +151,8 @@ public: * @param[in] aType The type of the query. * */ - void SetQueryType(QueryType aType) { + void SetQueryType(QueryType aType) + { mFlags[0] &= ~kOpCodeMask; mFlags[0] |= static_cast(aType) << kOpCodeOffset; } @@ -266,7 +267,8 @@ public: * @param[in] aResponse The type of the response. * */ - void SetResponseCode(Response aResponse) { + void SetResponseCode(Response aResponse) + { mFlags[1] &= ~kRCodeMask; mFlags[1] |= static_cast(aResponse) << kRCodeOffset; } @@ -342,29 +344,30 @@ private: */ enum { - kQrFlagOffset = 7, ///< QR Flag offset. - kQrFlagMask = 0x01 << kQrFlagOffset, ///< QR Flag mask. - kOpCodeOffset = 3, ///< OpCode field offset. - kOpCodeMask = 0x0f << kOpCodeOffset, ///< OpCode field mask. - kAaFlagOffset = 2, ///< AA Flag offset. - kAaFlagMask = 0x01 << kAaFlagOffset, ///< AA Flag mask. - kTcFlagOffset = 1, ///< TC Flag offset. - kTcFlagMask = 0x01 << kTcFlagOffset, ///< TC Flag mask. - kRdFlagOffset = 0, ///< RD Flag offset. - kRdFlagMask = 0x01 << kRdFlagOffset, ///< RD Flag mask. + kQrFlagOffset = 7, ///< QR Flag offset. + kQrFlagMask = 0x01 << kQrFlagOffset, ///< QR Flag mask. + kOpCodeOffset = 3, ///< OpCode field offset. + kOpCodeMask = 0x0f << kOpCodeOffset, ///< OpCode field mask. + kAaFlagOffset = 2, ///< AA Flag offset. + kAaFlagMask = 0x01 << kAaFlagOffset, ///< AA Flag mask. + kTcFlagOffset = 1, ///< TC Flag offset. + kTcFlagMask = 0x01 << kTcFlagOffset, ///< TC Flag mask. + kRdFlagOffset = 0, ///< RD Flag offset. + kRdFlagMask = 0x01 << kRdFlagOffset, ///< RD Flag mask. - kRaFlagOffset = 7, ///< RA Flag offset. - kRaFlagMask = 0x01 << kRaFlagOffset, ///< RA Flag mask. - kRCodeOffset = 0, ///< RCODE field offset. - kRCodeMask = 0x0f << kRCodeOffset, ///< RCODE field mask. + kRaFlagOffset = 7, ///< RA Flag offset. + kRaFlagMask = 0x01 << kRaFlagOffset, ///< RA Flag mask. + kRCodeOffset = 0, ///< RCODE field offset. + kRCodeMask = 0x0f << kRCodeOffset, ///< RCODE field mask. }; - uint16_t mMessageId; ///< A message identifier that is used by the requester to match up replies to outstanding queries. - uint8_t mFlags[2]; ///< DNS header flags. - uint16_t mQdCount; ///< A number specifying the number of entries in the question section. - uint16_t mAnCount; ///< A number specifying the number of entries in the answer section. - uint16_t mNsCount; ///< A number specifying the number of entries in the authority records section. - uint16_t mArCount; ///< A number specifying the number of entries in the additional records section. + uint16_t + mMessageId; ///< A message identifier that is used by the requester to match up replies to outstanding queries. + uint8_t mFlags[2]; ///< DNS header flags. + uint16_t mQdCount; ///< A number specifying the number of entries in the question section. + uint16_t mAnCount; ///< A number specifying the number of entries in the answer section. + uint16_t mNsCount; ///< A number specifying the number of entries in the authority records section. + uint16_t mArCount; ///< A number specifying the number of entries in the additional records section. } OT_TOOL_PACKED_END; @@ -437,10 +440,10 @@ public: void SetLength(uint16_t aLength) { mLength = HostSwap16(aLength); } private: - uint16_t mType; ///< The type of the data in RDATA section. - uint16_t mClass; ///< The class of the data in RDATA section. - uint32_t mTtl; ///< Specifies the maximum time that the resource record may be cached. - uint16_t mLength; ///< The length of RDATA section in bytes. + uint16_t mType; ///< The type of the data in RDATA section. + uint16_t mClass; ///< The class of the data in RDATA section. + uint32_t mTtl; ///< Specifies the maximum time that the resource record may be cached. + uint16_t mLength; ///< The length of RDATA section in bytes. } OT_TOOL_PACKED_END; @@ -449,21 +452,22 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ResourceRecordAaaa: public ResourceRecord +class ResourceRecordAaaa : public ResourceRecord { public: enum { - kType = 0x1C, ///< AAAA Resource Record type. - kClass = 0x01, ///< The value of the Internet class. - kLength = 16, ///< Size of the AAAA Resource Record type. + kType = 0x1C, ///< AAAA Resource Record type. + kClass = 0x01, ///< The value of the Internet class. + kLength = 16, ///< Size of the AAAA Resource Record type. }; /** * This method initializes the AAAA Resource Record. * */ - void Init(void) { + void Init(void) + { ResourceRecord::SetType(kType); ResourceRecord::SetClass(kClass); ResourceRecord::SetTtl(0); @@ -487,7 +491,7 @@ public: otIp6Address &GetAddress(void) { return mAddress; } private: - otIp6Address mAddress; ///< Ipv6 Address of AAAA Resource Record. + otIp6Address mAddress; ///< Ipv6 Address of AAAA Resource Record. } OT_TOOL_PACKED_END; @@ -503,7 +507,8 @@ public: * Constructor for Question. * */ - Question(uint16_t aType, uint16_t aClass) { + Question(uint16_t aType, uint16_t aClass) + { SetType(aType); SetClass(aClass); }; @@ -539,30 +544,30 @@ public: void SetClass(uint16_t aClass) { mClass = HostSwap16(aClass); } private: - uint16_t mType; ///< The type of the data in question section. - uint16_t mClass; ///< The class of the data in question section. + uint16_t mType; ///< The type of the data in question section. + uint16_t mClass; ///< The class of the data in question section. } OT_TOOL_PACKED_END; - /** * This class implements Question format of AAAA type. * */ -class QuestionAaaa: public Question +class QuestionAaaa : public Question { public: enum { - kType = 0x1C, ///< AAAA Resource Record type. - kClass = 0x01, ///< The value of the Internet class. + kType = 0x1C, ///< AAAA Resource Record type. + kClass = 0x01, ///< The value of the Internet class. }; /** * Default constructor for AAAA Question. * */ - QuestionAaaa(void) : Question(kType, kClass) {}; + QuestionAaaa(void) + : Question(kType, kClass){}; /** * This method appends request data to the message. @@ -573,10 +578,7 @@ public: * @retval OT_ERROR_NO_BUFS Insufficient available buffers to grow the message. * */ - otError AppendTo(Message &aMessage) const { - return aMessage.Append(this, sizeof(*this)); - }; - + otError AppendTo(Message &aMessage) const { return aMessage.Append(this, sizeof(*this)); }; }; /** @@ -584,7 +586,7 @@ public: * */ -} // namespace Dns -} // namespace ot +} // namespace Dns +} // namespace ot -#endif // DNS_HEADER_HPP_ +#endif // DNS_HEADER_HPP_ diff --git a/src/core/net/icmp6.cpp b/src/core/net/icmp6.cpp index 376164713..47d885b90 100644 --- a/src/core/net/icmp6.cpp +++ b/src/core/net/icmp6.cpp @@ -49,11 +49,11 @@ using ot::Encoding::BigEndian::HostSwap16; namespace ot { namespace Ip6 { -Icmp::Icmp(Instance &aInstance): - InstanceLocator(aInstance), - mHandlers(NULL), - mEchoSequence(1), - mIsEchoEnabled(true) +Icmp::Icmp(Instance &aInstance) + : InstanceLocator(aInstance) + , mHandlers(NULL) + , mEchoSequence(1) + , mIsEchoEnabled(true) { } @@ -75,18 +75,17 @@ otError Icmp::RegisterHandler(IcmpHandler &aHandler) } aHandler.mNext = mHandlers; - mHandlers = &aHandler; + mHandlers = &aHandler; exit: return error; } -otError Icmp::SendEchoRequest(Message &aMessage, const MessageInfo &aMessageInfo, - uint16_t aIdentifier) +otError Icmp::SendEchoRequest(Message &aMessage, const MessageInfo &aMessageInfo, uint16_t aIdentifier) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; MessageInfo messageInfoLocal; - IcmpHeader icmpHeader; + IcmpHeader icmpHeader; messageInfoLocal = aMessageInfo; @@ -105,13 +104,15 @@ exit: return error; } -otError Icmp::SendError(IcmpHeader::Type aType, IcmpHeader::Code aCode, const MessageInfo &aMessageInfo, - const Header &aHeader) +otError Icmp::SendError(IcmpHeader::Type aType, + IcmpHeader::Code aCode, + const MessageInfo &aMessageInfo, + const Header & aHeader) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; MessageInfo messageInfoLocal; - Message *message = NULL; - IcmpHeader icmp6Header; + Message * message = NULL; + IcmpHeader icmp6Header; messageInfoLocal = aMessageInfo; @@ -141,18 +142,18 @@ exit: otError Icmp::HandleMessage(Message &aMessage, MessageInfo &aMessageInfo) { - otError error = OT_ERROR_NONE; - uint16_t payloadLength; + otError error = OT_ERROR_NONE; + uint16_t payloadLength; IcmpHeader icmp6Header; - uint16_t checksum; + uint16_t checksum; VerifyOrExit(aMessage.Read(aMessage.GetOffset(), sizeof(icmp6Header), &icmp6Header) == sizeof(icmp6Header), error = OT_ERROR_PARSE); payloadLength = aMessage.GetLength() - aMessage.GetOffset(); // verify checksum - checksum = Ip6::ComputePseudoheaderChecksum(aMessageInfo.GetPeerAddr(), aMessageInfo.GetSockAddr(), - payloadLength, kProtoIcmp6); + checksum = Ip6::ComputePseudoheaderChecksum(aMessageInfo.GetPeerAddr(), aMessageInfo.GetSockAddr(), payloadLength, + kProtoIcmp6); checksum = aMessage.UpdateChecksum(checksum, aMessage.GetOffset(), payloadLength); VerifyOrExit(checksum == 0xffff, error = OT_ERROR_PARSE); @@ -174,11 +175,11 @@ exit: otError Icmp::HandleEchoRequest(Message &aRequestMessage, const MessageInfo &aMessageInfo) { - otError error = OT_ERROR_NONE; - IcmpHeader icmp6Header; - Message *replyMessage = NULL; + otError error = OT_ERROR_NONE; + IcmpHeader icmp6Header; + Message * replyMessage = NULL; MessageInfo replyMessageInfo; - uint16_t payloadLength; + uint16_t payloadLength; otLogInfoIcmp(GetInstance(), "Received Echo Request"); @@ -195,8 +196,8 @@ otError Icmp::HandleEchoRequest(Message &aRequestMessage, const MessageInfo &aMe SuccessOrExit(error = replyMessage->SetLength(IcmpHeader::GetDataOffset() + payloadLength)); replyMessage->Write(0, IcmpHeader::GetDataOffset(), &icmp6Header); - aRequestMessage.CopyTo(aRequestMessage.GetOffset() + IcmpHeader::GetDataOffset(), - IcmpHeader::GetDataOffset(), payloadLength, *replyMessage); + aRequestMessage.CopyTo(aRequestMessage.GetOffset() + IcmpHeader::GetDataOffset(), IcmpHeader::GetDataOffset(), + payloadLength, *replyMessage); replyMessageInfo.SetPeerAddr(aMessageInfo.GetPeerAddr()); @@ -224,8 +225,7 @@ exit: otError Icmp::UpdateChecksum(Message &aMessage, uint16_t aChecksum) { - aChecksum = aMessage.UpdateChecksum(aChecksum, aMessage.GetOffset(), - aMessage.GetLength() - aMessage.GetOffset()); + aChecksum = aMessage.UpdateChecksum(aChecksum, aMessage.GetOffset(), aMessage.GetLength() - aMessage.GetOffset()); if (aChecksum != 0xffff) { @@ -237,5 +237,5 @@ otError Icmp::UpdateChecksum(Message &aMessage, uint16_t aChecksum) return OT_ERROR_NONE; } -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot diff --git a/src/core/net/icmp6.hpp b/src/core/net/icmp6.hpp index 45303d61b..7a87bdd85 100644 --- a/src/core/net/icmp6.hpp +++ b/src/core/net/icmp6.hpp @@ -62,14 +62,20 @@ namespace Ip6 { * */ OT_TOOL_PACKED_BEGIN -class IcmpHeader: public otIcmp6Header +class IcmpHeader : public otIcmp6Header { public: /** * This method initializes the ICMPv6 header to all zeros. * */ - void Init(void) { mType = 0; mCode = 0; mChecksum = 0; mData.m32[0] = 0; } + void Init(void) + { + mType = 0; + mCode = 0; + mChecksum = 0; + mData.m32[0] = 0; + } /** * ICMPv6 Message Types @@ -77,9 +83,9 @@ public: */ enum Type { - kTypeDstUnreach = OT_ICMP6_TYPE_DST_UNREACH, ///< Destination Unreachable - kTypeEchoRequest = OT_ICMP6_TYPE_ECHO_REQUEST, ///< Echo Request - kTypeEchoReply = OT_ICMP6_TYPE_ECHO_REPLY, ///< Echo Reply + kTypeDstUnreach = OT_ICMP6_TYPE_DST_UNREACH, ///< Destination Unreachable + kTypeEchoRequest = OT_ICMP6_TYPE_ECHO_REQUEST, ///< Echo Request + kTypeEchoReply = OT_ICMP6_TYPE_ECHO_REPLY, ///< Echo Reply }; /** @@ -88,7 +94,7 @@ public: */ enum Code { - kCodeDstUnreachNoRoute = OT_ICMP6_CODE_DST_UNREACH_NO_ROUTE, ///< Destination Unreachable No Route + kCodeDstUnreachNoRoute = OT_ICMP6_CODE_DST_UNREACH_NO_ROUTE, ///< Destination Unreachable No Route }; /** @@ -204,14 +210,16 @@ public: * @param[in] aContext A pointer to arbitrary context information. * */ - IcmpHandler(otIcmp6ReceiveCallback aCallback, void *aContext) { + IcmpHandler(otIcmp6ReceiveCallback aCallback, void *aContext) + { mReceiveCallback = aCallback; mContext = aContext; mNext = NULL; } private: - void HandleReceiveMessage(Message &aMessage, const MessageInfo &aMessageInfo, const IcmpHeader &aIcmp6Header) { + void HandleReceiveMessage(Message &aMessage, const MessageInfo &aMessageInfo, const IcmpHeader &aIcmp6Header) + { mReceiveCallback(mContext, &aMessage, &aMessageInfo, &aIcmp6Header); } @@ -222,7 +230,7 @@ private: * This class implements ICMPv6. * */ -class Icmp: public InstanceLocator +class Icmp : public InstanceLocator { public: /** @@ -280,8 +288,10 @@ public: * @retval OT_ERROR_NO_BUFS Insufficient buffers available. * */ - otError SendError(IcmpHeader::Type aType, IcmpHeader::Code aCode, const MessageInfo &aMessageInfo, - const Header &aHeader); + otError SendError(IcmpHeader::Type aType, + IcmpHeader::Code aCode, + const MessageInfo &aMessageInfo, + const Header & aHeader); /** * This method handles an ICMPv6 message. @@ -331,7 +341,7 @@ private: IcmpHandler *mHandlers; uint16_t mEchoSequence; - bool mIsEchoEnabled; + bool mIsEchoEnabled; }; /** @@ -339,7 +349,7 @@ private: * */ -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot -#endif // NET_ICMP6_HPP_ +#endif // NET_ICMP6_HPP_ diff --git a/src/core/net/ip6.cpp b/src/core/net/ip6.cpp index 8b31eedfd..1184f65f4 100644 --- a/src/core/net/ip6.cpp +++ b/src/core/net/ip6.cpp @@ -51,19 +51,19 @@ namespace ot { namespace Ip6 { -Ip6::Ip6(Instance &aInstance): - InstanceLocator(aInstance), - mForwardingEnabled(false), - mIsReceiveIp6FilterEnabled(false), - mReceiveIp6DatagramCallback(NULL), - mReceiveIp6DatagramCallbackContext(NULL), - mNetifListHead(NULL), - mSendQueue(), - mSendQueueTask(aInstance, HandleSendQueue, this), - mRoutes(aInstance), - mIcmp(aInstance), - mUdp(aInstance), - mMpl(aInstance) +Ip6::Ip6(Instance &aInstance) + : InstanceLocator(aInstance) + , mForwardingEnabled(false) + , mIsReceiveIp6FilterEnabled(false) + , mReceiveIp6DatagramCallback(NULL) + , mReceiveIp6DatagramCallbackContext(NULL) + , mNetifListHead(NULL) + , mSendQueue() + , mSendQueueTask(aInstance, HandleSendQueue, this) + , mRoutes(aInstance) + , mIcmp(aInstance) + , mUdp(aInstance) + , mMpl(aInstance) { } @@ -78,8 +78,10 @@ uint16_t Ip6::UpdateChecksum(uint16_t aChecksum, const Address &aAddress) return Message::UpdateChecksum(aChecksum, aAddress.mFields.m8, sizeof(aAddress)); } -uint16_t Ip6::ComputePseudoheaderChecksum(const Address &aSource, const Address &aDestination, uint16_t aLength, - IpProto aProto) +uint16_t Ip6::ComputePseudoheaderChecksum(const Address &aSource, + const Address &aDestination, + uint16_t aLength, + IpProto aProto) { uint16_t checksum; @@ -93,16 +95,16 @@ uint16_t Ip6::ComputePseudoheaderChecksum(const Address &aSource, const Address void Ip6::SetReceiveDatagramCallback(otIp6ReceiveCallback aCallback, void *aCallbackContext) { - mReceiveIp6DatagramCallback = aCallback; + mReceiveIp6DatagramCallback = aCallback; mReceiveIp6DatagramCallbackContext = aCallbackContext; } otError Ip6::AddMplOption(Message &aMessage, Header &aHeader) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; HopByHopHeader hbhHeader; - OptionMpl mplOption; - OptionPadN padOption; + OptionMpl mplOption; + OptionPadN padOption; hbhHeader.SetNextHeader(aHeader.GetNextHeader()); hbhHeader.SetLength(0); @@ -125,10 +127,10 @@ exit: otError Ip6::AddTunneledMplOption(Message &aMessage, Header &aHeader, MessageInfo &aMessageInfo) { - otError error = OT_ERROR_NONE; - Header tunnelHeader; + otError error = OT_ERROR_NONE; + Header tunnelHeader; const NetifUnicastAddress *source; - MessageInfo messageInfo(aMessageInfo); + MessageInfo messageInfo(aMessageInfo); // Use IP-in-IP encapsulation (RFC2473) and ALL_MPL_FORWARDERS address. memset(&messageInfo.GetPeerAddr(), 0, sizeof(Address)); @@ -141,8 +143,7 @@ otError Ip6::AddTunneledMplOption(Message &aMessage, Header &aHeader, MessageInf tunnelHeader.SetDestination(messageInfo.GetPeerAddr()); tunnelHeader.SetNextHeader(kProtoIp6); - VerifyOrExit((source = SelectSourceAddress(messageInfo)) != NULL, - error = OT_ERROR_INVALID_SOURCE_ADDRESS); + VerifyOrExit((source = SelectSourceAddress(messageInfo)) != NULL, error = OT_ERROR_INVALID_SOURCE_ADDRESS); tunnelHeader.SetSource(source->GetAddress()); @@ -167,8 +168,8 @@ otError Ip6::InsertMplOption(Message &aMessage, Header &aIp6Header, MessageInfo if (aIp6Header.GetNextHeader() == kProtoHopOpts) { HopByHopHeader hbh; - uint16_t hbhLength = 0; - OptionMpl mplOption; + uint16_t hbhLength = 0; + OptionMpl mplOption; // read existing hop-by-hop option header aMessage.Read(0, sizeof(hbh), &hbh); @@ -234,14 +235,14 @@ exit: otError Ip6::RemoveMplOption(Message &aMessage) { - otError error = OT_ERROR_NONE; - Header ip6Header; + otError error = OT_ERROR_NONE; + Header ip6Header; HopByHopHeader hbh; - uint16_t offset; - uint16_t endOffset; - uint16_t mplOffset = 0; - uint8_t mplLength = 0; - bool remove = false; + uint16_t offset; + uint16_t endOffset; + uint16_t mplOffset = 0; + uint8_t mplLength = 0; + bool remove = false; offset = 0; aMessage.Read(offset, sizeof(ip6Header), &ip6Header); @@ -351,10 +352,10 @@ void Ip6::EnqueueDatagram(Message &aMessage) otError Ip6::SendDatagram(Message &aMessage, MessageInfo &aMessageInfo, IpProto aIpProto) { - otError error = OT_ERROR_NONE; - Header header; - uint16_t payloadLength = aMessage.GetLength(); - uint16_t checksum; + otError error = OT_ERROR_NONE; + Header header; + uint16_t payloadLength = aMessage.GetLength(); + uint16_t checksum; const NetifUnicastAddress *source; header.Init(); @@ -362,11 +363,9 @@ otError Ip6::SendDatagram(Message &aMessage, MessageInfo &aMessageInfo, IpProto header.SetNextHeader(aIpProto); header.SetHopLimit(aMessageInfo.mHopLimit ? aMessageInfo.mHopLimit : static_cast(kDefaultHopLimit)); - if (aMessageInfo.GetSockAddr().IsUnspecified() || - aMessageInfo.GetSockAddr().IsMulticast()) + if (aMessageInfo.GetSockAddr().IsUnspecified() || aMessageInfo.GetSockAddr().IsMulticast()) { - VerifyOrExit((source = SelectSourceAddress(aMessageInfo)) != NULL, - error = OT_ERROR_INVALID_SOURCE_ADDRESS); + VerifyOrExit((source = SelectSourceAddress(aMessageInfo)) != NULL, error = OT_ERROR_INVALID_SOURCE_ADDRESS); header.SetSource(source->GetAddress()); } else @@ -389,8 +388,7 @@ otError Ip6::SendDatagram(Message &aMessage, MessageInfo &aMessageInfo, IpProto SuccessOrExit(error = aMessage.Prepend(&header, sizeof(header))); // compute checksum - checksum = ComputePseudoheaderChecksum(header.GetSource(), header.GetDestination(), - payloadLength, aIpProto); + checksum = ComputePseudoheaderChecksum(header.GetSource(), header.GetDestination(), payloadLength, aIpProto); switch (aIpProto) { @@ -457,10 +455,10 @@ void Ip6::HandleSendQueue(void) otError Ip6::HandleOptions(Message &aMessage, Header &aHeader, bool &aForward) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; HopByHopHeader hbhHeader; - OptionHeader optionHeader; - uint16_t endOffset; + OptionHeader optionHeader; + uint16_t endOffset; VerifyOrExit(aMessage.Read(aMessage.GetOffset(), sizeof(hbhHeader), &hbhHeader) == sizeof(hbhHeader), error = OT_ERROR_DROP); @@ -506,7 +504,6 @@ otError Ip6::HandleOptions(Message &aMessage, Header &aHeader, bool &aForward) case OptionHeader::kActionIcmp: // TODO: send icmp error ExitNow(error = OT_ERROR_DROP); - } break; @@ -521,14 +518,13 @@ exit: otError Ip6::HandleFragment(Message &aMessage) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; FragmentHeader fragmentHeader; VerifyOrExit(aMessage.Read(aMessage.GetOffset(), sizeof(fragmentHeader), &fragmentHeader) == sizeof(fragmentHeader), error = OT_ERROR_DROP); - VerifyOrExit(fragmentHeader.GetOffset() == 0 && fragmentHeader.IsMoreFlagSet() == false, - error = OT_ERROR_DROP); + VerifyOrExit(fragmentHeader.GetOffset() == 0 && fragmentHeader.IsMoreFlagSet() == false, error = OT_ERROR_DROP); aMessage.MoveOffset(sizeof(fragmentHeader)); @@ -536,10 +532,13 @@ exit: return error; } -otError Ip6::HandleExtensionHeaders(Message &aMessage, Header &aHeader, uint8_t &aNextHeader, bool aForward, - bool aReceive) +otError Ip6::HandleExtensionHeaders(Message &aMessage, + Header & aHeader, + uint8_t &aNextHeader, + bool aForward, + bool aReceive) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; ExtensionHeader extHeader; while (aReceive == true || aNextHeader == kProtoHopOpts) @@ -596,10 +595,12 @@ exit: return error; } -otError Ip6::ProcessReceiveCallback(const Message &aMessage, const MessageInfo &aMessageInfo, uint8_t aIpProto, - bool aFromNcpHost) +otError Ip6::ProcessReceiveCallback(const Message & aMessage, + const MessageInfo &aMessageInfo, + uint8_t aIpProto, + bool aFromNcpHost) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Message *messageCopy = NULL; VerifyOrExit(aFromNcpHost == false, error = OT_ERROR_DROP); @@ -609,7 +610,7 @@ otError Ip6::ProcessReceiveCallback(const Message &aMessage, const MessageInfo & { // do not pass messages sent to an RLOC/ALOC VerifyOrExit(!aMessageInfo.GetSockAddr().IsRoutingLocator() && - !aMessageInfo.GetSockAddr().IsAnycastRoutingLocator(), + !aMessageInfo.GetSockAddr().IsAnycastRoutingLocator(), error = OT_ERROR_NO_ROUTE); switch (aIpProto) @@ -636,8 +637,7 @@ otError Ip6::ProcessReceiveCallback(const Message &aMessage, const MessageInfo & case Mle::kUdpPort: // do not pass MLE messages - if (aMessageInfo.GetSockAddr().IsLinkLocal() || - aMessageInfo.GetSockAddr().IsLinkLocalMulticast()) + if (aMessageInfo.GetSockAddr().IsLinkLocal() || aMessageInfo.GetSockAddr().IsLinkLocalMulticast()) { ExitNow(error = OT_ERROR_NO_ROUTE); } @@ -694,10 +694,10 @@ exit: otError Ip6::SendRaw(Message &aMessage, int8_t aInterfaceId) { - otError error = OT_ERROR_NONE; - Header header; + otError error = OT_ERROR_NONE; + Header header; MessageInfo messageInfo; - bool freed = false; + bool freed = false; SuccessOrExit(error = header.Init(aMessage)); @@ -725,20 +725,22 @@ exit: return error; } -otError Ip6::HandleDatagram(Message &aMessage, Netif *aNetif, int8_t aInterfaceId, const void *aLinkMessageInfo, - bool aFromNcpHost) +otError Ip6::HandleDatagram(Message & aMessage, + Netif * aNetif, + int8_t aInterfaceId, + const void *aLinkMessageInfo, + bool aFromNcpHost) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; MessageInfo messageInfo; - Header header; - bool receive = false; - bool forward = false; - bool tunnel = false; - bool multicastPromiscuous = false; - uint8_t nextHeader; - uint8_t hopLimit; - int8_t forwardInterfaceId; - + Header header; + bool receive = false; + bool forward = false; + bool tunnel = false; + bool multicastPromiscuous = false; + uint8_t nextHeader; + uint8_t hopLimit; + int8_t forwardInterfaceId; SuccessOrExit(error = header.Init(aMessage)); @@ -903,7 +905,7 @@ int8_t Ip6::FindForwardInterfaceId(const MessageInfo &aMessageInfo) otError Ip6::AddNetif(Netif &aNetif) { otError error = OT_ERROR_NONE; - Netif *netif; + Netif * netif; if (mNetifListHead == NULL) { @@ -919,8 +921,7 @@ otError Ip6::AddNetif(Netif &aNetif) { ExitNow(error = OT_ERROR_ALREADY); } - } - while (netif->mNext); + } while (netif->mNext); netif->mNext = &aNetif; } @@ -951,7 +952,7 @@ otError Ip6::RemoveNetif(Netif &aNetif) } netif->mNext = aNetif.mNext; - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; break; } } @@ -998,14 +999,14 @@ exit: const NetifUnicastAddress *Ip6::SelectSourceAddress(MessageInfo &aMessageInfo) { - Address *destination = &aMessageInfo.GetPeerAddr(); - int interfaceId = aMessageInfo.mInterfaceId; - const NetifUnicastAddress *rvalAddr = NULL; - const Address *candidateAddr; - int8_t candidateId; - int8_t rvalIface = 0; - uint8_t rvalPrefixMatched = 0; - uint8_t destinationScope = destination->GetScope(); + Address * destination = &aMessageInfo.GetPeerAddr(); + int interfaceId = aMessageInfo.mInterfaceId; + const NetifUnicastAddress *rvalAddr = NULL; + const Address * candidateAddr; + int8_t candidateId; + int8_t rvalIface = 0; + uint8_t rvalPrefixMatched = 0; + uint8_t destinationScope = destination->GetScope(); for (Netif *netif = GetNetifList(); netif; netif = netif->mNext) { @@ -1024,7 +1025,7 @@ const NetifUnicastAddress *Ip6::SelectSourceAddress(MessageInfo &aMessageInfo) uint8_t overrideScope; uint8_t candidatePrefixMatched; - candidateAddr = &addr->GetAddress(); + candidateAddr = &addr->GetAddress(); candidatePrefixMatched = destination->PrefixMatch(*candidateAddr); overrideScope = (candidatePrefixMatched >= addr->mPrefixLength) ? addr->GetScope() : destinationScope; @@ -1037,14 +1038,14 @@ const NetifUnicastAddress *Ip6::SelectSourceAddress(MessageInfo &aMessageInfo) if (rvalAddr == NULL) { // Rule 0: Prefer any address - rvalAddr = addr; - rvalIface = candidateId; + rvalAddr = addr; + rvalIface = candidateId; rvalPrefixMatched = candidatePrefixMatched; } else if (*candidateAddr == *destination) { // Rule 1: Prefer same address - rvalAddr = addr; + rvalAddr = addr; rvalIface = candidateId; ExitNow(); } @@ -1053,8 +1054,8 @@ const NetifUnicastAddress *Ip6::SelectSourceAddress(MessageInfo &aMessageInfo) // Rule 2: Prefer appropriate scope if (addr->GetScope() >= overrideScope) { - rvalAddr = addr; - rvalIface = candidateId; + rvalAddr = addr; + rvalIface = candidateId; rvalPrefixMatched = candidatePrefixMatched; } } @@ -1062,8 +1063,8 @@ const NetifUnicastAddress *Ip6::SelectSourceAddress(MessageInfo &aMessageInfo) { if (rvalAddr->GetScope() < overrideScope) { - rvalAddr = addr; - rvalIface = candidateId; + rvalAddr = addr; + rvalIface = candidateId; rvalPrefixMatched = candidatePrefixMatched; } } @@ -1075,8 +1076,8 @@ const NetifUnicastAddress *Ip6::SelectSourceAddress(MessageInfo &aMessageInfo) if (rvalAddr->GetAddress().IsRoutingLocator()) { // Prefer EID if destination is not realm local. - rvalAddr = addr; - rvalIface = candidateId; + rvalAddr = addr; + rvalIface = candidateId; rvalPrefixMatched = candidatePrefixMatched; } } @@ -1085,8 +1086,8 @@ const NetifUnicastAddress *Ip6::SelectSourceAddress(MessageInfo &aMessageInfo) if (candidateAddr->IsRoutingLocator()) { // Prefer RLOC if destination is realm local. - rvalAddr = addr; - rvalIface = candidateId; + rvalAddr = addr; + rvalIface = candidateId; rvalPrefixMatched = candidatePrefixMatched; } } @@ -1094,8 +1095,8 @@ const NetifUnicastAddress *Ip6::SelectSourceAddress(MessageInfo &aMessageInfo) else if (addr->mPreferred && !rvalAddr->mPreferred) { // Rule 3: Avoid deprecated addresses - rvalAddr = addr; - rvalIface = candidateId; + rvalAddr = addr; + rvalIface = candidateId; rvalPrefixMatched = candidatePrefixMatched; } else if (aMessageInfo.mInterfaceId != 0 && aMessageInfo.mInterfaceId == candidateId && @@ -1103,8 +1104,8 @@ const NetifUnicastAddress *Ip6::SelectSourceAddress(MessageInfo &aMessageInfo) { // Rule 4: Prefer home address // Rule 5: Prefer outgoing interface - rvalAddr = addr; - rvalIface = candidateId; + rvalAddr = addr; + rvalIface = candidateId; rvalPrefixMatched = candidatePrefixMatched; } else if (candidatePrefixMatched > rvalPrefixMatched) @@ -1112,8 +1113,8 @@ const NetifUnicastAddress *Ip6::SelectSourceAddress(MessageInfo &aMessageInfo) // Rule 6: Prefer matching label // Rule 7: Prefer public address // Rule 8: Use longest prefix matching - rvalAddr = addr; - rvalIface = candidateId; + rvalAddr = addr; + rvalIface = candidateId; rvalPrefixMatched = candidatePrefixMatched; } } @@ -1193,5 +1194,5 @@ const char *Ip6::IpProtoToString(IpProto aIpProto) return retval; } -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot diff --git a/src/core/net/ip6.hpp b/src/core/net/ip6.hpp index 00600af77..2f0b7f052 100644 --- a/src/core/net/ip6.hpp +++ b/src/core/net/ip6.hpp @@ -103,7 +103,7 @@ class Ip6 : public InstanceLocator public: enum { - kDefaultHopLimit = 64, + kDefaultHopLimit = 64, kMaxDatagramLength = 1280, }; @@ -163,9 +163,11 @@ public: * @retval OT_ERROR_DROP Message processing failed and the message should be dropped. * */ - otError HandleDatagram(Message &aMessage, Netif *aNetif, int8_t aInterfaceId, - const void *aLinkMessageInfo, bool aFromNcpHost); - + otError HandleDatagram(Message & aMessage, + Netif * aNetif, + int8_t aInterfaceId, + const void *aLinkMessageInfo, + bool aFromNcpHost); /** * This methods adds a full IPv6 packet to the transmit queue. @@ -196,8 +198,10 @@ public: * @returns The pseudoheader checksum. * */ - static uint16_t ComputePseudoheaderChecksum(const Address &aSource, const Address &aDestination, - uint16_t aLength, IpProto aProto); + static uint16_t ComputePseudoheaderChecksum(const Address &aSource, + const Address &aDestination, + uint16_t aLength, + IpProto aProto); /** * This method registers a callback to provide received raw IPv6 datagrams. @@ -376,12 +380,17 @@ public: private: static void HandleSendQueue(Tasklet &aTasklet); - void HandleSendQueue(void); + void HandleSendQueue(void); - otError ProcessReceiveCallback(const Message &aMessage, const MessageInfo &aMessageInfo, uint8_t aIpProto, - bool aFromNcpHost); - otError HandleExtensionHeaders(Message &aMessage, Header &aHeader, uint8_t &aNextHeader, bool aForward, - bool aReceive); + otError ProcessReceiveCallback(const Message & aMessage, + const MessageInfo &aMessageInfo, + uint8_t aIpProto, + bool aFromNcpHost); + otError HandleExtensionHeaders(Message &aMessage, + Header & aHeader, + uint8_t &aNextHeader, + bool aForward, + bool aReceive); otError HandleFragment(Message &aMessage); otError AddMplOption(Message &aMessage, Header &aHeader); otError AddTunneledMplOption(Message &aMessage, Header &aHeader, MessageInfo &aMessageInfo); @@ -389,22 +398,21 @@ private: otError RemoveMplOption(Message &aMessage); otError HandleOptions(Message &aMessage, Header &aHeader, bool &aForward); otError HandlePayload(Message &aMessage, MessageInfo &aMessageInfo, uint8_t aIpProto); - int8_t FindForwardInterfaceId(const MessageInfo &aMessageInfo); + int8_t FindForwardInterfaceId(const MessageInfo &aMessageInfo); - bool mForwardingEnabled; - bool mIsReceiveIp6FilterEnabled; + bool mForwardingEnabled; + bool mIsReceiveIp6FilterEnabled; otIp6ReceiveCallback mReceiveIp6DatagramCallback; - void *mReceiveIp6DatagramCallbackContext; - Netif *mNetifListHead; + void * mReceiveIp6DatagramCallbackContext; + Netif * mNetifListHead; PriorityQueue mSendQueue; - Tasklet mSendQueueTask; + Tasklet mSendQueueTask; Routes mRoutes; - Icmp mIcmp; - Udp mUdp; - Mpl mMpl; - + Icmp mIcmp; + Udp mUdp; + Mpl mMpl; }; /** @@ -412,7 +420,7 @@ private: * */ -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot -#endif // NET_IP6_HPP_ +#endif // NET_IP6_HPP_ diff --git a/src/core/net/ip6_address.cpp b/src/core/net/ip6_address.cpp index 66b39bb7b..101f4de65 100644 --- a/src/core/net/ip6_address.cpp +++ b/src/core/net/ip6_address.cpp @@ -79,14 +79,14 @@ bool Address::IsLinkLocalMulticast(void) const bool Address::IsLinkLocalAllNodesMulticast(void) const { - return (mFields.m32[0] == HostSwap32(0xff020000) && mFields.m32[1] == 0 && - mFields.m32[2] == 0 && mFields.m32[3] == HostSwap32(0x01)); + return (mFields.m32[0] == HostSwap32(0xff020000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 && + mFields.m32[3] == HostSwap32(0x01)); } bool Address::IsLinkLocalAllRoutersMulticast(void) const { - return (mFields.m32[0] == HostSwap32(0xff020000) && mFields.m32[1] == 0 && - mFields.m32[2] == 0 && mFields.m32[3] == HostSwap32(0x02)); + return (mFields.m32[0] == HostSwap32(0xff020000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 && + mFields.m32[3] == HostSwap32(0x02)); } bool Address::IsRealmLocalMulticast(void) const @@ -101,20 +101,20 @@ bool Address::IsMulticastLargerThanRealmLocal(void) const bool Address::IsRealmLocalAllNodesMulticast(void) const { - return (mFields.m32[0] == HostSwap32(0xff030000) && mFields.m32[1] == 0 && - mFields.m32[2] == 0 && mFields.m32[3] == HostSwap32(0x01)); + return (mFields.m32[0] == HostSwap32(0xff030000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 && + mFields.m32[3] == HostSwap32(0x01)); } bool Address::IsRealmLocalAllRoutersMulticast(void) const { - return (mFields.m32[0] == HostSwap32(0xff030000) && mFields.m32[1] == 0 && - mFields.m32[2] == 0 && mFields.m32[3] == HostSwap32(0x02)); + return (mFields.m32[0] == HostSwap32(0xff030000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 && + mFields.m32[3] == HostSwap32(0x02)); } bool Address::IsRealmLocalAllMplForwarders(void) const { - return (mFields.m32[0] == HostSwap32(0xff030000) && mFields.m32[1] == 0 && - mFields.m32[2] == 0 && mFields.m32[3] == HostSwap32(0xfc)); + return (mFields.m32[0] == HostSwap32(0xff030000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 && + mFields.m32[3] == HostSwap32(0xfc)); } bool Address::IsRoutingLocator(void) const @@ -247,15 +247,15 @@ bool Address::operator!=(const Address &aOther) const otError Address::FromString(const char *aBuf) { - otError error = OT_ERROR_NONE; - uint8_t *dst = reinterpret_cast(mFields.m8); - uint8_t *endp = reinterpret_cast(mFields.m8 + 15); + otError error = OT_ERROR_NONE; + uint8_t *dst = reinterpret_cast(mFields.m8); + uint8_t *endp = reinterpret_cast(mFields.m8 + 15); uint8_t *colonp = NULL; - uint16_t val = 0; - uint8_t count = 0; - bool first = true; - char ch; - uint8_t d; + uint16_t val = 0; + uint8_t count = 0; + bool first = true; + char ch; + uint8_t d; memset(mFields.m8, 0, 16); @@ -264,7 +264,7 @@ otError Address::FromString(const char *aBuf) for (;;) { ch = *aBuf++; - d = ch & 0xf; + d = ch & 0xf; if (('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F')) { @@ -279,7 +279,7 @@ otError Address::FromString(const char *aBuf) *(dst + 2) = static_cast(val); dst += 2; count = 0; - val = 0; + val = 0; } else if (ch == ':') { @@ -300,7 +300,7 @@ otError Address::FromString(const char *aBuf) } first = false; - val = static_cast((val << 4) | d); + val = static_cast((val << 4) | d); VerifyOrExit(++count <= 4, error = OT_ERROR_PARSE); } @@ -320,14 +320,12 @@ exit: const char *Address::ToString(char *aBuf, uint16_t aSize) const { - snprintf(aBuf, aSize, "%x:%x:%x:%x:%x:%x:%x:%x", - HostSwap16(mFields.m16[0]), HostSwap16(mFields.m16[1]), - HostSwap16(mFields.m16[2]), HostSwap16(mFields.m16[3]), - HostSwap16(mFields.m16[4]), HostSwap16(mFields.m16[5]), - HostSwap16(mFields.m16[6]), HostSwap16(mFields.m16[7])); + snprintf(aBuf, aSize, "%x:%x:%x:%x:%x:%x:%x:%x", HostSwap16(mFields.m16[0]), HostSwap16(mFields.m16[1]), + HostSwap16(mFields.m16[2]), HostSwap16(mFields.m16[3]), HostSwap16(mFields.m16[4]), + HostSwap16(mFields.m16[5]), HostSwap16(mFields.m16[6]), HostSwap16(mFields.m16[7])); return aBuf; } -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot diff --git a/src/core/net/ip6_address.hpp b/src/core/net/ip6_address.hpp index 7f2b87635..c6a96a3d2 100644 --- a/src/core/net/ip6_address.hpp +++ b/src/core/net/ip6_address.hpp @@ -57,7 +57,7 @@ namespace Ip6 { * */ OT_TOOL_PACKED_BEGIN -class Address: public otIp6Address +class Address : public otIp6Address { public: /** @@ -66,8 +66,8 @@ public: */ enum { - kAloc16Mask = 0xfc, ///< The mask for Aloc16. - kRloc16ReservedBitMask = 0x02, ///< The mask for the reserved bit of Rloc16. + kAloc16Mask = 0xfc, ///< The mask for Aloc16. + kRloc16ReservedBitMask = 0x02, ///< The mask for the reserved bit of Rloc16. }; /** @@ -76,10 +76,10 @@ public: */ enum { - kInterfaceIdentifierSize = 8, ///< Interface Identifier size in bytes. - kIp6AddressStringSize = 40, ///< Max buffer size in bytes to store an IPv6 address in string format. - kMeshLocalPrefixLength = 64, ///< Length of Thread mesh local prefix. - kMeshLocalPrefixSize = 8, ///< Mesh local prefix size in bytes. + kInterfaceIdentifierSize = 8, ///< Interface Identifier size in bytes. + kIp6AddressStringSize = 40, ///< Max buffer size in bytes to store an IPv6 address in string format. + kMeshLocalPrefixLength = 64, ///< Length of Thread mesh local prefix. + kMeshLocalPrefixSize = 8, ///< Mesh local prefix size in bytes. }; /** @@ -390,7 +390,7 @@ public: private: enum { - kInterfaceIdentifierOffset = 8, ///< Interface Identifier offset in bytes. + kInterfaceIdentifierOffset = 8, ///< Interface Identifier offset in bytes. }; } OT_TOOL_PACKED_END; @@ -399,7 +399,7 @@ private: * */ -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot -#endif // NET_IP6_ADDRESS_HPP_ +#endif // NET_IP6_ADDRESS_HPP_ diff --git a/src/core/net/ip6_filter.cpp b/src/core/net/ip6_filter.cpp index c79a979cb..6a0b8ea93 100644 --- a/src/core/net/ip6_filter.cpp +++ b/src/core/net/ip6_filter.cpp @@ -52,11 +52,11 @@ Filter::Filter(void) bool Filter::Accept(Message &aMessage) const { - bool rval = false; - Header ip6; + bool rval = false; + Header ip6; UdpHeader udp; TcpHeader tcp; - uint16_t dstport; + uint16_t dstport; // Allow all received IPv6 datagrams with link security enabled if (aMessage.IsLinkSecurityEnabled()) @@ -180,5 +180,5 @@ const uint16_t *Filter::GetUnsecurePorts(uint8_t &aNumEntries) const return mUnsecurePorts; } -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot diff --git a/src/core/net/ip6_filter.hpp b/src/core/net/ip6_filter.hpp index 64a0fe9fb..8a0d04978 100644 --- a/src/core/net/ip6_filter.hpp +++ b/src/core/net/ip6_filter.hpp @@ -119,7 +119,7 @@ private: uint16_t mUnsecurePorts[kMaxUnsecurePorts]; }; -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot -#endif // IP6_FILTER_HPP_ +#endif // IP6_FILTER_HPP_ diff --git a/src/core/net/ip6_headers.cpp b/src/core/net/ip6_headers.cpp index e8027f95a..759047113 100644 --- a/src/core/net/ip6_headers.cpp +++ b/src/core/net/ip6_headers.cpp @@ -40,7 +40,7 @@ namespace Ip6 { otError Header::Init(const Message &aMessage) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint16_t length; // check aMessage length @@ -57,5 +57,5 @@ exit: return error; } -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot diff --git a/src/core/net/ip6_headers.hpp b/src/core/net/ip6_headers.hpp index 2e1c44efa..e08153179 100644 --- a/src/core/net/ip6_headers.hpp +++ b/src/core/net/ip6_headers.hpp @@ -92,20 +92,20 @@ namespace Ip6 { */ enum IpProto { - kProtoHopOpts = 0, ///< IPv6 Hop-by-Hop Option - kProtoTcp = 6, ///< Transmission Control Protocol - kProtoUdp = 17, ///< User Datagram - kProtoIp6 = 41, ///< IPv6 encapsulation - kProtoRouting = 43, ///< Routing Header for IPv6 - kProtoFragment = 44, ///< Fragment Header for IPv6 - kProtoIcmp6 = 58, ///< ICMP for IPv6 - kProtoNone = 59, ///< No Next Header for IPv6 - kProtoDstOpts = 60, ///< Destination Options for IPv6 + kProtoHopOpts = 0, ///< IPv6 Hop-by-Hop Option + kProtoTcp = 6, ///< Transmission Control Protocol + kProtoUdp = 17, ///< User Datagram + kProtoIp6 = 41, ///< IPv6 encapsulation + kProtoRouting = 43, ///< Routing Header for IPv6 + kProtoFragment = 44, ///< Fragment Header for IPv6 + kProtoIcmp6 = 58, ///< ICMP for IPv6 + kProtoNone = 59, ///< No Next Header for IPv6 + kProtoDstOpts = 60, ///< Destination Options for IPv6 }; enum { - kVersionClassFlowSize = 4, ///< Combined size of Version, Class, Flow Label in bytes. + kVersionClassFlowSize = 4, ///< Combined size of Version, Class, Flow Label in bytes. }; /** @@ -117,15 +117,15 @@ struct HeaderPoD { union OT_TOOL_PACKED_FIELD { - uint8_t m8[kVersionClassFlowSize / sizeof(uint8_t)]; - uint16_t m16[kVersionClassFlowSize / sizeof(uint16_t)]; - uint32_t m32[kVersionClassFlowSize / sizeof(uint32_t)]; - } mVersionClassFlow; ///< Version, Class, Flow Label - uint16_t mPayloadLength; ///< Payload Length - uint8_t mNextHeader; ///< Next Header - uint8_t mHopLimit; ///< Hop Limit - otIp6Address mSource; ///< Source - otIp6Address mDestination; ///< Destination + uint8_t m8[kVersionClassFlowSize / sizeof(uint8_t)]; + uint16_t m16[kVersionClassFlowSize / sizeof(uint16_t)]; + uint32_t m32[kVersionClassFlowSize / sizeof(uint32_t)]; + } mVersionClassFlow; ///< Version, Class, Flow Label + uint16_t mPayloadLength; ///< Payload Length + uint8_t mNextHeader; ///< Next Header + uint8_t mHopLimit; ///< Hop Limit + otIp6Address mSource; ///< Source + otIp6Address mDestination; ///< Destination } OT_TOOL_PACKED_END; /** @@ -133,14 +133,18 @@ struct HeaderPoD * */ OT_TOOL_PACKED_BEGIN -class Header: private HeaderPoD +class Header : private HeaderPoD { public: /** * This method initializes the IPv6 header. * */ - void Init(void) { mVersionClassFlow.m32[0] = 0; mVersionClassFlow.m8[0] = kVersion6; } + void Init(void) + { + mVersionClassFlow.m32[0] = 0; + mVersionClassFlow.m8[0] = kVersion6; + } /** * This method initializes the IPv6 header and sets Version, Traffic Control and Flow Label fields. @@ -283,7 +287,7 @@ public: private: enum { - kVersion6 = 0x60, + kVersion6 = 0x60, kVersionMask = 0xf0, }; } OT_TOOL_PACKED_END; @@ -338,7 +342,7 @@ private: * */ OT_TOOL_PACKED_BEGIN -class HopByHopHeader: public ExtensionHeader +class HopByHopHeader : public ExtensionHeader { } OT_TOOL_PACKED_END; @@ -354,9 +358,11 @@ public: * Default constructor. * */ - OptionHeader(void): - mType(0), - mLength(0) {} + OptionHeader(void) + : mType(0) + , mLength(0) + { + } /** * This method returns the IPv6 Option Type value. @@ -380,11 +386,11 @@ public: */ enum Action { - kActionSkip = 0x00, ///< skip over this option and continue processing the header - kActionDiscard = 0x40, ///< discard the packet - kActionForceIcmp = 0x80, ///< discard the packet and forcibly send an ICMP Parameter Problem - kActionIcmp = 0xc0, ///< discard packet and conditionally send an ICMP Parameter Problem - kActionMask = 0xc0, ///< mask for action bits + kActionSkip = 0x00, ///< skip over this option and continue processing the header + kActionDiscard = 0x40, ///< discard the packet + kActionForceIcmp = 0x80, ///< discard the packet and forcibly send an ICMP Parameter Problem + kActionIcmp = 0xc0, ///< discard packet and conditionally send an ICMP Parameter Problem + kActionMask = 0xc0, ///< mask for action bits }; /** @@ -426,8 +432,8 @@ class OptionPadN : public OptionHeader public: enum { - kType = 0x01, ///< PadN type - kData = 0x00, ///< PadN specific data + kType = 0x01, ///< PadN type + kData = 0x00, ///< PadN specific data kMaxLength = 0x05 ///< Maximum length of PadN option data }; @@ -438,7 +444,8 @@ public: * range 2-7. * */ - void Init(uint8_t aPadLength) { + void Init(uint8_t aPadLength) + { OptionHeader::SetType(kType); OptionHeader::SetLength(aPadLength - sizeof(OptionHeader)); memset(mPad, kData, aPadLength - sizeof(OptionHeader)); @@ -481,7 +488,6 @@ private: uint8_t mType; } OT_TOOL_PACKED_END; - /** * This class implements IPv6 Fragment Header generation and parsing. * @@ -494,7 +500,11 @@ public: * This method initializes the IPv6 Fragment header. * */ - void Init(void) { mReserved = 0; mIdentification = 0; } + void Init(void) + { + mReserved = 0; + mIdentification = 0; + } /** * This method returns the IPv6 Next Header value. @@ -525,10 +535,11 @@ public: * * @param[in] aOffset The Fragment Offset value. */ - void SetOffset(uint16_t aOffset) { + void SetOffset(uint16_t aOffset) + { uint16_t tmp = HostSwap16(mOffsetMore); - tmp = (tmp & ~kOffsetMask) | ((aOffset << kOffsetOffset) & kOffsetMask); - mOffsetMore = HostSwap16(tmp); + tmp = (tmp & ~kOffsetMask) | ((aOffset << kOffsetOffset) & kOffsetMask); + mOffsetMore = HostSwap16(tmp); } /** @@ -558,8 +569,8 @@ private: enum { kOffsetOffset = 3, - kOffsetMask = 0xfff8, - kMoreFlag = 1, + kOffsetMask = 0xfff8, + kMoreFlag = 1, }; uint16_t mOffsetMore; uint32_t mIdentification; @@ -570,7 +581,7 @@ private: * */ -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot -#endif // NET_IP6_HEADERS_HPP_ +#endif // NET_IP6_HEADERS_HPP_ diff --git a/src/core/net/ip6_mpl.cpp b/src/core/net/ip6_mpl.cpp index f7393380b..092ed1910 100644 --- a/src/core/net/ip6_mpl.cpp +++ b/src/core/net/ip6_mpl.cpp @@ -54,14 +54,14 @@ void MplBufferedMessageMetadata::GenerateNextTransmissionTime(uint32_t aCurrentT SetIntervalOffset(aInterval - t); } -Mpl::Mpl(Instance &aInstance): - InstanceLocator(aInstance), - mTimerExpirations(0), - mSequence(0), - mSeedId(0), - mSeedSetTimer(aInstance, &Mpl::HandleSeedSetTimer, this), - mRetransmissionTimer(aInstance, &Mpl::HandleRetransmissionTimer, this), - mMatchingAddress(NULL) +Mpl::Mpl(Instance &aInstance) + : InstanceLocator(aInstance) + , mTimerExpirations(0) + , mSequence(0) + , mSeedId(0) + , mSeedSetTimer(aInstance, &Mpl::HandleSeedSetTimer, this) + , mRetransmissionTimer(aInstance, &Mpl::HandleRetransmissionTimer, this) + , mMatchingAddress(NULL) { memset(mSeedSet, 0, sizeof(mSeedSet)); } @@ -88,9 +88,9 @@ void Mpl::InitOption(OptionMpl &aOption, const Address &aAddress) otError Mpl::UpdateSeedSet(uint16_t aSeedId, uint8_t aSequence) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; MplSeedEntry *entry = NULL; - int8_t diff; + int8_t diff; for (uint32_t i = 0; i < kNumSeedEntries; i++) { @@ -105,7 +105,7 @@ otError Mpl::UpdateSeedSet(uint16_t aSeedId, uint8_t aSequence) else if (mSeedSet[i].GetSeedId() == aSeedId) { entry = &mSeedSet[i]; - diff = static_cast(aSequence - entry->GetSequence()); + diff = static_cast(aSequence - entry->GetSequence()); VerifyOrExit(diff > 0, error = OT_ERROR_DROP); @@ -126,10 +126,10 @@ exit: void Mpl::UpdateBufferedSet(uint16_t aSeedId, uint8_t aSequence) { - int8_t diff; + int8_t diff; MplBufferedMessageMetadata messageMetadata; - Message *message = mBufferedMessageSet.GetHead(); + Message *message = mBufferedMessageSet.GetHead(); Message *nextMessage = NULL; // Check if multicast forwarding is enabled. @@ -163,12 +163,12 @@ exit: void Mpl::AddBufferedMessage(Message &aMessage, uint16_t aSeedId, uint8_t aSequence, bool aIsOutbound) { - uint32_t now = TimerMilli::GetNow(); - otError error = OT_ERROR_NONE; - Message *messageCopy = NULL; + uint32_t now = TimerMilli::GetNow(); + otError error = OT_ERROR_NONE; + Message * messageCopy = NULL; MplBufferedMessageMetadata messageMetadata; - uint32_t nextTransmissionTime; - uint8_t hopLimit = 0; + uint32_t nextTransmissionTime; + uint8_t hopLimit = 0; #if OPENTHREAD_CONFIG_ENABLE_DYNAMIC_MPL_INTERVAL // adjust the first MPL forward interval dynamically according to the network scale @@ -223,12 +223,12 @@ exit: otError Mpl::ProcessOption(Message &aMessage, const Address &aAddress, bool aIsOutbound) { - otError error; + otError error; OptionMpl option; VerifyOrExit(aMessage.Read(aMessage.GetOffset(), sizeof(option), &option) >= OptionMpl::kMinLength && - (option.GetSeedIdLength() == OptionMpl::kSeedIdLength0 || - option.GetSeedIdLength() == OptionMpl::kSeedIdLength2), + (option.GetSeedIdLength() == OptionMpl::kSeedIdLength0 || + option.GetSeedIdLength() == OptionMpl::kSeedIdLength2), error = OT_ERROR_DROP); if (option.GetSeedIdLength() == OptionMpl::kSeedIdLength0) @@ -265,11 +265,11 @@ void Mpl::HandleRetransmissionTimer(Timer &aTimer) void Mpl::HandleRetransmissionTimer(void) { - uint32_t now = TimerMilli::GetNow(); - uint32_t nextDelta = 0xffffffff; + uint32_t now = TimerMilli::GetNow(); + uint32_t nextDelta = 0xffffffff; MplBufferedMessageMetadata messageMetadata; - Message *message = mBufferedMessageSet.GetHead(); + Message *message = mBufferedMessageSet.GetHead(); Message *nextMessage = NULL; while (message != NULL) @@ -369,5 +369,5 @@ void Mpl::HandleSeedSetTimer(void) } } -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot diff --git a/src/core/net/ip6_mpl.hpp b/src/core/net/ip6_mpl.hpp index 98b699cf2..8d038cddb 100644 --- a/src/core/net/ip6_mpl.hpp +++ b/src/core/net/ip6_mpl.hpp @@ -61,12 +61,12 @@ namespace Ip6 { * */ OT_TOOL_PACKED_BEGIN -class OptionMpl: public OptionHeader +class OptionMpl : public OptionHeader { public: enum { - kType = 0x6d, /* 01 1 01101 */ + kType = 0x6d, /* 01 1 01101 */ kMinLength = 2 }; @@ -74,7 +74,8 @@ public: * This method initializes the MPL header. * */ - void Init(void) { + void Init(void) + { OptionHeader::SetType(kType); OptionHeader::SetLength(sizeof(*this) - sizeof(OptionHeader)); mControl = 0; @@ -94,10 +95,10 @@ public: */ enum SeedIdLength { - kSeedIdLength0 = 0 << 6, ///< 0-byte MPL Seed Id Length. - kSeedIdLength2 = 1 << 6, ///< 2-byte MPL Seed Id Length. - kSeedIdLength8 = 2 << 6, ///< 8-byte MPL Seed Id Length. - kSeedIdLength16 = 3 << 6, ///< 16-byte MPL Seed Id Length. + kSeedIdLength0 = 0 << 6, ///< 0-byte MPL Seed Id Length. + kSeedIdLength2 = 1 << 6, ///< 2-byte MPL Seed Id Length. + kSeedIdLength8 = 2 << 6, ///< 8-byte MPL Seed Id Length. + kSeedIdLength16 = 3 << 6, ///< 16-byte MPL Seed Id Length. }; /** @@ -114,7 +115,10 @@ public: * @param[in] aSeedIdLength The MPL Seed Length. * */ - void SetSeedIdLength(SeedIdLength aSeedIdLength) { mControl = static_cast((mControl & ~kSeedIdLengthMask) | aSeedIdLength); } + void SetSeedIdLength(SeedIdLength aSeedIdLength) + { + mControl = static_cast((mControl & ~kSeedIdLengthMask) | aSeedIdLength); + } /** * This method indicates whether or not the MPL M flag is set. @@ -173,7 +177,7 @@ private: enum { kSeedIdLengthMask = 3 << 6, - kMaxFlag = 1 << 5 + kMaxFlag = 1 << 5 }; uint8_t mControl; uint8_t mSequence; @@ -253,13 +257,12 @@ public: * Default constructor for the object. * */ - MplBufferedMessageMetadata(void): - mSeedId(0), - mSequence(0), - mTransmissionCount(0), - mTransmissionTime(0), - mIntervalOffset(0) { - }; + MplBufferedMessageMetadata(void) + : mSeedId(0) + , mSequence(0) + , mTransmissionCount(0) + , mTransmissionTime(0) + , mIntervalOffset(0){}; /** * This method appends MPL Buffered Message metadata to the message. @@ -270,9 +273,7 @@ public: * @retval OT_ERROR_NO_BUFS Insufficient available buffers to grow the message. * */ - otError AppendTo(Message &aMessage) const { - return aMessage.Append(this, sizeof(*this)); - }; + otError AppendTo(Message &aMessage) const { return aMessage.Append(this, sizeof(*this)); }; /** * This method reads request data from the message. @@ -282,7 +283,8 @@ public: * @returns The number of bytes that have been read. * */ - uint16_t ReadFrom(const Message &aMessage) { + uint16_t ReadFrom(const Message &aMessage) + { return aMessage.Read(aMessage.GetLength() - sizeof(*this), sizeof(*this), this); }; @@ -294,9 +296,7 @@ public: * @retval OT_ERROR_NONE Successfully removed the header. * */ - otError RemoveFrom(Message &aMessage) { - return aMessage.SetLength(aMessage.GetLength() - sizeof(*this)); - }; + otError RemoveFrom(Message &aMessage) { return aMessage.SetLength(aMessage.GetLength() - sizeof(*this)); }; /** * This method updates MPL Buffered Messsage metadata in the message. @@ -306,7 +306,8 @@ public: * @returns The number of bytes that have been updated. * */ - int UpdateIn(Message &aMessage) const { + int UpdateIn(Message &aMessage) const + { return aMessage.Write(aMessage.GetLength() - sizeof(*this), sizeof(*this), this); } @@ -430,7 +431,7 @@ private: * This class implements MPL message processing. * */ -class Mpl: public InstanceLocator +class Mpl : public InstanceLocator { public: /** @@ -519,24 +520,24 @@ public: private: enum { - kNumSeedEntries = OPENTHREAD_CONFIG_MPL_SEED_SET_ENTRIES, - kSeedEntryLifetime = OPENTHREAD_CONFIG_MPL_SEED_SET_ENTRY_LIFETIME, + kNumSeedEntries = OPENTHREAD_CONFIG_MPL_SEED_SET_ENTRIES, + kSeedEntryLifetime = OPENTHREAD_CONFIG_MPL_SEED_SET_ENTRY_LIFETIME, kSeedEntryLifetimeDt = 1000, kDataMessageInterval = 64 }; otError UpdateSeedSet(uint16_t aSeedId, uint8_t aSequence); - void UpdateBufferedSet(uint16_t aSeedId, uint8_t aSequence); - void AddBufferedMessage(Message &aMessage, uint16_t aSeedId, uint8_t aSequence, bool aIsOutbound); + void UpdateBufferedSet(uint16_t aSeedId, uint8_t aSequence); + void AddBufferedMessage(Message &aMessage, uint16_t aSeedId, uint8_t aSequence, bool aIsOutbound); static void HandleSeedSetTimer(Timer &aTimer); - void HandleSeedSetTimer(void); + void HandleSeedSetTimer(void); static void HandleRetransmissionTimer(Timer &aTimer); - void HandleRetransmissionTimer(void); + void HandleRetransmissionTimer(void); - uint8_t mTimerExpirations; - uint8_t mSequence; + uint8_t mTimerExpirations; + uint8_t mSequence; uint16_t mSeedId; TimerMilli mSeedSetTimer; @@ -548,13 +549,12 @@ private: MessageQueue mBufferedMessageSet; }; - /** * @} * */ -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot -#endif // NET_IP6_MPL_HPP_ +#endif // NET_IP6_MPL_HPP_ diff --git a/src/core/net/ip6_routes.cpp b/src/core/net/ip6_routes.cpp index 2739c46fe..9b37c4600 100644 --- a/src/core/net/ip6_routes.cpp +++ b/src/core/net/ip6_routes.cpp @@ -42,9 +42,9 @@ namespace ot { namespace Ip6 { -Routes::Routes(Instance &aInstance): - InstanceLocator(aInstance), - mRoutes(NULL) +Routes::Routes(Instance &aInstance) + : InstanceLocator(aInstance) + , mRoutes(NULL) { } @@ -58,7 +58,7 @@ otError Routes::Add(Route &aRoute) } aRoute.mNext = mRoutes; - mRoutes = &aRoute; + mRoutes = &aRoute; exit: return error; @@ -89,9 +89,9 @@ otError Routes::Remove(Route &aRoute) int8_t Routes::Lookup(const Address &aSource, const Address &aDestination) { - int8_t maxPrefixMatch = -1; + int8_t maxPrefixMatch = -1; uint8_t prefixMatch; - int8_t rval = -1; + int8_t rval = -1; for (Route *cur = mRoutes; cur; cur = cur->mNext) { @@ -113,7 +113,7 @@ int8_t Routes::Lookup(const Address &aSource, const Address &aDestination) } maxPrefixMatch = static_cast(prefixMatch); - rval = cur->mInterfaceId; + rval = cur->mInterfaceId; } for (Netif *netif = GetIp6().GetNetifList(); netif; netif = netif->GetNext()) @@ -122,12 +122,12 @@ int8_t Routes::Lookup(const Address &aSource, const Address &aDestination) static_cast(prefixMatch) > maxPrefixMatch) { maxPrefixMatch = static_cast(prefixMatch); - rval = netif->GetInterfaceId(); + rval = netif->GetInterfaceId(); } } return rval; } -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot diff --git a/src/core/net/ip6_routes.hpp b/src/core/net/ip6_routes.hpp index ed184f5c3..823ce8e74 100644 --- a/src/core/net/ip6_routes.hpp +++ b/src/core/net/ip6_routes.hpp @@ -61,17 +61,17 @@ class Ip6; */ struct Route { - Address mPrefix; ///< The IPv6 prefix. - uint8_t mPrefixLength; ///< The IPv6 prefix length. - int8_t mInterfaceId; ///< The interface identifier. - struct Route *mNext; ///< A pointer to the next IPv6 route. + Address mPrefix; ///< The IPv6 prefix. + uint8_t mPrefixLength; ///< The IPv6 prefix length. + int8_t mInterfaceId; ///< The interface identifier. + struct Route *mNext; ///< A pointer to the next IPv6 route. }; /** * This class implements IPv6 route management. * */ -class Routes: public InstanceLocator +class Routes : public InstanceLocator { public: /** @@ -124,7 +124,7 @@ private: * */ -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot -#endif // NET_IP6_ROUTES_HPP_ +#endif // NET_IP6_ROUTES_HPP_ diff --git a/src/core/net/netif.cpp b/src/core/net/netif.cpp index ab708212e..f6369dda0 100644 --- a/src/core/net/netif.cpp +++ b/src/core/net/netif.cpp @@ -56,48 +56,37 @@ namespace Ip6 { */ // "ff03::fc" -const otNetifMulticastAddress Netif::kRealmLocalAllMplForwardersMulticastAddress = -{ - {{{ 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc }}}, - NULL -}; +const otNetifMulticastAddress Netif::kRealmLocalAllMplForwardersMulticastAddress = { + {{{0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc}}}, + NULL}; // "ff03::01" -const otNetifMulticastAddress Netif::kRealmLocalAllNodesMulticastAddress = -{ - {{{ 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }}}, - &Netif::kRealmLocalAllMplForwardersMulticastAddress -}; +const otNetifMulticastAddress Netif::kRealmLocalAllNodesMulticastAddress = { + {{{0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}}}, + &Netif::kRealmLocalAllMplForwardersMulticastAddress}; // "ff02::01" -const otNetifMulticastAddress Netif::kLinkLocalAllNodesMulticastAddress = -{ - {{{ 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }}}, - &Netif::kRealmLocalAllNodesMulticastAddress -}; +const otNetifMulticastAddress Netif::kLinkLocalAllNodesMulticastAddress = { + {{{0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}}}, + &Netif::kRealmLocalAllNodesMulticastAddress}; // "ff03:02" -const otNetifMulticastAddress Netif::kRealmLocalAllRoutersMulticastAddress = -{ - {{{ 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02 }}}, - &Netif::kLinkLocalAllNodesMulticastAddress -}; +const otNetifMulticastAddress Netif::kRealmLocalAllRoutersMulticastAddress = { + {{{0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02}}}, + &Netif::kLinkLocalAllNodesMulticastAddress}; // "ff02:02" -const otNetifMulticastAddress Netif::kLinkLocalAllRoutersMulticastAddress = -{ - {{{ 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02 }}}, - &Netif::kRealmLocalAllRoutersMulticastAddress -}; +const otNetifMulticastAddress Netif::kLinkLocalAllRoutersMulticastAddress = { + {{{0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02}}}, + &Netif::kRealmLocalAllRoutersMulticastAddress}; - -Netif::Netif(Instance &aInstance, int8_t aInterfaceId): - InstanceLocator(aInstance), - mUnicastAddresses(NULL), - mMulticastAddresses(NULL), - mInterfaceId(aInterfaceId), - mMulticastPromiscuous(false), - mNext(NULL) +Netif::Netif(Instance &aInstance, int8_t aInterfaceId) + : InstanceLocator(aInstance) + , mUnicastAddresses(NULL) + , mMulticastAddresses(NULL) + , mInterfaceId(aInterfaceId) + , mMulticastPromiscuous(false) + , mNext(NULL) { for (size_t i = 0; i < sizeof(mExtUnicastAddresses) / sizeof(mExtUnicastAddresses[0]); i++) { @@ -112,7 +101,7 @@ Netif::Netif(Instance &aInstance, int8_t aInterfaceId): } mMulticastAddresses = static_cast( - const_cast(&kLinkLocalAllNodesMulticastAddress)); + const_cast(&kLinkLocalAllNodesMulticastAddress)); } bool Netif::IsMulticastSubscribed(const Address &aAddress) const @@ -138,7 +127,7 @@ otError Netif::SubscribeAllRoutersMulticast(void) if (mMulticastAddresses == &kLinkLocalAllNodesMulticastAddress) { mMulticastAddresses = static_cast( - const_cast(&kLinkLocalAllRoutersMulticastAddress)); + const_cast(&kLinkLocalAllRoutersMulticastAddress)); } else { @@ -170,7 +159,7 @@ otError Netif::UnsubscribeAllRoutersMulticast(void) if (mMulticastAddresses == &kLinkLocalAllRoutersMulticastAddress) { mMulticastAddresses = static_cast( - const_cast(&kLinkLocalAllNodesMulticastAddress)); + const_cast(&kLinkLocalAllNodesMulticastAddress)); ExitNow(); } @@ -195,7 +184,6 @@ exit: return error; } - otError Netif::SubscribeMulticast(NetifMulticastAddress &aAddress) { otError error = OT_ERROR_NONE; @@ -208,7 +196,7 @@ otError Netif::SubscribeMulticast(NetifMulticastAddress &aAddress) } } - aAddress.mNext = mMulticastAddresses; + aAddress.mNext = mMulticastAddresses; mMulticastAddresses = &aAddress; GetNotifier().SetFlags(OT_CHANGED_IP6_MULTICAST_SUBSRCRIBED); @@ -251,8 +239,8 @@ exit: otError Netif::GetNextExternalMulticast(uint8_t &aIterator, Address &aAddress) { - otError error = OT_ERROR_NOT_FOUND; - size_t num = sizeof(mExtMulticastAddresses) / sizeof(mExtMulticastAddresses[0]); + otError error = OT_ERROR_NOT_FOUND; + size_t num = sizeof(mExtMulticastAddresses) / sizeof(mExtMulticastAddresses[0]); NetifMulticastAddress *entry; VerifyOrExit(aIterator < num); @@ -265,7 +253,7 @@ otError Netif::GetNextExternalMulticast(uint8_t &aIterator, Address &aAddress) // In an unused/available entry, `mNext` points back to the entry itself. if (entry->mNext != entry) { - aAddress = entry->GetAddress(); + aAddress = entry->GetAddress(); aIterator = i + 1; ExitNow(error = OT_ERROR_NONE); } @@ -277,9 +265,9 @@ exit: otError Netif::SubscribeExternalMulticast(const Address &aAddress) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; NetifMulticastAddress *entry; - size_t num = sizeof(mExtMulticastAddresses) / sizeof(mExtMulticastAddresses[0]); + size_t num = sizeof(mExtMulticastAddresses) / sizeof(mExtMulticastAddresses[0]); if (IsMulticastSubscribed(aAddress)) { @@ -299,8 +287,8 @@ otError Netif::SubscribeExternalMulticast(const Address &aAddress) VerifyOrExit(num > 0, error = OT_ERROR_NO_BUFS); // Copy the address into the available entry and add it to linked-list. - entry->mAddress = aAddress; - entry->mNext = mMulticastAddresses; + entry->mAddress = aAddress; + entry->mNext = mMulticastAddresses; mMulticastAddresses = entry; GetNotifier().SetFlags(OT_CHANGED_IP6_MULTICAST_SUBSRCRIBED); @@ -310,10 +298,10 @@ exit: otError Netif::UnsubscribeExternalMulticast(const Address &aAddress) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; NetifMulticastAddress *entry; NetifMulticastAddress *last = NULL; - size_t num = sizeof(mExtMulticastAddresses) / sizeof(mExtMulticastAddresses[0]); + size_t num = sizeof(mExtMulticastAddresses) / sizeof(mExtMulticastAddresses[0]); for (entry = mMulticastAddresses; entry; entry = entry->GetNext()) { @@ -374,7 +362,7 @@ otError Netif::AddUnicastAddress(NetifUnicastAddress &aAddress) } } - aAddress.mNext = mUnicastAddresses; + aAddress.mNext = mUnicastAddresses; mUnicastAddresses = &aAddress; GetNotifier().SetFlags(aAddress.mRloc ? OT_CHANGED_THREAD_RLOC_ADDED : OT_CHANGED_IP6_ADDRESS_ADDED); @@ -410,8 +398,7 @@ exit: if (error != OT_ERROR_NOT_FOUND) { - GetNotifier().SetFlags(aAddress.mRloc ? - OT_CHANGED_THREAD_RLOC_REMOVED : OT_CHANGED_IP6_ADDRESS_REMOVED); + GetNotifier().SetFlags(aAddress.mRloc ? OT_CHANGED_THREAD_RLOC_REMOVED : OT_CHANGED_IP6_ADDRESS_REMOVED); } return error; @@ -419,9 +406,9 @@ exit: otError Netif::AddExternalUnicastAddress(const NetifUnicastAddress &aAddress) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; NetifUnicastAddress *entry; - size_t num = sizeof(mExtUnicastAddresses) / sizeof(mExtUnicastAddresses[0]); + size_t num = sizeof(mExtUnicastAddresses) / sizeof(mExtUnicastAddresses[0]); for (entry = mUnicastAddresses; entry; entry = entry->GetNext()) { @@ -431,8 +418,8 @@ otError Netif::AddExternalUnicastAddress(const NetifUnicastAddress &aAddress) error = OT_ERROR_INVALID_ARGS); entry->mPrefixLength = aAddress.mPrefixLength; - entry->mPreferred = aAddress.mPreferred; - entry->mValid = aAddress.mValid; + entry->mPreferred = aAddress.mPreferred; + entry->mValid = aAddress.mValid; ExitNow(); } } @@ -450,8 +437,8 @@ otError Netif::AddExternalUnicastAddress(const NetifUnicastAddress &aAddress) VerifyOrExit(num > 0, error = OT_ERROR_NO_BUFS); // Copy the new address into the available entry and insert it in linked-list. - *entry = aAddress; - entry->mNext = mUnicastAddresses; + *entry = aAddress; + entry->mNext = mUnicastAddresses; mUnicastAddresses = entry; GetNotifier().SetFlags(OT_CHANGED_IP6_ADDRESS_ADDED); @@ -462,10 +449,10 @@ exit: otError Netif::RemoveExternalUnicastAddress(const Address &aAddress) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; NetifUnicastAddress *entry; NetifUnicastAddress *last = NULL; - size_t num = sizeof(mExtUnicastAddresses) / sizeof(mExtUnicastAddresses[0]); + size_t num = sizeof(mExtUnicastAddresses) / sizeof(mExtUnicastAddresses[0]); for (entry = mUnicastAddresses; entry; entry = entry->GetNext()) { @@ -530,5 +517,5 @@ exit: return rval; } -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot diff --git a/src/core/net/netif.hpp b/src/core/net/netif.hpp index 68be50351..f52c8613f 100644 --- a/src/core/net/netif.hpp +++ b/src/core/net/netif.hpp @@ -64,7 +64,7 @@ class Ip6; */ class LinkAddress { -public : +public: /** * Hardware types. * @@ -73,16 +73,16 @@ public : { kEui64 = 27, }; - HardwareType mType; ///< Link address type. - uint8_t mLength; ///< Length of link address. - Mac::ExtAddress mExtAddress; ///< Link address. + HardwareType mType; ///< Link address type. + uint8_t mLength; ///< Length of link address. + Mac::ExtAddress mExtAddress; ///< Link address. }; /** * This class implements an IPv6 network interface unicast address. * */ -class NetifUnicastAddress: public otNetifAddress +class NetifUnicastAddress : public otNetifAddress { friend class Netif; @@ -109,7 +109,8 @@ public: * @returns The IPv6 scope value. * */ - uint8_t GetScope(void) const { + uint8_t GetScope(void) const + { return mScopeOverrideValid ? static_cast(mScopeOverride) : GetAddress().GetScope(); } @@ -134,7 +135,7 @@ public: * This class implements an IPv6 network interface multicast address. * */ -class NetifMulticastAddress: public otNetifMulticastAddress +class NetifMulticastAddress : public otNetifMulticastAddress { friend class Netif; @@ -169,7 +170,8 @@ public: * @returns A pointer to the next multicast address. * */ - NetifMulticastAddress *GetNext(void) { + NetifMulticastAddress *GetNext(void) + { return static_cast(const_cast(mNext)); } }; @@ -178,7 +180,7 @@ public: * This class implements an IPv6 network interface. * */ -class Netif: public InstanceLocator +class Netif : public InstanceLocator { friend class Ip6; @@ -429,17 +431,16 @@ public: * @retval OT_ERROR_NO_ROUTE No route to destination. * */ - virtual otError RouteLookup(const Address &aSource, const Address &aDestination, - uint8_t *aPrefixMatch) = 0; + virtual otError RouteLookup(const Address &aSource, const Address &aDestination, uint8_t *aPrefixMatch) = 0; private: - NetifUnicastAddress *mUnicastAddresses; + NetifUnicastAddress * mUnicastAddresses; NetifMulticastAddress *mMulticastAddresses; - int8_t mInterfaceId; - bool mMulticastPromiscuous; - Netif *mNext; + int8_t mInterfaceId; + bool mMulticastPromiscuous; + Netif * mNext; - NetifUnicastAddress mExtUnicastAddresses[OPENTHREAD_CONFIG_MAX_EXT_IP_ADDRS]; + NetifUnicastAddress mExtUnicastAddresses[OPENTHREAD_CONFIG_MAX_EXT_IP_ADDRS]; NetifMulticastAddress mExtMulticastAddresses[OPENTHREAD_CONFIG_MAX_EXT_MULTICAST_IP_ADDRS]; static const otNetifMulticastAddress kRealmLocalAllMplForwardersMulticastAddress; @@ -454,7 +455,7 @@ private: * */ -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot -#endif // NET_NETIF_HPP_ +#endif // NET_NETIF_HPP_ diff --git a/src/core/net/socket.hpp b/src/core/net/socket.hpp index c768cc36b..c250526d3 100644 --- a/src/core/net/socket.hpp +++ b/src/core/net/socket.hpp @@ -54,7 +54,7 @@ namespace Ip6 { * This class implements message information for an IPv6 message. * */ -class MessageInfo: public otMessageInfo +class MessageInfo : public otMessageInfo { public: /** @@ -69,7 +69,7 @@ public: * @returns A reference to the local socket address. * */ - const Address &GetSockAddr(void) const { return *static_cast(&mSockAddr);} + const Address &GetSockAddr(void) const { return *static_cast(&mSockAddr); } /** * This method sets the local socket address. @@ -101,7 +101,7 @@ public: * @returns A reference to the peer socket address. * */ - Address &GetPeerAddr(void) { return *static_cast
(&mPeerAddr);} + Address &GetPeerAddr(void) { return *static_cast
(&mPeerAddr); } /** * This method returns a reference to the peer socket address. @@ -109,7 +109,7 @@ public: * @returns A reference to the peer socket address. * */ - const Address &GetPeerAddr(void) const { return *static_cast(&mPeerAddr);} + const Address &GetPeerAddr(void) const { return *static_cast(&mPeerAddr); } /** * This method sets the peer's socket address. @@ -188,7 +188,7 @@ public: * This class implements a socket address. * */ -class SockAddr: public otSockAddr +class SockAddr : public otSockAddr { public: /** @@ -218,7 +218,7 @@ public: * @} */ -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot -#endif // NET_SOCKET_HPP_ +#endif // NET_SOCKET_HPP_ diff --git a/src/core/net/tcp.hpp b/src/core/net/tcp.hpp index ec51739b6..3acd2a85f 100644 --- a/src/core/net/tcp.hpp +++ b/src/core/net/tcp.hpp @@ -71,7 +71,7 @@ struct TcpHeaderPoD * */ OT_TOOL_PACKED_BEGIN -class TcpHeader: private TcpHeaderPoD +class TcpHeader : private TcpHeaderPoD { public: /** @@ -145,7 +145,7 @@ public: * */ -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot -#endif // TCP_HPP_ +#endif // TCP_HPP_ diff --git a/src/core/net/udp6.cpp b/src/core/net/udp6.cpp index dc8a10346..770feaa56 100644 --- a/src/core/net/udp6.cpp +++ b/src/core/net/udp6.cpp @@ -97,9 +97,9 @@ exit: otError UdpSocket::SendTo(Message &aMessage, const MessageInfo &aMessageInfo) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; MessageInfo messageInfoLocal; - UdpHeader udpHeader; + UdpHeader udpHeader; messageInfoLocal = aMessageInfo; @@ -139,10 +139,10 @@ exit: return error; } -Udp::Udp(Instance &aInstance): - InstanceLocator(aInstance), - mEphemeralPort(kDynamicPortMin), - mSockets(NULL) +Udp::Udp(Instance &aInstance) + : InstanceLocator(aInstance) + , mEphemeralPort(kDynamicPortMin) + , mSockets(NULL) { } @@ -214,10 +214,10 @@ otError Udp::SendDatagram(Message &aMessage, MessageInfo &aMessageInfo, IpProto otError Udp::HandleMessage(Message &aMessage, MessageInfo &aMessageInfo) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; UdpHeader udpHeader; - uint16_t payloadLength; - uint16_t checksum; + uint16_t payloadLength; + uint16_t checksum; payloadLength = aMessage.GetLength() - aMessage.GetOffset(); @@ -225,8 +225,8 @@ otError Udp::HandleMessage(Message &aMessage, MessageInfo &aMessageInfo) VerifyOrExit(payloadLength >= sizeof(UdpHeader), error = OT_ERROR_PARSE); // verify checksum - checksum = Ip6::ComputePseudoheaderChecksum(aMessageInfo.GetPeerAddr(), aMessageInfo.GetSockAddr(), - payloadLength, kProtoUdp); + checksum = Ip6::ComputePseudoheaderChecksum(aMessageInfo.GetPeerAddr(), aMessageInfo.GetSockAddr(), payloadLength, + kProtoUdp); checksum = aMessage.UpdateChecksum(checksum, aMessage.GetOffset(), payloadLength); #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION @@ -247,14 +247,12 @@ otError Udp::HandleMessage(Message &aMessage, MessageInfo &aMessageInfo) continue; } - if (socket->GetSockName().mScopeId != 0 && - socket->GetSockName().mScopeId != aMessageInfo.mInterfaceId) + if (socket->GetSockName().mScopeId != 0 && socket->GetSockName().mScopeId != aMessageInfo.mInterfaceId) { continue; } - if (!aMessageInfo.GetSockAddr().IsMulticast() && - !socket->GetSockName().GetAddress().IsUnspecified() && + if (!aMessageInfo.GetSockAddr().IsMulticast() && !socket->GetSockName().GetAddress().IsUnspecified() && socket->GetSockName().GetAddress() != aMessageInfo.GetSockAddr()) { continue; @@ -296,5 +294,5 @@ otError Udp::UpdateChecksum(Message &aMessage, uint16_t aChecksum) return OT_ERROR_NONE; } -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot diff --git a/src/core/net/udp6.hpp b/src/core/net/udp6.hpp index bcce9fa93..d8db11a05 100644 --- a/src/core/net/udp6.hpp +++ b/src/core/net/udp6.hpp @@ -60,7 +60,7 @@ class Udp; * This class implements a UDP/IPv6 socket. * */ -class UdpSocket: public otUdpSocket +class UdpSocket : public otUdpSocket { friend class Udp; @@ -153,9 +153,10 @@ public: private: UdpSocket *GetNext(void) { return static_cast(mNext); } - void SetNext(UdpSocket *socket) { mNext = static_cast(socket); } + void SetNext(UdpSocket *socket) { mNext = static_cast(socket); } - void HandleUdpReceive(Message &aMessage, const MessageInfo &aMessageInfo) { + void HandleUdpReceive(Message &aMessage, const MessageInfo &aMessageInfo) + { mHandler(mContext, &aMessage, &aMessageInfo); } }; @@ -164,7 +165,7 @@ private: * This class implements core UDP message handling. * */ -class Udp: public InstanceLocator +class Udp : public InstanceLocator { friend class UdpSocket; @@ -255,10 +256,10 @@ public: private: enum { - kDynamicPortMin = 49152, ///< Service Name and Transport Protocol Port Number Registry - kDynamicPortMax = 65535, ///< Service Name and Transport Protocol Port Number Registry + kDynamicPortMin = 49152, ///< Service Name and Transport Protocol Port Number Registry + kDynamicPortMax = 65535, ///< Service Name and Transport Protocol Port Number Registry }; - uint16_t mEphemeralPort; + uint16_t mEphemeralPort; UdpSocket *mSockets; }; @@ -276,7 +277,7 @@ struct UdpHeaderPoD * */ OT_TOOL_PACKED_BEGIN -class UdpHeader: private UdpHeaderPoD +class UdpHeader : private UdpHeaderPoD { public: /** @@ -366,7 +367,7 @@ public: * */ -} // namespace Ip6 -} // namespace ot +} // namespace Ip6 +} // namespace ot -#endif // NET_UDP6_HPP_ +#endif // NET_UDP6_HPP_ diff --git a/src/core/openthread-core-config.h b/src/core/openthread-core-config.h index 89668914c..9fd0a88b8 100644 --- a/src/core/openthread-core-config.h +++ b/src/core/openthread-core-config.h @@ -46,5 +46,4 @@ #undef OPENTHREAD_CORE_CONFIG_H_IN -#endif // OPENTHREAD_CORE_CONFIG_H_ - +#endif // OPENTHREAD_CORE_CONFIG_H_ diff --git a/src/core/openthread-core-default-config.h b/src/core/openthread-core-default-config.h index f82bdd347..5a38f4b9a 100644 --- a/src/core/openthread-core-default-config.h +++ b/src/core/openthread-core-default-config.h @@ -42,7 +42,7 @@ * */ #ifndef OPENTHREAD_CONFIG_STACK_VENDOR_OUI -#define OPENTHREAD_CONFIG_STACK_VENDOR_OUI 0x18b430 +#define OPENTHREAD_CONFIG_STACK_VENDOR_OUI 0x18b430 #endif /** @@ -52,7 +52,7 @@ * */ #ifndef OPENTHREAD_CONFIG_STACK_VERSION_REV -#define OPENTHREAD_CONFIG_STACK_VERSION_REV 0 +#define OPENTHREAD_CONFIG_STACK_VERSION_REV 0 #endif /** @@ -62,7 +62,7 @@ * */ #ifndef OPENTHREAD_CONFIG_STACK_VERSION_MAJOR -#define OPENTHREAD_CONFIG_STACK_VERSION_MAJOR 0 +#define OPENTHREAD_CONFIG_STACK_VERSION_MAJOR 0 #endif /** @@ -72,7 +72,7 @@ * */ #ifndef OPENTHREAD_CONFIG_STACK_VERSION_MINOR -#define OPENTHREAD_CONFIG_STACK_VERSION_MINOR 1 +#define OPENTHREAD_CONFIG_STACK_VERSION_MINOR 1 #endif /** @@ -82,7 +82,7 @@ * */ #ifndef OPENTHREAD_CONFIG_PLATFORM_INFO -#define OPENTHREAD_CONFIG_PLATFORM_INFO "NONE" +#define OPENTHREAD_CONFIG_PLATFORM_INFO "NONE" #endif /** @@ -92,7 +92,7 @@ * */ #ifndef OPENTHREAD_CONFIG_NUM_MESSAGE_BUFFERS -#define OPENTHREAD_CONFIG_NUM_MESSAGE_BUFFERS 40 +#define OPENTHREAD_CONFIG_NUM_MESSAGE_BUFFERS 40 #endif /** @@ -102,7 +102,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MESSAGE_BUFFER_SIZE -#define OPENTHREAD_CONFIG_MESSAGE_BUFFER_SIZE 128 +#define OPENTHREAD_CONFIG_MESSAGE_BUFFER_SIZE 128 #endif /** @@ -112,7 +112,7 @@ * */ #ifndef OPENTHREAD_CONFIG_DEFAULT_CHANNEL -#define OPENTHREAD_CONFIG_DEFAULT_CHANNEL 11 +#define OPENTHREAD_CONFIG_DEFAULT_CHANNEL 11 #endif /** @@ -122,7 +122,7 @@ * */ #ifndef OPENTHREAD_CONFIG_DEFAULT_TRANSMIT_POWER -#define OPENTHREAD_CONFIG_DEFAULT_TRANSMIT_POWER 0 +#define OPENTHREAD_CONFIG_DEFAULT_TRANSMIT_POWER 0 #endif /** @@ -133,7 +133,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MAX_TX_ATTEMPTS_DIRECT -#define OPENTHREAD_CONFIG_MAX_TX_ATTEMPTS_DIRECT 4 +#define OPENTHREAD_CONFIG_MAX_TX_ATTEMPTS_DIRECT 4 #endif /** @@ -144,7 +144,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MAX_TX_ATTEMPTS_INDIRECT_PER_POLL -#define OPENTHREAD_CONFIG_MAX_TX_ATTEMPTS_INDIRECT_PER_POLL 1 +#define OPENTHREAD_CONFIG_MAX_TX_ATTEMPTS_INDIRECT_PER_POLL 1 #endif /** @@ -156,7 +156,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MAX_TX_ATTEMPTS_INDIRECT_POLLS -#define OPENTHREAD_CONFIG_MAX_TX_ATTEMPTS_INDIRECT_POLLS 4 +#define OPENTHREAD_CONFIG_MAX_TX_ATTEMPTS_INDIRECT_POLLS 4 #endif /** @@ -172,7 +172,7 @@ * */ #ifndef OPENTHREAD_CONFIG_DROP_MESSAGE_ON_FRAGMENT_TX_FAILURE -#define OPENTHREAD_CONFIG_DROP_MESSAGE_ON_FRAGMENT_TX_FAILURE 1 +#define OPENTHREAD_CONFIG_DROP_MESSAGE_ON_FRAGMENT_TX_FAILURE 1 #endif /** @@ -182,7 +182,7 @@ * */ #ifndef OPENTHREAD_CONFIG_ATTACH_DATA_POLL_PERIOD -#define OPENTHREAD_CONFIG_ATTACH_DATA_POLL_PERIOD 100 +#define OPENTHREAD_CONFIG_ATTACH_DATA_POLL_PERIOD 100 #endif /** @@ -192,7 +192,7 @@ * */ #ifndef OPENTHREAD_CONFIG_ADDRESS_CACHE_ENTRIES -#define OPENTHREAD_CONFIG_ADDRESS_CACHE_ENTRIES 10 +#define OPENTHREAD_CONFIG_ADDRESS_CACHE_ENTRIES 10 #endif /** @@ -204,7 +204,7 @@ * */ #ifndef OPENTHREAD_CONFIG_ADDRESS_QUERY_TIMEOUT -#define OPENTHREAD_CONFIG_ADDRESS_QUERY_TIMEOUT 3 +#define OPENTHREAD_CONFIG_ADDRESS_QUERY_TIMEOUT 3 #endif /** @@ -216,7 +216,7 @@ * */ #ifndef OPENTHREAD_CONFIG_ADDRESS_QUERY_INITIAL_RETRY_DELAY -#define OPENTHREAD_CONFIG_ADDRESS_QUERY_INITIAL_RETRY_DELAY 15 +#define OPENTHREAD_CONFIG_ADDRESS_QUERY_INITIAL_RETRY_DELAY 15 #endif /** @@ -228,7 +228,7 @@ * */ #ifndef OPENTHREAD_CONFIG_ADDRESS_QUERY_MAX_RETRY_DELAY -#define OPENTHREAD_CONFIG_ADDRESS_QUERY_MAX_RETRY_DELAY 28800 +#define OPENTHREAD_CONFIG_ADDRESS_QUERY_MAX_RETRY_DELAY 28800 #endif /** @@ -238,7 +238,7 @@ * */ #ifndef OPENTHREAD_CONFIG_CLI_MAX_LINE_LENGTH -#define OPENTHREAD_CONFIG_CLI_MAX_LINE_LENGTH 128 +#define OPENTHREAD_CONFIG_CLI_MAX_LINE_LENGTH 128 #endif /** @@ -248,7 +248,7 @@ * */ #ifndef OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE -#define OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE 512 +#define OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE 512 #endif /** @@ -258,7 +258,7 @@ * */ #ifndef OPENTHREAD_CONFIG_CLI_UART_TX_BUFFER_SIZE -#define OPENTHREAD_CONFIG_CLI_UART_TX_BUFFER_SIZE 1024 +#define OPENTHREAD_CONFIG_CLI_UART_TX_BUFFER_SIZE 1024 #endif /** @@ -268,7 +268,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MAX_CHILDREN -#define OPENTHREAD_CONFIG_MAX_CHILDREN 10 +#define OPENTHREAD_CONFIG_MAX_CHILDREN 10 #endif /** @@ -278,7 +278,7 @@ * */ #ifndef OPENTHREAD_CONFIG_DEFAULT_CHILD_TIMEOUT -#define OPENTHREAD_CONFIG_DEFAULT_CHILD_TIMEOUT 240 +#define OPENTHREAD_CONFIG_DEFAULT_CHILD_TIMEOUT 240 #endif /** @@ -288,7 +288,7 @@ * */ #ifndef OPENTHREAD_CONFIG_IP_ADDRS_PER_CHILD -#define OPENTHREAD_CONFIG_IP_ADDRS_PER_CHILD 4 +#define OPENTHREAD_CONFIG_IP_ADDRS_PER_CHILD 4 #endif /** @@ -298,7 +298,7 @@ * */ #ifndef OPENTHREAD_CONFIG_IP_ADDRS_TO_REGISTER -#define OPENTHREAD_CONFIG_IP_ADDRS_TO_REGISTER (OPENTHREAD_CONFIG_IP_ADDRS_PER_CHILD) +#define OPENTHREAD_CONFIG_IP_ADDRS_TO_REGISTER (OPENTHREAD_CONFIG_IP_ADDRS_PER_CHILD) #endif /** @@ -308,7 +308,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MAX_EXT_IP_ADDRS -#define OPENTHREAD_CONFIG_MAX_EXT_IP_ADDRS 4 +#define OPENTHREAD_CONFIG_MAX_EXT_IP_ADDRS 4 #endif /** @@ -318,7 +318,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MAX_EXT_MULTICAST_IP_ADDRS -#define OPENTHREAD_CONFIG_MAX_EXT_MULTICAST_IP_ADDRS 2 +#define OPENTHREAD_CONFIG_MAX_EXT_MULTICAST_IP_ADDRS 2 #endif /** @@ -328,7 +328,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MAX_SERVER_ALOCS -#define OPENTHREAD_CONFIG_MAX_SERVER_ALOCS 1 +#define OPENTHREAD_CONFIG_MAX_SERVER_ALOCS 1 #endif /** @@ -338,7 +338,7 @@ * */ #ifndef OPENTHREAD_CONFIG_6LOWPAN_REASSEMBLY_TIMEOUT -#define OPENTHREAD_CONFIG_6LOWPAN_REASSEMBLY_TIMEOUT 5 +#define OPENTHREAD_CONFIG_6LOWPAN_REASSEMBLY_TIMEOUT 5 #endif /** @@ -348,7 +348,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MPL_SEED_SET_ENTRIES -#define OPENTHREAD_CONFIG_MPL_SEED_SET_ENTRIES 32 +#define OPENTHREAD_CONFIG_MPL_SEED_SET_ENTRIES 32 #endif /** @@ -358,7 +358,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MPL_SEED_SET_ENTRY_LIFETIME -#define OPENTHREAD_CONFIG_MPL_SEED_SET_ENTRY_LIFETIME 5 +#define OPENTHREAD_CONFIG_MPL_SEED_SET_ENTRY_LIFETIME 5 #endif /** @@ -368,7 +368,7 @@ * */ #ifndef OPENTHREAD_CONFIG_JOINER_UDP_PORT -#define OPENTHREAD_CONFIG_JOINER_UDP_PORT 1000 +#define OPENTHREAD_CONFIG_JOINER_UDP_PORT 1000 #endif /** @@ -378,7 +378,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MAX_ENERGY_RESULTS -#define OPENTHREAD_CONFIG_MAX_ENERGY_RESULTS 64 +#define OPENTHREAD_CONFIG_MAX_ENERGY_RESULTS 64 #endif /** @@ -388,7 +388,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MAX_JOINER_ENTRIES -#define OPENTHREAD_CONFIG_MAX_JOINER_ENTRIES 2 +#define OPENTHREAD_CONFIG_MAX_JOINER_ENTRIES 2 #endif /** @@ -398,7 +398,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MAX_JOINER_ROUTER_ENTRIES -#define OPENTHREAD_CONFIG_MAX_JOINER_ROUTER_ENTRIES 2 +#define OPENTHREAD_CONFIG_MAX_JOINER_ROUTER_ENTRIES 2 #endif /** @@ -408,7 +408,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MAX_STATECHANGE_HANDLERS -#define OPENTHREAD_CONFIG_MAX_STATECHANGE_HANDLERS 1 +#define OPENTHREAD_CONFIG_MAX_STATECHANGE_HANDLERS 1 #endif /** @@ -418,7 +418,7 @@ * */ #ifndef OPENTHREAD_CONFIG_COAP_ACK_TIMEOUT -#define OPENTHREAD_CONFIG_COAP_ACK_TIMEOUT 2 +#define OPENTHREAD_CONFIG_COAP_ACK_TIMEOUT 2 #endif /** @@ -429,7 +429,7 @@ * */ #ifndef OPENTHREAD_CONFIG_COAP_ACK_RANDOM_FACTOR_NUMERATOR -#define OPENTHREAD_CONFIG_COAP_ACK_RANDOM_FACTOR_NUMERATOR 3 +#define OPENTHREAD_CONFIG_COAP_ACK_RANDOM_FACTOR_NUMERATOR 3 #endif /** @@ -440,7 +440,7 @@ * */ #ifndef OPENTHREAD_CONFIG_COAP_ACK_RANDOM_FACTOR_DENOMINATOR -#define OPENTHREAD_CONFIG_COAP_ACK_RANDOM_FACTOR_DENOMINATOR 2 +#define OPENTHREAD_CONFIG_COAP_ACK_RANDOM_FACTOR_DENOMINATOR 2 #endif /** @@ -450,7 +450,7 @@ * */ #ifndef OPENTHREAD_CONFIG_COAP_MAX_RETRANSMIT -#define OPENTHREAD_CONFIG_COAP_MAX_RETRANSMIT 4 +#define OPENTHREAD_CONFIG_COAP_MAX_RETRANSMIT 4 #endif /** @@ -462,7 +462,7 @@ * */ #ifndef OPENTHREAD_CONFIG_COAP_SERVER_MAX_CACHED_RESPONSES -#define OPENTHREAD_CONFIG_COAP_SERVER_MAX_CACHED_RESPONSES 10 +#define OPENTHREAD_CONFIG_COAP_SERVER_MAX_CACHED_RESPONSES 10 #endif /** @@ -472,7 +472,7 @@ * */ #ifndef OPENTHREAD_CONFIG_DNS_RESPONSE_TIMEOUT -#define OPENTHREAD_CONFIG_DNS_RESPONSE_TIMEOUT 3000 +#define OPENTHREAD_CONFIG_DNS_RESPONSE_TIMEOUT 3000 #endif /** @@ -482,7 +482,7 @@ * */ #ifndef OPENTHREAD_CONFIG_DNS_MAX_RETRANSMIT -#define OPENTHREAD_CONFIG_DNS_MAX_RETRANSMIT 2 +#define OPENTHREAD_CONFIG_DNS_MAX_RETRANSMIT 2 #endif /** @@ -492,7 +492,7 @@ * */ #ifndef OPENTHREAD_CONFIG_JOIN_BEACON_VERSION -#define OPENTHREAD_CONFIG_JOIN_BEACON_VERSION kProtocolVersion +#define OPENTHREAD_CONFIG_JOIN_BEACON_VERSION kProtocolVersion #endif /** @@ -504,7 +504,7 @@ * */ #ifndef OPENTHREAD_CONFIG_PLATFORM_MESSAGE_MANAGEMENT -#define OPENTHREAD_CONFIG_PLATFORM_MESSAGE_MANAGEMENT 0 +#define OPENTHREAD_CONFIG_PLATFORM_MESSAGE_MANAGEMENT 0 #endif /** @@ -514,7 +514,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MAC_FILTER_SIZE -#define OPENTHREAD_CONFIG_MAC_FILTER_SIZE 32 +#define OPENTHREAD_CONFIG_MAC_FILTER_SIZE 32 #endif /** @@ -524,7 +524,7 @@ * */ #ifndef OPENTHREAD_CONFIG_STORE_FRAME_COUNTER_AHEAD -#define OPENTHREAD_CONFIG_STORE_FRAME_COUNTER_AHEAD 1000 +#define OPENTHREAD_CONFIG_STORE_FRAME_COUNTER_AHEAD 1000 #endif /** @@ -547,17 +547,17 @@ * */ #ifndef OPENTHREAD_CONFIG_LOG_OUTPUT -#define OPENTHREAD_CONFIG_LOG_OUTPUT OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED +#define OPENTHREAD_CONFIG_LOG_OUTPUT OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED #endif /** Log output goes to the bit bucket (disabled) */ -#define OPENTHREAD_CONFIG_LOG_OUTPUT_NONE 0 +#define OPENTHREAD_CONFIG_LOG_OUTPUT_NONE 0 /** Log output goes to the debug uart - requires OPENTHREAD_CONFIG_ENABLE_DEBUG_UART to be enabled */ -#define OPENTHREAD_CONFIG_LOG_OUTPUT_DEBUG_UART 1 +#define OPENTHREAD_CONFIG_LOG_OUTPUT_DEBUG_UART 1 /** Log output goes to the "application" provided otPlatLog() in NCP and CLI code */ -#define OPENTHREAD_CONFIG_LOG_OUTPUT_APP 2 +#define OPENTHREAD_CONFIG_LOG_OUTPUT_APP 2 /** Log output is handled by a platform defined function */ -#define OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED 3 +#define OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED 3 /** * @def OPENTHREAD_CONFIG_LOG_LEVEL @@ -566,7 +566,7 @@ * */ #ifndef OPENTHREAD_CONFIG_LOG_LEVEL -#define OPENTHREAD_CONFIG_LOG_LEVEL OT_LOG_LEVEL_CRIT +#define OPENTHREAD_CONFIG_LOG_LEVEL OT_LOG_LEVEL_CRIT #endif /** @@ -580,7 +580,7 @@ * */ #ifndef OPENTHREAD_CONFIG_ENABLE_DYNAMIC_LOG_LEVEL -#define OPENTHREAD_CONFIG_ENABLE_DYNAMIC_LOG_LEVEL 0 +#define OPENTHREAD_CONFIG_ENABLE_DYNAMIC_LOG_LEVEL 0 #endif /** @@ -590,7 +590,7 @@ * */ #ifndef OPENTHREAD_CONFIG_LOG_API -#define OPENTHREAD_CONFIG_LOG_API 1 +#define OPENTHREAD_CONFIG_LOG_API 1 #endif /** @@ -600,7 +600,7 @@ * */ #ifndef OPENTHREAD_CONFIG_LOG_MLE -#define OPENTHREAD_CONFIG_LOG_MLE 1 +#define OPENTHREAD_CONFIG_LOG_MLE 1 #endif /** @@ -610,7 +610,7 @@ * */ #ifndef OPENTHREAD_CONFIG_LOG_ARP -#define OPENTHREAD_CONFIG_LOG_ARP 1 +#define OPENTHREAD_CONFIG_LOG_ARP 1 #endif /** @@ -620,7 +620,7 @@ * */ #ifndef OPENTHREAD_CONFIG_LOG_NETDATA -#define OPENTHREAD_CONFIG_LOG_NETDATA 1 +#define OPENTHREAD_CONFIG_LOG_NETDATA 1 #endif /** @@ -630,7 +630,7 @@ * */ #ifndef OPENTHREAD_CONFIG_LOG_ICMP -#define OPENTHREAD_CONFIG_LOG_ICMP 1 +#define OPENTHREAD_CONFIG_LOG_ICMP 1 #endif /** @@ -640,7 +640,7 @@ * */ #ifndef OPENTHREAD_CONFIG_LOG_IP6 -#define OPENTHREAD_CONFIG_LOG_IP6 1 +#define OPENTHREAD_CONFIG_LOG_IP6 1 #endif /** @@ -650,7 +650,7 @@ * */ #ifndef OPENTHREAD_CONFIG_LOG_MAC -#define OPENTHREAD_CONFIG_LOG_MAC 1 +#define OPENTHREAD_CONFIG_LOG_MAC 1 #endif /** @@ -660,7 +660,7 @@ * */ #ifndef OPENTHREAD_CONFIG_LOG_MEM -#define OPENTHREAD_CONFIG_LOG_MEM 1 +#define OPENTHREAD_CONFIG_LOG_MEM 1 #endif /** @@ -670,7 +670,7 @@ * */ #ifndef OPENTHREAD_CONFIG_LOG_PKT_DUMP -#define OPENTHREAD_CONFIG_LOG_PKT_DUMP 1 +#define OPENTHREAD_CONFIG_LOG_PKT_DUMP 1 #endif /** @@ -680,17 +680,17 @@ * */ #ifndef OPENTHREAD_CONFIG_LOG_NETDIAG -#define OPENTHREAD_CONFIG_LOG_NETDIAG 1 +#define OPENTHREAD_CONFIG_LOG_NETDIAG 1 #endif /** -* @def OPENTHREAD_CONFIG_LOG_PLATFORM -* -* Define to enable platform region logging. -* -*/ + * @def OPENTHREAD_CONFIG_LOG_PLATFORM + * + * Define to enable platform region logging. + * + */ #ifndef OPENTHREAD_CONFIG_LOG_PLATFORM -#define OPENTHREAD_CONFIG_LOG_PLATFORM 0 +#define OPENTHREAD_CONFIG_LOG_PLATFORM 0 #endif /** @@ -700,7 +700,7 @@ * */ #ifndef OPENTHREAD_CONFIG_LOG_CLI -#define OPENTHREAD_CONFIG_LOG_CLI 1 +#define OPENTHREAD_CONFIG_LOG_CLI 1 #endif /** @@ -710,7 +710,7 @@ * */ #ifndef OPENTHREAD_CONFIG_LOG_COAP -#define OPENTHREAD_CONFIG_LOG_COAP 1 +#define OPENTHREAD_CONFIG_LOG_COAP 1 #endif /** @@ -720,7 +720,7 @@ * */ #ifndef OPENTHREAD_CONFIG_LOG_CORE -#define OPENTHREAD_CONFIG_LOG_CORE 1 +#define OPENTHREAD_CONFIG_LOG_CORE 1 #endif /** @@ -730,7 +730,7 @@ * */ #ifndef OPENTHREAD_CONFIG_LOG_UTIL -#define OPENTHREAD_CONFIG_LOG_UTIL 1 +#define OPENTHREAD_CONFIG_LOG_UTIL 1 #endif /** @@ -740,17 +740,17 @@ * */ #ifndef OPENTHREAD_CONFIG_LOG_PREPEND_LEVEL -#define OPENTHREAD_CONFIG_LOG_PREPEND_LEVEL 1 +#define OPENTHREAD_CONFIG_LOG_PREPEND_LEVEL 1 #endif /** -* @def OPENTHREAD_CONFIG_LOG_PREPEND_REGION -* -* Define to prepend the log region to all log messages -* -*/ + * @def OPENTHREAD_CONFIG_LOG_PREPEND_REGION + * + * Define to prepend the log region to all log messages + * + */ #ifndef OPENTHREAD_CONFIG_LOG_PREPEND_REGION -#define OPENTHREAD_CONFIG_LOG_PREPEND_REGION 1 +#define OPENTHREAD_CONFIG_LOG_PREPEND_REGION 1 #endif /** @@ -760,7 +760,7 @@ * */ #ifndef OPENTHREAD_CONFIG_LOG_SUFFIX -#define OPENTHREAD_CONFIG_LOG_SUFFIX "" +#define OPENTHREAD_CONFIG_LOG_SUFFIX "" #endif /** @@ -770,7 +770,7 @@ * */ #ifndef OPENTHREAD_CONFIG_PLAT_LOG_FUNCTION -#define OPENTHREAD_CONFIG_PLAT_LOG_FUNCTION otPlatLog +#define OPENTHREAD_CONFIG_PLAT_LOG_FUNCTION otPlatLog #endif /** @@ -780,7 +780,7 @@ * */ #ifndef OPENTHREAD_CONFIG_NUM_DHCP_PREFIXES -#define OPENTHREAD_CONFIG_NUM_DHCP_PREFIXES 4 +#define OPENTHREAD_CONFIG_NUM_DHCP_PREFIXES 4 #endif /** @@ -790,7 +790,7 @@ * */ #ifndef OPENTHREAD_CONFIG_NUM_SLAAC_ADDRESSES -#define OPENTHREAD_CONFIG_NUM_SLAAC_ADDRESSES 4 +#define OPENTHREAD_CONFIG_NUM_SLAAC_ADDRESSES 4 #endif /** @@ -800,7 +800,7 @@ * */ #ifndef OPENTHREAD_CONFIG_NCP_TX_BUFFER_SIZE -#define OPENTHREAD_CONFIG_NCP_TX_BUFFER_SIZE 512 +#define OPENTHREAD_CONFIG_NCP_TX_BUFFER_SIZE 512 #endif /** @@ -810,7 +810,7 @@ * */ #ifndef OPENTHREAD_CONFIG_NCP_UART_TX_CHUNK_SIZE -#define OPENTHREAD_CONFIG_NCP_UART_TX_CHUNK_SIZE 128 +#define OPENTHREAD_CONFIG_NCP_UART_TX_CHUNK_SIZE 128 #endif /** @@ -820,7 +820,7 @@ * */ #ifndef OPENTHREAD_CONFIG_NCP_UART_RX_BUFFER_SIZE -#define OPENTHREAD_CONFIG_NCP_UART_RX_BUFFER_SIZE 1300 +#define OPENTHREAD_CONFIG_NCP_UART_RX_BUFFER_SIZE 1300 #endif /** @@ -830,7 +830,7 @@ * */ #ifndef OPENTHREAD_CONFIG_NCP_SPI_BUFFER_SIZE -#define OPENTHREAD_CONFIG_NCP_SPI_BUFFER_SIZE 1300 +#define OPENTHREAD_CONFIG_NCP_SPI_BUFFER_SIZE 1300 #endif /** @@ -841,7 +841,7 @@ * */ #ifndef OPENTHREAD_CONFIG_NCP_SPINEL_ENCRYPTER_EXTRA_DATA_SIZE -#define OPENTHREAD_CONFIG_NCP_SPINEL_ENCRYPTER_EXTRA_DATA_SIZE 0 +#define OPENTHREAD_CONFIG_NCP_SPINEL_ENCRYPTER_EXTRA_DATA_SIZE 0 #endif /** @@ -851,7 +851,7 @@ * */ #ifndef OPENTHREAD_CONFIG_PLATFORM_ASSERT_MANAGEMENT -#define OPENTHREAD_CONFIG_PLATFORM_ASSERT_MANAGEMENT 0 +#define OPENTHREAD_CONFIG_PLATFORM_ASSERT_MANAGEMENT 0 #endif /** @@ -863,7 +863,7 @@ * */ #ifndef OPENTHREAD_CONFIG_ENABLE_SOFTWARE_ACK_TIMEOUT -#define OPENTHREAD_CONFIG_ENABLE_SOFTWARE_ACK_TIMEOUT 0 +#define OPENTHREAD_CONFIG_ENABLE_SOFTWARE_ACK_TIMEOUT 0 #endif /** @@ -875,7 +875,7 @@ * */ #ifndef OPENTHREAD_CONFIG_ENABLE_SOFTWARE_RETRANSMIT -#define OPENTHREAD_CONFIG_ENABLE_SOFTWARE_RETRANSMIT 0 +#define OPENTHREAD_CONFIG_ENABLE_SOFTWARE_RETRANSMIT 0 #endif /** @@ -887,7 +887,7 @@ * */ #ifndef OPENTHREAD_CONFIG_ENABLE_SOFTWARE_ENERGY_SCAN -#define OPENTHREAD_CONFIG_ENABLE_SOFTWARE_ENERGY_SCAN 0 +#define OPENTHREAD_CONFIG_ENABLE_SOFTWARE_ENERGY_SCAN 0 #endif /** @@ -897,7 +897,7 @@ * */ #ifndef OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_TIMER -#define OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_TIMER 0 +#define OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_TIMER 0 #endif /** @@ -907,7 +907,7 @@ * */ #ifndef OPENTHREAD_CONFIG_ENABLE_AUTO_START_SUPPORT -#define OPENTHREAD_CONFIG_ENABLE_AUTO_START_SUPPORT 1 +#define OPENTHREAD_CONFIG_ENABLE_AUTO_START_SUPPORT 1 #endif /** @@ -920,7 +920,7 @@ * */ #ifndef OPENTHREAD_CONFIG_ENABLE_BEACON_RSP_WHEN_JOINABLE -#define OPENTHREAD_CONFIG_ENABLE_BEACON_RSP_WHEN_JOINABLE 0 +#define OPENTHREAD_CONFIG_ENABLE_BEACON_RSP_WHEN_JOINABLE 0 #endif /** @@ -930,7 +930,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MBEDTLS_HEAP_SIZE -#define OPENTHREAD_CONFIG_MBEDTLS_HEAP_SIZE (1536 * sizeof(void *)) +#define OPENTHREAD_CONFIG_MBEDTLS_HEAP_SIZE (1536 * sizeof(void *)) #endif /** @@ -940,7 +940,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MBEDTLS_HEAP_SIZE_NO_DTLS -#define OPENTHREAD_CONFIG_MBEDTLS_HEAP_SIZE_NO_DTLS 384 +#define OPENTHREAD_CONFIG_MBEDTLS_HEAP_SIZE_NO_DTLS 384 #endif /** @@ -950,7 +950,7 @@ * */ #ifndef OPENTHREAD_CONFIG_ENABLE_STEERING_DATA_SET_OOB -#define OPENTHREAD_CONFIG_ENABLE_STEERING_DATA_SET_OOB 0 +#define OPENTHREAD_CONFIG_ENABLE_STEERING_DATA_SET_OOB 0 #endif /** @@ -963,7 +963,7 @@ * */ #ifndef OPENTHREAD_CONFIG_CCA_FAILURE_RATE_AVERAGING_WINDOW -#define OPENTHREAD_CONFIG_CCA_FAILURE_RATE_AVERAGING_WINDOW 512 +#define OPENTHREAD_CONFIG_CCA_FAILURE_RATE_AVERAGING_WINDOW 512 #endif /** @@ -976,7 +976,7 @@ * */ #ifndef OPENTHREAD_CONFIG_ENABLE_TX_ERROR_RATE_TRACKING -#define OPENTHREAD_CONFIG_ENABLE_TX_ERROR_RATE_TRACKING 1 +#define OPENTHREAD_CONFIG_ENABLE_TX_ERROR_RATE_TRACKING 1 #endif /** @@ -991,7 +991,7 @@ * */ #ifndef OPENTHREAD_CONFIG_FRAME_TX_ERR_RATE_AVERAGING_WINDOW -#define OPENTHREAD_CONFIG_FRAME_TX_ERR_RATE_AVERAGING_WINDOW 128 +#define OPENTHREAD_CONFIG_FRAME_TX_ERR_RATE_AVERAGING_WINDOW 128 #endif /** @@ -1006,7 +1006,7 @@ * */ #ifndef OPENTHREAD_CONFIG_IPV6_TX_ERR_RATE_AVERAGING_WINDOW -#define OPENTHREAD_CONFIG_IPV6_TX_ERR_RATE_AVERAGING_WINDOW 128 +#define OPENTHREAD_CONFIG_IPV6_TX_ERR_RATE_AVERAGING_WINDOW 128 #endif /** @@ -1021,7 +1021,7 @@ * */ #ifndef OPENTHREAD_CONFIG_CHANNEL_MONITOR_SAMPLE_INTERVAL -#define OPENTHREAD_CONFIG_CHANNEL_MONITOR_SAMPLE_INTERVAL 41000 +#define OPENTHREAD_CONFIG_CHANNEL_MONITOR_SAMPLE_INTERVAL 41000 #endif /** @@ -1038,7 +1038,7 @@ * */ #ifndef OPENTHREAD_CONFIG_CHANNEL_MONITOR_RSSI_THRESHOLD -#define OPENTHREAD_CONFIG_CHANNEL_MONITOR_RSSI_THRESHOLD -75 +#define OPENTHREAD_CONFIG_CHANNEL_MONITOR_RSSI_THRESHOLD -75 #endif /** @@ -1053,7 +1053,7 @@ * */ #ifndef OPENTHREAD_CONFIG_CHANNEL_MONITOR_SAMPLE_WINDOW -#define OPENTHREAD_CONFIG_CHANNEL_MONITOR_SAMPLE_WINDOW 960 +#define OPENTHREAD_CONFIG_CHANNEL_MONITOR_SAMPLE_WINDOW 960 #endif /** @@ -1068,7 +1068,7 @@ * */ #ifndef OPENTHREAD_CONFIG_CHANNEL_MANAGER_MINIMUM_DELAY -#define OPENTHREAD_CONFIG_CHANNEL_MANAGER_MINIMUM_DELAY 120 +#define OPENTHREAD_CONFIG_CHANNEL_MANAGER_MINIMUM_DELAY 120 #endif /** @@ -1085,7 +1085,7 @@ * */ #ifndef OPENTHREAD_CONFIG_CHILD_SUPERVISION_INTERVAL -#define OPENTHREAD_CONFIG_CHILD_SUPERVISION_INTERVAL 129 +#define OPENTHREAD_CONFIG_CHILD_SUPERVISION_INTERVAL 129 #endif /** @@ -1101,7 +1101,7 @@ * */ #ifndef OPENTHREAD_CONFIG_SUPERVISION_CHECK_TIMEOUT -#define OPENTHREAD_CONFIG_SUPERVISION_CHECK_TIMEOUT 190 +#define OPENTHREAD_CONFIG_SUPERVISION_CHECK_TIMEOUT 190 #endif /** @@ -1113,7 +1113,7 @@ * */ #ifndef OPENTHREAD_CONFIG_SUPERVISION_MSG_NO_ACK_REQUEST -#define OPENTHREAD_CONFIG_SUPERVISION_MSG_NO_ACK_REQUEST 0 +#define OPENTHREAD_CONFIG_SUPERVISION_MSG_NO_ACK_REQUEST 0 #endif /** @@ -1126,7 +1126,7 @@ * */ #ifndef OPENTHREAD_CONFIG_INFORM_PREVIOUS_PARENT_ON_REATTACH -#define OPENTHREAD_CONFIG_INFORM_PREVIOUS_PARENT_ON_REATTACH 0 +#define OPENTHREAD_CONFIG_INFORM_PREVIOUS_PARENT_ON_REATTACH 0 #endif /** @@ -1147,7 +1147,7 @@ * */ #ifndef OPENTHREAD_CONFIG_ENABLE_PERIODIC_PARENT_SEARCH -#define OPENTHREAD_CONFIG_ENABLE_PERIODIC_PARENT_SEARCH 0 +#define OPENTHREAD_CONFIG_ENABLE_PERIODIC_PARENT_SEARCH 0 #endif /** @@ -1159,7 +1159,7 @@ * */ #ifndef OPENTHREAD_CONFIG_PARENT_SEARCH_CHECK_INTERVAL -#define OPENTHREAD_CONFIG_PARENT_SEARCH_CHECK_INTERVAL (9 * 60) +#define OPENTHREAD_CONFIG_PARENT_SEARCH_CHECK_INTERVAL (9 * 60) #endif /** @@ -1172,7 +1172,7 @@ * */ #ifndef OPENTHREAD_CONFIG_PARENT_SEARCH_BACKOFF_INTERVAL -#define OPENTHREAD_CONFIG_PARENT_SEARCH_BACKOFF_INTERVAL (10* 60 * 60) +#define OPENTHREAD_CONFIG_PARENT_SEARCH_BACKOFF_INTERVAL (10 * 60 * 60) #endif /** @@ -1184,7 +1184,7 @@ * */ #ifndef OPENTHREAD_CONFIG_PARENT_SEARCH_RSS_THRESHOLD -#define OPENTHREAD_CONFIG_PARENT_SEARCH_RSS_THRESHOLD -65 +#define OPENTHREAD_CONFIG_PARENT_SEARCH_RSS_THRESHOLD -65 #endif /** @@ -1196,7 +1196,7 @@ * */ #ifndef OPENTHREAD_CONFIG_NCP_ENABLE_PEEK_POKE -#define OPENTHREAD_CONFIG_NCP_ENABLE_PEEK_POKE 0 +#define OPENTHREAD_CONFIG_NCP_ENABLE_PEEK_POKE 0 #endif /** @@ -1214,7 +1214,7 @@ * */ #ifndef OPENTHREAD_CONFIG_NCP_SPINEL_RESPONSE_QUEUE_SIZE -#define OPENTHREAD_CONFIG_NCP_SPINEL_RESPONSE_QUEUE_SIZE 15 +#define OPENTHREAD_CONFIG_NCP_SPINEL_RESPONSE_QUEUE_SIZE 15 #endif /** @@ -1225,7 +1225,7 @@ * */ #ifndef OPENTHREAD_CONFIG_STAY_AWAKE_BETWEEN_FRAGMENTS -#define OPENTHREAD_CONFIG_STAY_AWAKE_BETWEEN_FRAGMENTS 0 +#define OPENTHREAD_CONFIG_STAY_AWAKE_BETWEEN_FRAGMENTS 0 #endif /** @@ -1235,7 +1235,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MLE_SEND_LINK_REQUEST_ON_ADV_TIMEOUT -#define OPENTHREAD_CONFIG_MLE_SEND_LINK_REQUEST_ON_ADV_TIMEOUT 0 +#define OPENTHREAD_CONFIG_MLE_SEND_LINK_REQUEST_ON_ADV_TIMEOUT 0 #endif /** @@ -1245,7 +1245,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MLE_LINK_REQUEST_MARGIN_MIN -#define OPENTHREAD_CONFIG_MLE_LINK_REQUEST_MARGIN_MIN 10 +#define OPENTHREAD_CONFIG_MLE_LINK_REQUEST_MARGIN_MIN 10 #endif /** @@ -1255,7 +1255,7 @@ * */ #ifndef OPENTHREAD_CONFIG_MLE_PARTITION_MERGE_MARGIN_MIN -#define OPENTHREAD_CONFIG_MLE_PARTITION_MERGE_MARGIN_MIN 10 +#define OPENTHREAD_CONFIG_MLE_PARTITION_MERGE_MARGIN_MIN 10 #endif /** @@ -1277,7 +1277,7 @@ * See #include for more details */ #ifndef OPENTHREAD_CONFIG_ENABLE_DEBUG_UART -#define OPENTHREAD_CONFIG_ENABLE_DEBUG_UART 0 +#define OPENTHREAD_CONFIG_ENABLE_DEBUG_UART 0 #endif /** @@ -1290,7 +1290,7 @@ * */ #ifndef OPENTHREAD_CONFIG_ENABLE_DYNAMIC_MPL_INTERVAL -#define OPENTHREAD_CONFIG_ENABLE_DYNAMIC_MPL_INTERVAL 0 +#define OPENTHREAD_CONFIG_ENABLE_DYNAMIC_MPL_INTERVAL 0 #endif /** @@ -1300,7 +1300,7 @@ * */ #ifndef OPENTHREAD_CONFIG_DISABLE_CCA_ON_LAST_ATTEMPT -#define OPENTHREAD_CONFIG_DISABLE_CCA_ON_LAST_ATTEMPT 0 +#define OPENTHREAD_CONFIG_DISABLE_CCA_ON_LAST_ATTEMPT 0 #endif -#endif // OPENTHREAD_CORE_DEFAULT_CONFIG_H_ +#endif // OPENTHREAD_CORE_DEFAULT_CONFIG_H_ diff --git a/src/core/thread/address_resolver.cpp b/src/core/thread/address_resolver.cpp index fd85a9cd7..0d783c96d 100644 --- a/src/core/thread/address_resolver.cpp +++ b/src/core/thread/address_resolver.cpp @@ -57,13 +57,13 @@ using ot::Encoding::BigEndian::HostSwap16; namespace ot { -AddressResolver::AddressResolver(Instance &aInstance) : - InstanceLocator(aInstance), - mAddressError(OT_URI_PATH_ADDRESS_ERROR, &AddressResolver::HandleAddressError, this), - mAddressQuery(OT_URI_PATH_ADDRESS_QUERY, &AddressResolver::HandleAddressQuery, this), - mAddressNotification(OT_URI_PATH_ADDRESS_NOTIFY, &AddressResolver::HandleAddressNotification, this), - mIcmpHandler(&AddressResolver::HandleIcmpReceive, this), - mTimer(aInstance, &AddressResolver::HandleTimer, this) +AddressResolver::AddressResolver(Instance &aInstance) + : InstanceLocator(aInstance) + , mAddressError(OT_URI_PATH_ADDRESS_ERROR, &AddressResolver::HandleAddressError, this) + , mAddressQuery(OT_URI_PATH_ADDRESS_QUERY, &AddressResolver::HandleAddressQuery, this) + , mAddressNotification(OT_URI_PATH_ADDRESS_NOTIFY, &AddressResolver::HandleAddressNotification, this) + , mIcmpHandler(&AddressResolver::HandleIcmpReceive, this) + , mTimer(aInstance, &AddressResolver::HandleTimer, this) { Clear(); @@ -91,7 +91,7 @@ otError AddressResolver::GetEntry(uint8_t aIndex, otEidCacheEntry &aEntry) const VerifyOrExit(aIndex < kCacheEntries, error = OT_ERROR_INVALID_ARGS); memcpy(&aEntry.mTarget, &mCache[aIndex].mTarget, sizeof(aEntry.mTarget)); aEntry.mRloc16 = mCache[aIndex].mRloc16; - aEntry.mValid = mCache[aIndex].mState == Cache::kStateCached; + aEntry.mValid = mCache[aIndex].mState == Cache::kStateCached; exit: return error; @@ -205,15 +205,15 @@ void AddressResolver::InvalidateCacheEntry(Cache &aEntry, InvalidationReason aRe case Cache::kStateQuery: otLogInfoArp(GetInstance(), "Cache entry (query mode) removed: %s, timeout:%d, retry:%d - %s", - aEntry.mTarget.ToString(stringBuffer, sizeof(stringBuffer)), aEntry.mTimeout, - aEntry.mRetryTimeout, ConvertInvalidationReasonToString(aReason)); + aEntry.mTarget.ToString(stringBuffer, sizeof(stringBuffer)), aEntry.mTimeout, aEntry.mRetryTimeout, + ConvertInvalidationReasonToString(aReason)); break; default: break; } - aEntry.mAge = kCacheEntries - 1; + aEntry.mAge = kCacheEntries - 1; aEntry.mState = Cache::kStateInvalid; OT_UNUSED_VARIABLE(stringBuffer); @@ -238,11 +238,11 @@ void AddressResolver::UpdateCacheEntry(const Ip6::Address &aEid, Mac::ShortAddre if (mCache[i].mState != Cache::kStateCached) { - mCache[i].mRetryTimeout = 0; + mCache[i].mRetryTimeout = 0; mCache[i].mLastTransactionTime = static_cast(kLastTransactionTimeInvalid); - mCache[i].mTimeout = 0; - mCache[i].mFailures = 0; - mCache[i].mState = Cache::kStateCached; + mCache[i].mTimeout = 0; + mCache[i].mFailures = 0; + mCache[i].mState = Cache::kStateCached; GetNetif().GetMeshForwarder().HandleResolved(aEid, OT_ERROR_NONE); } @@ -263,7 +263,7 @@ exit: otError AddressResolver::Resolve(const Ip6::Address &aEid, uint16_t &aRloc16) { otError error = OT_ERROR_NONE; - Cache *entry = NULL; + Cache * entry = NULL; for (int i = 0; i < kCacheEntries; i++) { @@ -288,13 +288,13 @@ otError AddressResolver::Resolve(const Ip6::Address &aEid, uint16_t &aRloc16) { case Cache::kStateInvalid: SuccessOrExit(error = SendAddressQuery(aEid)); - entry->mTarget = aEid; - entry->mRloc16 = Mac::kShortAddrInvalid; - entry->mTimeout = kAddressQueryTimeout; - entry->mFailures = 0; + entry->mTarget = aEid; + entry->mRloc16 = Mac::kShortAddrInvalid; + entry->mTimeout = kAddressQueryTimeout; + entry->mFailures = 0; entry->mRetryTimeout = kAddressQueryInitialRetryDelay; - entry->mState = Cache::kStateQuery; - error = OT_ERROR_ADDRESS_QUERY; + entry->mState = Cache::kStateQuery; + error = OT_ERROR_ADDRESS_QUERY; break; case Cache::kStateQuery: @@ -306,7 +306,7 @@ otError AddressResolver::Resolve(const Ip6::Address &aEid, uint16_t &aRloc16) { SuccessOrExit(error = SendAddressQuery(aEid)); entry->mTimeout = kAddressQueryTimeout; - error = OT_ERROR_ADDRESS_QUERY; + error = OT_ERROR_ADDRESS_QUERY; } else { @@ -327,13 +327,13 @@ exit: otError AddressResolver::SendAddressQuery(const Ip6::Address &aEid) { - ThreadNetif &netif = GetNetif(); - otError error; - Message *message; - Coap::Header header; - ThreadTargetTlv targetTlv; + ThreadNetif & netif = GetNetif(); + otError error; + Message * message; + Coap::Header header; + ThreadTargetTlv targetTlv; Ip6::MessageInfo messageInfo; - char stringBuffer[Ip6::Address::kIp6AddressStringSize]; + char stringBuffer[Ip6::Address::kIp6AddressStringSize]; header.Init(OT_COAP_TYPE_NON_CONFIRMABLE, OT_COAP_CODE_POST); header.AppendUriPathOptions(OT_URI_PATH_ADDRESS_QUERY); @@ -372,7 +372,9 @@ exit: return error; } -void AddressResolver::HandleAddressNotification(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void AddressResolver::HandleAddressNotification(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { static_cast(aContext)->HandleAddressNotification( @@ -380,19 +382,19 @@ void AddressResolver::HandleAddressNotification(void *aContext, otCoapHeader *aH *static_cast(aMessageInfo)); } -void AddressResolver::HandleAddressNotification(Coap::Header &aHeader, Message &aMessage, +void AddressResolver::HandleAddressNotification(Coap::Header & aHeader, + Message & aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - ThreadTargetTlv targetTlv; - ThreadMeshLocalEidTlv mlIidTlv; - ThreadRloc16Tlv rloc16Tlv; + ThreadNetif & netif = GetNetif(); + ThreadTargetTlv targetTlv; + ThreadMeshLocalEidTlv mlIidTlv; + ThreadRloc16Tlv rloc16Tlv; ThreadLastTransactionTimeTlv lastTransactionTimeTlv; - uint32_t lastTransactionTime; - char stringBuffer[Ip6::Address::kIp6AddressStringSize]; + uint32_t lastTransactionTime; + char stringBuffer[Ip6::Address::kIp6AddressStringSize]; - VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && - aHeader.GetCode() == OT_COAP_CODE_POST); + VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && aHeader.GetCode() == OT_COAP_CODE_POST); SuccessOrExit(ThreadTlv::GetTlv(aMessage, ThreadTlv::kTarget, sizeof(targetTlv), targetTlv)); VerifyOrExit(targetTlv.IsValid()); @@ -443,20 +445,20 @@ void AddressResolver::HandleAddressNotification(Coap::Header &aHeader, Message & } } - // fall through + // fall through case Cache::kStateQuery: memcpy(mCache[i].mMeshLocalIid, mlIidTlv.GetIid(), sizeof(mCache[i].mMeshLocalIid)); - mCache[i].mRloc16 = rloc16Tlv.GetRloc16(); - mCache[i].mRetryTimeout = 0; + mCache[i].mRloc16 = rloc16Tlv.GetRloc16(); + mCache[i].mRetryTimeout = 0; mCache[i].mLastTransactionTime = lastTransactionTime; - mCache[i].mTimeout = 0; - mCache[i].mFailures = 0; - mCache[i].mState = Cache::kStateCached; + mCache[i].mTimeout = 0; + mCache[i].mFailures = 0; + mCache[i].mState = Cache::kStateCached; MarkCacheEntryAsUsed(mCache[i]); - otLogInfoArp(GetInstance(), "Cache entry updated (notification): %s, 0x%04x, lastTrans:%d", - stringBuffer, rloc16Tlv.GetRloc16(), lastTransactionTime); + otLogInfoArp(GetInstance(), "Cache entry updated (notification): %s, 0x%04x, lastTrans:%d", stringBuffer, + rloc16Tlv.GetRloc16(), lastTransactionTime); if (netif.GetCoap().SendEmptyAck(aHeader, aMessageInfo) == OT_ERROR_NONE) { @@ -474,18 +476,18 @@ exit: return; } -otError AddressResolver::SendAddressError(const ThreadTargetTlv &aTarget, const ThreadMeshLocalEidTlv &aEid, - const Ip6::Address *aDestination) +otError AddressResolver::SendAddressError(const ThreadTargetTlv & aTarget, + const ThreadMeshLocalEidTlv &aEid, + const Ip6::Address * aDestination) { - ThreadNetif &netif = GetNetif(); - otError error; - Message *message; - Coap::Header header; + ThreadNetif & netif = GetNetif(); + otError error; + Message * message; + Coap::Header header; Ip6::MessageInfo messageInfo; - char stringBuffer[Ip6::Address::kIp6AddressStringSize]; + char stringBuffer[Ip6::Address::kIp6AddressStringSize]; - header.Init(aDestination == NULL ? OT_COAP_TYPE_NON_CONFIRMABLE : OT_COAP_TYPE_CONFIRMABLE, - OT_COAP_CODE_POST); + header.Init(aDestination == NULL ? OT_COAP_TYPE_NON_CONFIRMABLE : OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); header.AppendUriPathOptions(OT_URI_PATH_ADDRESS_ERROR); header.SetPayloadMarker(); @@ -525,27 +527,29 @@ exit: return error; } -void AddressResolver::HandleAddressError(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void AddressResolver::HandleAddressError(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleAddressError( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleAddressError(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void AddressResolver::HandleAddressError(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - ThreadTargetTlv targetTlv; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + ThreadTargetTlv targetTlv; ThreadMeshLocalEidTlv mlIidTlv; - Child *children; - uint8_t numChildren; - Mac::ExtAddress macAddr; - Ip6::Address destination; + Child * children; + uint8_t numChildren; + Mac::ExtAddress macAddr; + Ip6::Address destination; - VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && - aHeader.GetCode() == OT_COAP_CODE_POST, error = OT_ERROR_DROP); + VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && aHeader.GetCode() == OT_COAP_CODE_POST, + error = OT_ERROR_DROP); otLogInfoArp(GetInstance(), "Received address error notification"); @@ -616,27 +620,27 @@ exit: return; } -void AddressResolver::HandleAddressQuery(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void AddressResolver::HandleAddressQuery(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleAddressQuery( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleAddressQuery(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } -void AddressResolver::HandleAddressQuery(Coap::Header &aHeader, Message &aMessage, - const Ip6::MessageInfo &aMessageInfo) +void AddressResolver::HandleAddressQuery(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - ThreadTargetTlv targetTlv; - ThreadMeshLocalEidTlv mlIidTlv; + ThreadNetif & netif = GetNetif(); + ThreadTargetTlv targetTlv; + ThreadMeshLocalEidTlv mlIidTlv; ThreadLastTransactionTimeTlv lastTransactionTimeTlv; - Child *children; - uint8_t numChildren; - char stringBuffer[Ip6::Address::kIp6AddressStringSize]; + Child * children; + uint8_t numChildren; + char stringBuffer[Ip6::Address::kIp6AddressStringSize]; - VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_NON_CONFIRMABLE && - aHeader.GetCode() == OT_COAP_CODE_POST); + VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_NON_CONFIRMABLE && aHeader.GetCode() == OT_COAP_CODE_POST); SuccessOrExit(ThreadTlv::GetTlv(aMessage, ThreadTlv::kTarget, sizeof(targetTlv), targetTlv)); VerifyOrExit(targetTlv.IsValid()); @@ -662,8 +666,7 @@ void AddressResolver::HandleAddressQuery(Coap::Header &aHeader, Message &aMessag { Child &child = children[i]; - if (child.GetState() != Neighbor::kStateValid || - child.IsFullThreadDevice() || + if (child.GetState() != Neighbor::kStateValid || child.IsFullThreadDevice() || child.GetLinkFailures() >= Mle::kFailedChildTransmissions) { continue; @@ -684,18 +687,18 @@ exit: return; } -void AddressResolver::SendAddressQueryResponse(const ThreadTargetTlv &aTargetTlv, - const ThreadMeshLocalEidTlv &aMlIidTlv, +void AddressResolver::SendAddressQueryResponse(const ThreadTargetTlv & aTargetTlv, + const ThreadMeshLocalEidTlv & aMlIidTlv, const ThreadLastTransactionTimeTlv *aLastTransactionTimeTlv, - const Ip6::Address &aDestination) + const Ip6::Address & aDestination) { - ThreadNetif &netif = GetNetif(); - otError error; - Message *message; - Coap::Header header; - ThreadRloc16Tlv rloc16Tlv; + ThreadNetif & netif = GetNetif(); + otError error; + Message * message; + Coap::Header header; + ThreadRloc16Tlv rloc16Tlv; Ip6::MessageInfo messageInfo; - char stringBuffer[Ip6::Address::kIp6AddressStringSize]; + char stringBuffer[Ip6::Address::kIp6AddressStringSize]; header.Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); header.AppendUriPathOptions(OT_URI_PATH_ADDRESS_NOTIFY); @@ -791,7 +794,9 @@ void AddressResolver::HandleTimer(void) OT_UNUSED_VARIABLE(stringBuffer); } -void AddressResolver::HandleIcmpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo, +void AddressResolver::HandleIcmpReceive(void * aContext, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, const otIcmp6Header *aIcmpHeader) { static_cast(aContext)->HandleIcmpReceive(*static_cast(aMessage), @@ -801,8 +806,9 @@ void AddressResolver::HandleIcmpReceive(void *aContext, otMessage *aMessage, con OT_UNUSED_VARIABLE(aMessageInfo); } -void AddressResolver::HandleIcmpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - const Ip6::IcmpHeader &aIcmpHeader) +void AddressResolver::HandleIcmpReceive(Message & aMessage, + const Ip6::MessageInfo &aMessageInfo, + const Ip6::IcmpHeader & aIcmpHeader) { Ip6::Header ip6Header; @@ -823,6 +829,6 @@ exit: OT_UNUSED_VARIABLE(aMessageInfo); } -} // namespace ot +} // namespace ot #endif // OPENTHREAD_FTD diff --git a/src/core/thread/address_resolver.hpp b/src/core/thread/address_resolver.hpp index 0f592a35b..7d60ce46c 100644 --- a/src/core/thread/address_resolver.hpp +++ b/src/core/thread/address_resolver.hpp @@ -66,7 +66,7 @@ class ThreadTargetTlv; * This class implements the EID-to-RLOC mapping and caching. * */ -class AddressResolver: public InstanceLocator +class AddressResolver : public InstanceLocator { public: /** @@ -134,8 +134,8 @@ public: private: enum { - kCacheEntries = OPENTHREAD_CONFIG_ADDRESS_CACHE_ENTRIES, - kStateUpdatePeriod = 1000u, ///< State update period in milliseconds. + kCacheEntries = OPENTHREAD_CONFIG_ADDRESS_CACHE_ENTRIES, + kStateUpdatePeriod = 1000u, ///< State update period in milliseconds. }; /** @@ -144,14 +144,14 @@ private: */ enum { - kAddressQueryTimeout = OPENTHREAD_CONFIG_ADDRESS_QUERY_TIMEOUT, // in seconds + kAddressQueryTimeout = OPENTHREAD_CONFIG_ADDRESS_QUERY_TIMEOUT, // in seconds kAddressQueryInitialRetryDelay = OPENTHREAD_CONFIG_ADDRESS_QUERY_INITIAL_RETRY_DELAY, // in seconds - kAddressQueryMaxRetryDelay = OPENTHREAD_CONFIG_ADDRESS_QUERY_MAX_RETRY_DELAY, // in seconds + kAddressQueryMaxRetryDelay = OPENTHREAD_CONFIG_ADDRESS_QUERY_MAX_RETRY_DELAY, // in seconds }; enum { - kLastTransactionTimeInvalid = 0xffffffff, ///< Used when entry is populated using forwarded data message. + kLastTransactionTimeInvalid = 0xffffffff, ///< Used when entry is populated using forwarded data message. }; struct Cache @@ -171,7 +171,7 @@ private: kStateQuery, kStateCached, }; - State mState; + State mState; }; enum InvalidationReason @@ -185,49 +185,59 @@ private: static const char *ConvertInvalidationReasonToString(InvalidationReason aReason); Cache *NewCacheEntry(void); - void MarkCacheEntryAsUsed(Cache &aEntry); - void InvalidateCacheEntry(Cache &aEntry, InvalidationReason aReason); + void MarkCacheEntryAsUsed(Cache &aEntry); + void InvalidateCacheEntry(Cache &aEntry, InvalidationReason aReason); otError SendAddressQuery(const Ip6::Address &aEid); - otError SendAddressError(const ThreadTargetTlv &aTarget, const ThreadMeshLocalEidTlv &aEid, - const Ip6::Address *aDestination); - void SendAddressQueryResponse(const ThreadTargetTlv &aTargetTlv, const ThreadMeshLocalEidTlv &aMlEidTlv, - const ThreadLastTransactionTimeTlv *aLastTransactionTimeTlv, - const Ip6::Address &aDestination); + otError SendAddressError(const ThreadTargetTlv & aTarget, + const ThreadMeshLocalEidTlv &aEid, + const Ip6::Address * aDestination); + void SendAddressQueryResponse(const ThreadTargetTlv & aTargetTlv, + const ThreadMeshLocalEidTlv & aMlEidTlv, + const ThreadLastTransactionTimeTlv *aLastTransactionTimeTlv, + const Ip6::Address & aDestination); static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo); - static void HandleAddressError(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleAddressError(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleAddressError(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleAddressError(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - static void HandleAddressQuery(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleAddressQuery(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleAddressQuery(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleAddressQuery(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - static void HandleAddressNotification(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleAddressNotification(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); void HandleAddressNotification(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - static void HandleIcmpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo, + static void HandleIcmpReceive(void * aContext, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, const otIcmp6Header *aIcmpHeader); void HandleIcmpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo, const Ip6::IcmpHeader &aIcmpHeader); static void HandleTimer(Timer &aTimer); - void HandleTimer(void); + void HandleTimer(void); - Coap::Resource mAddressError; - Coap::Resource mAddressQuery; - Coap::Resource mAddressNotification; - Cache mCache[kCacheEntries]; + Coap::Resource mAddressError; + Coap::Resource mAddressQuery; + Coap::Resource mAddressNotification; + Cache mCache[kCacheEntries]; Ip6::IcmpHandler mIcmpHandler; - TimerMilli mTimer; + TimerMilli mTimer; }; /** * @} */ -} // namespace ot +} // namespace ot -#endif // ADDRESS_RESOLVER_HPP_ +#endif // ADDRESS_RESOLVER_HPP_ diff --git a/src/core/thread/announce_begin_server.cpp b/src/core/thread/announce_begin_server.cpp index 3d2e7ab64..e6ce43806 100644 --- a/src/core/thread/announce_begin_server.cpp +++ b/src/core/thread/announce_begin_server.cpp @@ -39,8 +39,8 @@ #include "coap/coap_header.hpp" #include "common/code_utils.hpp" -#include "common/instance.hpp" #include "common/debug.hpp" +#include "common/instance.hpp" #include "common/logging.hpp" #include "common/owner-locator.hpp" #include "meshcop/meshcop_tlvs.hpp" @@ -51,14 +51,14 @@ using ot::Encoding::BigEndian::HostSwap32; namespace ot { -AnnounceBeginServer::AnnounceBeginServer(Instance &aInstance) : - InstanceLocator(aInstance), - mChannelMask(0), - mPeriod(0), - mCount(0), - mChannel(0), - mTimer(aInstance, &AnnounceBeginServer::HandleTimer, this), - mAnnounceBegin(OT_URI_PATH_ANNOUNCE_BEGIN, &AnnounceBeginServer::HandleRequest, this) +AnnounceBeginServer::AnnounceBeginServer(Instance &aInstance) + : InstanceLocator(aInstance) + , mChannelMask(0) + , mPeriod(0) + , mCount(0) + , mChannel(0) + , mTimer(aInstance, &AnnounceBeginServer::HandleTimer, this) + , mAnnounceBegin(OT_URI_PATH_ANNOUNCE_BEGIN, &AnnounceBeginServer::HandleRequest, this) { GetNetif().GetCoap().AddResource(mAnnounceBegin); } @@ -73,9 +73,9 @@ otError AnnounceBeginServer::SendAnnounce(uint32_t aChannelMask, uint8_t aCount, otError error = OT_ERROR_NONE; mChannelMask = aChannelMask; - mCount = aCount; - mPeriod = aPeriod; - mChannel = OT_RADIO_CHANNEL_MIN; + mCount = aCount; + mPeriod = aPeriod; + mChannel = OT_RADIO_CHANNEL_MIN; while ((mChannelMask & (1 << mChannel)) == 0) { @@ -89,19 +89,21 @@ exit: return error; } -void AnnounceBeginServer::HandleRequest(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void AnnounceBeginServer::HandleRequest(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleRequest( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleRequest(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void AnnounceBeginServer::HandleRequest(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { MeshCoP::ChannelMask0Tlv channelMask; - MeshCoP::CountTlv count; - MeshCoP::PeriodTlv period; - Ip6::MessageInfo responseInfo(aMessageInfo); + MeshCoP::CountTlv count; + MeshCoP::PeriodTlv period; + Ip6::MessageInfo responseInfo(aMessageInfo); VerifyOrExit(aHeader.GetCode() == OT_COAP_CODE_POST); @@ -153,4 +155,4 @@ void AnnounceBeginServer::HandleTimer(void) } } -} // namespace ot +} // namespace ot diff --git a/src/core/thread/announce_begin_server.hpp b/src/core/thread/announce_begin_server.hpp index 07cc37c3d..8b800fbfb 100644 --- a/src/core/thread/announce_begin_server.hpp +++ b/src/core/thread/announce_begin_server.hpp @@ -49,7 +49,7 @@ namespace ot { * This class implements handling Announce Begin Requests. * */ -class AnnounceBeginServer: public InstanceLocator +class AnnounceBeginServer : public InstanceLocator { public: /** @@ -87,17 +87,19 @@ private: kDefaultPeriod = 1000, }; - static void HandleRequest(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleRequest(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleRequest(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleRequest(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); static void HandleTimer(Timer &aTimer); - void HandleTimer(void); + void HandleTimer(void); uint32_t mChannelMask; uint16_t mPeriod; - uint8_t mCount; - uint8_t mChannel; + uint8_t mCount; + uint8_t mChannel; TimerMilli mTimer; @@ -108,6 +110,6 @@ private: * @} */ -} // namespace ot +} // namespace ot -#endif // ANNOUNCE_BEGIN_SERVER_HPP_ +#endif // ANNOUNCE_BEGIN_SERVER_HPP_ diff --git a/src/core/thread/data_poll_manager.cpp b/src/core/thread/data_poll_manager.cpp index 2b03fdcef..2fd574310 100644 --- a/src/core/thread/data_poll_manager.cpp +++ b/src/core/thread/data_poll_manager.cpp @@ -50,19 +50,19 @@ namespace ot { -DataPollManager::DataPollManager(Instance &aInstance): - InstanceLocator(aInstance), - mTimerStartTime(0), - mExternalPollPeriod(0), - mPollPeriod(0), - mTimer(aInstance, &DataPollManager::HandlePollTimer, this), - mEnabled(false), - mAttachMode(false), - mRetxMode(false), - mNoBufferRetxMode(false), - mPollTimeoutCounter(0), - mPollTxFailureCounter(0), - mRemainingFastPolls(0) +DataPollManager::DataPollManager(Instance &aInstance) + : InstanceLocator(aInstance) + , mTimerStartTime(0) + , mExternalPollPeriod(0) + , mPollPeriod(0) + , mTimer(aInstance, &DataPollManager::HandlePollTimer, this) + , mEnabled(false) + , mAttachMode(false) + , mRetxMode(false) + , mNoBufferRetxMode(false) + , mPollTimeoutCounter(0) + , mPollTxFailureCounter(0) + , mRemainingFastPolls(0) { } @@ -71,8 +71,7 @@ otError DataPollManager::StartPolling(void) otError error = OT_ERROR_NONE; VerifyOrExit(!mEnabled, error = OT_ERROR_ALREADY); - VerifyOrExit((GetNetif().GetMle().GetDeviceMode() & Mle::ModeTlv::kModeFFD) == 0, - error = OT_ERROR_INVALID_STATE); + VerifyOrExit((GetNetif().GetMle().GetDeviceMode() & Mle::ModeTlv::kModeFFD) == 0, error = OT_ERROR_INVALID_STATE); mEnabled = true; ScheduleNextPoll(kRecalculatePollPeriod); @@ -84,21 +83,21 @@ exit: void DataPollManager::StopPolling(void) { mTimer.Stop(); - mAttachMode = false; - mRetxMode = false; - mNoBufferRetxMode = false; - mPollTimeoutCounter = 0; + mAttachMode = false; + mRetxMode = false; + mNoBufferRetxMode = false; + mPollTimeoutCounter = 0; mPollTxFailureCounter = 0; - mRemainingFastPolls = 0; - mEnabled = false; + mRemainingFastPolls = 0; + mEnabled = false; } otError DataPollManager::SendDataPoll(void) { ThreadNetif &netif = GetNetif(); - otError error; - Message *message; - Neighbor *parent; + otError error; + Message * message; + Neighbor * parent; VerifyOrExit(mEnabled, error = OT_ERROR_INVALID_STATE); VerifyOrExit(!netif.GetMac().GetRxOnWhenIdle(), error = OT_ERROR_INVALID_STATE); @@ -209,8 +208,8 @@ void DataPollManager::HandlePollSent(otError aError) if (mRetxMode == true) { - mRetxMode = false; - mPollTxFailureCounter = 0; + mRetxMode = false; + mPollTxFailureCounter = 0; shouldRecalculatePollPeriod = true; } @@ -221,21 +220,21 @@ void DataPollManager::HandlePollSent(otError aError) default: mPollTxFailureCounter++; - otLogInfoMac(GetInstance(), "Failed to send data poll, error:%s, retx:%d/%d", - otThreadErrorToString(aError), mPollTxFailureCounter, kMaxPollRetxAttempts); + otLogInfoMac(GetInstance(), "Failed to send data poll, error:%s, retx:%d/%d", otThreadErrorToString(aError), + mPollTxFailureCounter, kMaxPollRetxAttempts); if (mPollTxFailureCounter < kMaxPollRetxAttempts) { if (mRetxMode == false) { - mRetxMode = true; + mRetxMode = true; shouldRecalculatePollPeriod = true; } } else { - mRetxMode = false; - mPollTxFailureCounter = 0; + mRetxMode = false; + mPollTxFailureCounter = 0; shouldRecalculatePollPeriod = true; } @@ -420,4 +419,4 @@ uint32_t DataPollManager::GetDefaultPollPeriod(void) const static_cast(kRetxPollPeriod) * kMaxPollRetxAttempts; } -} // namespace ot +} // namespace ot diff --git a/src/core/thread/data_poll_manager.hpp b/src/core/thread/data_poll_manager.hpp index eb3e932de..a2748e976 100644 --- a/src/core/thread/data_poll_manager.hpp +++ b/src/core/thread/data_poll_manager.hpp @@ -59,13 +59,13 @@ namespace ot { * */ -class DataPollManager: public InstanceLocator +class DataPollManager : public InstanceLocator { public: enum { - kDefaultFastPolls = 8, ///< Default number of fast poll transmissions (@sa StartFastPolls). - kMaxFastPolls = 15, ///< Maximum number of fast poll transmissions allowed. + kDefaultFastPolls = 8, ///< Default number of fast poll transmissions (@sa StartFastPolls). + kMaxFastPolls = 15, ///< Maximum number of fast poll transmissions allowed. }; /** @@ -195,19 +195,19 @@ public: uint32_t GetKeepAlivePollPeriod(void) const; private: - enum // Poll period under different conditions (in milliseconds). + enum // Poll period under different conditions (in milliseconds). { - kAttachDataPollPeriod = OPENTHREAD_CONFIG_ATTACH_DATA_POLL_PERIOD, ///< Poll period during attach. - kRetxPollPeriod = 1000, ///< Poll retx period due to tx failure. - kNoBufferRetxPollPeriod = 200, ///< Poll retx due to no buffer space. - kFastPollPeriod = 188, ///< Period used for fast polls. - kMinPollPeriod = 10, ///< Minimum allowed poll period. + kAttachDataPollPeriod = OPENTHREAD_CONFIG_ATTACH_DATA_POLL_PERIOD, ///< Poll period during attach. + kRetxPollPeriod = 1000, ///< Poll retx period due to tx failure. + kNoBufferRetxPollPeriod = 200, ///< Poll retx due to no buffer space. + kFastPollPeriod = 188, ///< Period used for fast polls. + kMinPollPeriod = 10, ///< Minimum allowed poll period. }; enum { - kQuickPollsAfterTimeout = 5, ///< Maximum number of quick data poll tx in case of back-to-back poll timeouts. - kMaxPollRetxAttempts = 5, ///< Maximum number of retransmit attempts of data poll (mac data request). + kQuickPollsAfterTimeout = 5, ///< Maximum number of quick data poll tx in case of back-to-back poll timeouts. + kMaxPollRetxAttempts = 5, ///< Maximum number of retransmit attempts of data poll (mac data request). }; enum PollPeriodSelector @@ -216,24 +216,24 @@ private: kRecalculatePollPeriod, }; - void ScheduleNextPoll(PollPeriodSelector aPollPeriodSelector); - uint32_t CalculatePollPeriod(void) const; + void ScheduleNextPoll(PollPeriodSelector aPollPeriodSelector); + uint32_t CalculatePollPeriod(void) const; static void HandlePollTimer(Timer &aTimer); - uint32_t GetDefaultPollPeriod(void) const; + uint32_t GetDefaultPollPeriod(void) const; - uint32_t mTimerStartTime; - uint32_t mExternalPollPeriod; - uint32_t mPollPeriod; + uint32_t mTimerStartTime; + uint32_t mExternalPollPeriod; + uint32_t mPollPeriod; - TimerMilli mTimer; + TimerMilli mTimer; - bool mEnabled: 1; //< Indicates whether data polling is enabled/started. - bool mAttachMode: 1; //< Indicates whether in attach mode (to use attach poll period). - bool mRetxMode: 1; //< Indicates whether last poll tx failed at mac/radio layer (poll retx mode). - bool mNoBufferRetxMode: 1; //< Indicates whether last poll tx failed due to insufficient buffer. - uint8_t mPollTimeoutCounter: 4; //< Poll timeouts counter (0 to `kQuickPollsAfterTimout`). - uint8_t mPollTxFailureCounter: 4; //< Poll tx failure counter (0 to `kMaxPollRetxAttempts`). - uint8_t mRemainingFastPolls: 4; //< Number of remaining fast polls when in transient fast polling mode. + bool mEnabled : 1; //< Indicates whether data polling is enabled/started. + bool mAttachMode : 1; //< Indicates whether in attach mode (to use attach poll period). + bool mRetxMode : 1; //< Indicates whether last poll tx failed at mac/radio layer (poll retx mode). + bool mNoBufferRetxMode : 1; //< Indicates whether last poll tx failed due to insufficient buffer. + uint8_t mPollTimeoutCounter : 4; //< Poll timeouts counter (0 to `kQuickPollsAfterTimout`). + uint8_t mPollTxFailureCounter : 4; //< Poll tx failure counter (0 to `kMaxPollRetxAttempts`). + uint8_t mRemainingFastPolls : 4; //< Number of remaining fast polls when in transient fast polling mode. }; /** @@ -241,6 +241,6 @@ private: * */ -} // namespace ot +} // namespace ot -#endif // DATA_POLL_MANAGER_HPP_ +#endif // DATA_POLL_MANAGER_HPP_ diff --git a/src/core/thread/energy_scan_server.cpp b/src/core/thread/energy_scan_server.cpp index 0f5c0e71c..e57d6ff95 100644 --- a/src/core/thread/energy_scan_server.cpp +++ b/src/core/thread/energy_scan_server.cpp @@ -50,38 +50,40 @@ namespace ot { -EnergyScanServer::EnergyScanServer(Instance &aInstance) : - InstanceLocator(aInstance), - mChannelMask(0), - mChannelMaskCurrent(0), - mPeriod(0), - mScanDuration(0), - mCount(0), - mActive(false), - mScanResultsLength(0), - mTimer(aInstance, &EnergyScanServer::HandleTimer, this), - mNotifierCallback(&EnergyScanServer::HandleStateChanged, this), - mEnergyScan(OT_URI_PATH_ENERGY_SCAN, &EnergyScanServer::HandleRequest, this) +EnergyScanServer::EnergyScanServer(Instance &aInstance) + : InstanceLocator(aInstance) + , mChannelMask(0) + , mChannelMaskCurrent(0) + , mPeriod(0) + , mScanDuration(0) + , mCount(0) + , mActive(false) + , mScanResultsLength(0) + , mTimer(aInstance, &EnergyScanServer::HandleTimer, this) + , mNotifierCallback(&EnergyScanServer::HandleStateChanged, this) + , mEnergyScan(OT_URI_PATH_ENERGY_SCAN, &EnergyScanServer::HandleRequest, this) { aInstance.GetNotifier().RegisterCallback(mNotifierCallback); GetNetif().GetCoap().AddResource(mEnergyScan); } -void EnergyScanServer::HandleRequest(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void EnergyScanServer::HandleRequest(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleRequest( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleRequest(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void EnergyScanServer::HandleRequest(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - MeshCoP::CountTlv count; - MeshCoP::PeriodTlv period; + MeshCoP::CountTlv count; + MeshCoP::PeriodTlv period; MeshCoP::ScanDurationTlv scanDuration; MeshCoP::ChannelMask0Tlv channelMask; - Ip6::MessageInfo responseInfo(aMessageInfo); + Ip6::MessageInfo responseInfo(aMessageInfo); VerifyOrExit(aHeader.GetCode() == OT_COAP_CODE_POST); @@ -97,13 +99,13 @@ void EnergyScanServer::HandleRequest(Coap::Header &aHeader, Message &aMessage, c SuccessOrExit(MeshCoP::Tlv::GetTlv(aMessage, MeshCoP::Tlv::kChannelMask, sizeof(channelMask), channelMask)); VerifyOrExit(channelMask.IsValid()); - mChannelMask = channelMask.GetMask(); + mChannelMask = channelMask.GetMask(); mChannelMaskCurrent = mChannelMask; - mCount = count.GetCount(); - mPeriod = period.GetPeriod(); - mScanDuration = scanDuration.GetScanDuration(); - mScanResultsLength = 0; - mActive = true; + mCount = count.GetCount(); + mPeriod = period.GetPeriod(); + mScanDuration = scanDuration.GetScanDuration(); + mScanResultsLength = 0; + mActive = true; mTimer.Start(kScanDelay); mCommissioner = aMessageInfo.GetPeerAddr(); @@ -182,12 +184,12 @@ exit: otError EnergyScanServer::SendReport(void) { - otError error = OT_ERROR_NONE; - Coap::Header header; + otError error = OT_ERROR_NONE; + Coap::Header header; MeshCoP::ChannelMask0Tlv channelMask; - MeshCoP::EnergyListTlv energyList; - Ip6::MessageInfo messageInfo; - Message *message; + MeshCoP::EnergyListTlv energyList; + Ip6::MessageInfo messageInfo; + Message * message; header.Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); header.SetToken(Coap::Header::kDefaultTokenLength); @@ -232,8 +234,7 @@ void EnergyScanServer::HandleStateChanged(Notifier::Callback &aCallback, uint32_ void EnergyScanServer::HandleStateChanged(uint32_t aFlags) { - if ((aFlags & OT_CHANGED_THREAD_NETDATA) != 0 && - !mActive && + if ((aFlags & OT_CHANGED_THREAD_NETDATA) != 0 && !mActive && GetNetif().GetNetworkDataLeader().GetCommissioningData() == NULL) { mActive = false; @@ -241,4 +242,4 @@ void EnergyScanServer::HandleStateChanged(uint32_t aFlags) } } -} // namespace ot +} // namespace ot diff --git a/src/core/thread/energy_scan_server.hpp b/src/core/thread/energy_scan_server.hpp index 19cd6e267..c38313aba 100644 --- a/src/core/thread/energy_scan_server.hpp +++ b/src/core/thread/energy_scan_server.hpp @@ -57,7 +57,7 @@ class ThreadTargetTlv; * This class implements handling Energy Scan Requests. * */ -class EnergyScanServer: public InstanceLocator +class EnergyScanServer : public InstanceLocator { public: /** @@ -69,34 +69,36 @@ public: private: enum { - kScanDelay = 1000, ///< SCAN_DELAY (milliseconds) - kReportDelay = 500, ///< Delay before sending a report (milliseconds) + kScanDelay = 1000, ///< SCAN_DELAY (milliseconds) + kReportDelay = 500, ///< Delay before sending a report (milliseconds) }; - static void HandleRequest(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleRequest(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleRequest(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleRequest(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); static void HandleScanResult(void *aContext, otEnergyScanResult *aResult); - void HandleScanResult(otEnergyScanResult *aResult); + void HandleScanResult(otEnergyScanResult *aResult); static void HandleTimer(Timer &aTimer); - void HandleTimer(void); + void HandleTimer(void); static void HandleStateChanged(Notifier::Callback &aCallback, uint32_t aFlags); - void HandleStateChanged(uint32_t aFlags); + void HandleStateChanged(uint32_t aFlags); otError SendReport(void); Ip6::Address mCommissioner; - uint32_t mChannelMask; - uint32_t mChannelMaskCurrent; - uint16_t mPeriod; - uint16_t mScanDuration; - uint8_t mCount; - bool mActive; + uint32_t mChannelMask; + uint32_t mChannelMaskCurrent; + uint16_t mPeriod; + uint16_t mScanDuration; + uint8_t mCount; + bool mActive; - int8_t mScanResults[OPENTHREAD_CONFIG_MAX_ENERGY_RESULTS]; + int8_t mScanResults[OPENTHREAD_CONFIG_MAX_ENERGY_RESULTS]; uint8_t mScanResultsLength; TimerMilli mTimer; @@ -110,6 +112,6 @@ private: * @} */ -} // namespace ot +} // namespace ot -#endif // ENERGY_SCAN_SERVER_HPP_ +#endif // ENERGY_SCAN_SERVER_HPP_ diff --git a/src/core/thread/key_manager.cpp b/src/core/thread/key_manager.cpp index 3233e8ea1..490549ac4 100644 --- a/src/core/thread/key_manager.cpp +++ b/src/core/thread/key_manager.cpp @@ -35,33 +35,32 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" -#include "common/timer.hpp" #include "common/owner-locator.hpp" +#include "common/timer.hpp" #include "crypto/hmac_sha256.hpp" #include "thread/mle_router.hpp" #include "thread/thread_netif.hpp" namespace ot { -static const uint8_t kThreadString[] = -{ +static const uint8_t kThreadString[] = { 'T', 'h', 'r', 'e', 'a', 'd', }; -KeyManager::KeyManager(Instance &aInstance): - InstanceLocator(aInstance), - mKeySequence(0), - mMacFrameCounter(0), - mMleFrameCounter(0), - mStoredMacFrameCounter(0), - mStoredMleFrameCounter(0), - mHoursSinceKeyRotation(0), - mKeyRotationTime(kDefaultKeyRotationTime), - mKeySwitchGuardTime(kDefaultKeySwitchGuardTime), - mKeySwitchGuardEnabled(false), - mKeyRotationTimer(aInstance, &KeyManager::HandleKeyRotationTimer, this), - mKekFrameCounter(0), - mSecurityPolicyFlags(0xff) +KeyManager::KeyManager(Instance &aInstance) + : InstanceLocator(aInstance) + , mKeySequence(0) + , mMacFrameCounter(0) + , mMleFrameCounter(0) + , mStoredMacFrameCounter(0) + , mStoredMleFrameCounter(0) + , mHoursSinceKeyRotation(0) + , mKeyRotationTime(kDefaultKeyRotationTime) + , mKeySwitchGuardTime(kDefaultKeySwitchGuardTime) + , mKeySwitchGuardEnabled(false) + , mKeyRotationTimer(aInstance, &KeyManager::HandleKeyRotationTimer, this) + , mKekFrameCounter(0) + , mSecurityPolicyFlags(0xff) { } @@ -101,12 +100,12 @@ otError KeyManager::SetMasterKey(const otMasterKey &aKey) { otError error = OT_ERROR_NONE; Router *routers; - Child *children; + Child * children; uint8_t num; VerifyOrExit(memcmp(&mMasterKey, &aKey, sizeof(mMasterKey)) != 0); - mMasterKey = aKey; + mMasterKey = aKey; mKeySequence = 0; ComputeKey(mKeySequence, mKey); @@ -145,7 +144,7 @@ exit: otError KeyManager::ComputeKey(uint32_t aKeySequence, uint8_t *aKey) { Crypto::HmacSha256 hmac; - uint8_t keySequenceBytes[4]; + uint8_t keySequenceBytes[4]; hmac.Start(mMasterKey.m8, sizeof(mMasterKey.m8)); @@ -169,9 +168,7 @@ void KeyManager::SetCurrentKeySequence(uint32_t aKeySequence) } // Check if the guard timer has expired if key rotation is requested. - if ((aKeySequence == (mKeySequence + 1)) && - (mKeySwitchGuardTime != 0) && - mKeyRotationTimer.IsRunning() && + if ((aKeySequence == (mKeySequence + 1)) && (mKeySwitchGuardTime != 0) && mKeyRotationTimer.IsRunning() && mKeySwitchGuardEnabled) { VerifyOrExit(mHoursSinceKeyRotation >= mKeySwitchGuardTime); @@ -284,4 +281,4 @@ void KeyManager::HandleKeyRotationTimer(void) } } -} // namespace ot +} // namespace ot diff --git a/src/core/thread/key_manager.hpp b/src/core/thread/key_manager.hpp index 66cd2209c..b52ef6af3 100644 --- a/src/core/thread/key_manager.hpp +++ b/src/core/thread/key_manager.hpp @@ -55,7 +55,7 @@ namespace ot { * @{ */ -class KeyManager: public InstanceLocator +class KeyManager : public InstanceLocator { public: enum @@ -328,23 +328,23 @@ public: private: enum { - kMinKeyRotationTime = 1, - kDefaultKeyRotationTime = 672, + kMinKeyRotationTime = 1, + kDefaultKeyRotationTime = 672, kDefaultKeySwitchGuardTime = 624, - kMacKeyOffset = 16, - kOneHourIntervalInMsec = 3600u * 1000u, + kMacKeyOffset = 16, + kOneHourIntervalInMsec = 3600u * 1000u, }; otError ComputeKey(uint32_t aKeySequence, uint8_t *aKey); - void StartKeyRotationTimer(void); + void StartKeyRotationTimer(void); static void HandleKeyRotationTimer(Timer &aTimer); - void HandleKeyRotationTimer(void); + void HandleKeyRotationTimer(void); otMasterKey mMasterKey; uint32_t mKeySequence; - uint8_t mKey[Crypto::HmacSha256::kHashSize]; + uint8_t mKey[Crypto::HmacSha256::kHashSize]; uint8_t mTemporaryKey[Crypto::HmacSha256::kHashSize]; @@ -353,16 +353,16 @@ private: uint32_t mStoredMacFrameCounter; uint32_t mStoredMleFrameCounter; - uint32_t mHoursSinceKeyRotation; - uint32_t mKeyRotationTime; - uint32_t mKeySwitchGuardTime; - bool mKeySwitchGuardEnabled; + uint32_t mHoursSinceKeyRotation; + uint32_t mKeyRotationTime; + uint32_t mKeySwitchGuardTime; + bool mKeySwitchGuardEnabled; TimerMilli mKeyRotationTimer; #if OPENTHREAD_FTD uint8_t mPSKc[kMaxKeyLength]; #endif - uint8_t mKek[kMaxKeyLength]; + uint8_t mKek[kMaxKeyLength]; uint32_t mKekFrameCounter; uint8_t mSecurityPolicyFlags; @@ -372,6 +372,6 @@ private: * @} */ -} // namespace ot +} // namespace ot -#endif // KEY_MANAGER_HPP_ +#endif // KEY_MANAGER_HPP_ diff --git a/src/core/thread/link_quality.cpp b/src/core/thread/link_quality.cpp index f89e5c54d..cf2ea600d 100644 --- a/src/core/thread/link_quality.cpp +++ b/src/core/thread/link_quality.cpp @@ -42,17 +42,15 @@ namespace ot { // This array gives the decimal point digits representing 0/8, 1/8, ..., 7/8 (does not include the '.'). -static const char *const kDigitsString[8] = -{ +static const char *const kDigitsString[8] = { // 0/8, 1/8, 2/8, 3/8, 4/8, 5/8, 6/8, 7/8 - "0", "125", "25", "375", "5", "625", "75", "875" -}; + "0", "125", "25", "375", "5", "625", "75", "875"}; void SuccessRateTracker::AddSample(bool aSuccess, uint16_t aWeight) { uint32_t oldAverage = mFailureRate; - uint32_t newValue = (aSuccess) ? 0 : kMaxRateValue; - uint32_t n = aWeight; + uint32_t newValue = (aSuccess) ? 0 : kMaxRateValue; + uint32_t n = aWeight; // `n/2` is added to the sum to ensure rounding the value to the nearest integer when dividing by `n` // (e.g., 1.2 -> 1, 3.5 -> 4). @@ -63,12 +61,12 @@ void SuccessRateTracker::AddSample(bool aSuccess, uint16_t aWeight) void RssAverager::Reset(void) { mAverage = 0; - mCount = 0; + mCount = 0; } otError RssAverager::Add(int8_t aRss) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint16_t newValue; uint16_t oldAverage; @@ -147,8 +145,8 @@ exit: return aBuf; } -LinkQualityInfo::LinkQualityInfo(void): - mLastRss(OT_RADIO_RSSI_INVALID) +LinkQualityInfo::LinkQualityInfo(void) + : mLastRss(OT_RADIO_RSSI_INVALID) { mRssAverager.Reset(); SetLinkQuality(0); @@ -186,8 +184,8 @@ const char *LinkQualityInfo::ToInfoString(char *aBuf, uint16_t aSize) const { char rssString[RssAverager::kStringSize]; - snprintf(aBuf, aSize, "aveRss:%s, lastRss:%d, linkQuality:%d", - mRssAverager.ToString(rssString, sizeof(rssString)), GetLastRss(), GetLinkQuality()); + snprintf(aBuf, aSize, "aveRss:%s, lastRss:%d, linkQuality:%d", mRssAverager.ToString(rssString, sizeof(rssString)), + GetLastRss(), GetLinkQuality()); return aBuf; } @@ -256,17 +254,17 @@ uint8_t LinkQualityInfo::CalculateLinkQuality(uint8_t aLinkMargin, uint8_t aLast case 0: threshold1 += kHysteresisThreshold; - // fall-through + // fall-through case 1: threshold2 += kHysteresisThreshold; - // fall-through + // fall-through case 2: threshold3 += kHysteresisThreshold; - // fall-through + // fall-through default: break; @@ -288,4 +286,4 @@ uint8_t LinkQualityInfo::CalculateLinkQuality(uint8_t aLinkMargin, uint8_t aLast return linkQuality; } -} // namespace ot +} // namespace ot diff --git a/src/core/thread/link_quality.hpp b/src/core/thread/link_quality.hpp index 1a5998034..128a613d5 100644 --- a/src/core/thread/link_quality.hpp +++ b/src/core/thread/link_quality.hpp @@ -36,8 +36,8 @@ #include "openthread-core-config.h" -#include #include +#include namespace ot { @@ -62,7 +62,7 @@ class SuccessRateTracker public: enum { - kMaxRateValue = 0xffff, ///< Indicates value corresponding to maximum (failure/success) rate of 100%. + kMaxRateValue = 0xffff, ///< Indicates value corresponding to maximum (failure/success) rate of 100%. }; /** @@ -71,7 +71,10 @@ public: * After initialization the tracker starts with success rate 100% (failure rate 0%). * */ - SuccessRateTracker(void): mFailureRate(0) { } + SuccessRateTracker(void) + : mFailureRate(0) + { + } /** * This method resets the tracker to its initialized state, setting success rate to 100%. @@ -124,7 +127,7 @@ class RssAverager public: enum { - kStringSize = 10, ///< Max chars needed for a string representation of average (@sa ToString()). + kStringSize = 10, ///< Max chars needed for a string representation of average (@sa ToString()). }; /** @@ -201,17 +204,17 @@ private: enum { - kPrecisionBitShift = 3, // Precision multiple for RSS average (1 << PrecisionBitShift). - kPrecision = (1 << kPrecisionBitShift), - kPrecisionBitMask = (kPrecision - 1), + kPrecisionBitShift = 3, // Precision multiple for RSS average (1 << PrecisionBitShift). + kPrecision = (1 << kPrecisionBitShift), + kPrecisionBitMask = (kPrecision - 1), - kCoeffBitShift = 3, // Coefficient used for exponentially weighted filter (1 << kCoeffBitShift). + kCoeffBitShift = 3, // Coefficient used for exponentially weighted filter (1 << kCoeffBitShift). }; // Member variables fit into two bytes. - uint16_t mAverage : 11; // The raw average signal strength value (stored as RSS times precision multiple). - uint16_t mCount : 5; // Number of RSS values added to averager so far (limited to 2^kCoeffBitShift-1). + uint16_t mAverage : 11; // The raw average signal strength value (stored as RSS times precision multiple). + uint16_t mCount : 5; // Number of RSS values added to averager so far (limited to 2^kCoeffBitShift-1). }; /** @@ -221,11 +224,10 @@ private: */ class LinkQualityInfo { - public: enum { - kInfoStringSize = 50, ///< Max chars needed for the info string representation (@sa ToInfoString()) + kInfoStringSize = 50, ///< Max chars needed for the info string representation (@sa ToInfoString()) }; /** @@ -322,7 +324,8 @@ public: * @param[in] aTxStatus Success/Failure of MAC frame transmission (`true` -> success, `false` -> failure). * */ - void AddFrameTxStatus(bool aTxStatus) { + void AddFrameTxStatus(bool aTxStatus) + { mFrameErrorRate.AddSample(aTxStatus, OPENTHREAD_CONFIG_FRAME_TX_ERR_RATE_AVERAGING_WINDOW); } @@ -335,7 +338,8 @@ public: * attempts. * */ - void AddMessageTxStatus(bool aTxStatus) { + void AddMessageTxStatus(bool aTxStatus) + { mMessageErrorRate.AddSample(aTxStatus, OPENTHREAD_CONFIG_IPV6_TX_ERR_RATE_AVERAGING_WINDOW); } @@ -415,19 +419,19 @@ private: { // Constants for obtaining link quality from link margin: - kThreshold3 = 20, ///< Link margin threshold for quality 3 link. - kThreshold2 = 10, ///< Link margin threshold for quality 2 link. - kThreshold1 = 2, ///< Link margin threshold for quality 1 link. - kHysteresisThreshold = 2, ///< Link margin hysteresis threshold. + kThreshold3 = 20, ///< Link margin threshold for quality 3 link. + kThreshold2 = 10, ///< Link margin threshold for quality 2 link. + kThreshold1 = 2, ///< Link margin threshold for quality 1 link. + kHysteresisThreshold = 2, ///< Link margin hysteresis threshold. // constants for test: - kLinkQuality3LinkMargin = 50, ///< link margin for Link Quality 3 (21 - 255) - kLinkQuality2LinkMargin = 15, ///< link margin for Link Quality 3 (21 - 255) - kLinkQuality1LinkMargin = 5, ///< link margin for Link Quality 3 (21 - 255) - kLinkQuality0LinkMargin = 0, ///< link margin for Link Quality 3 (21 - 255) + kLinkQuality3LinkMargin = 50, ///< link margin for Link Quality 3 (21 - 255) + kLinkQuality2LinkMargin = 15, ///< link margin for Link Quality 3 (21 - 255) + kLinkQuality1LinkMargin = 5, ///< link margin for Link Quality 3 (21 - 255) + kLinkQuality0LinkMargin = 0, ///< link margin for Link Quality 3 (21 - 255) - kNoLinkQuality = 0xff, // Used to indicate that there is no previous/last link quality. + kNoLinkQuality = 0xff, // Used to indicate that there is no previous/last link quality. }; void SetLinkQuality(uint8_t aLinkQuality) { mLinkQuality = aLinkQuality; } @@ -452,6 +456,6 @@ private: * @} */ -} // namespace ot +} // namespace ot #endif // LINK_QUALITY_HPP_ diff --git a/src/core/thread/lowpan.cpp b/src/core/thread/lowpan.cpp index 3f4e158de..a1367078e 100644 --- a/src/core/thread/lowpan.cpp +++ b/src/core/thread/lowpan.cpp @@ -47,8 +47,8 @@ using ot::Encoding::BigEndian::HostSwap16; namespace ot { namespace Lowpan { -Lowpan::Lowpan(Instance &aInstance): - InstanceLocator(aInstance) +Lowpan::Lowpan(Instance &aInstance) + : InstanceLocator(aInstance) { } @@ -99,10 +99,13 @@ exit: return error; } -int Lowpan::CompressSourceIid(const Mac::Address &aMacAddr, const Ip6::Address &aIpAddr, const Context &aContext, - uint16_t &aHcCtl, uint8_t *aBuf) +int Lowpan::CompressSourceIid(const Mac::Address &aMacAddr, + const Ip6::Address &aIpAddr, + const Context & aContext, + uint16_t & aHcCtl, + uint8_t * aBuf) { - uint8_t *cur = aBuf; + uint8_t * cur = aBuf; Ip6::Address ipaddr; Mac::Address tmp; @@ -135,10 +138,13 @@ int Lowpan::CompressSourceIid(const Mac::Address &aMacAddr, const Ip6::Address & return static_cast(cur - aBuf); } -int Lowpan::CompressDestinationIid(const Mac::Address &aMacAddr, const Ip6::Address &aIpAddr, const Context &aContext, - uint16_t &aHcCtl, uint8_t *aBuf) +int Lowpan::CompressDestinationIid(const Mac::Address &aMacAddr, + const Ip6::Address &aIpAddr, + const Context & aContext, + uint16_t & aHcCtl, + uint8_t * aBuf) { - uint8_t *cur = aBuf; + uint8_t * cur = aBuf; Ip6::Address ipaddr; Mac::Address tmp; @@ -174,8 +180,8 @@ int Lowpan::CompressDestinationIid(const Mac::Address &aMacAddr, const Ip6::Addr int Lowpan::CompressMulticast(const Ip6::Address &aIpAddr, uint16_t &aHcCtl, uint8_t *aBuf) { NetworkData::Leader &networkData = GetNetif().GetNetworkDataLeader(); - uint8_t *cur = aBuf; - Context multicastContext; + uint8_t * cur = aBuf; + Context multicastContext; aHcCtl |= kHcMulticast; @@ -235,20 +241,19 @@ int Lowpan::CompressMulticast(const Ip6::Address &aIpAddr, uint16_t &aHcCtl, uin int Lowpan::Compress(Message &aMessage, const Mac::Address &aMacSource, const Mac::Address &aMacDest, uint8_t *aBuf) { NetworkData::Leader &networkData = GetNetif().GetNetworkDataLeader(); - uint8_t *cur = aBuf; - uint16_t hcCtl = 0; - Ip6::Header ip6Header; - uint8_t *ip6HeaderBytes = reinterpret_cast(&ip6Header); - Context srcContext, dstContext; - bool srcContextValid = true, dstContextValid = true; - uint8_t nextHeader; - uint8_t ecn = 0; - uint8_t dscp = 0; + uint8_t * cur = aBuf; + uint16_t hcCtl = 0; + Ip6::Header ip6Header; + uint8_t * ip6HeaderBytes = reinterpret_cast(&ip6Header); + Context srcContext, dstContext; + bool srcContextValid = true, dstContextValid = true; + uint8_t nextHeader; + uint8_t ecn = 0; + uint8_t dscp = 0; aMessage.Read(aMessage.GetOffset(), sizeof(ip6Header), &ip6Header); - if (networkData.GetContext(ip6Header.GetSource(), srcContext) != OT_ERROR_NONE || - srcContext.mCompressFlag == false) + if (networkData.GetContext(ip6Header.GetSource(), srcContext) != OT_ERROR_NONE || srcContext.mCompressFlag == false) { networkData.GetContext(0, srcContext); srcContextValid = false; @@ -275,7 +280,7 @@ int Lowpan::Compress(Message &aMessage, const Mac::Address &aMacSource, const Ma } dscp = ((ip6HeaderBytes[0] << 2) & 0x3c) | (ip6HeaderBytes[1] >> 6); - ecn = (ip6HeaderBytes[1] << 2) & 0xc0; + ecn = (ip6HeaderBytes[1] << 2) & 0xc0; // Flow Label if (((ip6HeaderBytes[1] & 0x0f) == 0) && ((ip6HeaderBytes[2]) == 0) && ((ip6HeaderBytes[3]) == 0)) @@ -413,7 +418,7 @@ int Lowpan::Compress(Message &aMessage, const Mac::Address &aMacSource, const Ma cur += Compress(aMessage, aMacSource, aMacDest, cur); - // fall through + // fall through default: ExitNow(); @@ -427,11 +432,11 @@ exit: int Lowpan::CompressExtensionHeader(Message &aMessage, uint8_t *aBuf, uint8_t &aNextHeader) { Ip6::ExtensionHeader extHeader; - Ip6::OptionHeader optionHeader; - uint8_t *cur = aBuf; - uint8_t len; - uint8_t padLength = 0; - uint16_t offset; + Ip6::OptionHeader optionHeader; + uint8_t * cur = aBuf; + uint8_t len; + uint8_t padLength = 0; + uint16_t offset; aMessage.Read(aMessage.GetOffset(), sizeof(extHeader), &extHeader); aMessage.MoveOffset(sizeof(extHeader)); @@ -505,13 +510,13 @@ int Lowpan::CompressExtensionHeader(Message &aMessage, uint8_t *aBuf, uint8_t &a int Lowpan::CompressUdp(Message &aMessage, uint8_t *aBuf) { Ip6::UdpHeader udpHeader; - uint8_t *cur = aBuf; - uint8_t *udpCtl = cur; - uint16_t source; - uint16_t destination; + uint8_t * cur = aBuf; + uint8_t * udpCtl = cur; + uint16_t source; + uint16_t destination; aMessage.Read(aMessage.GetOffset(), sizeof(udpHeader), &udpHeader); - source = udpHeader.GetSourcePort(); + source = udpHeader.GetSourcePort(); destination = udpHeader.GetDestinationPort(); cur[0] = kUdpDispatch; @@ -591,18 +596,21 @@ exit: return error; } -int Lowpan::DecompressBaseHeader(Ip6::Header &aIp6Header, const Mac::Address &aMacSource, const Mac::Address &aMacDest, - const uint8_t *aBuf, uint16_t aBufLength) +int Lowpan::DecompressBaseHeader(Ip6::Header & aIp6Header, + const Mac::Address &aMacSource, + const Mac::Address &aMacDest, + const uint8_t * aBuf, + uint16_t aBufLength) { NetworkData::Leader &networkData = GetNetif().GetNetworkDataLeader(); - otError error = OT_ERROR_PARSE; - const uint8_t *cur = aBuf; - uint16_t remaining = aBufLength; - uint16_t hcCtl; - Context srcContext, dstContext; - bool srcContextValid = true, dstContextValid = true; - Ip6::IpProto nextHeader; - uint8_t *bytes; + otError error = OT_ERROR_PARSE; + const uint8_t * cur = aBuf; + uint16_t remaining = aBufLength; + uint16_t hcCtl; + Context srcContext, dstContext; + bool srcContextValid = true, dstContextValid = true; + Ip6::IpProto nextHeader; + uint8_t * bytes; VerifyOrExit(remaining >= 2); hcCtl = static_cast((cur[0] << 8) | cur[1]); @@ -832,7 +840,7 @@ int Lowpan::DecompressBaseHeader(Ip6::Header &aIp6Header, const Mac::Address &aM case kHcDstAddrMode3: VerifyOrExit(remaining >= 1); - aIp6Header.GetDestination().mFields.m8[1] = 0x02; + aIp6Header.GetDestination().mFields.m8[1] = 0x02; aIp6Header.GetDestination().mFields.m8[15] = cur[0]; cur++; remaining--; @@ -876,14 +884,14 @@ exit: int Lowpan::DecompressExtensionHeader(Message &aMessage, const uint8_t *aBuf, uint16_t aBufLength) { - otError error = OT_ERROR_PARSE; - const uint8_t *cur = aBuf; - uint16_t remaining = aBufLength; - uint8_t hdr[2]; - uint8_t len; - Ip6::IpProto nextHeader; - uint8_t ctl = cur[0]; - uint8_t padLength; + otError error = OT_ERROR_PARSE; + const uint8_t * cur = aBuf; + uint16_t remaining = aBufLength; + uint8_t hdr[2]; + uint8_t len; + Ip6::IpProto nextHeader; + uint8_t ctl = cur[0]; + uint8_t padLength; Ip6::OptionPad1 optionPad1; Ip6::OptionPadN optionPadN; @@ -909,7 +917,7 @@ int Lowpan::DecompressExtensionHeader(Message &aMessage, const uint8_t *aBuf, ui VerifyOrExit(remaining >= 2); hdr[0] = cur[0]; - len = cur[1]; + len = cur[1]; cur += 2; remaining -= 2; @@ -956,11 +964,11 @@ exit: int Lowpan::DecompressUdpHeader(Message &aMessage, const uint8_t *aBuf, uint16_t aBufLength, uint16_t aDatagramLength) { - otError error = OT_ERROR_PARSE; - const uint8_t *cur = aBuf; - uint16_t remaining = aBufLength; + otError error = OT_ERROR_PARSE; + const uint8_t *cur = aBuf; + uint16_t remaining = aBufLength; Ip6::UdpHeader udpHeader; - uint8_t udpCtl; + uint8_t udpCtl; VerifyOrExit(remaining >= 1); udpCtl = cur[0]; @@ -1036,18 +1044,22 @@ exit: return (error == OT_ERROR_NONE) ? static_cast(cur - aBuf) : -1; } -int Lowpan::Decompress(Message &aMessage, const Mac::Address &aMacSource, const Mac::Address &aMacDest, - const uint8_t *aBuf, uint16_t aBufLength, uint16_t aDatagramLength) +int Lowpan::Decompress(Message & aMessage, + const Mac::Address &aMacSource, + const Mac::Address &aMacDest, + const uint8_t * aBuf, + uint16_t aBufLength, + uint16_t aDatagramLength) { - otError error = OT_ERROR_PARSE; - Ip6::Header ip6Header; - const uint8_t *cur = aBuf; - uint16_t remaining = aBufLength; - bool compressed; - int rval; - uint16_t ip6PayloadLength; - uint16_t compressedLength = 0; - uint16_t currentOffset = aMessage.GetOffset(); + otError error = OT_ERROR_PARSE; + Ip6::Header ip6Header; + const uint8_t *cur = aBuf; + uint16_t remaining = aBufLength; + bool compressed; + int rval; + uint16_t ip6PayloadLength; + uint16_t compressedLength = 0; + uint16_t currentOffset = aMessage.GetOffset(); VerifyOrExit(remaining >= 2); compressed = (((static_cast(cur[0]) << 8) | cur[1]) & kHcNextHeader) != 0; @@ -1073,8 +1085,7 @@ int Lowpan::Decompress(Message &aMessage, const Mac::Address &aMacSource, const cur++; remaining--; - VerifyOrExit((rval = Decompress(aMessage, aMacSource, aMacDest, cur, remaining, - aDatagramLength)) >= 0); + VerifyOrExit((rval = Decompress(aMessage, aMacSource, aMacDest, cur, remaining, aDatagramLength)) >= 0); } else { @@ -1105,12 +1116,11 @@ int Lowpan::Decompress(Message &aMessage, const Mac::Address &aMacSource, const } else { - ip6PayloadLength = HostSwap16(aMessage.GetOffset() - currentOffset - - sizeof(Ip6::Header) + aBufLength - compressedLength); + ip6PayloadLength = + HostSwap16(aMessage.GetOffset() - currentOffset - sizeof(Ip6::Header) + aBufLength - compressedLength); } - aMessage.Write(currentOffset + Ip6::Header::GetPayloadLengthOffset(), - sizeof(ip6PayloadLength), &ip6PayloadLength); + aMessage.Write(currentOffset + Ip6::Header::GetPayloadLengthOffset(), sizeof(ip6PayloadLength), &ip6PayloadLength); error = OT_ERROR_NONE; @@ -1146,7 +1156,7 @@ exit: otError MeshHeader::Init(const Message &aMessage) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint16_t offset = 0; uint16_t bytesRead; @@ -1193,5 +1203,5 @@ exit: return error; } -} // namespace Lowpan -} // namespace ot +} // namespace Lowpan +} // namespace ot diff --git a/src/core/thread/lowpan.hpp b/src/core/thread/lowpan.hpp index 48e074e61..f63bcc4f8 100644 --- a/src/core/thread/lowpan.hpp +++ b/src/core/thread/lowpan.hpp @@ -68,17 +68,17 @@ namespace Lowpan { */ struct Context { - const uint8_t *mPrefix; ///< A pointer to the prefix. - uint8_t mPrefixLength; ///< The prefix length. - uint8_t mContextId; ///< The Context ID. - bool mCompressFlag; ///< The Context compression flag. + const uint8_t *mPrefix; ///< A pointer to the prefix. + uint8_t mPrefixLength; ///< The prefix length. + uint8_t mContextId; ///< The Context ID. + bool mCompressFlag; ///< The Context compression flag. }; /** * This class implements LOWPAN_IPHC header compression. * */ -class Lowpan: public InstanceLocator +class Lowpan : public InstanceLocator { public: /** @@ -97,7 +97,8 @@ public: * @retval TRUE If the header matches the LOWPAN_IPHC dispatch value. * @retval FALSE If the header does not match the LOWPAN_IPHC dispatch value. */ - static bool IsLowpanHc(uint8_t *aHeader) { + static bool IsLowpanHc(uint8_t *aHeader) + { return (aHeader[0] & (Lowpan::kHcDispatchMask >> 8)) == (Lowpan::kHcDispatch >> 8); } @@ -127,8 +128,12 @@ public: * @returns The size of the compressed header in bytes. * */ - int Decompress(Message &aMessage, const Mac::Address &aMacSource, const Mac::Address &aMacDest, - const uint8_t *aBuf, uint16_t aBufLen, uint16_t aDatagramLen); + int Decompress(Message & aMessage, + const Mac::Address &aMacSource, + const Mac::Address &aMacDest, + const uint8_t * aBuf, + uint16_t aBufLen, + uint16_t aDatagramLen); /** * This method decompresses a LOWPAN_IPHC header. @@ -142,14 +147,17 @@ public: * @returns The size of the compressed header in bytes. * */ - int DecompressBaseHeader(Ip6::Header &aHeader, const Mac::Address &aMacSource, const Mac::Address &aMacDest, - const uint8_t *aBuf, uint16_t aBufLength); + int DecompressBaseHeader(Ip6::Header & aHeader, + const Mac::Address &aMacSource, + const Mac::Address &aMacDest, + const uint8_t * aBuf, + uint16_t aBufLength); private: enum { - kHcDispatch = 3 << 13, - kHcDispatchMask = 7 << 13, + kHcDispatch = 3 << 13, + kHcDispatchMask = 7 << 13, kHcTrafficClass = 1 << 11, kHcFlowLabel = 2 << 11, @@ -178,32 +186,38 @@ private: kExtHdrDispatch = 0xe0, kExtHdrDispatchMask = 0xf0, - kExtHdrEidHbh = 0x00, - kExtHdrEidRouting = 0x02, - kExtHdrEidFragment = 0x04, - kExtHdrEidDst = 0x06, - kExtHdrEidMobility = 0x08, - kExtHdrEidIp6 = 0x0e, - kExtHdrEidMask = 0x0e, + kExtHdrEidHbh = 0x00, + kExtHdrEidRouting = 0x02, + kExtHdrEidFragment = 0x04, + kExtHdrEidDst = 0x06, + kExtHdrEidMobility = 0x08, + kExtHdrEidIp6 = 0x0e, + kExtHdrEidMask = 0x0e, - kExtHdrNextHeader = 0x01, + kExtHdrNextHeader = 0x01, - kUdpDispatch = 0xf0, - kUdpDispatchMask = 0xf8, - kUdpChecksum = 1 << 2, - kUdpPortMask = 3 << 0, + kUdpDispatch = 0xf0, + kUdpDispatchMask = 0xf8, + kUdpChecksum = 1 << 2, + kUdpPortMask = 3 << 0, }; int CompressExtensionHeader(Message &aMessage, uint8_t *aBuf, uint8_t &aNextHeader); - int CompressSourceIid(const Mac::Address &aMacAddr, const Ip6::Address &aIpAddr, const Context &aContext, - uint16_t &aHcCtl, uint8_t *aBuf); - int CompressDestinationIid(const Mac::Address &aMacAddr, const Ip6::Address &aIpAddr, const Context &aContext, - uint16_t &aHcCtl, uint8_t *aBuf); + int CompressSourceIid(const Mac::Address &aMacAddr, + const Ip6::Address &aIpAddr, + const Context & aContext, + uint16_t & aHcCtl, + uint8_t * aBuf); + int CompressDestinationIid(const Mac::Address &aMacAddr, + const Ip6::Address &aIpAddr, + const Context & aContext, + uint16_t & aHcCtl, + uint8_t * aBuf); int CompressMulticast(const Ip6::Address &aIpAddr, uint16_t &aHcCtl, uint8_t *aBuf); int CompressUdp(Message &aMessage, uint8_t *aBuf); - int DecompressExtensionHeader(Message &aMessage, const uint8_t *aBuf, uint16_t aBufLength); - int DecompressUdpHeader(Message &aMessage, const uint8_t *aBuf, uint16_t aBufLength, uint16_t aDatagramLength); + int DecompressExtensionHeader(Message &aMessage, const uint8_t *aBuf, uint16_t aBufLength); + int DecompressUdpHeader(Message &aMessage, const uint8_t *aBuf, uint16_t aBufLength, uint16_t aDatagramLength); otError DispatchToNextHeader(uint8_t aDispatch, Ip6::IpProto &aNextHeader); static otError CopyContext(const Context &aContext, Ip6::Address &aAddress); @@ -220,7 +234,7 @@ class MeshHeader public: enum { - kAdditionalHopsLeft = 1 ///< The additional value that is added to predicted value of the route cost. + kAdditionalHopsLeft = 1 ///< The additional value that is added to predicted value of the route cost. }; /** @@ -291,7 +305,7 @@ public: * @returns The size of the Mesh Header in bytes. * */ - uint8_t GetHeaderLength(void) { return sizeof(*this) - (IsDeepHopsLeftField() ? 0 : sizeof(mDeepHopsLeft)) ; } + uint8_t GetHeaderLength(void) { return sizeof(*this) - (IsDeepHopsLeftField() ? 0 : sizeof(mDeepHopsLeft)); } /** * This method returns the Hops Left value. @@ -307,13 +321,16 @@ public: * @param[in] aHops The Hops Left value. * */ - void SetHopsLeft(uint8_t aHops) { - if (aHops < kDeepHopsLeft && !IsDeepHopsLeftField()) { + void SetHopsLeft(uint8_t aHops) + { + if (aHops < kDeepHopsLeft && !IsDeepHopsLeftField()) + { mDispatchHopsLeft = (mDispatchHopsLeft & ~kHopsLeftMask) | aHops; } - else { + else + { mDispatchHopsLeft = (mDispatchHopsLeft & ~kHopsLeftMask) | kDeepHopsLeft; - mDeepHopsLeft = aHops; + mDeepHopsLeft = aHops; } } @@ -355,10 +372,12 @@ public: * @param[in] aFrame The pointer to the frame. * */ - void AppendTo(uint8_t *aFrame) { + void AppendTo(uint8_t *aFrame) + { *aFrame++ = mDispatchHopsLeft; - if (IsDeepHopsLeftField()) { + if (IsDeepHopsLeftField()) + { *aFrame++ = mDeepHopsLeft; } @@ -376,8 +395,8 @@ private: kDeepHopsLeft = 0x0f }; - uint8_t mDispatchHopsLeft; - uint8_t mDeepHopsLeft; + uint8_t mDispatchHopsLeft; + uint8_t mDeepHopsLeft; struct OT_TOOL_PACKED_FIELD { uint16_t mSource; @@ -397,7 +416,12 @@ public: * This constructor initializes the Fragment Header. * */ - FragmentHeader(void) { mDispatchSize = HostSwap16(kDispatch); mTag = 0; mOffset = 0; } + FragmentHeader(void) + { + mDispatchSize = HostSwap16(kDispatch); + mTag = 0; + mOffset = 0; + } /** * This method initializes the Fragment Header. @@ -456,7 +480,8 @@ public: * @param[in] aSize The Datagram Size value. * */ - void SetDatagramSize(uint16_t aSize) { + void SetDatagramSize(uint16_t aSize) + { mDispatchSize = HostSwap16((HostSwap16(mDispatchSize) & ~kSizeMask) | (aSize & kSizeMask)); } @@ -490,13 +515,16 @@ public: * @param[in] aOffset The Datagram Offset value. * */ - void SetDatagramOffset(uint16_t aOffset) { - if (aOffset == 0) { + void SetDatagramOffset(uint16_t aOffset) + { + if (aOffset == 0) + { mDispatchSize = HostSwap16(HostSwap16(mDispatchSize) & ~kOffset); } - else { + else + { mDispatchSize = HostSwap16(HostSwap16(mDispatchSize) | kOffset); - mOffset = (aOffset >> 3) & kOffsetMask; + mOffset = (aOffset >> 3) & kOffsetMask; } } @@ -505,7 +533,7 @@ private: { kDispatch = 3 << 14, kOffset = 1 << 13, - kDispatchMask = 0xd800, ///< Accept FRAG1 and FRAGN only. + kDispatchMask = 0xd800, ///< Accept FRAG1 and FRAGN only. kSizeMask = 0x7ff, kOffsetMask = 0xff, }; @@ -519,7 +547,7 @@ private: * @} */ -} // namespace Lowpan -} // namespace ot +} // namespace Lowpan +} // namespace ot -#endif // LOWPAN_HPP_ +#endif // LOWPAN_HPP_ diff --git a/src/core/thread/mesh_forwarder.cpp b/src/core/thread/mesh_forwarder.cpp index cf7926719..3d814bf28 100644 --- a/src/core/thread/mesh_forwarder.cpp +++ b/src/core/thread/mesh_forwarder.cpp @@ -57,33 +57,35 @@ using ot::Encoding::BigEndian::HostSwap16; namespace ot { -MeshForwarder::MeshForwarder(Instance &aInstance): - InstanceLocator(aInstance), - mMacReceiver(&MeshForwarder::HandleReceivedFrame, &MeshForwarder::HandleDataPollTimeout, this), - mMacSender(&MeshForwarder::HandleFrameRequest, &MeshForwarder::HandleSentFrame, this), - mDiscoverTimer(aInstance, &MeshForwarder::HandleDiscoverTimer, this), - mReassemblyTimer(aInstance, &MeshForwarder::HandleReassemblyTimer, this), - mMessageNextOffset(0), - mSendMessage(NULL), - mSendMessageIsARetransmission(false), - mSendMessageMaxMacTxAttempts(Mac::kDirectFrameMacTxAttempts), - mMeshSource(), - mMeshDest(), - mAddMeshHeader(false), - mSendBusy(false), - mScheduleTransmissionTask(aInstance, ScheduleTransmissionTask, this), - mEnabled(false), - mScanChannels(0), - mScanChannel(0), - mRestoreChannel(0), - mRestorePanId(Mac::kPanIdBroadcast), - mScanning(false), +MeshForwarder::MeshForwarder(Instance &aInstance) + : InstanceLocator(aInstance) + , mMacReceiver(&MeshForwarder::HandleReceivedFrame, &MeshForwarder::HandleDataPollTimeout, this) + , mMacSender(&MeshForwarder::HandleFrameRequest, &MeshForwarder::HandleSentFrame, this) + , mDiscoverTimer(aInstance, &MeshForwarder::HandleDiscoverTimer, this) + , mReassemblyTimer(aInstance, &MeshForwarder::HandleReassemblyTimer, this) + , mMessageNextOffset(0) + , mSendMessage(NULL) + , mSendMessageIsARetransmission(false) + , mSendMessageMaxMacTxAttempts(Mac::kDirectFrameMacTxAttempts) + , mMeshSource() + , mMeshDest() + , mAddMeshHeader(false) + , mSendBusy(false) + , mScheduleTransmissionTask(aInstance, ScheduleTransmissionTask, this) + , mEnabled(false) + , mScanChannels(0) + , mScanChannel(0) + , mRestoreChannel(0) + , mRestorePanId(Mac::kPanIdBroadcast) + , mScanning(false) + , #if OPENTHREAD_FTD - mSourceMatchController(aInstance), - mSendMessageFrameCounter(0), - mSendMessageKeyId(0), - mSendMessageDataSequenceNumber(0), - mStartChildIndex(0), + mSourceMatchController(aInstance) + , mSendMessageFrameCounter(0) + , mSendMessageKeyId(0) + , mSendMessageDataSequenceNumber(0) + , mStartChildIndex(0) + , #endif mDataPollManager(aInstance) { @@ -112,8 +114,8 @@ otError MeshForwarder::Start(void) otError MeshForwarder::Stop(void) { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Message *message; + otError error = OT_ERROR_NONE; + Message * message; VerifyOrExit(mEnabled == true); @@ -139,7 +141,7 @@ otError MeshForwarder::Stop(void) message->Free(); } - mEnabled = false; + mEnabled = false; mSendMessage = NULL; netif.GetMac().SetRxOnWhenIdle(false); @@ -149,7 +151,7 @@ exit: void MeshForwarder::RemoveMessage(Message &aMessage) { - Child *children; + Child * children; uint8_t numChildren; children = GetNetif().GetMle().GetChildren(&numChildren); @@ -204,14 +206,14 @@ exit: otError MeshForwarder::PrepareDiscoverRequest(void) { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; VerifyOrExit(!mScanning); mScanChannel = OT_RADIO_CHANNEL_MIN; mScanChannels >>= OT_RADIO_CHANNEL_MIN; mRestoreChannel = netif.GetMac().GetChannel(); - mRestorePanId = netif.GetMac().GetPanId(); + mRestorePanId = netif.GetMac().GetPanId(); while ((mScanChannels & 1) == 0) { @@ -234,7 +236,7 @@ exit: Message *MeshForwarder::GetDirectTransmission(void) { Message *curMessage, *nextMessage; - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; for (curMessage = mSendQueue.GetHead(); curMessage; curMessage = nextMessage) { @@ -307,10 +309,10 @@ exit: otError MeshForwarder::PrepareDataPoll(void) { - otError error = OT_ERROR_NONE; - ThreadNetif &netif = GetNetif(); - Neighbor *parent = netif.GetMle().GetParentCandidate(); - uint16_t shortAddress; + otError error = OT_ERROR_NONE; + ThreadNetif &netif = GetNetif(); + Neighbor * parent = netif.GetMle().GetParentCandidate(); + uint16_t shortAddress; VerifyOrExit((parent != NULL) && parent->IsStateValidOrRestoring(), error = OT_ERROR_DROP); @@ -334,8 +336,8 @@ exit: otError MeshForwarder::UpdateIp6Route(Message &aMessage) { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Ip6::Header ip6Header; + otError error = OT_ERROR_NONE; + Ip6::Header ip6Header; mAddMeshHeader = false; @@ -347,8 +349,7 @@ otError MeshForwarder::UpdateIp6Route(Message &aMessage) GetMacSourceAddress(ip6Header.GetSource(), mMacSource); // 2. Choose correct MAC Destination Address. - if (netif.GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED || - netif.GetMle().GetRole() == OT_DEVICE_ROLE_DETACHED) + if (netif.GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED || netif.GetMle().GetRole() == OT_DEVICE_ROLE_DETACHED) { // Allow only for link-local unicasts and multicasts. if (ip6Header.GetDestination().IsLinkLocal() || ip6Header.GetDestination().IsLinkLocalMulticast()) @@ -449,12 +450,9 @@ otError MeshForwarder::GetMacDestinationAddress(const Ip6::Address &aIp6Addr, Ma { aMacAddr.SetShort(Mac::kShortAddrBroadcast); } - else if (aIp6Addr.mFields.m16[0] == HostSwap16(0xfe80) && - aIp6Addr.mFields.m16[1] == HostSwap16(0x0000) && - aIp6Addr.mFields.m16[2] == HostSwap16(0x0000) && - aIp6Addr.mFields.m16[3] == HostSwap16(0x0000) && - aIp6Addr.mFields.m16[4] == HostSwap16(0x0000) && - aIp6Addr.mFields.m16[5] == HostSwap16(0x00ff) && + else if (aIp6Addr.mFields.m16[0] == HostSwap16(0xfe80) && aIp6Addr.mFields.m16[1] == HostSwap16(0x0000) && + aIp6Addr.mFields.m16[2] == HostSwap16(0x0000) && aIp6Addr.mFields.m16[3] == HostSwap16(0x0000) && + aIp6Addr.mFields.m16[4] == HostSwap16(0x0000) && aIp6Addr.mFields.m16[5] == HostSwap16(0x00ff) && aIp6Addr.mFields.m16[6] == HostSwap16(0xfe00)) { aMacAddr.SetShort(HostSwap16(aIp6Addr.mFields.m16[7])); @@ -479,7 +477,7 @@ otError MeshForwarder::HandleFrameRequest(Mac::Sender &aSender, Mac::Frame &aFra otError MeshForwarder::HandleFrameRequest(Mac::Frame &aFrame) { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; VerifyOrExit(mEnabled, error = OT_ERROR_ABORT); @@ -505,16 +503,14 @@ otError MeshForwarder::HandleFrameRequest(Mac::Frame &aFrame) // Request messages MUST have the Destination PAN ID in the IEEE 802.15.4 MAC header set // to be the Broadcast PAN ID (0xFFFF) and the Source PAN ID set to a randomly generated // value. - if (mSendMessage->GetPanId() == Mac::kPanIdBroadcast && - netif.GetMac().GetPanId() == Mac::kPanIdBroadcast) + if (mSendMessage->GetPanId() == Mac::kPanIdBroadcast && netif.GetMac().GetPanId() == Mac::kPanIdBroadcast) { uint16_t panid; do { panid = static_cast(otPlatRandomGet()); - } - while (panid == Mac::kPanIdBroadcast); + } while (panid == Mac::kPanIdBroadcast); netif.GetMac().SetPanId(panid); } @@ -545,7 +541,7 @@ otError MeshForwarder::HandleFrameRequest(Mac::Frame &aFrame) break; case Message::kTypeSupervision: - error = SendEmptyFrame(aFrame, kSupervisionMsgAckRequest); + error = SendEmptyFrame(aFrame, kSupervisionMsgAckRequest); mMessageNextOffset = mSendMessage->GetLength(); break; @@ -561,7 +557,7 @@ otError MeshForwarder::HandleFrameRequest(Mac::Frame &aFrame) { Mac::Address macDest; - Child *child = NULL; + Child * child = NULL; if (mSendMessageIsARetransmission) { @@ -585,9 +581,8 @@ otError MeshForwarder::HandleFrameRequest(Mac::Frame &aFrame) // The case where the current message requires fragmentation is // already checked and handled in `SendFragment()` method. - if (((child = netif.GetMle().GetChild(macDest)) != NULL) - && !child->IsRxOnWhenIdle() - && (child->GetIndirectMessageCount() > 1)) + if (((child = netif.GetMle().GetChild(macDest)) != NULL) && !child->IsRxOnWhenIdle() && + (child->GetIndirectMessageCount() > 1)) { aFrame.SetFramePending(true); } @@ -602,12 +597,11 @@ exit: otError MeshForwarder::SendPoll(Message &aMessage, Mac::Frame &aFrame) { ThreadNetif &netif = GetNetif(); - uint16_t fcf; + uint16_t fcf; // initialize MAC header fcf = Mac::Frame::kFcfFrameMacCmd | Mac::Frame::kFcfPanidCompression | Mac::Frame::kFcfFrameVersion2006; - if (mMacSource.IsShort()) { fcf |= Mac::Frame::kFcfDstAddrShort | Mac::Frame::kFcfSrcAddrShort; @@ -632,18 +626,18 @@ otError MeshForwarder::SendPoll(Message &aMessage, Mac::Frame &aFrame) otError MeshForwarder::SendFragment(Message &aMessage, Mac::Frame &aFrame) { - ThreadNetif &netif = GetNetif(); - Mac::Address meshDest, meshSource; - uint16_t fcf; + ThreadNetif & netif = GetNetif(); + Mac::Address meshDest, meshSource; + uint16_t fcf; Lowpan::FragmentHeader *fragmentHeader; - uint8_t *payload; - uint8_t headerLength; - uint16_t payloadLength; - int hcLength; - uint16_t fragmentLength; - uint16_t dstpan; - uint8_t secCtl = Mac::Frame::kSecNone; - otError error = OT_ERROR_NONE; + uint8_t * payload; + uint8_t headerLength; + uint16_t payloadLength; + int hcLength; + uint16_t fragmentLength; + uint16_t dstpan; + uint8_t secCtl = Mac::Frame::kSecNone; + otError error = OT_ERROR_NONE; if (mAddMeshHeader) { @@ -652,7 +646,7 @@ otError MeshForwarder::SendFragment(Message &aMessage, Mac::Frame &aFrame) } else { - meshDest = mMacDest; + meshDest = mMacDest; meshSource = mMacSource; } @@ -728,7 +722,7 @@ otError MeshForwarder::SendFragment(Message &aMessage, Mac::Frame &aFrame) if (mAddMeshHeader) { Lowpan::MeshHeader meshHeader; - uint8_t hopsLeft; + uint8_t hopsLeft; if (netif.GetMle().GetRole() == OT_DEVICE_ROLE_CHILD) { @@ -742,15 +736,14 @@ otError MeshForwarder::SendFragment(Message &aMessage, Mac::Frame &aFrame) if (hopsLeft != Mle::kMaxRouteCost) { - hopsLeft += netif.GetMle().GetLinkCost( - netif.GetMle().GetRouterId(netif.GetMle().GetNextHop(mMeshDest))); + hopsLeft += + netif.GetMle().GetLinkCost(netif.GetMle().GetRouterId(netif.GetMle().GetNextHop(mMeshDest))); } else { // In case there is no route to the destination router (only link). hopsLeft = netif.GetMle().GetLinkCost(netif.GetMle().GetRouterId(mMeshDest)); } - } // The hopsLft field MUST be incremented by one if the destination RLOC16 @@ -866,8 +859,8 @@ exit: otError MeshForwarder::SendEmptyFrame(Mac::Frame &aFrame, bool aAckRequest) { ThreadNetif &netif = GetNetif(); - uint16_t fcf; - uint8_t secCtl; + uint16_t fcf; + uint8_t secCtl; Mac::Address macSource; macSource.SetShort(netif.GetMac().GetShortAddress()); @@ -913,7 +906,7 @@ void MeshForwarder::HandleSentFrame(Mac::Frame &aFrame, otError aError) { ThreadNetif &netif = GetNetif(); Mac::Address macDest; - Neighbor *neighbor; + Neighbor * neighbor; mSendBusy = false; @@ -1040,7 +1033,7 @@ void MeshForwarder::HandleSentFrame(Mac::Frame &aFrame, otError aError) { mSendQueue.Dequeue(*mSendMessage); mSendMessage->Free(); - mSendMessage = NULL; + mSendMessage = NULL; mMessageNextOffset = 0; } @@ -1082,8 +1075,7 @@ void MeshForwarder::HandleDiscoverTimer(void) netif.GetMle().HandleDiscoverComplete(); ExitNow(); } - } - while ((mScanChannels & 1) == 0); + } while ((mScanChannels & 1) == 0); mSendMessage->SetDirectTransmission(); @@ -1099,14 +1091,14 @@ void MeshForwarder::HandleReceivedFrame(Mac::Receiver &aReceiver, Mac::Frame &aF void MeshForwarder::HandleReceivedFrame(Mac::Frame &aFrame) { - ThreadNetif &netif = GetNetif(); + ThreadNetif & netif = GetNetif(); otThreadLinkInfo linkInfo; - Mac::Address macDest; - Mac::Address macSource; - uint8_t *payload; - uint8_t payloadLength; - otError error = OT_ERROR_NONE; - char stringBuffer[Mac::Frame::kInfoStringSize]; + Mac::Address macDest; + Mac::Address macSource; + uint8_t * payload; + uint8_t payloadLength; + otError error = OT_ERROR_NONE; + char stringBuffer[Mac::Frame::kInfoStringSize]; if (!mEnabled) { @@ -1117,12 +1109,12 @@ void MeshForwarder::HandleReceivedFrame(Mac::Frame &aFrame) SuccessOrExit(error = aFrame.GetDstAddr(macDest)); aFrame.GetSrcPanId(linkInfo.mPanId); - linkInfo.mChannel = aFrame.GetChannel(); - linkInfo.mRss = aFrame.GetRssi(); - linkInfo.mLqi = aFrame.GetLqi(); + linkInfo.mChannel = aFrame.GetChannel(); + linkInfo.mRss = aFrame.GetRssi(); + linkInfo.mLqi = aFrame.GetLqi(); linkInfo.mLinkSecurity = aFrame.GetSecurityEnabled(); - payload = aFrame.GetPayload(); + payload = aFrame.GetPayload(); payloadLength = aFrame.GetPayloadLength(); netif.GetSupervisionListener().UpdateOnReceive(macSource, linkInfo.mLinkSecurity); @@ -1189,21 +1181,22 @@ exit: { otLogInfoMac(GetInstance(), "Dropping rx frame, error:%s, %s", otThreadErrorToString(error), aFrame.ToInfoString(stringBuffer, sizeof(stringBuffer))); - } OT_UNUSED_VARIABLE(stringBuffer); } -void MeshForwarder::HandleFragment(uint8_t *aFrame, uint8_t aFrameLength, - const Mac::Address &aMacSource, const Mac::Address &aMacDest, +void MeshForwarder::HandleFragment(uint8_t * aFrame, + uint8_t aFrameLength, + const Mac::Address & aMacSource, + const Mac::Address & aMacDest, const otThreadLinkInfo &aLinkInfo) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; Lowpan::FragmentHeader fragmentHeader; - Message *message = NULL; - int headerLength; + Message * message = NULL; + int headerLength; // Check the fragment header VerifyOrExit(fragmentHeader.Init(aFrame, aFrameLength) == OT_ERROR_NONE, error = OT_ERROR_DROP); @@ -1309,18 +1302,13 @@ exit: OT_UNUSED_VARIABLE(srcStringBuffer); OT_UNUSED_VARIABLE(dstStringBuffer); - otLogInfoMac( - GetInstance(), - "Dropping rx frag frame, error:%s, len:%d, src:%s, dst:%s, tag:%d, offset:%d, dglen:%d, sec:%s", - otThreadErrorToString(error), - aFrameLength, - aMacSource.ToString(srcStringBuffer, sizeof(srcStringBuffer)), - aMacDest.ToString(dstStringBuffer, sizeof(dstStringBuffer)), - fragmentHeader.GetDatagramTag(), - fragmentHeader.GetDatagramOffset(), - fragmentHeader.GetDatagramSize(), - aLinkInfo.mLinkSecurity ? "yes" : "no" - ); + otLogInfoMac(GetInstance(), + "Dropping rx frag frame, error:%s, len:%d, src:%s, dst:%s, tag:%d, offset:%d, dglen:%d, sec:%s", + otThreadErrorToString(error), aFrameLength, + aMacSource.ToString(srcStringBuffer, sizeof(srcStringBuffer)), + aMacDest.ToString(dstStringBuffer, sizeof(dstStringBuffer)), fragmentHeader.GetDatagramTag(), + fragmentHeader.GetDatagramOffset(), fragmentHeader.GetDatagramSize(), + aLinkInfo.mLinkSecurity ? "yes" : "no"); if (message != NULL) { @@ -1354,11 +1342,11 @@ void MeshForwarder::HandleReassemblyTimer(Timer &aTimer) void MeshForwarder::HandleReassemblyTimer(void) { Message *next = NULL; - uint8_t timeout; + uint8_t timeout; for (Message *message = mReassemblyList.GetHead(); message; message = next) { - next = message->GetNext(); + next = message->GetNext(); timeout = message->GetTimeout(); if (timeout > 0) @@ -1382,14 +1370,16 @@ void MeshForwarder::HandleReassemblyTimer(void) } } -void MeshForwarder::HandleLowpanHC(uint8_t *aFrame, uint8_t aFrameLength, - const Mac::Address &aMacSource, const Mac::Address &aMacDest, +void MeshForwarder::HandleLowpanHC(uint8_t * aFrame, + uint8_t aFrameLength, + const Mac::Address & aMacSource, + const Mac::Address & aMacDest, const otThreadLinkInfo &aLinkInfo) { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Message *message; - int headerLength; + otError error = OT_ERROR_NONE; + Message * message; + int headerLength; VerifyOrExit((message = GetInstance().GetMessagePool().New(Message::kTypeIp6, 0)) != NULL, error = OT_ERROR_NO_BUFS); @@ -1424,14 +1414,9 @@ exit: OT_UNUSED_VARIABLE(dstStringBuffer); otLogInfoMac( - GetInstance(), - "Dropping rx lowpan HC frame, error:%s, len:%d, src:%s, dst:%s, sec:%s", - otThreadErrorToString(error), - aFrameLength, - aMacSource.ToString(srcStringBuffer, sizeof(srcStringBuffer)), - aMacDest.ToString(dstStringBuffer, sizeof(dstStringBuffer)), - aLinkInfo.mLinkSecurity ? "yes" : "no" - ); + GetInstance(), "Dropping rx lowpan HC frame, error:%s, len:%d, src:%s, dst:%s, sec:%s", + otThreadErrorToString(error), aFrameLength, aMacSource.ToString(srcStringBuffer, sizeof(srcStringBuffer)), + aMacDest.ToString(dstStringBuffer, sizeof(dstStringBuffer)), aLinkInfo.mLinkSecurity ? "yes" : "no"); if (message != NULL) { @@ -1440,8 +1425,9 @@ exit: } } -otError MeshForwarder::HandleDatagram(Message &aMessage, const otThreadLinkInfo &aLinkInfo, - const Mac::Address &aMacSource) +otError MeshForwarder::HandleDatagram(Message & aMessage, + const otThreadLinkInfo &aLinkInfo, + const Mac::Address & aMacSource) { ThreadNetif &netif = GetNetif(); @@ -1458,18 +1444,20 @@ void MeshForwarder::HandleDataPollTimeout(Mac::Receiver &aReceiver) #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MAC == 1) -void MeshForwarder::LogIp6Message(MessageAction aAction, const Message &aMessage, const Mac::Address *aMacAddress, - otError aError) +void MeshForwarder::LogIp6Message(MessageAction aAction, + const Message & aMessage, + const Mac::Address *aMacAddress, + otError aError) { - uint16_t checksum = 0; - Ip6::Header ip6Header; + uint16_t checksum = 0; + Ip6::Header ip6Header; Ip6::IpProto protocol; - const char *actionText; - const char *priorityText; - bool shouldLogRss = false; - bool shouldLogSrcDstAddresses = true; - char stringBuffer[Ip6::Address::kIp6AddressStringSize]; - char rssString[RssAverager::kStringSize]; + const char * actionText; + const char * priorityText; + bool shouldLogRss = false; + bool shouldLogSrcDstAddresses = true; + char stringBuffer[Ip6::Address::kIp6AddressStringSize]; + char rssString[RssAverager::kStringSize]; VerifyOrExit(aMessage.GetType() == Message::kTypeIp6); @@ -1511,7 +1499,7 @@ void MeshForwarder::LogIp6Message(MessageAction aAction, const Message &aMessage switch (aAction) { case kMessageReceive: - actionText = "Received"; + actionText = "Received"; shouldLogRss = true; break; @@ -1528,7 +1516,7 @@ void MeshForwarder::LogIp6Message(MessageAction aAction, const Message &aMessage break; case kMessagePrepareIndirect: - actionText = "Prepping indir tx"; + actionText = "Prepping indir tx"; shouldLogSrcDstAddresses = false; break; @@ -1537,7 +1525,7 @@ void MeshForwarder::LogIp6Message(MessageAction aAction, const Message &aMessage break; case kMessageReassemblyDrop: - actionText = "Dropping (reassembly queue)"; + actionText = "Dropping (reassembly queue)"; shouldLogRss = true; break; @@ -1573,22 +1561,14 @@ void MeshForwarder::LogIp6Message(MessageAction aAction, const Message &aMessage break; } - otLogInfoMac( - GetInstance(), - "%s IPv6 %s msg, len:%d, chksum:%04x%s%s, sec:%s%s%s, prio:%s%s%s", - actionText, - Ip6::Ip6::IpProtoToString(protocol), - aMessage.GetLength(), - checksum, - (aMacAddress == NULL) ? "" : ((aAction == kMessageReceive) ? ", from:" : ", to:"), - (aMacAddress == NULL) ? "" : aMacAddress->ToString(stringBuffer, sizeof(stringBuffer)), - aMessage.IsLinkSecurityEnabled() ? "yes" : "no", - (aError == OT_ERROR_NONE) ? "" : ", error:", - (aError == OT_ERROR_NONE) ? "" : otThreadErrorToString(aError), - priorityText, - shouldLogRss ? ", rss:" : "", - shouldLogRss ? aMessage.GetRssAverager().ToString(rssString, sizeof(rssString)) : "" - ); + otLogInfoMac(GetInstance(), "%s IPv6 %s msg, len:%d, chksum:%04x%s%s, sec:%s%s%s, prio:%s%s%s", actionText, + Ip6::Ip6::IpProtoToString(protocol), aMessage.GetLength(), checksum, + (aMacAddress == NULL) ? "" : ((aAction == kMessageReceive) ? ", from:" : ", to:"), + (aMacAddress == NULL) ? "" : aMacAddress->ToString(stringBuffer, sizeof(stringBuffer)), + aMessage.IsLinkSecurityEnabled() ? "yes" : "no", (aError == OT_ERROR_NONE) ? "" : ", error:", + (aError == OT_ERROR_NONE) ? "" : otThreadErrorToString(aError), priorityText, + shouldLogRss ? ", rss:" : "", + shouldLogRss ? aMessage.GetRssAverager().ToString(rssString, sizeof(rssString)) : ""); if (shouldLogSrcDstAddresses) { @@ -1608,4 +1588,4 @@ void MeshForwarder::LogIp6Message(MessageAction, const Message &, const Mac::Add #endif //#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO -} // namespace ot +} // namespace ot diff --git a/src/core/thread/mesh_forwarder.hpp b/src/core/thread/mesh_forwarder.hpp index 5959d0130..9cae77cfb 100644 --- a/src/core/thread/mesh_forwarder.hpp +++ b/src/core/thread/mesh_forwarder.hpp @@ -71,7 +71,7 @@ class MleRouter; * This class implements mesh forwarding within Thread. * */ -class MeshForwarder: public InstanceLocator +class MeshForwarder : public InstanceLocator { public: /** @@ -242,7 +242,7 @@ public: private: enum { - kStateUpdatePeriod = 1000, ///< State update period in milliseconds. + kStateUpdatePeriod = 1000, ///< State update period in milliseconds. }; enum @@ -259,106 +259,114 @@ private: * Indicates whether to set/enable 15.4 ack request in the MAC header of a supervision message. * */ - kSupervisionMsgAckRequest = (OPENTHREAD_CONFIG_SUPERVISION_MSG_NO_ACK_REQUEST == 0) ? true : false, + kSupervisionMsgAckRequest = (OPENTHREAD_CONFIG_SUPERVISION_MSG_NO_ACK_REQUEST == 0) ? true : false, }; - enum MessageAction ///< Defines the action parameter in `LogMessageInfo()` method. + enum MessageAction ///< Defines the action parameter in `LogMessageInfo()` method. { - kMessageReceive, ///< Indicates that the message was received. - kMessageTransmit, ///< Indicates that the message was sent. - kMessagePrepareIndirect, ///< Indicates that the message is being prepared for indirect tx. - kMessageDrop, ///< Indicates that the outbound message is being dropped (e.g., dst unknown). - kMessageReassemblyDrop, ///< Indicates that the message is being dropped from reassembly list. - kMessageEvict, ///< Indicates that the message was evicted. + kMessageReceive, ///< Indicates that the message was received. + kMessageTransmit, ///< Indicates that the message was sent. + kMessagePrepareIndirect, ///< Indicates that the message is being prepared for indirect tx. + kMessageDrop, ///< Indicates that the outbound message is being dropped (e.g., dst unknown). + kMessageReassemblyDrop, ///< Indicates that the message is being dropped from reassembly list. + kMessageEvict, ///< Indicates that the message was evicted. }; - otError CheckReachability(uint8_t *aFrame, uint8_t aFrameLength, - const Mac::Address &aMeshSource, const Mac::Address &aMeshDest); - void UpdateRoutes(uint8_t *aFrame, uint8_t aFrameLength, - const Mac::Address &aMeshSource, const Mac::Address &aMeshDest); + otError CheckReachability(uint8_t * aFrame, + uint8_t aFrameLength, + const Mac::Address &aMeshSource, + const Mac::Address &aMeshDest); + void UpdateRoutes(uint8_t * aFrame, + uint8_t aFrameLength, + const Mac::Address &aMeshSource, + const Mac::Address &aMeshDest); - otError GetMacDestinationAddress(const Ip6::Address &aIp6Addr, Mac::Address &aMacAddr); - otError GetMacSourceAddress(const Ip6::Address &aIp6Addr, Mac::Address &aMacAddr); + otError GetMacDestinationAddress(const Ip6::Address &aIp6Addr, Mac::Address &aMacAddr); + otError GetMacSourceAddress(const Ip6::Address &aIp6Addr, Mac::Address &aMacAddr); Message *GetDirectTransmission(void); - otError GetIndirectTransmission(void); + otError GetIndirectTransmission(void); Message *GetIndirectTransmission(Child &aChild); - otError PrepareDiscoverRequest(void); - void PrepareIndirectTransmission(Message &aMessage, const Child &aChild); - otError PrepareDataPoll(void); - void HandleMesh(uint8_t *aFrame, uint8_t aPayloadLength, const Mac::Address &aMacSource, - const otThreadLinkInfo &aLinkInfo); - void HandleFragment(uint8_t *aFrame, uint8_t aPayloadLength, - const Mac::Address &aMacSource, const Mac::Address &aMacDest, + otError PrepareDiscoverRequest(void); + void PrepareIndirectTransmission(Message &aMessage, const Child &aChild); + otError PrepareDataPoll(void); + void HandleMesh(uint8_t * aFrame, + uint8_t aPayloadLength, + const Mac::Address & aMacSource, const otThreadLinkInfo &aLinkInfo); - void HandleLowpanHC(uint8_t *aFrame, uint8_t aPayloadLength, - const Mac::Address &aMacSource, const Mac::Address &aMacDest, - const otThreadLinkInfo &aLinkInfo); - void HandleDataRequest(const Mac::Address &aMacSource, const otThreadLinkInfo &aLinkInfo); - otError SendPoll(Message &aMessage, Mac::Frame &aFrame); - otError SendMesh(Message &aMessage, Mac::Frame &aFrame); - otError SendFragment(Message &aMessage, Mac::Frame &aFrame); - otError SendEmptyFrame(Mac::Frame &aFrame, bool aAckRequest); - otError UpdateIp6Route(Message &aMessage); - otError UpdateIp6RouteFtd(Ip6::Header &ip6Header); - otError UpdateMeshRoute(Message &aMessage); - otError HandleDatagram(Message &aMessage, const otThreadLinkInfo &aLinkInfo, - const Mac::Address &aMacSource); - void ClearReassemblyList(void); - otError RemoveMessageFromSleepyChild(Message &aMessage, Child &aChild); - void RemoveMessage(Message &aMessage); + void HandleFragment(uint8_t * aFrame, + uint8_t aPayloadLength, + const Mac::Address & aMacSource, + const Mac::Address & aMacDest, + const otThreadLinkInfo &aLinkInfo); + void HandleLowpanHC(uint8_t * aFrame, + uint8_t aPayloadLength, + const Mac::Address & aMacSource, + const Mac::Address & aMacDest, + const otThreadLinkInfo &aLinkInfo); + void HandleDataRequest(const Mac::Address &aMacSource, const otThreadLinkInfo &aLinkInfo); + otError SendPoll(Message &aMessage, Mac::Frame &aFrame); + otError SendMesh(Message &aMessage, Mac::Frame &aFrame); + otError SendFragment(Message &aMessage, Mac::Frame &aFrame); + otError SendEmptyFrame(Mac::Frame &aFrame, bool aAckRequest); + otError UpdateIp6Route(Message &aMessage); + otError UpdateIp6RouteFtd(Ip6::Header &ip6Header); + otError UpdateMeshRoute(Message &aMessage); + otError HandleDatagram(Message &aMessage, const otThreadLinkInfo &aLinkInfo, const Mac::Address &aMacSource); + void ClearReassemblyList(void); + otError RemoveMessageFromSleepyChild(Message &aMessage, Child &aChild); + void RemoveMessage(Message &aMessage); - static void HandleReceivedFrame(Mac::Receiver &aReceiver, Mac::Frame &aFrame); - void HandleReceivedFrame(Mac::Frame &aFrame); + static void HandleReceivedFrame(Mac::Receiver &aReceiver, Mac::Frame &aFrame); + void HandleReceivedFrame(Mac::Frame &aFrame); static otError HandleFrameRequest(Mac::Sender &aSender, Mac::Frame &aFrame); - otError HandleFrameRequest(Mac::Frame &aFrame); - static void HandleSentFrame(Mac::Sender &aSender, Mac::Frame &aFrame, otError aError); - void HandleSentFrame(Mac::Frame &aFrame, otError aError); - void HandleSentFrameToChild(const Mac::Frame &aFrame, otError aError, const Mac::Address &macDest); - static void HandleDiscoverTimer(Timer &aTimer); - void HandleDiscoverTimer(void); - static void HandleReassemblyTimer(Timer &aTimer); - void HandleReassemblyTimer(void); - static void ScheduleTransmissionTask(Tasklet &aTasklet); - void ScheduleTransmissionTask(void); - static void HandleDataPollTimeout(Mac::Receiver &aReceiver); + otError HandleFrameRequest(Mac::Frame &aFrame); + static void HandleSentFrame(Mac::Sender &aSender, Mac::Frame &aFrame, otError aError); + void HandleSentFrame(Mac::Frame &aFrame, otError aError); + void HandleSentFrameToChild(const Mac::Frame &aFrame, otError aError, const Mac::Address &macDest); + static void HandleDiscoverTimer(Timer &aTimer); + void HandleDiscoverTimer(void); + static void HandleReassemblyTimer(Timer &aTimer); + void HandleReassemblyTimer(void); + static void ScheduleTransmissionTask(Tasklet &aTasklet); + void ScheduleTransmissionTask(void); + static void HandleDataPollTimeout(Mac::Receiver &aReceiver); otError GetDestinationRlocByServiceAloc(uint16_t aServiceAloc, uint16_t &aMeshDest); - void LogIp6Message(MessageAction aAction, const Message &aMessage, const Mac::Address *aMacAddress, - otError aError); + void LogIp6Message(MessageAction aAction, const Message &aMessage, const Mac::Address *aMacAddress, otError aError); - Mac::Receiver mMacReceiver; - Mac::Sender mMacSender; - TimerMilli mDiscoverTimer; - TimerMilli mReassemblyTimer; + Mac::Receiver mMacReceiver; + Mac::Sender mMacSender; + TimerMilli mDiscoverTimer; + TimerMilli mReassemblyTimer; - PriorityQueue mSendQueue; - MessageQueue mReassemblyList; - uint16_t mFragTag; - uint16_t mMessageNextOffset; + PriorityQueue mSendQueue; + MessageQueue mReassemblyList; + uint16_t mFragTag; + uint16_t mMessageNextOffset; - Message *mSendMessage; - bool mSendMessageIsARetransmission; - uint8_t mSendMessageMaxMacTxAttempts; + Message *mSendMessage; + bool mSendMessageIsARetransmission; + uint8_t mSendMessageMaxMacTxAttempts; - Mac::Address mMacSource; - Mac::Address mMacDest; - uint16_t mMeshSource; - uint16_t mMeshDest; - bool mAddMeshHeader; + Mac::Address mMacSource; + Mac::Address mMacDest; + uint16_t mMeshSource; + uint16_t mMeshDest; + bool mAddMeshHeader; - bool mSendBusy; + bool mSendBusy; - Tasklet mScheduleTransmissionTask; - bool mEnabled; + Tasklet mScheduleTransmissionTask; + bool mEnabled; - uint32_t mScanChannels; - uint8_t mScanChannel; - uint8_t mRestoreChannel; - uint16_t mRestorePanId; - bool mScanning; + uint32_t mScanChannels; + uint8_t mScanChannel; + uint8_t mRestoreChannel; + uint16_t mRestorePanId; + bool mScanning; - otIpCounters mIpCounters; + otIpCounters mIpCounters; #if OPENTHREAD_FTD MessageQueue mResolvingQueue; @@ -369,7 +377,7 @@ private: uint8_t mStartChildIndex; #endif - DataPollManager mDataPollManager; + DataPollManager mDataPollManager; }; /** @@ -377,6 +385,6 @@ private: * */ -} // namespace ot +} // namespace ot -#endif // MESH_FORWARDER_HPP_ +#endif // MESH_FORWARDER_HPP_ diff --git a/src/core/thread/mesh_forwarder_ftd.cpp b/src/core/thread/mesh_forwarder_ftd.cpp index a03757d4e..725fd5c06 100644 --- a/src/core/thread/mesh_forwarder_ftd.cpp +++ b/src/core/thread/mesh_forwarder_ftd.cpp @@ -45,11 +45,11 @@ namespace ot { otError MeshForwarder::SendMessage(Message &aMessage) { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Neighbor *neighbor; + otError error = OT_ERROR_NONE; + Neighbor * neighbor; uint8_t numChildren; - Child *child; + Child * child; switch (aMessage.GetType()) { @@ -103,8 +103,7 @@ otError MeshForwarder::SendMessage(Message &aMessage) } } else if ((neighbor = netif.GetMle().GetNeighbor(ip6Header.GetDestination())) != NULL && - !neighbor->IsRxOnWhenIdle() && - !aMessage.GetDirectTransmission()) + !neighbor->IsRxOnWhenIdle() && !aMessage.GetDirectTransmission()) { // destined for a sleepy child child = static_cast(neighbor); @@ -145,9 +144,9 @@ exit: void MeshForwarder::HandleResolved(const Ip6::Address &aEid, otError aError) { - Message *cur, *next; + Message * cur, *next; Ip6::Address ip6Dst; - bool enqueuedMessage = false; + bool enqueuedMessage = false; for (cur = mResolvingQueue.GetHead(); cur; cur = next) { @@ -216,7 +215,7 @@ exit: void MeshForwarder::UpdateIndirectMessages(void) { - Child *children; + Child * children; uint8_t numChildren; children = GetNetif().GetMle().GetChildren(&numChildren); @@ -255,7 +254,7 @@ exit: otError MeshForwarder::RemoveMessageFromSleepyChild(Message &aMessage, Child &aChild) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint8_t childIndex = GetNetif().GetMle().GetChildIndex(aChild); VerifyOrExit(aMessage.GetChildMask(childIndex) == true, error = OT_ERROR_NOT_FOUND); @@ -275,7 +274,7 @@ exit: void MeshForwarder::RemoveMessages(Child &aChild, uint8_t aSubType) { ThreadNetif &netif = GetNetif(); - Message *nextMessage; + Message * nextMessage; for (Message *message = mSendQueue.GetHead(); message; message = nextMessage) { @@ -351,7 +350,7 @@ void MeshForwarder::RemoveDataResponseMessages(void) if (!(ip6Header.GetDestination().IsMulticast())) { - Child *children; + Child * children; uint8_t numChildren; children = GetNetif().GetMle().GetChildren(&numChildren); @@ -375,12 +374,12 @@ void MeshForwarder::RemoveDataResponseMessages(void) otError MeshForwarder::GetIndirectTransmission(void) { - otError error = OT_ERROR_NOT_FOUND; + otError error = OT_ERROR_NOT_FOUND; ThreadNetif &netif = GetNetif(); - uint8_t numChildren; - uint8_t childIndex; - uint8_t nextIndex; - Child *children; + uint8_t numChildren; + uint8_t childIndex; + uint8_t nextIndex; + Child * children; UpdateIndirectMessages(); @@ -407,7 +406,7 @@ otError MeshForwarder::GetIndirectTransmission(void) continue; } - mSendMessage = child.GetIndirectMessage(); + mSendMessage = child.GetIndirectMessage(); mSendMessageMaxMacTxAttempts = Mac::kIndirectFrameMacTxAttempts; if (mSendMessage == NULL) @@ -451,7 +450,7 @@ Message *MeshForwarder::GetIndirectTransmission(Child &aChild) { Message *message = NULL; Message *next; - uint8_t childIndex = GetNetif().GetMle().GetChildIndex(aChild); + uint8_t childIndex = GetNetif().GetMle().GetChildIndex(aChild); for (message = mSendQueue.GetHead(); message; message = next) { @@ -493,9 +492,9 @@ void MeshForwarder::PrepareIndirectTransmission(Message &aMessage, const Child & { if (aChild.GetIndirectTxAttempts() > 0) { - mSendMessageIsARetransmission = true; - mSendMessageFrameCounter = aChild.GetIndirectFrameCounter(); - mSendMessageKeyId = aChild.GetIndirectKeyId(); + mSendMessageIsARetransmission = true; + mSendMessageFrameCounter = aChild.GetIndirectFrameCounter(); + mSendMessageKeyId = aChild.GetIndirectKeyId(); mSendMessageDataSequenceNumber = aChild.GetIndirectDataSequenceNumber(); } @@ -537,12 +536,12 @@ void MeshForwarder::PrepareIndirectTransmission(Message &aMessage, const Child & otError MeshForwarder::SendMesh(Message &aMessage, Mac::Frame &aFrame) { ThreadNetif &netif = GetNetif(); - uint16_t fcf; + uint16_t fcf; // initialize MAC header fcf = Mac::Frame::kFcfFrameData | Mac::Frame::kFcfPanidCompression | Mac::Frame::kFcfFrameVersion2006 | - Mac::Frame::kFcfDstAddrShort | Mac::Frame::kFcfSrcAddrShort | - Mac::Frame::kFcfAckRequest | Mac::Frame::kFcfSecurityEnabled; + Mac::Frame::kFcfDstAddrShort | Mac::Frame::kFcfSrcAddrShort | Mac::Frame::kFcfAckRequest | + Mac::Frame::kFcfSecurityEnabled; aFrame.InitMacHeader(fcf, Mac::Frame::kKeyIdMode1 | Mac::Frame::kSecEncMic32); aFrame.SetDstPanId(netif.GetMac().GetPanId()); @@ -562,8 +561,8 @@ otError MeshForwarder::SendMesh(Message &aMessage, Mac::Frame &aFrame) void MeshForwarder::HandleDataRequest(const Mac::Address &aMacSource, const otThreadLinkInfo &aLinkInfo) { ThreadNetif &netif = GetNetif(); - Child *child; - uint16_t indirectMsgCount; + Child * child; + uint16_t indirectMsgCount; // Security Check: only process secure Data Poll frames. VerifyOrExit(aLinkInfo.mLinkSecurity); @@ -592,7 +591,7 @@ exit: void MeshForwarder::HandleSentFrameToChild(const Mac::Frame &aFrame, otError aError, const Mac::Address &aMacDest) { ThreadNetif &netif = GetNetif(); - Child *child; + Child * child; child = netif.GetMle().GetChild(aMacDest); VerifyOrExit(child != NULL); @@ -632,7 +631,7 @@ void MeshForwarder::HandleSentFrameToChild(const Mac::Frame &aFrame, otError aEr if (aFrame.GetSecurityEnabled()) { uint32_t frameCounter; - uint8_t keyId; + uint8_t keyId; aFrame.GetFrameCounter(frameCounter); child->SetIndirectFrameCounter(frameCounter); @@ -706,11 +705,11 @@ exit: otError MeshForwarder::UpdateMeshRoute(Message &aMessage) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; Lowpan::MeshHeader meshHeader; - Neighbor *neighbor; - uint16_t nextHop; + Neighbor * neighbor; + uint16_t nextHop; IgnoreReturnValue(meshHeader.Init(aMessage)); @@ -734,8 +733,8 @@ otError MeshForwarder::UpdateMeshRoute(Message &aMessage) mMacSource.SetShort(netif.GetMac().GetShortAddress()); mAddMeshHeader = true; - mMeshDest = meshHeader.GetDestination(); - mMeshSource = meshHeader.GetSource(); + mMeshDest = meshHeader.GetDestination(); + mMeshSource = meshHeader.GetSource(); exit: return error; @@ -743,15 +742,14 @@ exit: otError MeshForwarder::UpdateIp6RouteFtd(Ip6::Header &ip6Header) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; ThreadNetif &netif = GetNetif(); - Neighbor *neighbor; + Neighbor * neighbor; if (netif.GetMle().IsRoutingLocator(ip6Header.GetDestination())) { uint16_t rloc16 = HostSwap16(ip6Header.GetDestination().mFields.m16[7]); - VerifyOrExit(netif.GetMle().IsRouterIdValid(netif.GetMle().GetRouterId(rloc16)), - error = OT_ERROR_DROP); + VerifyOrExit(netif.GetMle().IsRouterIdValid(netif.GetMle().GetRouterId(rloc16)), error = OT_ERROR_DROP); mMeshDest = rloc16; } else if (netif.GetMle().IsAnycastLocator(ip6Header.GetDestination())) @@ -767,10 +765,9 @@ otError MeshForwarder::UpdateIp6RouteFtd(Ip6::Header &ip6Header) else if (aloc16 <= Mle::kAloc16DhcpAgentEnd) { uint16_t agentRloc16; - uint8_t routerId; + uint8_t routerId; VerifyOrExit((netif.GetNetworkDataLeader().GetRlocByContextId( - static_cast(aloc16 & Mle::kAloc16DhcpAgentMask), - agentRloc16) == OT_ERROR_NONE), + static_cast(aloc16 & Mle::kAloc16DhcpAgentMask), agentRloc16) == OT_ERROR_NONE), error = OT_ERROR_DROP); routerId = netif.GetMle().GetRouterId(agentRloc16); @@ -788,7 +785,7 @@ otError MeshForwarder::UpdateIp6RouteFtd(Ip6::Header &ip6Header) } } -#endif // OPENTHREAD_ENABLE_DHCP6_SERVER || OPENTHREAD_ENABLE_DHCP6_CLIENT +#endif // OPENTHREAD_ENABLE_DHCP6_SERVER || OPENTHREAD_ENABLE_DHCP6_CLIENT #if OPENTHREAD_ENABLE_SERVICE else if ((aloc16 >= Mle::kAloc16ServiceStart) && (aloc16 <= Mle::kAloc16ServiceEnd)) { @@ -812,12 +809,7 @@ otError MeshForwarder::UpdateIp6RouteFtd(Ip6::Header &ip6Header) } else { - netif.GetNetworkDataLeader().RouteLookup( - ip6Header.GetSource(), - ip6Header.GetDestination(), - NULL, - &mMeshDest - ); + netif.GetNetworkDataLeader().RouteLookup(ip6Header.GetSource(), ip6Header.GetDestination(), NULL, &mMeshDest); } VerifyOrExit(mMeshDest != Mac::kShortAddrInvalid, error = OT_ERROR_DROP); @@ -838,12 +830,14 @@ exit: return error; } -otError MeshForwarder::CheckReachability(uint8_t *aFrame, uint8_t aFrameLength, - const Mac::Address &aMeshSource, const Mac::Address &aMeshDest) +otError MeshForwarder::CheckReachability(uint8_t * aFrame, + uint8_t aFrameLength, + const Mac::Address &aMeshSource, + const Mac::Address &aMeshDest) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Ip6::Header ip6Header; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Ip6::Header ip6Header; Lowpan::MeshHeader meshHeader; VerifyOrExit(meshHeader.Init(aFrame, aFrameLength) == OT_ERROR_NONE, error = OT_ERROR_DROP); @@ -853,8 +847,7 @@ otError MeshForwarder::CheckReachability(uint8_t *aFrame, uint8_t aFrameLength, aFrameLength -= meshHeader.GetHeaderLength(); // skip fragment header - if (aFrameLength >= 1 && - reinterpret_cast(aFrame)->IsFragmentHeader()) + if (aFrameLength >= 1 && reinterpret_cast(aFrame)->IsFragmentHeader()) { VerifyOrExit(sizeof(Lowpan::FragmentHeader) <= aFrameLength, error = OT_ERROR_DROP); VerifyOrExit(reinterpret_cast(aFrame)->GetDatagramOffset() == 0); @@ -875,14 +868,16 @@ exit: return error; } -void MeshForwarder::HandleMesh(uint8_t *aFrame, uint8_t aFrameLength, const Mac::Address &aMacSource, +void MeshForwarder::HandleMesh(uint8_t * aFrame, + uint8_t aFrameLength, + const Mac::Address & aMacSource, const otThreadLinkInfo &aLinkInfo) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Message *message = NULL; - Mac::Address meshDest; - Mac::Address meshSource; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Message * message = NULL; + Mac::Address meshDest; + Mac::Address meshSource; Lowpan::MeshHeader meshHeader; // Check the mesh header @@ -896,8 +891,7 @@ void MeshForwarder::HandleMesh(uint8_t *aFrame, uint8_t aFrameLength, const Mac: UpdateRoutes(aFrame, aFrameLength, meshSource, meshDest); - if (meshDest.GetShort() == netif.GetMac().GetShortAddress() || - netif.GetMle().IsMinimalChild(meshDest.GetShort())) + if (meshDest.GetShort() == netif.GetMac().GetShortAddress() || netif.GetMle().IsMinimalChild(meshDest.GetShort())) { aFrame += meshHeader.GetHeaderLength(); aFrameLength -= meshHeader.GetHeaderLength(); @@ -940,14 +934,10 @@ exit: { char srcStringBuffer[Mac::Address::kAddressStringSize]; - otLogInfoMac( - GetInstance(), - "Dropping rx mesh frame, error:%s, len:%d, src:%s, sec:%s", - otThreadErrorToString(error), - aFrameLength, - aMacSource.ToString(srcStringBuffer, sizeof(srcStringBuffer)), - aLinkInfo.mLinkSecurity ? "yes" : "no" - ); + otLogInfoMac(GetInstance(), "Dropping rx mesh frame, error:%s, len:%d, src:%s, sec:%s", + otThreadErrorToString(error), aFrameLength, + aMacSource.ToString(srcStringBuffer, sizeof(srcStringBuffer)), + aLinkInfo.mLinkSecurity ? "yes" : "no"); OT_UNUSED_VARIABLE(srcStringBuffer); @@ -958,13 +948,15 @@ exit: } } -void MeshForwarder::UpdateRoutes(uint8_t *aFrame, uint8_t aFrameLength, - const Mac::Address &aMeshSource, const Mac::Address &aMeshDest) +void MeshForwarder::UpdateRoutes(uint8_t * aFrame, + uint8_t aFrameLength, + const Mac::Address &aMeshSource, + const Mac::Address &aMeshDest) { - ThreadNetif &netif = GetNetif(); + ThreadNetif & netif = GetNetif(); Lowpan::MeshHeader meshHeader; - Ip6::Header ip6Header; - Neighbor *neighbor; + Ip6::Header ip6Header; + Neighbor * neighbor; VerifyOrExit(meshHeader.Init(aFrame, aFrameLength) == OT_ERROR_NONE); @@ -973,8 +965,7 @@ void MeshForwarder::UpdateRoutes(uint8_t *aFrame, uint8_t aFrameLength, aFrameLength -= meshHeader.GetHeaderLength(); // skip fragment header - if (aFrameLength >= 1 && - reinterpret_cast(aFrame)->IsFragmentHeader()) + if (aFrameLength >= 1 && reinterpret_cast(aFrame)->IsFragmentHeader()) { VerifyOrExit(sizeof(Lowpan::FragmentHeader) <= aFrameLength); VerifyOrExit(reinterpret_cast(aFrame)->GetDatagramOffset() == 0); @@ -1005,26 +996,26 @@ exit: #if OPENTHREAD_ENABLE_SERVICE otError MeshForwarder::GetDestinationRlocByServiceAloc(uint16_t aServiceAloc, uint16_t &aMeshDest) { - otError error = OT_ERROR_NONE; - ThreadNetif &netif = GetNetif(); - uint8_t serviceId = netif.GetMle().GetServiceIdFromAloc(aServiceAloc); + otError error = OT_ERROR_NONE; + ThreadNetif & netif = GetNetif(); + uint8_t serviceId = netif.GetMle().GetServiceIdFromAloc(aServiceAloc); NetworkData::ServiceTlv *serviceTlv = netif.GetNetworkDataLeader().FindServiceById(serviceId); if (serviceTlv != NULL) { NetworkData::NetworkDataTlv *cur = serviceTlv->GetSubTlvs(); NetworkData::NetworkDataTlv *end = serviceTlv->GetNext(); - NetworkData::ServerTlv *server; - uint8_t bestCost = Mle::kMaxRouteCost; - uint8_t curCost = 0x00; - uint16_t bestDest = Mac::kShortAddrInvalid; + NetworkData::ServerTlv * server; + uint8_t bestCost = Mle::kMaxRouteCost; + uint8_t curCost = 0x00; + uint16_t bestDest = Mac::kShortAddrInvalid; while (cur < end) { switch (cur->GetType()) { case NetworkData::NetworkDataTlv::kTypeServer: - server = static_cast(cur); + server = static_cast(cur); curCost = netif.GetMle().GetCost(server->GetServer16()); if ((bestDest == Mac::kShortAddrInvalid) || (curCost < bestCost)) @@ -1063,6 +1054,6 @@ exit: } #endif // OPENTHREAD_ENABLE_SERVICE -} // namespace ot +} // namespace ot -#endif // OPENTHREAD_FTD +#endif // OPENTHREAD_FTD diff --git a/src/core/thread/mesh_forwarder_mtd.cpp b/src/core/thread/mesh_forwarder_mtd.cpp index 882b5a8c8..b3c206e1c 100644 --- a/src/core/thread/mesh_forwarder_mtd.cpp +++ b/src/core/thread/mesh_forwarder_mtd.cpp @@ -78,7 +78,9 @@ void MeshForwarder::HandleSentFrameToChild(const Mac::Frame &aFrame, otError aEr OT_UNUSED_VARIABLE(aMacDest); } -void MeshForwarder::HandleMesh(uint8_t *aFrame, uint8_t aFrameLength, const Mac::Address &aMacSource, +void MeshForwarder::HandleMesh(uint8_t * aFrame, + uint8_t aFrameLength, + const Mac::Address & aMacSource, const otThreadLinkInfo &aLinkInfo) { OT_UNUSED_VARIABLE(aFrame); @@ -87,6 +89,6 @@ void MeshForwarder::HandleMesh(uint8_t *aFrame, uint8_t aFrameLength, const Mac: OT_UNUSED_VARIABLE(aLinkInfo); } -} // namespace ot +} // namespace ot -#endif // OPENTHREAD_MTD +#endif // OPENTHREAD_MTD diff --git a/src/core/thread/mle.cpp b/src/core/thread/mle.cpp index bf845ed88..ce6e9601f 100644 --- a/src/core/thread/mle.cpp +++ b/src/core/thread/mle.cpp @@ -62,53 +62,56 @@ using ot::Encoding::BigEndian::HostSwap16; namespace ot { namespace Mle { -Mle::Mle(Instance &aInstance) : - InstanceLocator(aInstance), - mRetrieveNewNetworkData(false), - mRole(OT_DEVICE_ROLE_DISABLED), - mDeviceMode(ModeTlv::kModeRxOnWhenIdle | ModeTlv::kModeSecureDataRequest), - mParentRequestState(kParentIdle), - mReattachState(kReattachStop), - mParentRequestTimer(aInstance, &Mle::HandleParentRequestTimer, this), - mDelayedResponseTimer(aInstance, &Mle::HandleDelayedResponseTimer, this), - mChildUpdateRequestTimer(aInstance, &Mle::HandleChildUpdateRequestTimer, this), - mLastPartitionId(0), - mLastPartitionRouterIdSequence(0), - mLastPartitionIdTimeout(0), - mParentLeaderCost(0), - mParentRequestMode(kAttachAny), - mParentPriority(0), - mParentLinkQuality3(0), - mParentLinkQuality2(0), - mParentLinkQuality1(0), - mChildUpdateAttempts(0), - mParentLinkMargin(0), - mParentIsSingleton(false), - mReceivedResponseFromParent(false), - mSocket(aInstance.GetThreadNetif().GetIp6().GetUdp()), - mTimeout(kMleEndDeviceTimeout), - mSendChildUpdateRequest(aInstance, &Mle::HandleSendChildUpdateRequest, this), - mDiscoverHandler(NULL), - mDiscoverContext(NULL), - mIsDiscoverInProgress(false), - mEnableEui64Filtering(false), +Mle::Mle(Instance &aInstance) + : InstanceLocator(aInstance) + , mRetrieveNewNetworkData(false) + , mRole(OT_DEVICE_ROLE_DISABLED) + , mDeviceMode(ModeTlv::kModeRxOnWhenIdle | ModeTlv::kModeSecureDataRequest) + , mParentRequestState(kParentIdle) + , mReattachState(kReattachStop) + , mParentRequestTimer(aInstance, &Mle::HandleParentRequestTimer, this) + , mDelayedResponseTimer(aInstance, &Mle::HandleDelayedResponseTimer, this) + , mChildUpdateRequestTimer(aInstance, &Mle::HandleChildUpdateRequestTimer, this) + , mLastPartitionId(0) + , mLastPartitionRouterIdSequence(0) + , mLastPartitionIdTimeout(0) + , mParentLeaderCost(0) + , mParentRequestMode(kAttachAny) + , mParentPriority(0) + , mParentLinkQuality3(0) + , mParentLinkQuality2(0) + , mParentLinkQuality1(0) + , mChildUpdateAttempts(0) + , mParentLinkMargin(0) + , mParentIsSingleton(false) + , mReceivedResponseFromParent(false) + , mSocket(aInstance.GetThreadNetif().GetIp6().GetUdp()) + , mTimeout(kMleEndDeviceTimeout) + , mSendChildUpdateRequest(aInstance, &Mle::HandleSendChildUpdateRequest, this) + , mDiscoverHandler(NULL) + , mDiscoverContext(NULL) + , mIsDiscoverInProgress(false) + , mEnableEui64Filtering(false) + , #if OPENTHREAD_CONFIG_INFORM_PREVIOUS_PARENT_ON_REATTACH - mPreviousParentRloc(Mac::kShortAddrInvalid), + mPreviousParentRloc(Mac::kShortAddrInvalid) + , #endif #if OPENTHREAD_CONFIG_ENABLE_PERIODIC_PARENT_SEARCH - mParentSearchIsInBackoff(false), - mParentSearchBackoffWasCanceled(false), - mParentSearchRecentlyDetached(false), - mParentSearchBackoffCancelTime(0), - mParentSearchTimer(aInstance, &Mle::HandleParentSearchTimer, this), + mParentSearchIsInBackoff(false) + , mParentSearchBackoffWasCanceled(false) + , mParentSearchRecentlyDetached(false) + , mParentSearchBackoffCancelTime(0) + , mParentSearchTimer(aInstance, &Mle::HandleParentSearchTimer, this) + , #endif - mAnnounceChannel(OT_RADIO_CHANNEL_MIN), - mPreviousChannel(0), - mPreviousPanId(Mac::kPanIdBroadcast), - mNotifierCallback(&Mle::HandleStateChanged, this) + mAnnounceChannel(OT_RADIO_CHANNEL_MIN) + , mPreviousChannel(0) + , mPreviousPanId(Mac::kPanIdBroadcast) + , mNotifierCallback(&Mle::HandleStateChanged, this) { uint8_t meshLocalPrefix[8]; - size_t i = 0; + size_t i = 0; memset(&mLeaderData, 0, sizeof(mLeaderData)); memset(&mParentLeaderData, 0, sizeof(mParentLeaderData)); @@ -126,15 +129,15 @@ Mle::Mle(Instance &aInstance) : mLinkLocal64.GetAddress().mFields.m16[0] = HostSwap16(0xfe80); mLinkLocal64.GetAddress().SetIid(GetNetif().GetMac().GetExtAddress()); mLinkLocal64.mPrefixLength = 64; - mLinkLocal64.mPreferred = true; - mLinkLocal64.mValid = true; + mLinkLocal64.mPreferred = true; + mLinkLocal64.mValid = true; GetNetif().AddUnicastAddress(mLinkLocal64); // Leader Aloc - mLeaderAloc.mPrefixLength = 128; - mLeaderAloc.mPreferred = true; - mLeaderAloc.mValid = true; - mLeaderAloc.mScopeOverride = Ip6::Address::kRealmLocalScope; + mLeaderAloc.mPrefixLength = 128; + mLeaderAloc.mPreferred = true; + mLeaderAloc.mValid = true; + mLeaderAloc.mScopeOverride = Ip6::Address::kRealmLocalScope; mLeaderAloc.mScopeOverrideValid = true; #if OPENTHREAD_ENABLE_SERVICE @@ -144,11 +147,11 @@ Mle::Mle(Instance &aInstance) : { memset(&mServiceAlocs[i], 0, sizeof(mServiceAlocs[i])); - mServiceAlocs[i].mPrefixLength = 128; - mServiceAlocs[i].mPreferred = true; - mServiceAlocs[i].mValid = true; - mServiceAlocs[i].mScopeOverride = Ip6::Address::kRealmLocalScope; - mServiceAlocs[i].mScopeOverrideValid = true; + mServiceAlocs[i].mPrefixLength = 128; + mServiceAlocs[i].mPreferred = true; + mServiceAlocs[i].mValid = true; + mServiceAlocs[i].mScopeOverride = Ip6::Address::kRealmLocalScope; + mServiceAlocs[i].mScopeOverrideValid = true; mServiceAlocs[i].GetAddress().mFields.m16[7] = HostSwap16(Mac::kShortAddrInvalid); } @@ -166,22 +169,22 @@ Mle::Mle(Instance &aInstance) : mMeshLocal64.GetAddress().mFields.m8[i] = static_cast(otPlatRandomGet()); } - mMeshLocal64.mPrefixLength = 64; - mMeshLocal64.mPreferred = true; - mMeshLocal64.mValid = true; - mMeshLocal64.mScopeOverride = Ip6::Address::kRealmLocalScope; + mMeshLocal64.mPrefixLength = 64; + mMeshLocal64.mPreferred = true; + mMeshLocal64.mValid = true; + mMeshLocal64.mScopeOverride = Ip6::Address::kRealmLocalScope; mMeshLocal64.mScopeOverrideValid = true; // mesh-local 16 mMeshLocal16.GetAddress().mFields.m16[4] = HostSwap16(0x0000); mMeshLocal16.GetAddress().mFields.m16[5] = HostSwap16(0x00ff); mMeshLocal16.GetAddress().mFields.m16[6] = HostSwap16(0xfe00); - mMeshLocal16.mPrefixLength = 64; - mMeshLocal16.mPreferred = true; - mMeshLocal16.mValid = true; - mMeshLocal16.mScopeOverride = Ip6::Address::kRealmLocalScope; - mMeshLocal16.mScopeOverrideValid = true; - mMeshLocal16.mRloc = true; + mMeshLocal16.mPrefixLength = 64; + mMeshLocal16.mPreferred = true; + mMeshLocal16.mValid = true; + mMeshLocal16.mScopeOverride = Ip6::Address::kRealmLocalScope; + mMeshLocal16.mScopeOverrideValid = true; + mMeshLocal16.mRloc = true; // Store RLOC address reference in MPL module. GetNetif().GetIp6().GetMpl().SetMatchingAddress(mMeshLocal16.GetAddress()); @@ -210,7 +213,7 @@ Mle::Mle(Instance &aInstance) : otError Mle::Enable(void) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Ip6::SockAddr sockaddr; // memcpy(&sockaddr.mAddr, &mLinkLocal64.GetAddress(), sizeof(sockaddr.mAddr)); @@ -236,7 +239,7 @@ exit: otError Mle::Start(bool aEnableReattach, bool aAnnounceAttach) { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; // cannot bring up the interface if IEEE 802.15.4 promiscuous mode is enabled VerifyOrExit(otPlatRadioGetPromiscuous(&netif.GetInstance()) == false, error = OT_ERROR_INVALID_STATE); @@ -266,7 +269,7 @@ otError Mle::Start(bool aEnableReattach, bool aAnnounceAttach) } else { - mParentRequestState = kParentSynchronize; + mParentRequestState = kParentSynchronize; mChildUpdateAttempts = 0; SendChildUpdateRequest(); } @@ -300,11 +303,11 @@ otError Mle::Stop(bool aClearNetworkDatasets) otError Mle::Restore(void) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; Settings::NetworkInfo networkInfo; - Settings::ParentInfo parentInfo; - uint16_t length; + Settings::ParentInfo parentInfo; + uint16_t length; netif.GetActiveDataset().Restore(); netif.GetPendingDataset().Restore(); @@ -325,8 +328,7 @@ otError Mle::Restore(void) netif.GetMac().SetExtAddress(networkInfo.mExtAddress); UpdateLinkLocalAddress(); - memcpy(&mMeshLocal64.GetAddress().mFields.m8[OT_IP6_PREFIX_SIZE], - networkInfo.mMlIid, + memcpy(&mMeshLocal64.GetAddress().mFields.m8[OT_IP6_PREFIX_SIZE], networkInfo.mMlIid, OT_IP6_ADDRESS_SIZE - OT_IP6_PREFIX_SIZE); if (networkInfo.mRloc16 == Mac::kShortAddrInvalid) @@ -380,8 +382,8 @@ exit: otError Mle::Store(void) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; Settings::NetworkInfo networkInfo; memset(&networkInfo, 0, sizeof(networkInfo)); @@ -390,11 +392,11 @@ otError Mle::Store(void) { // only update network information while we are attached to avoid losing information when a reboot occurs after // a message is sent but before attaching - networkInfo.mDeviceMode = mDeviceMode; - networkInfo.mRole = mRole; - networkInfo.mRloc16 = GetRloc16(); + networkInfo.mDeviceMode = mDeviceMode; + networkInfo.mRole = mRole; + networkInfo.mRloc16 = GetRloc16(); networkInfo.mPreviousPartitionId = mLeaderData.GetPartitionId(); - networkInfo.mExtAddress = netif.GetMac().GetExtAddress(); + networkInfo.mExtAddress = netif.GetMac().GetExtAddress(); memcpy(networkInfo.mMlIid, &mMeshLocal64.GetAddress().mFields.m8[OT_IP6_PREFIX_SIZE], OT_IP6_IID_SIZE); if (mRole == OT_DEVICE_ROLE_CHILD) @@ -418,10 +420,10 @@ otError Mle::Store(void) // update MAC and MLE Frame Counters even when we are not attached MLE messages are sent before a device attached networkInfo.mKeySequence = netif.GetKeyManager().GetCurrentKeySequence(); - networkInfo.mMleFrameCounter = netif.GetKeyManager().GetMleFrameCounter() + - OPENTHREAD_CONFIG_STORE_FRAME_COUNTER_AHEAD; - networkInfo.mMacFrameCounter = netif.GetKeyManager().GetMacFrameCounter() + - OPENTHREAD_CONFIG_STORE_FRAME_COUNTER_AHEAD; + networkInfo.mMleFrameCounter = + netif.GetKeyManager().GetMleFrameCounter() + OPENTHREAD_CONFIG_STORE_FRAME_COUNTER_AHEAD; + networkInfo.mMacFrameCounter = + netif.GetKeyManager().GetMacFrameCounter() + OPENTHREAD_CONFIG_STORE_FRAME_COUNTER_AHEAD; SuccessOrExit(error = otPlatSettingsSet(&netif.GetInstance(), Settings::kKeyNetworkInfo, reinterpret_cast(&networkInfo), sizeof(networkInfo))); @@ -435,15 +437,19 @@ exit: return error; } -otError Mle::Discover(uint32_t aScanChannels, uint16_t aPanId, bool aJoiner, bool aEnableEui64Filtering, - DiscoverHandler aCallback, void *aContext) +otError Mle::Discover(uint32_t aScanChannels, + uint16_t aPanId, + bool aJoiner, + bool aEnableEui64Filtering, + DiscoverHandler aCallback, + void * aContext) { - otError error = OT_ERROR_NONE; - Message *message = NULL; - Ip6::Address destination; - Tlv tlv; + otError error = OT_ERROR_NONE; + Message * message = NULL; + Ip6::Address destination; + Tlv tlv; MeshCoP::DiscoveryRequestTlv discoveryRequest; - uint16_t startOffset; + uint16_t startOffset; VerifyOrExit(!mIsDiscoverInProgress, error = OT_ERROR_BUSY); @@ -507,7 +513,7 @@ void Mle::HandleDiscoverComplete(void) otError Mle::BecomeDetached(void) { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; VerifyOrExit(mRole != OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); @@ -533,7 +539,7 @@ exit: otError Mle::BecomeChild(AttachMode aMode) { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; VerifyOrExit(mRole != OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); VerifyOrExit(mParentRequestState == kParentIdle, error = OT_ERROR_BUSY); @@ -554,7 +560,7 @@ otError Mle::BecomeChild(AttachMode aMode) ResetParentCandidate(); mParentRequestState = kParentRequestStart; - mParentRequestMode = aMode; + mParentRequestMode = aMode; if (aMode != kAttachBetter) { @@ -591,7 +597,7 @@ otError Mle::SetStateDetached(void) netif.RemoveUnicastAddress(mLeaderAloc); } - mRole = OT_DEVICE_ROLE_DETACHED; + mRole = OT_DEVICE_ROLE_DETACHED; mParentRequestState = kParentIdle; mParentRequestTimer.Stop(); mChildUpdateRequestTimer.Stop(); @@ -620,17 +626,16 @@ otError Mle::SetStateChild(uint16_t aRloc16) } SetRloc16(aRloc16); - mRole = OT_DEVICE_ROLE_CHILD; - mParentRequestState = kParentIdle; - mReattachState = kReattachStop; + mRole = OT_DEVICE_ROLE_CHILD; + mParentRequestState = kParentIdle; + mReattachState = kReattachStop; mChildUpdateAttempts = 0; netif.GetMac().SetBeaconEnabled(false); if ((mDeviceMode & ModeTlv::kModeRxOnWhenIdle) != 0) { mChildUpdateRequestTimer.Start(TimerMilli::SecToMsec(mTimeout) - - static_cast(kUnicastRetransmissionDelay) * - kMaxChildKeepAliveAttempts); + static_cast(kUnicastRetransmissionDelay) * kMaxChildKeepAliveAttempts); } if ((mDeviceMode & ModeTlv::kModeFFD) != 0) @@ -665,8 +670,7 @@ void Mle::InformPreviousChannel(void) VerifyOrExit(mPreviousPanId != Mac::kPanIdBroadcast); VerifyOrExit(mRole == OT_DEVICE_ROLE_CHILD || mRole == OT_DEVICE_ROLE_ROUTER); - if ((mDeviceMode & ModeTlv::kModeFFD) == 0 || - mRole == OT_DEVICE_ROLE_ROUTER || + if ((mDeviceMode & ModeTlv::kModeFFD) == 0 || mRole == OT_DEVICE_ROLE_ROUTER || GetNetif().GetMle().GetRouterSelectionJitterTimeout() == 0) { mPreviousPanId = Mac::kPanIdBroadcast; @@ -701,7 +705,7 @@ exit: otError Mle::SetDeviceMode(uint8_t aDeviceMode) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint8_t oldMode = mDeviceMode; VerifyOrExit((aDeviceMode & ModeTlv::kModeFFD) == 0 || (aDeviceMode & ModeTlv::kModeRxOnWhenIdle) != 0, @@ -865,9 +869,9 @@ void Mle::SetLeaderData(uint32_t aPartitionId, uint8_t aWeighting, uint8_t aLead if (mLeaderData.GetPartitionId() != aPartitionId) { GetNetif().GetMle().HandlePartitionChange(); - mLastPartitionId = mLeaderData.GetPartitionId(); + mLastPartitionId = mLeaderData.GetPartitionId(); mLastPartitionRouterIdSequence = GetNetif().GetMle().GetRouterIdSequence(); - mLastPartitionIdTimeout = GetNetif().GetMle().GetNetworkIdTimeout(); + mLastPartitionIdTimeout = GetNetif().GetMle().GetNetworkIdTimeout(); GetNotifier().SetFlags(OT_CHANGED_THREAD_PARTITION_ID); } @@ -962,22 +966,24 @@ const LeaderDataTlv &Mle::GetLeaderDataTlv(void) otError Mle::GetLeaderData(otLeaderData &aLeaderData) { const LeaderDataTlv &leaderData(GetLeaderDataTlv()); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; VerifyOrExit(mRole != OT_DEVICE_ROLE_DISABLED && mRole != OT_DEVICE_ROLE_DETACHED, error = OT_ERROR_DETACHED); - aLeaderData.mPartitionId = leaderData.GetPartitionId(); - aLeaderData.mWeighting = leaderData.GetWeighting(); - aLeaderData.mDataVersion = leaderData.GetDataVersion(); + aLeaderData.mPartitionId = leaderData.GetPartitionId(); + aLeaderData.mWeighting = leaderData.GetWeighting(); + aLeaderData.mDataVersion = leaderData.GetDataVersion(); aLeaderData.mStableDataVersion = leaderData.GetStableDataVersion(); - aLeaderData.mLeaderRouterId = leaderData.GetLeaderRouterId(); + aLeaderData.mLeaderRouterId = leaderData.GetLeaderRouterId(); exit: return error; } -void Mle::GenerateNonce(const Mac::ExtAddress &aMacAddr, uint32_t aFrameCounter, uint8_t aSecurityLevel, - uint8_t *aNonce) +void Mle::GenerateNonce(const Mac::ExtAddress &aMacAddr, + uint32_t aFrameCounter, + uint8_t aSecurityLevel, + uint8_t * aNonce) { // source address memcpy(aNonce, aMacAddr.m8, sizeof(aMacAddr)); @@ -1012,12 +1018,11 @@ exit: otError Mle::AppendHeader(Message &aMessage, Header::Command aCommand) { otError error = OT_ERROR_NONE; - Header header; + Header header; header.Init(); - if (aCommand == Header::kCommandDiscoveryRequest || - aCommand == Header::kCommandDiscoveryResponse) + if (aCommand == Header::kCommandDiscoveryRequest || aCommand == Header::kCommandDiscoveryResponse) { header.SetSecuritySuite(Header::kNoSecurity); } @@ -1077,7 +1082,7 @@ otError Mle::AppendTimeout(Message &aMessage, uint32_t aTimeout) otError Mle::AppendChallenge(Message &aMessage, const uint8_t *aChallenge, uint8_t aChallengeLength) { otError error; - Tlv tlv; + Tlv tlv; tlv.SetType(Tlv::kChallenge); tlv.SetLength(aChallengeLength); @@ -1091,7 +1096,7 @@ exit: otError Mle::AppendResponse(Message &aMessage, const uint8_t *aResponse, uint8_t aResponseLength) { otError error; - Tlv tlv; + Tlv tlv; tlv.SetType(Tlv::kResponse); tlv.SetLength(aResponseLength); @@ -1144,7 +1149,7 @@ otError Mle::AppendLeaderData(Message &aMessage) void Mle::FillNetworkDataTlv(NetworkDataTlv &aTlv, bool aStableOnly) { - uint8_t length = sizeof(NetworkDataTlv) - sizeof(Tlv); // sizeof( NetworkDataTlv::mNetworkData ) + uint8_t length = sizeof(NetworkDataTlv) - sizeof(Tlv); // sizeof( NetworkDataTlv::mNetworkData ) // Ignore result code, provided buffer must be enough GetNetif().GetNetworkDataLeader().GetNetworkData(aStableOnly, aTlv.GetNetworkData(), length); @@ -1153,7 +1158,7 @@ void Mle::FillNetworkDataTlv(NetworkDataTlv &aTlv, bool aStableOnly) otError Mle::AppendNetworkData(Message &aMessage, bool aStableOnly) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; NetworkDataTlv tlv; tlv.Init(); @@ -1168,7 +1173,7 @@ exit: otError Mle::AppendTlvRequest(Message &aMessage, const uint8_t *aTlvs, uint8_t aTlvsLength) { otError error; - Tlv tlv; + Tlv tlv; tlv.SetType(Tlv::kTlvRequest); tlv.SetLength(aTlvsLength); @@ -1212,14 +1217,14 @@ otError Mle::AppendVersion(Message &aMessage) otError Mle::AppendAddressRegistration(Message &aMessage) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Tlv tlv; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Tlv tlv; AddressRegistrationEntry entry; - Lowpan::Context context; - uint8_t length = 0; - uint8_t counter = 0; - uint16_t startOffset = aMessage.GetLength(); + Lowpan::Context context; + uint8_t length = 0; + uint8_t counter = 0; + uint16_t startOffset = aMessage.GetLength(); tlv.SetType(Tlv::kAddressRegistration); SuccessOrExit(error = aMessage.Append(&tlv, sizeof(tlv))); @@ -1227,8 +1232,7 @@ otError Mle::AppendAddressRegistration(Message &aMessage) // write entries to message for (const Ip6::NetifUnicastAddress *addr = netif.GetUnicastAddresses(); addr; addr = addr->GetNext()) { - if (addr->GetAddress().IsLinkLocal() || - IsRoutingLocator(addr->GetAddress()) || + if (addr->GetAddress().IsLinkLocal() || IsRoutingLocator(addr->GetAddress()) || IsAnycastLocator(addr->GetAddress())) { continue; @@ -1257,7 +1261,7 @@ otError Mle::AppendAddressRegistration(Message &aMessage) // For sleepy end device, register external multicast addresses to the parent for indirect transmission if ((mDeviceMode & ModeTlv::kModeRxOnWhenIdle) == 0) { - uint8_t iterator = 0; + uint8_t iterator = 0; Ip6::Address address; // append external multicast address @@ -1287,9 +1291,9 @@ exit: otError Mle::AppendActiveTimestamp(Message &aMessage) { - ThreadNetif &netif = GetNetif(); - otError error; - ActiveTimestampTlv timestampTlv; + ThreadNetif & netif = GetNetif(); + otError error; + ActiveTimestampTlv timestampTlv; const MeshCoP::Timestamp *timestamp; timestamp = netif.GetActiveDataset().GetTimestamp(); @@ -1297,7 +1301,7 @@ otError Mle::AppendActiveTimestamp(Message &aMessage) timestampTlv.Init(); *static_cast(×tampTlv) = *timestamp; - error = aMessage.Append(×tampTlv, sizeof(timestampTlv)); + error = aMessage.Append(×tampTlv, sizeof(timestampTlv)); exit: return error; @@ -1305,8 +1309,8 @@ exit: otError Mle::AppendPendingTimestamp(Message &aMessage) { - otError error; - PendingTimestampTlv timestampTlv; + otError error; + PendingTimestampTlv timestampTlv; const MeshCoP::Timestamp *timestamp; timestamp = GetNetif().GetPendingDataset().GetTimestamp(); @@ -1314,7 +1318,7 @@ otError Mle::AppendPendingTimestamp(Message &aMessage) timestampTlv.Init(); *static_cast(×tampTlv) = *timestamp; - error = aMessage.Append(×tampTlv, sizeof(timestampTlv)); + error = aMessage.Append(×tampTlv, sizeof(timestampTlv)); exit: return error; @@ -1352,8 +1356,7 @@ void Mle::HandleStateChanged(uint32_t aFlags) if ((aFlags & (OT_CHANGED_IP6_MULTICAST_SUBSRCRIBED | OT_CHANGED_IP6_MULTICAST_UNSUBSRCRIBED)) != 0) { - if (mRole == OT_DEVICE_ROLE_CHILD && - (mDeviceMode & ModeTlv::kModeFFD) == 0 && + if (mRole == OT_DEVICE_ROLE_CHILD && (mDeviceMode & ModeTlv::kModeFFD) == 0 && (mDeviceMode & ModeTlv::kModeRxOnWhenIdle) == 0) { mSendChildUpdateRequest.Post(); @@ -1391,14 +1394,14 @@ exit: #if OPENTHREAD_ENABLE_SERVICE void Mle::UpdateServiceAlocs(void) { - ThreadNetif &netif = GetNetif(); - uint16_t rloc = GetRloc16(); - uint16_t serviceAloc = 0; - uint8_t serviceId = 0; - int i = 0; - NetworkData::Leader &leaderData = netif.GetNetworkDataLeader(); - otNetworkDataIterator serviceIterator = OT_NETWORK_DATA_ITERATOR_INIT; - int serviceAlocsLength = sizeof(mServiceAlocs) / sizeof(mServiceAlocs[0]); + ThreadNetif & netif = GetNetif(); + uint16_t rloc = GetRloc16(); + uint16_t serviceAloc = 0; + uint8_t serviceId = 0; + int i = 0; + NetworkData::Leader & leaderData = netif.GetNetworkDataLeader(); + otNetworkDataIterator serviceIterator = OT_NETWORK_DATA_ITERATOR_INIT; + int serviceAlocsLength = sizeof(mServiceAlocs) / sizeof(mServiceAlocs[0]); VerifyOrExit(mRole != OT_DEVICE_ROLE_DISABLED); @@ -1442,7 +1445,6 @@ void Mle::UpdateServiceAlocs(void) break; } } - } } @@ -1486,7 +1488,7 @@ void Mle::HandleParentRequestTimer(void) break; } - // fall through + // fall through case kParentRequestChild: if (mParentCandidate.GetState() == Neighbor::kStateParentResponse && @@ -1498,7 +1500,7 @@ void Mle::HandleParentRequestTimer(void) break; } - // fall through + // fall through case kChildIdRequest: mParentRequestState = kParentIdle; @@ -1509,7 +1511,7 @@ void Mle::HandleParentRequestTimer(void) if (netif.GetPendingDataset().Restore() == OT_ERROR_NONE) { netif.GetPendingDataset().ApplyConfiguration(); - mReattachState = kReattachPending; + mReattachState = kReattachPending; mParentRequestState = kParentRequestStart; mParentRequestTimer.Start(kParentRequestRouterTimeout); } @@ -1582,10 +1584,10 @@ void Mle::HandleDelayedResponseTimer(Timer &aTimer) void Mle::HandleDelayedResponseTimer(void) { DelayedResponseHeader delayedResponse; - uint32_t now = TimerMilli::GetNow(); - uint32_t nextDelay = 0xffffffff; - Message *message = mDelayedResponses.GetHead(); - Message *nextMessage = NULL; + uint32_t now = TimerMilli::GetNow(); + uint32_t nextDelay = 0xffffffff; + Message * message = mDelayedResponses.GetHead(); + Message * nextMessage = NULL; while (message != NULL) { @@ -1629,7 +1631,7 @@ void Mle::HandleDelayedResponseTimer(void) void Mle::RemoveDelayedDataResponseMessage(void) { - Message *message = mDelayedResponses.GetHead(); + Message * message = mDelayedResponses.GetHead(); DelayedResponseHeader delayedResponse; while (message != NULL) @@ -1652,9 +1654,9 @@ void Mle::RemoveDelayedDataResponseMessage(void) otError Mle::SendParentRequest(void) { - otError error = OT_ERROR_NONE; - Message *message; - uint8_t scanMask = 0; + otError error = OT_ERROR_NONE; + Message * message; + uint8_t scanMask = 0; Ip6::Address destination; for (uint8_t i = 0; i < sizeof(mParentRequest.mChallenge); i++) @@ -1667,8 +1669,7 @@ otError Mle::SendParentRequest(void) case kParentRequestRouter: scanMask = ScanMaskTlv::kRouterFlag; - if (mParentRequestMode == kAttachSame1 || - mParentRequestMode == kAttachSame2) + if (mParentRequestMode == kAttachSame1 || mParentRequestMode == kAttachSame2) { scanMask |= ScanMaskTlv::kEndDeviceFlag; } @@ -1726,10 +1727,10 @@ exit: otError Mle::SendChildIdRequest(void) { - otError error = OT_ERROR_NONE; - uint8_t tlvs[] = {Tlv::kAddress16, Tlv::kNetworkData, Tlv::kRoute}; - uint8_t tlvsLen = sizeof(tlvs); - Message *message = NULL; + otError error = OT_ERROR_NONE; + uint8_t tlvs[] = {Tlv::kAddress16, Tlv::kNetworkData, Tlv::kRoute}; + uint8_t tlvsLen = sizeof(tlvs); + Message * message = NULL; Ip6::Address destination; if (mParent.GetExtAddress() == mParentCandidate.GetExtAddress()) @@ -1777,7 +1778,8 @@ otError Mle::SendChildIdRequest(void) destination.mFields.m16[0] = HostSwap16(0xfe80); destination.SetIid(mParentCandidate.GetExtAddress()); SuccessOrExit(error = SendMessage(*message, destination)); - LogMleMessage("Send Child ID Request", destination);; + LogMleMessage("Send Child ID Request", destination); + ; if ((mDeviceMode & ModeTlv::kModeRxOnWhenIdle) == 0) { @@ -1795,10 +1797,12 @@ exit: return error; } -otError Mle::SendDataRequest(const Ip6::Address &aDestination, const uint8_t *aTlvs, uint8_t aTlvsLength, - uint16_t aDelay) +otError Mle::SendDataRequest(const Ip6::Address &aDestination, + const uint8_t * aTlvs, + uint8_t aTlvsLength, + uint16_t aDelay) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Message *message; VerifyOrExit((message = NewMleMessage()) != NULL, error = OT_ERROR_NO_BUFS); @@ -1865,9 +1869,9 @@ void Mle::HandleChildUpdateRequestTimer(void) otError Mle::SendChildUpdateRequest(void) { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Ip6::Address destination; - Message *message = NULL; + Message * message = NULL; if (mChildUpdateAttempts >= kMaxChildKeepAliveAttempts) { @@ -1904,8 +1908,7 @@ otError Mle::SendChildUpdateRequest(void) mParentRequest.mChallenge[i] = static_cast(otPlatRandomGet()); } - SuccessOrExit(error = AppendChallenge(*message, mParentRequest.mChallenge, - sizeof(mParentRequest.mChallenge))); + SuccessOrExit(error = AppendChallenge(*message, mParentRequest.mChallenge, sizeof(mParentRequest.mChallenge))); break; case OT_DEVICE_ROLE_CHILD: @@ -1950,9 +1953,9 @@ exit: otError Mle::SendChildUpdateResponse(const uint8_t *aTlvs, uint8_t aNumTlvs, const ChallengeTlv &aChallenge) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Ip6::Address destination; - Message *message; + Message * message; VerifyOrExit((message = NewMleMessage()) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = AppendHeader(*message, Header::kCommandChildUpdateResponse)); @@ -2008,13 +2011,13 @@ exit: otError Mle::SendAnnounce(uint8_t aChannel, bool aOrphanAnnounce) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - ChannelTlv channel; - PanIdTlv panid; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + ChannelTlv channel; + PanIdTlv panid; ActiveTimestampTlv activeTimestamp; - Ip6::Address destination; - Message *message; + Ip6::Address destination; + Message * message; VerifyOrExit((message = NewMleMessage()) != NULL, error = OT_ERROR_NO_BUFS); message->SetLinkSecurityEnabled(true); @@ -2065,10 +2068,10 @@ exit: void Mle::SendOrphanAnnounce(void) { const MeshCoP::ChannelMask0Tlv *channelMask; - uint8_t channel; + uint8_t channel; - channelMask = static_cast(GetNetif().GetActiveDataset().GetTlv( - MeshCoP::Tlv::kChannelMask)); + channelMask = + static_cast(GetNetif().GetActiveDataset().GetTlv(MeshCoP::Tlv::kChannelMask)); VerifyOrExit(channelMask != NULL); @@ -2104,16 +2107,16 @@ exit: otError Mle::SendMessage(Message &aMessage, const Ip6::Address &aDestination) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Header header; - uint32_t keySequence; - uint8_t nonce[13]; - uint8_t tag[4]; - uint8_t tagLength; - Crypto::AesCcm aesCcm; - uint8_t buf[64]; - uint16_t length; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Header header; + uint32_t keySequence; + uint8_t nonce[13]; + uint8_t tag[4]; + uint8_t tagLength; + Crypto::AesCcm aesCcm; + uint8_t buf[64]; + uint16_t length; Ip6::MessageInfo messageInfo; aMessage.Read(0, sizeof(header), &header); @@ -2127,10 +2130,8 @@ otError Mle::SendMessage(Message &aMessage, const Ip6::Address &aDestination) aMessage.Write(0, header.GetLength(), &header); - GenerateNonce(netif.GetMac().GetExtAddress(), - netif.GetKeyManager().GetMleFrameCounter(), - Mac::Frame::kSecEncMic32, - nonce); + GenerateNonce(netif.GetMac().GetExtAddress(), netif.GetKeyManager().GetMleFrameCounter(), + Mac::Frame::kSecEncMic32, nonce); aesCcm.SetKey(netif.GetKeyManager().GetCurrentMleKey(), 16); error = aesCcm.Init(16 + 16 + header.GetHeaderLength(), aMessage.GetLength() - (header.GetLength() - 1), @@ -2172,7 +2173,7 @@ exit: otError Mle::AddDelayedResponse(Message &aMessage, const Ip6::Address &aDestination, uint16_t aDelay) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint32_t alarmFireTime; uint32_t sendTime = TimerMilli::GetNow() + aDelay; @@ -2209,23 +2210,23 @@ void Mle::HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageI void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - MleRouter &mle = netif.GetMle(); - Header header; - uint32_t keySequence; - const uint8_t *mleKey; - uint32_t frameCounter; - uint8_t messageTag[4]; - uint8_t nonce[13]; + ThreadNetif & netif = GetNetif(); + MleRouter & mle = netif.GetMle(); + Header header; + uint32_t keySequence; + const uint8_t * mleKey; + uint32_t frameCounter; + uint8_t messageTag[4]; + uint8_t nonce[13]; Mac::ExtAddress macAddr; - Crypto::AesCcm aesCcm; - uint16_t mleOffset; - uint8_t buf[64]; - uint16_t length; - uint8_t tag[4]; - uint8_t tagLength; - uint8_t command; - Neighbor *neighbor; + Crypto::AesCcm aesCcm; + uint16_t mleOffset; + uint8_t buf[64]; + uint16_t length; + uint8_t tag[4]; + uint8_t tagLength; + uint8_t command; + Neighbor * neighbor; VerifyOrExit(aMessageInfo.GetLinkInfo() != NULL); VerifyOrExit(aMessageInfo.GetHopLimit() == kMleHopLimit); @@ -2278,10 +2279,9 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn GenerateNonce(macAddr, frameCounter, Mac::Frame::kSecEncMic32, nonce); aesCcm.SetKey(mleKey, 16); - SuccessOrExit(aesCcm.Init(sizeof(aMessageInfo.GetPeerAddr()) + sizeof(aMessageInfo.GetSockAddr()) + - header.GetHeaderLength(), - aMessage.GetLength() - aMessage.GetOffset(), - sizeof(messageTag), nonce, sizeof(nonce))); + SuccessOrExit( + aesCcm.Init(sizeof(aMessageInfo.GetPeerAddr()) + sizeof(aMessageInfo.GetSockAddr()) + header.GetHeaderLength(), + aMessage.GetLength() - aMessage.GetOffset(), sizeof(messageTag), nonce, sizeof(nonce))); aesCcm.Header(&aMessageInfo.GetPeerAddr(), sizeof(aMessageInfo.GetPeerAddr())); aesCcm.Header(&aMessageInfo.GetSockAddr(), sizeof(aMessageInfo.GetSockAddr())); @@ -2366,16 +2366,11 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn } else { - if (!(command == Header::kCommandLinkRequest || - command == Header::kCommandLinkAccept || - command == Header::kCommandLinkAcceptAndRequest || - command == Header::kCommandAdvertisement || - command == Header::kCommandParentRequest || - command == Header::kCommandParentResponse || - command == Header::kCommandChildIdRequest || - command == Header::kCommandChildUpdateRequest || - command == Header::kCommandChildUpdateResponse || - command == Header::kCommandAnnounce)) + if (!(command == Header::kCommandLinkRequest || command == Header::kCommandLinkAccept || + command == Header::kCommandLinkAcceptAndRequest || command == Header::kCommandAdvertisement || + command == Header::kCommandParentRequest || command == Header::kCommandParentResponse || + command == Header::kCommandChildIdRequest || command == Header::kCommandChildUpdateRequest || + command == Header::kCommandChildUpdateResponse || command == Header::kCommandAnnounce)) { otLogDebgMle(GetInstance(), "mle sequence unknown! %d", command); ExitNow(); @@ -2459,16 +2454,16 @@ exit: otError Mle::HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Mac::ExtAddress macAddr; - bool isNeighbor; - Neighbor *neighbor; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Mac::ExtAddress macAddr; + bool isNeighbor; + Neighbor * neighbor; SourceAddressTlv sourceAddress; - LeaderDataTlv leaderData; - RouteTlv route; - uint8_t tlvs[] = {Tlv::kNetworkData}; - uint16_t delay; + LeaderDataTlv leaderData; + RouteTlv route; + uint8_t tlvs[] = {Tlv::kNetworkData}; + uint16_t delay; // Source Address SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kSourceAddress, sizeof(sourceAddress), sourceAddress)); @@ -2520,8 +2515,7 @@ otError Mle::HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo SetLeaderData(leaderData.GetPartitionId(), leaderData.GetWeighting(), leaderData.GetLeaderRouterId()); if ((mDeviceMode & ModeTlv::kModeFFD) && - (Tlv::GetTlv(aMessage, Tlv::kRoute, sizeof(route), route) == OT_ERROR_NONE) && - route.IsValid()) + (Tlv::GetTlv(aMessage, Tlv::kRoute, sizeof(route), route) == OT_ERROR_NONE) && route.IsValid()) { // Overwrite Route Data netif.GetMle().ProcessRouteTlv(route); @@ -2536,8 +2530,7 @@ otError Mle::HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo case OT_DEVICE_ROLE_ROUTER: case OT_DEVICE_ROLE_LEADER: - if ((neighbor = netif.GetMle().GetNeighbor(macAddr)) != NULL && - neighbor->GetState() == Neighbor::kStateValid) + if ((neighbor = netif.GetMle().GetNeighbor(macAddr)) != NULL && neighbor->GetState() == Neighbor::kStateValid) { isNeighbor = true; } @@ -2577,24 +2570,23 @@ otError Mle::HandleDataResponse(const Message &aMessage, const Ip6::MessageInfo otError Mle::HandleLeaderData(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - LeaderDataTlv leaderData; - NetworkDataTlv networkData; - ActiveTimestampTlv activeTimestamp; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + LeaderDataTlv leaderData; + NetworkDataTlv networkData; + ActiveTimestampTlv activeTimestamp; PendingTimestampTlv pendingTimestamp; - uint16_t activeDatasetOffset = 0; - uint16_t pendingDatasetOffset = 0; - bool dataRequest = false; - Tlv tlv; + uint16_t activeDatasetOffset = 0; + uint16_t pendingDatasetOffset = 0; + bool dataRequest = false; + Tlv tlv; // Leader Data SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kLeaderData, sizeof(leaderData), leaderData)); VerifyOrExit(leaderData.IsValid(), error = OT_ERROR_PARSE); if ((leaderData.GetPartitionId() != mLeaderData.GetPartitionId()) || - (leaderData.GetWeighting() != mLeaderData.GetWeighting()) || - (leaderData.GetLeaderRouterId() != GetLeaderId())) + (leaderData.GetWeighting() != mLeaderData.GetWeighting()) || (leaderData.GetLeaderRouterId() != GetLeaderId())) { if (mRole == OT_DEVICE_ROLE_CHILD) { @@ -2684,8 +2676,7 @@ otError Mle::HandleLeaderData(const Message &aMessage, const Ip6::MessageInfo &a if (activeDatasetOffset > 0) { aMessage.Read(activeDatasetOffset, sizeof(tlv), &tlv); - netif.GetActiveDataset().Set(activeTimestamp, aMessage, activeDatasetOffset + sizeof(tlv), - tlv.GetLength()); + netif.GetActiveDataset().Set(activeTimestamp, aMessage, activeDatasetOffset + sizeof(tlv), tlv.GetLength()); } } @@ -2707,7 +2698,7 @@ exit: if (dataRequest) { static const uint8_t tlvs[] = {Tlv::kNetworkData}; - uint16_t delay; + uint16_t delay; if (aMessageInfo.GetSockAddr().IsMulticast()) { @@ -2727,14 +2718,14 @@ exit: return error; } -bool Mle::IsBetterParent(uint16_t aRloc16, uint8_t aLinkQuality, uint8_t aLinkMargin, - ConnectivityTlv &aConnectivityTlv) +bool Mle::IsBetterParent(uint16_t aRloc16, uint8_t aLinkQuality, uint8_t aLinkMargin, ConnectivityTlv &aConnectivityTlv) { bool rval = false; - uint8_t candidateLinkQualityIn = mParentCandidate.GetLinkInfo().GetLinkQuality(); + uint8_t candidateLinkQualityIn = mParentCandidate.GetLinkInfo().GetLinkQuality(); uint8_t candidateTwoWayLinkQuality = (candidateLinkQualityIn < mParentCandidate.GetLinkQualityOut()) - ? candidateLinkQualityIn : mParentCandidate.GetLinkQualityOut(); + ? candidateLinkQualityIn + : mParentCandidate.GetLinkQualityOut(); if (aLinkQuality != candidateTwoWayLinkQuality) { @@ -2778,24 +2769,23 @@ void Mle::ResetParentCandidate(void) mParentCandidate.SetState(Neighbor::kStateInvalid); } -otError Mle::HandleParentResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - uint32_t aKeySequence) +otError Mle::HandleParentResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, uint32_t aKeySequence) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; const otThreadLinkInfo *linkInfo = static_cast(aMessageInfo.GetLinkInfo()); - ResponseTlv response; - SourceAddressTlv sourceAddress; - LeaderDataTlv leaderData; - LinkMarginTlv linkMarginTlv; - uint8_t linkMargin; - uint8_t linkQuality; - ConnectivityTlv connectivity; - LinkFrameCounterTlv linkFrameCounter; - MleFrameCounterTlv mleFrameCounter; - ChallengeTlv challenge; - Mac::ExtAddress extAddress; - int8_t diff; + ResponseTlv response; + SourceAddressTlv sourceAddress; + LeaderDataTlv leaderData; + LinkMarginTlv linkMarginTlv; + uint8_t linkMargin; + uint8_t linkQuality; + ConnectivityTlv connectivity; + LinkFrameCounterTlv linkFrameCounter; + MleFrameCounterTlv mleFrameCounter; + ChallengeTlv challenge; + Mac::ExtAddress extAddress; + int8_t diff; // Source Address SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kSourceAddress, sizeof(sourceAddress), sourceAddress)); @@ -2806,13 +2796,12 @@ otError Mle::HandleParentResponse(const Message &aMessage, const Ip6::MessageInf // Response SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kResponse, sizeof(response), response)); VerifyOrExit(response.IsValid() && - memcmp(response.GetResponse(), mParentRequest.mChallenge, response.GetLength()) == 0, + memcmp(response.GetResponse(), mParentRequest.mChallenge, response.GetLength()) == 0, error = OT_ERROR_PARSE); aMessageInfo.GetPeerAddr().ToExtAddress(extAddress); - if (mRole == OT_DEVICE_ROLE_CHILD && - mParent.GetExtAddress() == extAddress) + if (mRole == OT_DEVICE_ROLE_CHILD && mParent.GetExtAddress() == extAddress) { mReceivedResponseFromParent = true; } @@ -2916,14 +2905,14 @@ otError Mle::HandleParentResponse(const Message &aMessage, const Ip6::MessageInf mParentCandidate.SetState(Neighbor::kStateParentResponse); mParentCandidate.SetKeySequence(aKeySequence); - mParentPriority = connectivity.GetParentPriority(); + mParentPriority = connectivity.GetParentPriority(); mParentLinkQuality3 = connectivity.GetLinkQuality3(); mParentLinkQuality2 = connectivity.GetLinkQuality2(); mParentLinkQuality1 = connectivity.GetLinkQuality1(); - mParentLeaderCost = connectivity.GetLeaderCost(); - mParentLeaderData = leaderData; - mParentIsSingleton = connectivity.GetActiveRouters() <= 1; - mParentLinkMargin = linkMargin; + mParentLeaderCost = connectivity.GetLeaderCost(); + mParentLeaderData = leaderData; + mParentIsSingleton = connectivity.GetActiveRouters() <= 1; + mParentLinkMargin = linkMargin; exit: @@ -2937,17 +2926,17 @@ exit: otError Mle::HandleChildIdResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - LeaderDataTlv leaderData; - SourceAddressTlv sourceAddress; - Address16Tlv shortAddress; - NetworkDataTlv networkData; - RouteTlv route; - ActiveTimestampTlv activeTimestamp; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + LeaderDataTlv leaderData; + SourceAddressTlv sourceAddress; + Address16Tlv shortAddress; + NetworkDataTlv networkData; + RouteTlv route; + ActiveTimestampTlv activeTimestamp; PendingTimestampTlv pendingTimestamp; - Tlv tlv; - uint16_t offset; + Tlv tlv; + uint16_t offset; // Source Address SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kSourceAddress, sizeof(sourceAddress), sourceAddress)); @@ -3055,16 +3044,16 @@ otError Mle::HandleChildUpdateRequest(const Message &aMessage, const Ip6::Messag { static const uint8_t kMaxResponseTlvs = 5; - otError error = OT_ERROR_NONE; - Mac::ExtAddress srcAddr; + otError error = OT_ERROR_NONE; + Mac::ExtAddress srcAddr; SourceAddressTlv sourceAddress; - LeaderDataTlv leaderData; - NetworkDataTlv networkData; - ChallengeTlv challenge; - StatusTlv status; - TlvRequestTlv tlvRequest; - uint8_t tlvs[kMaxResponseTlvs] = {}; - uint8_t numTlvs = 0; + LeaderDataTlv leaderData; + NetworkDataTlv networkData; + ChallengeTlv challenge; + StatusTlv status; + TlvRequestTlv tlvRequest; + uint8_t tlvs[kMaxResponseTlvs] = {}; + uint8_t numTlvs = 0; // Source Address SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kSourceAddress, sizeof(sourceAddress), sourceAddress)); @@ -3118,15 +3107,15 @@ exit: otError Mle::HandleChildUpdateResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - StatusTlv status; - ModeTlv mode; - ResponseTlv response; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + StatusTlv status; + ModeTlv mode; + ResponseTlv response; LinkFrameCounterTlv linkFrameCounter; - MleFrameCounterTlv mleFrameCounter; - SourceAddressTlv sourceAddress; - TimeoutTlv timeout; + MleFrameCounterTlv mleFrameCounter; + SourceAddressTlv sourceAddress; + TimeoutTlv timeout; LogMleMessage("Receive Child Update Response from parent", aMessageInfo.GetPeerAddr()); @@ -3148,16 +3137,14 @@ otError Mle::HandleChildUpdateResponse(const Message &aMessage, const Ip6::Messa // Response SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kResponse, sizeof(response), response)); VerifyOrExit(response.IsValid(), error = OT_ERROR_PARSE); - VerifyOrExit(memcmp(response.GetResponse(), mParentRequest.mChallenge, - sizeof(mParentRequest.mChallenge)) == 0, + VerifyOrExit(memcmp(response.GetResponse(), mParentRequest.mChallenge, sizeof(mParentRequest.mChallenge)) == 0, error = OT_ERROR_DROP); - SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kLinkFrameCounter, sizeof(linkFrameCounter), - linkFrameCounter)); + SuccessOrExit(error = + Tlv::GetTlv(aMessage, Tlv::kLinkFrameCounter, sizeof(linkFrameCounter), linkFrameCounter)); VerifyOrExit(linkFrameCounter.IsValid(), error = OT_ERROR_PARSE); - if (Tlv::GetTlv(aMessage, Tlv::kMleFrameCounter, sizeof(mleFrameCounter), mleFrameCounter) == - OT_ERROR_NONE) + if (Tlv::GetTlv(aMessage, Tlv::kMleFrameCounter, sizeof(mleFrameCounter), mleFrameCounter) == OT_ERROR_NONE) { VerifyOrExit(mleFrameCounter.IsValid(), error = OT_ERROR_PARSE); } @@ -3172,7 +3159,7 @@ otError Mle::HandleChildUpdateResponse(const Message &aMessage, const Ip6::Messa mParent.SetState(Neighbor::kStateValid); SetStateChild(GetRloc16()); - // fall through + // fall through case OT_DEVICE_ROLE_CHILD: // Source Address @@ -3205,7 +3192,7 @@ otError Mle::HandleChildUpdateResponse(const Message &aMessage, const Ip6::Messa { mChildUpdateRequestTimer.Start(TimerMilli::SecToMsec(mTimeout) - static_cast(kUnicastRetransmissionDelay) * - kMaxChildKeepAliveAttempts); + kMaxChildKeepAliveAttempts); netif.GetMeshForwarder().SetRxOnWhenIdle(true); } @@ -3230,12 +3217,12 @@ exit: otError Mle::HandleAnnounce(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - ChannelTlv channel; - ActiveTimestampTlv timestamp; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + ChannelTlv channel; + ActiveTimestampTlv timestamp; const MeshCoP::Timestamp *localTimestamp; - PanIdTlv panid; + PanIdTlv panid; LogMleMessage("Receive Announce", aMessageInfo.GetPeerAddr()); @@ -3254,7 +3241,7 @@ otError Mle::HandleAnnounce(const Message &aMessage, const Ip6::MessageInfo &aMe { Stop(false); mPreviousChannel = netif.GetMac().GetChannel(); - mPreviousPanId = netif.GetMac().GetPanId(); + mPreviousPanId = netif.GetMac().GetPanId(); netif.GetMac().SetChannel(static_cast(channel.GetChannel())); netif.GetMac().SetPanId(panid.GetPanId()); Start(false, true); @@ -3278,18 +3265,18 @@ exit: otError Mle::HandleDiscoveryResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - otError error = OT_ERROR_NONE; - const otThreadLinkInfo *linkInfo = static_cast(aMessageInfo.GetLinkInfo()); - Tlv tlv; - MeshCoP::Tlv meshcopTlv; + otError error = OT_ERROR_NONE; + const otThreadLinkInfo * linkInfo = static_cast(aMessageInfo.GetLinkInfo()); + Tlv tlv; + MeshCoP::Tlv meshcopTlv; MeshCoP::DiscoveryResponseTlv discoveryResponse; - MeshCoP::ExtendedPanIdTlv extPanId; - MeshCoP::NetworkNameTlv networkName; - MeshCoP::SteeringDataTlv steeringData; - MeshCoP::JoinerUdpPortTlv JoinerUdpPort; - otActiveScanResult result; - uint16_t offset; - uint16_t end; + MeshCoP::ExtendedPanIdTlv extPanId; + MeshCoP::NetworkNameTlv networkName; + MeshCoP::SteeringDataTlv steeringData; + MeshCoP::JoinerUdpPortTlv JoinerUdpPort; + otActiveScanResult result; + uint16_t offset; + uint16_t end; LogMleMessage("Receive Discovery Response", aMessageInfo.GetPeerAddr()); @@ -3303,10 +3290,10 @@ otError Mle::HandleDiscoveryResponse(const Message &aMessage, const Ip6::Message end = offset + tlv.GetLength(); memset(&result, 0, sizeof(result)); - result.mPanId = linkInfo->mPanId; + result.mPanId = linkInfo->mPanId; result.mChannel = linkInfo->mChannel; - result.mRssi = linkInfo->mRss; - result.mLqi = linkInfo->mLqi; + result.mRssi = linkInfo->mRss; + result.mLqi = linkInfo->mLqi; aMessageInfo.GetPeerAddr().ToExtAddress(*static_cast(&result.mExtAddress)); // process MeshCoP TLVs @@ -3319,7 +3306,7 @@ otError Mle::HandleDiscoveryResponse(const Message &aMessage, const Ip6::Message case MeshCoP::Tlv::kDiscoveryResponse: aMessage.Read(offset, sizeof(discoveryResponse), &discoveryResponse); VerifyOrExit(discoveryResponse.IsValid(), error = OT_ERROR_PARSE); - result.mVersion = discoveryResponse.GetVersion(); + result.mVersion = discoveryResponse.GetVersion(); result.mIsNative = discoveryResponse.IsNativeCommissioner(); break; @@ -3345,8 +3332,8 @@ otError Mle::HandleDiscoveryResponse(const Message &aMessage, const Ip6::Message if (mEnableEui64Filtering) { Mac::ExtAddress extaddr; - Crc16 ccitt(Crc16::kCcitt); - Crc16 ansi(Crc16::kAnsi); + Crc16 ccitt(Crc16::kCcitt); + Crc16 ansi(Crc16::kAnsi); otPlatRadioGetIeeeEui64(&GetInstance(), extaddr.m8); @@ -3415,14 +3402,12 @@ Neighbor *Mle::GetNeighbor(uint16_t aAddress) Neighbor *Mle::GetNeighbor(const Mac::ExtAddress &aAddress) { - if ((mParent.IsStateValidOrRestoring()) && - (mParent.GetExtAddress() == aAddress)) + if ((mParent.IsStateValidOrRestoring()) && (mParent.GetExtAddress() == aAddress)) { return &mParent; } - if ((mParentCandidate.GetState() == Neighbor::kStateValid) && - (mParentCandidate.GetExtAddress() == aAddress)) + if ((mParentCandidate.GetState() == Neighbor::kStateValid) && (mParentCandidate.GetExtAddress() == aAddress)) { return &mParentCandidate; } @@ -3454,8 +3439,8 @@ Neighbor *Mle::GetNeighbor(const Mac::Address &aAddress) uint16_t Mle::GetNextHop(uint16_t aDestination) const { OT_UNUSED_VARIABLE(aDestination); - return (mParent.GetState() == Neighbor::kStateValid) ? mParent.GetRloc16() : static_cast - (Mac::kShortAddrInvalid); + return (mParent.GetState() == Neighbor::kStateValid) ? mParent.GetRloc16() + : static_cast(Mac::kShortAddrInvalid); } bool Mle::IsRoutingLocator(const Ip6::Address &aAddress) const @@ -3499,8 +3484,8 @@ Router *Mle::GetParentCandidate(void) otError Mle::CheckReachability(uint16_t aMeshSource, uint16_t aMeshDest, Ip6::Header &aIp6Header) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_DROP; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_DROP; Ip6::MessageInfo messageInfo; if (aMeshDest != GetRloc16()) @@ -3513,12 +3498,11 @@ otError Mle::CheckReachability(uint16_t aMeshSource, uint16_t aMeshDest, Ip6::He ExitNow(error = OT_ERROR_NONE); } - messageInfo.GetPeerAddr() = GetMeshLocal16(); + messageInfo.GetPeerAddr() = GetMeshLocal16(); messageInfo.GetPeerAddr().mFields.m16[7] = HostSwap16(aMeshSource); messageInfo.SetInterfaceId(netif.GetInterfaceId()); - netif.GetIp6().GetIcmp().SendError(Ip6::IcmpHeader::kTypeDstUnreach, - Ip6::IcmpHeader::kCodeDstUnreachNoRoute, + netif.GetIp6().GetIcmp().SendError(Ip6::IcmpHeader::kTypeDstUnreach, Ip6::IcmpHeader::kCodeDstUnreachNoRoute, messageInfo, aIp6Header); exit: @@ -3528,12 +3512,12 @@ exit: #if OPENTHREAD_CONFIG_INFORM_PREVIOUS_PARENT_ON_REATTACH otError Mle::InformPreviousParent(void) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Message *message = NULL; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Message * message = NULL; Ip6::MessageInfo messageInfo; - VerifyOrExit((mPreviousParentRloc != Mac::kShortAddrInvalid) && (mPreviousParentRloc != mParent.GetRloc16())); + VerifyOrExit((mPreviousParentRloc != Mac::kShortAddrInvalid) && (mPreviousParentRloc != mParent.GetRloc16())); VerifyOrExit((message = netif.GetIp6().NewMessage(0)) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->SetLength(0)); @@ -3628,7 +3612,6 @@ void Mle::StartParentSearchTimer(void) otLogInfoMle(GetInstance(), "PeriodicParentSearch: (Re)starting timer for %s interval", mParentSearchIsInBackoff ? "backoff" : "check"); - } void Mle::UpdateParentSearchState(void) @@ -3652,11 +3635,11 @@ void Mle::UpdateParentSearchState(void) if (mParentSearchIsInBackoff && !mParentSearchBackoffWasCanceled && mParentSearchRecentlyDetached) { - if ((mPreviousParentRloc != Mac::kShortAddrInvalid) && (mPreviousParentRloc != mParent.GetRloc16())) + if ((mPreviousParentRloc != Mac::kShortAddrInvalid) && (mPreviousParentRloc != mParent.GetRloc16())) { - mParentSearchIsInBackoff = false; + mParentSearchIsInBackoff = false; mParentSearchBackoffWasCanceled = true; - mParentSearchBackoffCancelTime = TimerMilli::GetNow(); + mParentSearchBackoffCancelTime = TimerMilli::GetNow(); otLogInfoMle(GetInstance(), "PeriodicParentSearch: Canceling backoff on switching to a new parent"); } } @@ -3677,8 +3660,7 @@ void Mle::LogMleMessage(const char *aLogString, const Ip6::Address &aAddress) co #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MLE == 1) char stringBuffer[Ip6::Address::kIp6AddressStringSize]; - otLogInfoMle(GetInstance(), "%s (%s)", - aLogString, aAddress.ToString(stringBuffer, sizeof(stringBuffer))); + otLogInfoMle(GetInstance(), "%s (%s)", aLogString, aAddress.ToString(stringBuffer, sizeof(stringBuffer))); #endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MLE == 1) OT_UNUSED_VARIABLE(aLogString); @@ -3690,8 +3672,8 @@ void Mle::LogMleMessage(const char *aLogString, const Ip6::Address &aAddress, ui #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MLE == 1) char stringBuffer[Ip6::Address::kIp6AddressStringSize]; - otLogInfoMle(GetInstance(), "%s (%s,0x%04x)", - aLogString, aAddress.ToString(stringBuffer, sizeof(stringBuffer)), aRloc); + otLogInfoMle(GetInstance(), "%s (%s,0x%04x)", aLogString, aAddress.ToString(stringBuffer, sizeof(stringBuffer)), + aRloc); #endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MLE == 1) OT_UNUSED_VARIABLE(aLogString); @@ -3699,5 +3681,5 @@ void Mle::LogMleMessage(const char *aLogString, const Ip6::Address &aAddress, ui OT_UNUSED_VARIABLE(aRloc); } -} // namespace Mle -} // namespace ot +} // namespace Mle +} // namespace ot diff --git a/src/core/thread/mle.hpp b/src/core/thread/mle.hpp index c7732de13..0f1e9db48 100644 --- a/src/core/thread/mle.hpp +++ b/src/core/thread/mle.hpp @@ -54,8 +54,12 @@ class ThreadNetif; class KeyManager; class MeshForwarder; -namespace Mac { class Mac; } -namespace NetworkData { class Leader; } +namespace Mac { +class Mac; +} +namespace NetworkData { +class Leader; +} /** * @addtogroup core-mle MLE @@ -99,10 +103,10 @@ class MleRouter; */ enum AttachMode { - kAttachAny = 0, ///< Attach to any Thread partition. - kAttachSame1 = 1, ///< Attach to the same Thread partition (attempt 1). - kAttachSame2 = 2, ///< Attach to the same Thread partition (attempt 2). - kAttachBetter = 3, ///< Attach to a better (i.e. higher weight/partition id) Thread partition. + kAttachAny = 0, ///< Attach to any Thread partition. + kAttachSame1 = 1, ///< Attach to the same Thread partition (attempt 1). + kAttachSame2 = 2, ///< Attach to the same Thread partition (attempt 2). + kAttachBetter = 3, ///< Attach to a better (i.e. higher weight/partition id) Thread partition. }; /** @@ -111,16 +115,16 @@ enum AttachMode */ enum AlocAllocation { - kAloc16Leader = 0xfc00, - kAloc16DhcpAgentStart = 0xfc01, - kAloc16DhcpAgentEnd = 0xfc0f, - kAloc16DhcpAgentMask = 0x000f, - kAloc16ServiceStart = 0xfc10, - kAloc16ServiceEnd = 0xfc2f, - kAloc16CommissionerStart = 0xfc30, - kAloc16CommissionerEnd = 0xfc37, - kAloc16NeighborDiscoveryAgentStart = 0xfc40, - kAloc16NeighborDiscoveryAgentEnd = 0xfc4e, + kAloc16Leader = 0xfc00, + kAloc16DhcpAgentStart = 0xfc01, + kAloc16DhcpAgentEnd = 0xfc0f, + kAloc16DhcpAgentMask = 0x000f, + kAloc16ServiceStart = 0xfc10, + kAloc16ServiceEnd = 0xfc2f, + kAloc16CommissionerStart = 0xfc30, + kAloc16CommissionerEnd = 0xfc37, + kAloc16NeighborDiscoveryAgentStart = 0xfc40, + kAloc16NeighborDiscoveryAgentEnd = 0xfc4e, }; /** @@ -129,8 +133,8 @@ enum AlocAllocation */ enum ServiceID { - kServiceMinId = 0x00, ///< Minimal Service ID. - kServiceMaxId = 0x0f, ///< Maximal Service ID. + kServiceMinId = 0x00, ///< Minimal Service ID. + kServiceMaxId = 0x0f, ///< Maximal Service ID. }; /** @@ -145,7 +149,11 @@ public: * This method initializes the MLE header. * */ - void Init(void) { mSecuritySuite = k154Security; mSecurityControl = Mac::Frame::kSecEncMic32; } + void Init(void) + { + mSecuritySuite = k154Security; + mSecurityControl = Mac::Frame::kSecEncMic32; + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -154,7 +162,8 @@ public: * @retval FALSE If the TLV does not appear to be well-formed. * */ - bool IsValid(void) const { + bool IsValid(void) const + { return (mSecuritySuite == kNoSecurity) || (mSecuritySuite == k154Security && mSecurityControl == (Mac::Frame::kKeyIdMode2 | Mac::Frame::kSecEncMic32)); @@ -166,10 +175,12 @@ public: * @returns The MLE header and Command Type length. * */ - uint8_t GetLength(void) const { + uint8_t GetLength(void) const + { uint8_t rval = sizeof(mSecuritySuite) + sizeof(mCommand); - if (mSecuritySuite == k154Security) { + if (mSecuritySuite == k154Security) + { rval += sizeof(mSecurityControl) + sizeof(mFrameCounter) + sizeof(mKeySource) + sizeof(mKeyIndex); } @@ -178,8 +189,8 @@ public: enum SecuritySuite { - k154Security = 0, ///< IEEE 802.15.4-2006 security. - kNoSecurity = 255, ///< No security enabled. + k154Security = 0, ///< IEEE 802.15.4-2006 security. + kNoSecurity = 255, ///< No security enabled. }; /** @@ -204,7 +215,8 @@ public: * @returns The MLE header length (excluding the Command Type). * */ - uint8_t GetHeaderLength(void) const { + uint8_t GetHeaderLength(void) const + { return sizeof(mSecurityControl) + sizeof(mFrameCounter) + sizeof(mKeySource) + sizeof(mKeyIndex); } @@ -214,9 +226,7 @@ public: * @returns A pointer to the first byte of the MLE header. * */ - const uint8_t *GetBytes(void) const { - return reinterpret_cast(&mSecuritySuite); - } + const uint8_t *GetBytes(void) const { return reinterpret_cast(&mSecuritySuite); } /** * This method returns the Security Control value. @@ -233,15 +243,14 @@ public: * @retval FALSE If the Key ID Mode is not set to 2. * */ - bool IsKeyIdMode2(void) const { - return (mSecurityControl & Mac::Frame::kKeyIdModeMask) == Mac::Frame::kKeyIdMode2; - } + bool IsKeyIdMode2(void) const { return (mSecurityControl & Mac::Frame::kKeyIdModeMask) == Mac::Frame::kKeyIdMode2; } /** * This method sets the Key ID Mode to 2. * */ - void SetKeyIdMode2(void) { + void SetKeyIdMode2(void) + { mSecurityControl = (mSecurityControl & ~Mac::Frame::kKeyIdModeMask) | Mac::Frame::kKeyIdMode2; } @@ -251,9 +260,7 @@ public: * @returns The Key ID value. * */ - uint32_t GetKeyId(void) const { - return Encoding::BigEndian::HostSwap32(mKeySource); - } + uint32_t GetKeyId(void) const { return Encoding::BigEndian::HostSwap32(mKeySource); } /** * This method sets the Key ID value. @@ -261,9 +268,10 @@ public: * @param[in] aKeySequence The Key ID value. * */ - void SetKeyId(uint32_t aKeySequence) { + void SetKeyId(uint32_t aKeySequence) + { mKeySource = Encoding::BigEndian::HostSwap32(aKeySequence); - mKeyIndex = (aKeySequence & 0x7f) + 1; + mKeyIndex = (aKeySequence & 0x7f) + 1; } /** @@ -272,9 +280,7 @@ public: * @returns The Frame Counter value. * */ - uint32_t GetFrameCounter(void) const { - return Encoding::LittleEndian::HostSwap32(mFrameCounter); - } + uint32_t GetFrameCounter(void) const { return Encoding::LittleEndian::HostSwap32(mFrameCounter); } /** * This method sets the Frame Counter value. @@ -282,9 +288,7 @@ public: * @param[in] aFrameCounter The Frame Counter value. * */ - void SetFrameCounter(uint32_t aFrameCounter) { - mFrameCounter = Encoding::LittleEndian::HostSwap32(aFrameCounter); - } + void SetFrameCounter(uint32_t aFrameCounter) { mFrameCounter = Encoding::LittleEndian::HostSwap32(aFrameCounter); } /** * MLE Command Types. @@ -292,24 +296,24 @@ public: */ enum Command { - kCommandLinkRequest = 0, ///< Link Reject - kCommandLinkAccept = 1, ///< Link Accept - kCommandLinkAcceptAndRequest = 2, ///< Link Accept and Reject - kCommandLinkReject = 3, ///< Link Reject - kCommandAdvertisement = 4, ///< Advertisement - kCommandUpdate = 5, ///< Update - kCommandUpdateRequest = 6, ///< Update Request - kCommandDataRequest = 7, ///< Data Request - kCommandDataResponse = 8, ///< Data Response - kCommandParentRequest = 9, ///< Parent Request - kCommandParentResponse = 10, ///< Parent Response - kCommandChildIdRequest = 11, ///< Child ID Request - kCommandChildIdResponse = 12, ///< Child ID Response - kCommandChildUpdateRequest = 13, ///< Child Update Request - kCommandChildUpdateResponse = 14, ///< Child Update Response - kCommandAnnounce = 15, ///< Announce - kCommandDiscoveryRequest = 16, ///< Discovery Request - kCommandDiscoveryResponse = 17, ///< Discovery Response + kCommandLinkRequest = 0, ///< Link Reject + kCommandLinkAccept = 1, ///< Link Accept + kCommandLinkAcceptAndRequest = 2, ///< Link Accept and Reject + kCommandLinkReject = 3, ///< Link Reject + kCommandAdvertisement = 4, ///< Advertisement + kCommandUpdate = 5, ///< Update + kCommandUpdateRequest = 6, ///< Update Request + kCommandDataRequest = 7, ///< Data Request + kCommandDataResponse = 8, ///< Data Response + kCommandParentRequest = 9, ///< Parent Request + kCommandParentResponse = 10, ///< Parent Response + kCommandChildIdRequest = 11, ///< Child ID Request + kCommandChildIdResponse = 12, ///< Child ID Response + kCommandChildUpdateRequest = 13, ///< Child Update Request + kCommandChildUpdateResponse = 14, ///< Child Update Response + kCommandAnnounce = 15, ///< Announce + kCommandDiscoveryRequest = 16, ///< Discovery Request + kCommandDiscoveryResponse = 17, ///< Discovery Response }; /** @@ -318,11 +322,14 @@ public: * @returns The Command Type value. * */ - Command GetCommand(void) const { - if (mSecuritySuite == kNoSecurity) { + Command GetCommand(void) const + { + if (mSecuritySuite == kNoSecurity) + { return static_cast(mSecurityControl); } - else { + else + { return static_cast(mCommand); } } @@ -333,22 +340,25 @@ public: * @param[in] aCommand The Command Type value. * */ - void SetCommand(Command aCommand) { - if (mSecuritySuite == kNoSecurity) { + void SetCommand(Command aCommand) + { + if (mSecuritySuite == kNoSecurity) + { mSecurityControl = static_cast(aCommand); } - else { + else + { mCommand = static_cast(aCommand); } } private: - uint8_t mSecuritySuite; - uint8_t mSecurityControl; + uint8_t mSecuritySuite; + uint8_t mSecurityControl; uint32_t mFrameCounter; uint32_t mKeySource; - uint8_t mKeyIndex; - uint8_t mCommand; + uint8_t mKeyIndex; + uint8_t mCommand; } OT_TOOL_PACKED_END; /** @@ -372,8 +382,9 @@ public: * @param[in] aDestination IPv6 address of the message destination. * */ - DelayedResponseHeader(uint32_t aSendTime, const Ip6::Address &aDestination) { - mSendTime = aSendTime; + DelayedResponseHeader(uint32_t aSendTime, const Ip6::Address &aDestination) + { + mSendTime = aSendTime; mDestination = aDestination; }; @@ -386,9 +397,7 @@ public: * @retval OT_ERROR_NO_BUFS Insufficient available buffers to grow the message. * */ - otError AppendTo(Message &aMessage) { - return aMessage.Append(this, sizeof(*this)); - }; + otError AppendTo(Message &aMessage) { return aMessage.Append(this, sizeof(*this)); }; /** * This method reads delayed response header from the message. @@ -398,7 +407,8 @@ public: * @returns The number of bytes read. * */ - uint16_t ReadFrom(Message &aMessage) { + uint16_t ReadFrom(Message &aMessage) + { return aMessage.Read(aMessage.GetLength() - sizeof(*this), sizeof(*this), this); }; @@ -410,7 +420,8 @@ public: * @retval OT_ERROR_NONE Successfully removed the header. * */ - static otError RemoveFrom(Message &aMessage) { + static otError RemoveFrom(Message &aMessage) + { return aMessage.SetLength(aMessage.GetLength() - sizeof(DelayedResponseHeader)); }; @@ -451,15 +462,15 @@ public: bool IsLater(uint32_t aTime) { return (static_cast(aTime - mSendTime) < 0); }; private: - Ip6::Address mDestination; ///< IPv6 address of the message destination. - uint32_t mSendTime; ///< Time when the message shall be sent. + Ip6::Address mDestination; ///< IPv6 address of the message destination. + uint32_t mSendTime; ///< Time when the message shall be sent. } OT_TOOL_PACKED_END; /** * This class implements MLE functionality required by the Thread EndDevices, Router, and Leader roles. * */ -class Mle: public InstanceLocator +class Mle : public InstanceLocator { public: /** @@ -552,9 +563,12 @@ public: * @retval OT_ERROR_BUSY Thread Discovery is already in progress. * */ - otError Discover(uint32_t aScanChannels, uint16_t aPanId, bool aJoiner, bool aEnableEui64Filtering, + otError Discover(uint32_t aScanChannels, + uint16_t aPanId, + bool aJoiner, + bool aEnableEui64Filtering, DiscoverHandler aCallback, - void *aContext); + void * aContext); /** * This method indicates whether or not an MLE Thread Discovery is currently in progress. @@ -634,7 +648,8 @@ public: * @returns TRUE if the device is a Minimal End Device, FALSE otherwise. * */ - bool IsMinimalEndDevice(void) const { + bool IsMinimalEndDevice(void) const + { return (mDeviceMode & (ModeTlv::kModeFFD | ModeTlv::kModeRxOnWhenIdle)) != (ModeTlv::kModeFFD | ModeTlv::kModeRxOnWhenIdle); } @@ -887,7 +902,10 @@ public: * @returns The Service ID corresponding to given ALOC16. * */ - static uint8_t GetServiceIdFromAloc(uint16_t aAloc16) { return static_cast(aAloc16 - kAloc16ServiceStart); } + static uint8_t GetServiceIdFromAloc(uint16_t aAloc16) + { + return static_cast(aAloc16 - kAloc16ServiceStart); + } /** * This method returns the Service Aloc corresponding to a Service ID. @@ -897,7 +915,10 @@ public: * @returns The Service ALOC16 corresponding to given ID. * */ - static uint16_t GetServiceAlocFromId(uint8_t aServiceId) { return static_cast(aServiceId + kAloc16ServiceStart); } + static uint16_t GetServiceAlocFromId(uint8_t aServiceId) + { + return static_cast(aServiceId + kAloc16ServiceStart); + } /** * This method returns the RLOC16 of a given Router ID. @@ -946,7 +967,7 @@ public: protected: enum { - kMleMaxResponseDelay = 1000u, ///< Maximum delay before responding to a multicast request. + kMleMaxResponseDelay = 1000u, ///< Maximum delay before responding to a multicast request. }; /** @@ -1231,7 +1252,11 @@ protected: * @returns A pointer to the neighbor object. * */ - Neighbor *GetNeighbor(const Ip6::Address &aAddress) { OT_UNUSED_VARIABLE(aAddress); return NULL; } + Neighbor *GetNeighbor(const Ip6::Address &aAddress) + { + OT_UNUSED_VARIABLE(aAddress); + return NULL; + } /** * This method returns the next hop towards an RLOC16 destination. @@ -1255,8 +1280,10 @@ protected: * @retval OT_ERROR_NO_BUFS Insufficient buffers to generate the MLE Data Request message. * */ - otError SendDataRequest(const Ip6::Address &aDestination, const uint8_t *aTlvs, uint8_t aTlvsLength, - uint16_t aDelay); + otError SendDataRequest(const Ip6::Address &aDestination, + const uint8_t * aTlvs, + uint8_t aTlvsLength, + uint16_t aDelay); /** * This method generates an MLE Child Update Request message. @@ -1370,12 +1397,12 @@ protected: */ void InformPreviousChannel(void); - LeaderDataTlv mLeaderData; ///< Last received Leader Data TLV. - bool mRetrieveNewNetworkData; ///< Indicating new Network Data is needed if set. + LeaderDataTlv mLeaderData; ///< Last received Leader Data TLV. + bool mRetrieveNewNetworkData; ///< Indicating new Network Data is needed if set. - otDeviceRole mRole; ///< Current Thread role. - Router mParent; ///< Parent information. - uint8_t mDeviceMode; ///< Device mode setting. + otDeviceRole mRole; ///< Current Thread role. + Router mParent; ///< Parent information. + uint8_t mDeviceMode; ///< Device mode setting. /** * States when searching for a parent. @@ -1383,14 +1410,14 @@ protected: */ enum ParentRequestState { - kParentIdle, ///< Not currently searching for a parent. - kParentSynchronize, ///< Looking to synchronize with a parent (after reset). - kParentRequestStart, ///< Starting to look for a parent. - kParentRequestRouter, ///< Searching for a Router to attach to. - kParentRequestChild, ///< Searching for Routers or REEDs to attach to. - kChildIdRequest, ///< Sending a Child ID Request message. + kParentIdle, ///< Not currently searching for a parent. + kParentSynchronize, ///< Looking to synchronize with a parent (after reset). + kParentRequestStart, ///< Starting to look for a parent. + kParentRequestRouter, ///< Searching for a Router to attach to. + kParentRequestChild, ///< Searching for Routers or REEDs to attach to. + kChildIdRequest, ///< Sending a Child ID Request message. }; - ParentRequestState mParentRequestState; ///< The parent request state. + ParentRequestState mParentRequestState; ///< The parent request state. /** * States when reattaching network using stored dataset @@ -1398,19 +1425,19 @@ protected: */ enum ReattachState { - kReattachStop = 0, ///< Reattach process is disabled or finished - kReattachStart = 1, ///< Start reattach process - kReattachActive = 2, ///< Reattach using stored Active Dataset - kReattachPending = 3, ///< Reattach using stored Pending Dataset + kReattachStop = 0, ///< Reattach process is disabled or finished + kReattachStart = 1, ///< Start reattach process + kReattachActive = 2, ///< Reattach using stored Active Dataset + kReattachPending = 3, ///< Reattach using stored Pending Dataset }; ReattachState mReattachState; - TimerMilli mParentRequestTimer; ///< The timer for driving the Parent Request process. - TimerMilli mDelayedResponseTimer; ///< The timer to delay MLE responses. - TimerMilli mChildUpdateRequestTimer; ///< The timer for sending MLE Child Update Request messages. - uint32_t mLastPartitionId; ///< The partition ID of the previous Thread partition - uint8_t mLastPartitionRouterIdSequence; ///< The router ID sequence from the previous Thread partition - uint8_t mLastPartitionIdTimeout; ///< The time remaining to avoid the previous Thread partition + TimerMilli mParentRequestTimer; ///< The timer for driving the Parent Request process. + TimerMilli mDelayedResponseTimer; ///< The timer to delay MLE responses. + TimerMilli mChildUpdateRequestTimer; ///< The timer for sending MLE Child Update Request messages. + uint32_t mLastPartitionId; ///< The partition ID of the previous Thread partition + uint8_t mLastPartitionRouterIdSequence; ///< The router ID sequence from the previous Thread partition + uint8_t mLastPartitionIdTimeout; ///< The time remaining to avoid the previous Thread partition uint8_t mParentLeaderCost; @@ -1432,39 +1459,39 @@ private: }; #endif - void GenerateNonce(const Mac::ExtAddress &aMacAddr, uint32_t aFrameCounter, uint8_t aSecurityLevel, - uint8_t *aNonce); + void GenerateNonce(const Mac::ExtAddress &aMacAddr, + uint32_t aFrameCounter, + uint8_t aSecurityLevel, + uint8_t * aNonce); static void HandleStateChanged(Notifier::Callback &aCallback, uint32_t aFlags); - void HandleStateChanged(uint32_t aFlags); + void HandleStateChanged(uint32_t aFlags); static void HandleParentRequestTimer(Timer &aTimer); - void HandleParentRequestTimer(void); + void HandleParentRequestTimer(void); static void HandleDelayedResponseTimer(Timer &aTimer); - void HandleDelayedResponseTimer(void); + void HandleDelayedResponseTimer(void); static void HandleChildUpdateRequestTimer(Timer &aTimer); - void HandleChildUpdateRequestTimer(void); + void HandleChildUpdateRequestTimer(void); static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo); - void HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); static void HandleSendChildUpdateRequest(Tasklet &aTasklet); - void HandleSendChildUpdateRequest(void); + void HandleSendChildUpdateRequest(void); otError HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); otError HandleChildIdResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); otError HandleChildUpdateRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); otError HandleChildUpdateResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); otError HandleDataResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - otError HandleParentResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - uint32_t aKeySequence); + otError HandleParentResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, uint32_t aKeySequence); otError HandleAnnounce(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); otError HandleDiscoveryResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); otError HandleLeaderData(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); otError SendParentRequest(void); otError SendChildIdRequest(void); - void SendOrphanAnnounce(void); + void SendOrphanAnnounce(void); - bool IsBetterParent(uint16_t aRloc16, uint8_t aLinkQuality, uint8_t aLinkMargin, - ConnectivityTlv &aConnectivityTlv); + bool IsBetterParent(uint16_t aRloc16, uint8_t aLinkQuality, uint8_t aLinkMargin, ConnectivityTlv &aConnectivityTlv); void ResetParentCandidate(void); #if OPENTHREAD_ENABLE_SERVICE @@ -1481,9 +1508,9 @@ private: #if OPENTHREAD_CONFIG_ENABLE_PERIODIC_PARENT_SEARCH static void HandleParentSearchTimer(Timer &aTimer); - void HandleParentSearchTimer(void); - void StartParentSearchTimer(void); - void UpdateParentSearchState(void); + void HandleParentSearchTimer(void); + void StartParentSearchTimer(void); + void UpdateParentSearchState(void); #endif MessageQueue mDelayedResponses; @@ -1499,43 +1526,43 @@ private: uint8_t mChallenge[ChallengeTlv::kMaxSize]; } mParentRequest; - AttachMode mParentRequestMode; - int8_t mParentPriority; - uint8_t mParentLinkQuality3; - uint8_t mParentLinkQuality2; - uint8_t mParentLinkQuality1; - uint8_t mChildUpdateAttempts; + AttachMode mParentRequestMode; + int8_t mParentPriority; + uint8_t mParentLinkQuality3; + uint8_t mParentLinkQuality2; + uint8_t mParentLinkQuality1; + uint8_t mChildUpdateAttempts; LeaderDataTlv mParentLeaderData; - uint8_t mParentLinkMargin; - bool mParentIsSingleton; - bool mReceivedResponseFromParent; + uint8_t mParentLinkMargin; + bool mParentIsSingleton; + bool mReceivedResponseFromParent; Router mParentCandidate; Ip6::UdpSocket mSocket; - uint32_t mTimeout; + uint32_t mTimeout; Tasklet mSendChildUpdateRequest; DiscoverHandler mDiscoverHandler; - void *mDiscoverContext; - bool mIsDiscoverInProgress; - bool mEnableEui64Filtering; + void * mDiscoverContext; + bool mIsDiscoverInProgress; + bool mEnableEui64Filtering; #if OPENTHREAD_CONFIG_INFORM_PREVIOUS_PARENT_ON_REATTACH uint16_t mPreviousParentRloc; #endif #if OPENTHREAD_CONFIG_ENABLE_PERIODIC_PARENT_SEARCH - bool mParentSearchIsInBackoff : 1; - bool mParentSearchBackoffWasCanceled : 1; - bool mParentSearchRecentlyDetached : 1; - uint32_t mParentSearchBackoffCancelTime; + bool mParentSearchIsInBackoff : 1; + bool mParentSearchBackoffWasCanceled : 1; + bool mParentSearchRecentlyDetached : 1; + uint32_t mParentSearchBackoffCancelTime; TimerMilli mParentSearchTimer; #endif - uint8_t mAnnounceChannel; - uint8_t mPreviousChannel; + uint8_t mAnnounceChannel; + uint8_t mPreviousChannel; uint16_t mPreviousPanId; Ip6::NetifUnicastAddress mLeaderAloc; @@ -1544,22 +1571,22 @@ private: Ip6::NetifUnicastAddress mServiceAlocs[OPENTHREAD_CONFIG_MAX_SERVER_ALOCS]; #endif - Ip6::NetifUnicastAddress mLinkLocal64; - Ip6::NetifUnicastAddress mMeshLocal64; - Ip6::NetifUnicastAddress mMeshLocal16; + Ip6::NetifUnicastAddress mLinkLocal64; + Ip6::NetifUnicastAddress mMeshLocal64; + Ip6::NetifUnicastAddress mMeshLocal16; Ip6::NetifMulticastAddress mLinkLocalAllThreadNodes; Ip6::NetifMulticastAddress mRealmLocalAllThreadNodes; Notifier::Callback mNotifierCallback; }; -} // namespace Mle +} // namespace Mle /** * @} * */ -} // namespace ot +} // namespace ot -#endif // MLE_HPP_ +#endif // MLE_HPP_ diff --git a/src/core/thread/mle_constants.hpp b/src/core/thread/mle_constants.hpp index 9212ed34a..84f058503 100644 --- a/src/core/thread/mle_constants.hpp +++ b/src/core/thread/mle_constants.hpp @@ -46,9 +46,9 @@ namespace Mle { enum { - kMaxChildren = OPENTHREAD_CONFIG_MAX_CHILDREN, - kMaxChildKeepAliveAttempts = 4, ///< Maximum keep alive attempts before attempting to reattach to a new Parent - kFailedChildTransmissions = 4, ///< FAILED_CHILD_TRANSMISSIONS + kMaxChildren = OPENTHREAD_CONFIG_MAX_CHILDREN, + kMaxChildKeepAliveAttempts = 4, ///< Maximum keep alive attempts before attempting to reattach to a new Parent + kFailedChildTransmissions = 4, ///< FAILED_CHILD_TRANSMISSIONS }; /** @@ -69,15 +69,15 @@ enum kMaxChildIdRequestTimeout = 5000, ///< Maximum delay for receiving a Child ID Request kMaxChildUpdateResponseTimeout = 2000, ///< Maximum delay for receiving a Child Update Response kMaxLinkRequestTimeout = 2000, ///< Maximum delay for receiving a Link Accept - kMinTimeout = (((kMaxChildKeepAliveAttempts + 1) * kUnicastRetransmissionDelay) / 1000), ///< Minimum timeout(s) + kMinTimeout = (((kMaxChildKeepAliveAttempts + 1) * kUnicastRetransmissionDelay) / 1000), ///< Minimum timeout(s) }; enum { - kMinChildId = 1, ///< Minimum Child ID - kMaxChildId = 511, ///< Maximum Child ID - kRouterIdOffset = 10, ///< Bit offset of Router ID in RLOC16 - kRlocPrefixLength = 14, ///< Prefix length of RLOC in bytes + kMinChildId = 1, ///< Minimum Child ID + kMaxChildId = 511, ///< Maximum Child ID + kRouterIdOffset = 10, ///< Bit offset of Router ID in RLOC16 + kRlocPrefixLength = 14, ///< Prefix length of RLOC in bytes }; /** @@ -106,7 +106,7 @@ enum kReedAdvertiseInterval = 570, ///< REED_ADVERTISEMENT_INTERVAL (seconds) kReedAdvertiseJitter = 60, ///< REED_ADVERTISEMENT_JITTER (seconds) kLeaderWeight = 64, ///< Default leader weight for the Thread Network Partition - kMleEndDeviceTimeout = OPENTHREAD_CONFIG_DEFAULT_CHILD_TIMEOUT, ///< MLE_END_DEVICE_TIMEOUT (seconds) + kMleEndDeviceTimeout = OPENTHREAD_CONFIG_DEFAULT_CHILD_TIMEOUT, ///< MLE_END_DEVICE_TIMEOUT (seconds) }; /** @@ -115,18 +115,18 @@ enum */ enum { - kParentPriorityHigh = 1, // Parent Priority High - kParentPriorityMedium = 0, // Parent Priority Medium (default) - kParentPriorityLow = -1, // Parent Priority Low - kParentPriorityUnspecified = -2, // Parent Priority Unspecified + kParentPriorityHigh = 1, // Parent Priority High + kParentPriorityMedium = 0, // Parent Priority Medium (default) + kParentPriorityLow = -1, // Parent Priority Low + kParentPriorityUnspecified = -2, // Parent Priority Unspecified }; enum { - kLinkQuality3LinkCost = 1, ///< Link Cost for Link Quality 3 - kLinkQuality2LinkCost = 2, ///< Link Cost for Link Quality 2 - kLinkQuality1LinkCost = 4, ///< Link Cost for Link Quality 1 - kLinkQuality0LinkCost = 16, ///< Link Cost for Link Quality 0 + kLinkQuality3LinkCost = 1, ///< Link Cost for Link Quality 3 + kLinkQuality2LinkCost = 2, ///< Link Cost for Link Quality 2 + kLinkQuality1LinkCost = 4, ///< Link Cost for Link Quality 1 + kLinkQuality0LinkCost = 16, ///< Link Cost for Link Quality 0 }; /** @@ -139,13 +139,13 @@ enum kMplRouterDataMessageTimerExpirations = 2, ///< Number of MPL retransmissions for Routers. }; -} // namespace Mle +} // namespace Mle /** * @} * */ -} // namespace ot +} // namespace ot -#endif // MLE_CONSTANTS_HPP_ +#endif // MLE_CONSTANTS_HPP_ diff --git a/src/core/thread/mle_router.cpp b/src/core/thread/mle_router.cpp index 1f8a6bb41..ecf37d81e 100644 --- a/src/core/thread/mle_router.cpp +++ b/src/core/thread/mle_router.cpp @@ -58,29 +58,29 @@ using ot::Encoding::BigEndian::HostSwap16; namespace ot { namespace Mle { -MleRouter::MleRouter(Instance &aInstance): - Mle(aInstance), - mAdvertiseTimer(aInstance, &MleRouter::HandleAdvertiseTimer, NULL, this), - mStateUpdateTimer(aInstance, &MleRouter::HandleStateUpdateTimer, this), - mAddressSolicit(OT_URI_PATH_ADDRESS_SOLICIT, &MleRouter::HandleAddressSolicit, this), - mAddressRelease(OT_URI_PATH_ADDRESS_RELEASE, &MleRouter::HandleAddressRelease, this), - mRouterIdSequence(0), - mRouterIdSequenceLastUpdated(0), - mMaxChildrenAllowed(kMaxChildren), - mChildTableChangedCallback(NULL), - mChallengeTimeout(0), - mNextChildId(kMaxChildId), - mNetworkIdTimeout(kNetworkIdTimeout), - mRouterUpgradeThreshold(kRouterUpgradeThreshold), - mRouterDowngradeThreshold(kRouterDowngradeThreshold), - mLeaderWeight(kLeaderWeight), - mFixedLeaderPartitionId(0), - mRouterRoleEnabled(true), - mAddressSolicitPending(false), - mPreviousPartitionId(0), - mRouterSelectionJitter(kRouterSelectionJitter), - mRouterSelectionJitterTimeout(0), - mParentPriority(kParentPriorityUnspecified) +MleRouter::MleRouter(Instance &aInstance) + : Mle(aInstance) + , mAdvertiseTimer(aInstance, &MleRouter::HandleAdvertiseTimer, NULL, this) + , mStateUpdateTimer(aInstance, &MleRouter::HandleStateUpdateTimer, this) + , mAddressSolicit(OT_URI_PATH_ADDRESS_SOLICIT, &MleRouter::HandleAddressSolicit, this) + , mAddressRelease(OT_URI_PATH_ADDRESS_RELEASE, &MleRouter::HandleAddressRelease, this) + , mRouterIdSequence(0) + , mRouterIdSequenceLastUpdated(0) + , mMaxChildrenAllowed(kMaxChildren) + , mChildTableChangedCallback(NULL) + , mChallengeTimeout(0) + , mNextChildId(kMaxChildId) + , mNetworkIdTimeout(kNetworkIdTimeout) + , mRouterUpgradeThreshold(kRouterUpgradeThreshold) + , mRouterDowngradeThreshold(kRouterDowngradeThreshold) + , mLeaderWeight(kLeaderWeight) + , mFixedLeaderPartitionId(0) + , mRouterRoleEnabled(true) + , mAddressSolicitPending(false) + , mPreviousPartitionId(0) + , mRouterSelectionJitter(kRouterSelectionJitter) + , mRouterSelectionJitterTimeout(0) + , mParentPriority(kParentPriorityUnspecified) { mDeviceMode |= ModeTlv::kModeFFD | ModeTlv::kModeFullNetworkData; @@ -193,7 +193,7 @@ uint8_t MleRouter::AllocateRouterId(uint8_t aRouterId) // bump sequence number mRouterIdSequence++; mRouterIdSequenceLastUpdated = TimerMilli::GetNow(); - rval = aRouterId; + rval = aRouterId; otLogInfoMle(GetInstance(), "Allocate router id %d", aRouterId); @@ -203,9 +203,9 @@ exit: otError MleRouter::ReleaseRouterId(uint8_t aRouterId) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Router *router = GetRouter(aRouterId); + ThreadNetif &netif = GetNetif(); + otError error = OT_ERROR_NONE; + Router * router = GetRouter(aRouterId); VerifyOrExit(router != NULL, error = OT_ERROR_INVALID_ARGS); VerifyOrExit(mRole == OT_DEVICE_ROLE_LEADER, error = OT_ERROR_INVALID_STATE); @@ -243,7 +243,7 @@ uint32_t MleRouter::GetLeaderAge(void) const otError MleRouter::BecomeRouter(ThreadStatusTlv::Status aStatus) { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; VerifyOrExit(mRole != OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); VerifyOrExit(mRole != OT_DEVICE_ROLE_ROUTER, error = OT_ERROR_NONE); @@ -277,9 +277,9 @@ exit: otError MleRouter::BecomeLeader(void) { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - uint8_t routerId; - Router *router; + otError error = OT_ERROR_NONE; + uint8_t routerId; + Router * router; VerifyOrExit(mRole != OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); VerifyOrExit(mRole != OT_DEVICE_ROLE_LEADER, error = OT_ERROR_NONE); @@ -294,7 +294,7 @@ otError MleRouter::BecomeLeader(void) } routerId = IsRouterIdValid(mPreviousRouterId) ? AllocateRouterId(mPreviousRouterId) : AllocateRouterId(); - router = GetRouter(routerId); + router = GetRouter(routerId); VerifyOrExit(router != NULL, error = OT_ERROR_NO_BUFS); SetRouterId(routerId); @@ -352,9 +352,9 @@ otError MleRouter::HandleDetachStart(void) otError MleRouter::HandleChildStart(AttachMode aMode) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - mRouterIdSequenceLastUpdated = TimerMilli::GetNow(); + ThreadNetif &netif = GetNetif(); + otError error = OT_ERROR_NONE; + mRouterIdSequenceLastUpdated = TimerMilli::GetNow(); mRouterSelectionJitterTimeout = (otPlatRandomGet() % mRouterSelectionJitter) + 1; StopLeader(); @@ -397,8 +397,7 @@ otError MleRouter::HandleChildStart(AttachMode aMode) case kAttachAny: case kAttachBetter: - if (HasChildren() && - mPreviousPartitionId != mLeaderData.GetPartitionId()) + if (HasChildren() && mPreviousPartitionId != mLeaderData.GetPartitionId()) { BecomeRouter(ThreadStatusTlv::kParentPartitionChange); } @@ -408,8 +407,7 @@ otError MleRouter::HandleChildStart(AttachMode aMode) exit: - if (GetActiveRouterCount() >= mRouterUpgradeThreshold && - (!IsRouterIdValid(mPreviousRouterId) || !HasChildren())) + if (GetActiveRouterCount() >= mRouterUpgradeThreshold && (!IsRouterIdValid(mPreviousRouterId) || !HasChildren())) { SetRouterId(kInvalidRouterId); } @@ -427,7 +425,7 @@ otError MleRouter::SetStateRouter(uint16_t aRloc16) } SetRloc16(aRloc16); - mRole = OT_DEVICE_ROLE_ROUTER; + mRole = OT_DEVICE_ROLE_ROUTER; mParentRequestState = kParentIdle; mParentRequestTimer.Stop(); mChildUpdateRequestTimer.Stop(); @@ -454,8 +452,7 @@ otError MleRouter::SetStateRouter(uint16_t aRloc16) // remove children that do not have matching RLOC16 for (int i = 0; i < mMaxChildrenAllowed; i++) { - if (mChildren[i].IsStateValidOrRestoring() && - GetRouterId(mChildren[i].GetRloc16()) != mRouterId) + if (mChildren[i].IsStateValidOrRestoring() && GetRouterId(mChildren[i].GetRloc16()) != mRouterId) { RemoveNeighbor(mChildren[i]); } @@ -475,7 +472,7 @@ otError MleRouter::SetStateLeader(uint16_t aRloc16) } SetRloc16(aRloc16); - mRole = OT_DEVICE_ROLE_LEADER; + mRole = OT_DEVICE_ROLE_LEADER; mParentRequestState = kParentIdle; mParentRequestTimer.Stop(); mChildUpdateRequestTimer.Stop(); @@ -502,8 +499,7 @@ otError MleRouter::SetStateLeader(uint16_t aRloc16) // remove children that do not have matching RLOC16 for (int i = 0; i < mMaxChildrenAllowed; i++) { - if (mChildren[i].IsStateValidOrRestoring() && - GetRouterId(mChildren[i].GetRloc16()) != mRouterId) + if (mChildren[i].IsStateValidOrRestoring() && GetRouterId(mChildren[i].GetRloc16()) != mRouterId) { RemoveNeighbor(mChildren[i]); } @@ -541,10 +537,8 @@ void MleRouter::ResetAdvertiseInterval(void) if (!mAdvertiseTimer.IsRunning()) { - mAdvertiseTimer.Start( - TimerMilli::SecToMsec(kAdvertiseIntervalMin), - TimerMilli::SecToMsec(kAdvertiseIntervalMax), - TrickleTimer::kModeNormal); + mAdvertiseTimer.Start(TimerMilli::SecToMsec(kAdvertiseIntervalMin), + TimerMilli::SecToMsec(kAdvertiseIntervalMax), TrickleTimer::kModeNormal); } mAdvertiseTimer.IndicateInconsistent(); @@ -555,9 +549,9 @@ exit: otError MleRouter::SendAdvertisement(void) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Ip6::Address destination; - Message *message = NULL; + Message * message = NULL; // Suppress MLE Advertisements when trying to attach to a better partition. // @@ -612,12 +606,12 @@ exit: otError MleRouter::SendLinkRequest(Neighbor *aNeighbor) { - static const uint8_t detachedTlvs[] = {Tlv::kAddress16, Tlv::kRoute}; - static const uint8_t routerTlvs[] = {Tlv::kLinkMargin}; + static const uint8_t detachedTlvs[] = {Tlv::kAddress16, Tlv::kRoute}; + static const uint8_t routerTlvs[] = {Tlv::kLinkMargin}; static const uint8_t validNeighborTlvs[] = {Tlv::kLinkMargin, Tlv::kRoute}; - otError error = OT_ERROR_NONE; - Message *message; - Ip6::Address destination; + otError error = OT_ERROR_NONE; + Message * message; + Ip6::Address destination; memset(&destination, 0, sizeof(destination)); @@ -666,8 +660,8 @@ otError MleRouter::SendLinkRequest(Neighbor *aNeighbor) mChallengeTimeout = (((2 * kMaxResponseDelay) + kStateUpdatePeriod - 1) / kStateUpdatePeriod); SuccessOrExit(error = AppendChallenge(*message, mChallenge, sizeof(mChallenge))); - destination.mFields.m8[0] = 0xff; - destination.mFields.m8[1] = 0x02; + destination.mFields.m8[0] = 0xff; + destination.mFields.m8[1] = 0x02; destination.mFields.m8[15] = 2; } else @@ -675,8 +669,7 @@ otError MleRouter::SendLinkRequest(Neighbor *aNeighbor) if (aNeighbor->GetState() != Neighbor::kStateValid) { aNeighbor->GenerateChallenge(); - SuccessOrExit(error = AppendChallenge(*message, aNeighbor->GetChallenge(), - aNeighbor->GetChallengeSize())); + SuccessOrExit(error = AppendChallenge(*message, aNeighbor->GetChallenge(), aNeighbor->GetChallengeSize())); } else { @@ -710,15 +703,15 @@ exit: otError MleRouter::HandleLinkRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - otError error = OT_ERROR_NONE; - Neighbor *neighbor = NULL; - Mac::ExtAddress macAddr; - ChallengeTlv challenge; - VersionTlv version; - LeaderDataTlv leaderData; + otError error = OT_ERROR_NONE; + Neighbor * neighbor = NULL; + Mac::ExtAddress macAddr; + ChallengeTlv challenge; + VersionTlv version; + LeaderDataTlv leaderData; SourceAddressTlv sourceAddress; - TlvRequestTlv tlvRequest; - uint16_t rloc16; + TlvRequestTlv tlvRequest; + uint16_t rloc16; LogMleMessage("Receive Link Request", aMessageInfo.GetPeerAddr()); @@ -766,8 +759,7 @@ otError MleRouter::HandleLinkRequest(const Message &aMessage, const Ip6::Message if (neighbor->GetState() != Neighbor::kStateValid) { - const otThreadLinkInfo *linkInfo = - static_cast(aMessageInfo.GetLinkInfo()); + const otThreadLinkInfo *linkInfo = static_cast(aMessageInfo.GetLinkInfo()); neighbor->SetExtAddress(macAddr); neighbor->GetLinkInfo().Clear(); @@ -789,9 +781,8 @@ otError MleRouter::HandleLinkRequest(const Message &aMessage, const Ip6::Message else { // lack of source address indicates router coming out of reset - VerifyOrExit((neighbor = GetNeighbor(macAddr)) != NULL && - neighbor->GetState() == Neighbor::kStateValid && - IsActiveRouter(neighbor->GetRloc16()), + VerifyOrExit((neighbor = GetNeighbor(macAddr)) != NULL && neighbor->GetState() == Neighbor::kStateValid && + IsActiveRouter(neighbor->GetRloc16()), error = OT_ERROR_DROP); } @@ -811,18 +802,21 @@ exit: return error; } -otError MleRouter::SendLinkAccept(const Ip6::MessageInfo &aMessageInfo, Neighbor *aNeighbor, - const TlvRequestTlv &aTlvRequest, const ChallengeTlv &aChallenge) +otError MleRouter::SendLinkAccept(const Ip6::MessageInfo &aMessageInfo, + Neighbor * aNeighbor, + const TlvRequestTlv & aTlvRequest, + const ChallengeTlv & aChallenge) { - otError error = OT_ERROR_NONE; - const otThreadLinkInfo *linkInfo = static_cast(aMessageInfo.GetLinkInfo()); - static const uint8_t routerTlvs[] = {Tlv::kLinkMargin}; - Message *message; - Header::Command command; - uint8_t linkMargin; + otError error = OT_ERROR_NONE; + const otThreadLinkInfo *linkInfo = static_cast(aMessageInfo.GetLinkInfo()); + static const uint8_t routerTlvs[] = {Tlv::kLinkMargin}; + Message * message; + Header::Command command; + uint8_t linkMargin; - command = (aNeighbor == NULL || aNeighbor->GetState() == Neighbor::kStateValid) ? - Header::kCommandLinkAccept : Header::kCommandLinkAcceptAndRequest; + command = (aNeighbor == NULL || aNeighbor->GetState() == Neighbor::kStateValid) + ? Header::kCommandLinkAccept + : Header::kCommandLinkAcceptAndRequest; VerifyOrExit((message = NewMleMessage()) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = AppendHeader(*message, command)); @@ -896,40 +890,44 @@ exit: return error; } -otError MleRouter::HandleLinkAccept(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - uint32_t aKeySequence) +otError MleRouter::HandleLinkAccept(const Message & aMessage, + const Ip6::MessageInfo &aMessageInfo, + uint32_t aKeySequence) { return HandleLinkAccept(aMessage, aMessageInfo, aKeySequence, false); } -otError MleRouter::HandleLinkAcceptAndRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - uint32_t aKeySequence) +otError MleRouter::HandleLinkAcceptAndRequest(const Message & aMessage, + const Ip6::MessageInfo &aMessageInfo, + uint32_t aKeySequence) { return HandleLinkAccept(aMessage, aMessageInfo, aKeySequence, true); } -otError MleRouter::HandleLinkAccept(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - uint32_t aKeySequence, bool aRequest) +otError MleRouter::HandleLinkAccept(const Message & aMessage, + const Ip6::MessageInfo &aMessageInfo, + uint32_t aKeySequence, + bool aRequest) { static const uint8_t dataRequestTlvs[] = {Tlv::kNetworkData}; - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; const otThreadLinkInfo *linkInfo = static_cast(aMessageInfo.GetLinkInfo()); - Router *router; - Neighbor *neighbor; - Mac::ExtAddress macAddr; - VersionTlv version; - ResponseTlv response; - SourceAddressTlv sourceAddress; - LinkFrameCounterTlv linkFrameCounter; - MleFrameCounterTlv mleFrameCounter; - uint8_t routerId; - Address16Tlv address16; - RouteTlv route; - LeaderDataTlv leaderData; - LinkMarginTlv linkMargin; - ChallengeTlv challenge; - TlvRequestTlv tlvRequest; + Router * router; + Neighbor * neighbor; + Mac::ExtAddress macAddr; + VersionTlv version; + ResponseTlv response; + SourceAddressTlv sourceAddress; + LinkFrameCounterTlv linkFrameCounter; + MleFrameCounterTlv mleFrameCounter; + uint8_t routerId; + Address16Tlv address16; + RouteTlv route; + LeaderDataTlv leaderData; + LinkMarginTlv linkMargin; + ChallengeTlv challenge; + TlvRequestTlv tlvRequest; aMessageInfo.GetPeerAddr().ToExtAddress(macAddr); @@ -955,20 +953,17 @@ otError MleRouter::HandleLinkAccept(const Message &aMessage, const Ip6::MessageI VerifyOrExit(response.IsValid(), error = OT_ERROR_PARSE); // Remove stale neighbors - if ((neighbor = GetNeighbor(macAddr)) != NULL && - neighbor->GetRloc16() != sourceAddress.GetRloc16()) + if ((neighbor = GetNeighbor(macAddr)) != NULL && neighbor->GetRloc16() != sourceAddress.GetRloc16()) { RemoveNeighbor(*neighbor); } // Link-Layer Frame Counter - SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kLinkFrameCounter, sizeof(linkFrameCounter), - linkFrameCounter)); + SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kLinkFrameCounter, sizeof(linkFrameCounter), linkFrameCounter)); VerifyOrExit(linkFrameCounter.IsValid(), error = OT_ERROR_PARSE); // MLE Frame Counter - if (Tlv::GetTlv(aMessage, Tlv::kMleFrameCounter, sizeof(mleFrameCounter), mleFrameCounter) == - OT_ERROR_NONE) + if (Tlv::GetTlv(aMessage, Tlv::kMleFrameCounter, sizeof(mleFrameCounter), mleFrameCounter) == OT_ERROR_NONE) { VerifyOrExit(mleFrameCounter.IsValid(), error = OT_ERROR_PARSE); } @@ -980,7 +975,7 @@ otError MleRouter::HandleLinkAccept(const Message &aMessage, const Ip6::MessageI VerifyOrExit(IsActiveRouter(sourceAddress.GetRloc16()), error = OT_ERROR_PARSE); routerId = GetRouterId(sourceAddress.GetRloc16()); - router = GetRouter(routerId); + router = GetRouter(routerId); VerifyOrExit(router != NULL, error = OT_ERROR_PARSE); @@ -993,8 +988,7 @@ otError MleRouter::HandleLinkAccept(const Message &aMessage, const Ip6::MessageI break; case Neighbor::kStateInvalid: - VerifyOrExit((mChallengeTimeout > 0) && - (memcmp(mChallenge, response.GetResponse(), sizeof(mChallenge)) == 0), + VerifyOrExit((mChallengeTimeout > 0) && (memcmp(mChallenge, response.GetResponse(), sizeof(mChallenge)) == 0), error = OT_ERROR_SECURITY); break; @@ -1136,8 +1130,7 @@ Child *MleRouter::FindChild(uint16_t aChildId) for (int i = 0; i < mMaxChildrenAllowed; i++) { - if (mChildren[i].GetState() != Neighbor::kStateInvalid && - GetChildId(mChildren[i].GetRloc16()) == aChildId) + if (mChildren[i].GetState() != Neighbor::kStateInvalid && GetChildId(mChildren[i].GetRloc16()) == aChildId) { ExitNow(rval = &mChildren[i]); } @@ -1153,8 +1146,7 @@ Child *MleRouter::FindChild(const Mac::ExtAddress &aAddress) for (int i = 0; i < mMaxChildrenAllowed; i++) { - if (mChildren[i].GetState() != Neighbor::kStateInvalid && - mChildren[i].GetExtAddress() == aAddress) + if (mChildren[i].GetState() != Neighbor::kStateInvalid && mChildren[i].GetExtAddress() == aAddress) { ExitNow(rval = &mChildren[i]); } @@ -1221,7 +1213,7 @@ otError MleRouter::ProcessRouteTlv(const RouteTlv &aRoute) { otError error = OT_ERROR_NONE; - mRouterIdSequence = aRoute.GetRouterIdSequence(); + mRouterIdSequence = aRoute.GetRouterIdSequence(); mRouterIdSequenceLastUpdated = TimerMilli::GetNow(); for (uint8_t i = 0; i <= kMaxRouterId; i++) @@ -1266,8 +1258,10 @@ exit: return rval; } -int MleRouter::ComparePartitions(bool aSingletonA, const LeaderDataTlv &aLeaderDataA, - bool aSingletonB, const LeaderDataTlv &aLeaderDataB) +int MleRouter::ComparePartitions(bool aSingletonA, + const LeaderDataTlv &aLeaderDataA, + bool aSingletonB, + const LeaderDataTlv &aLeaderDataB) { int rval = 0; @@ -1322,7 +1316,7 @@ uint8_t MleRouter::GetActiveNeighborRouterCount(void) const bool MleRouter::IsSingleton(const RouteTlv &aRouteTlv) { - bool rval = true; + bool rval = true; uint8_t count = 0; // REEDs do not include a Route TLV and indicate not a singleton @@ -1346,19 +1340,19 @@ exit: otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; const otThreadLinkInfo *linkInfo = static_cast(aMessageInfo.GetLinkInfo()); uint8_t linkMargin = LinkQualityInfo::ConvertRssToLinkMargin(GetNetif().GetMac().GetNoiseFloor(), linkInfo->mRss); - Mac::ExtAddress macAddr; + Mac::ExtAddress macAddr; SourceAddressTlv sourceAddress; - LeaderDataTlv leaderData; - RouteTlv route; - uint32_t partitionId; - Router *router; - Neighbor *neighbor; - uint8_t routerId; - uint8_t routerCount; + LeaderDataTlv leaderData; + RouteTlv route; + uint32_t partitionId; + Router * router; + Neighbor * neighbor; + uint8_t routerId; + uint8_t routerCount; aMessageInfo.GetPeerAddr().ToExtAddress(macAddr); @@ -1367,8 +1361,7 @@ otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Messa VerifyOrExit(sourceAddress.IsValid(), error = OT_ERROR_PARSE); // Remove stale neighbors - if ((neighbor = GetNeighbor(macAddr)) != NULL && - neighbor->GetRloc16() != sourceAddress.GetRloc16()) + if ((neighbor = GetNeighbor(macAddr)) != NULL && neighbor->GetRloc16() != sourceAddress.GetRloc16()) { RemoveNeighbor(*neighbor); } @@ -1392,22 +1385,19 @@ otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Messa if (partitionId != mLeaderData.GetPartitionId()) { - otLogInfoMle(GetInstance(), "Different partition (peer:%d, local:%d)", - leaderData.GetPartitionId(), mLeaderData.GetPartitionId()); + otLogInfoMle(GetInstance(), "Different partition (peer:%d, local:%d)", leaderData.GetPartitionId(), + mLeaderData.GetPartitionId()); VerifyOrExit(linkMargin >= OPENTHREAD_CONFIG_MLE_PARTITION_MERGE_MARGIN_MIN, error = OT_ERROR_LINK_MARGIN_LOW); - if (route.IsValid() && - (mDeviceMode & ModeTlv::kModeFFD) && - (mLastPartitionIdTimeout > 0) && + if (route.IsValid() && (mDeviceMode & ModeTlv::kModeFFD) && (mLastPartitionIdTimeout > 0) && (partitionId == mLastPartitionId)) { VerifyOrExit((static_cast(route.GetRouterIdSequence() - mLastPartitionRouterIdSequence) > 0), error = OT_ERROR_DROP); } - if (mRole == OT_DEVICE_ROLE_CHILD && - (mParent.GetExtAddress() == macAddr || !(mDeviceMode & ModeTlv::kModeFFD))) + if (mRole == OT_DEVICE_ROLE_CHILD && (mParent.GetExtAddress() == macAddr || !(mDeviceMode & ModeTlv::kModeFFD))) { ExitNow(); } @@ -1433,11 +1423,10 @@ otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Messa VerifyOrExit(IsActiveRouter(sourceAddress.GetRloc16()) && route.IsValid()); routerId = GetRouterId(sourceAddress.GetRloc16()); - router = GetRouter(routerId); + router = GetRouter(routerId); VerifyOrExit(router != NULL, error = OT_ERROR_PARSE); - if ((mDeviceMode & ModeTlv::kModeFFD) && - static_cast(route.GetRouterIdSequence() - mRouterIdSequence) > 0) + if ((mDeviceMode & ModeTlv::kModeFFD) && static_cast(route.GetRouterIdSequence() - mRouterIdSequence) > 0) { bool processRouteTlv = false; @@ -1448,8 +1437,7 @@ otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Messa break; case OT_DEVICE_ROLE_CHILD: - if ((sourceAddress.GetRloc16() == mParent.GetRloc16()) || - (router->GetState() == Neighbor::kStateValid)) + if ((sourceAddress.GetRloc16() == mParent.GetRloc16()) || (router->GetState() == Neighbor::kStateValid)) { processRouteTlv = true; } @@ -1476,8 +1464,7 @@ otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Messa case OT_DEVICE_ROLE_CHILD: if ((sourceAddress.GetRloc16() == mParent.GetRloc16() || router->GetState() == Neighbor::kStateValid) && - (mDeviceMode & ModeTlv::kModeFFD) && - (mRouterSelectionJitterTimeout == 0) && + (mDeviceMode & ModeTlv::kModeFFD) && (mRouterSelectionJitterTimeout == 0) && (GetActiveRouterCount() < mRouterUpgradeThreshold)) { mRouterSelectionJitterTimeout = (otPlatRandomGet() % mRouterSelectionJitter) + 1; @@ -1552,16 +1539,14 @@ otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Messa } } - if (routerCount > mRouterDowngradeThreshold && - mRouterSelectionJitterTimeout == 0 && - HasMinDowngradeNeighborRouters() && - HasSmallNumberOfChildren() && + if (routerCount > mRouterDowngradeThreshold && mRouterSelectionJitterTimeout == 0 && + HasMinDowngradeNeighborRouters() && HasSmallNumberOfChildren() && HasOneNeighborwithComparableConnectivity(route, routerId)) { mRouterSelectionJitterTimeout = (otPlatRandomGet() % mRouterSelectionJitter) + 1; } - // fall through + // fall through case OT_DEVICE_ROLE_LEADER: @@ -1573,8 +1558,7 @@ otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Messa } // Send link request if no link to router - if ((router->GetState() != Neighbor::kStateValid) && - (router->GetState() != Neighbor::kStateLinkRequest) && + if ((router->GetState() != Neighbor::kStateValid) && (router->GetState() != Neighbor::kStateLinkRequest) && (linkMargin >= OPENTHREAD_CONFIG_MLE_LINK_REQUEST_MARGIN_MIN)) { router->SetExtAddress(macAddr); @@ -1608,7 +1592,7 @@ void MleRouter::UpdateRoutes(const RouteTlv &aRoute, uint8_t aRouterId) uint8_t oldNextHop; uint8_t cost; uint8_t linkQuality; - bool update; + bool update; // update routes do @@ -1702,8 +1686,7 @@ void MleRouter::UpdateRoutes(const RouteTlv &aRoute, uint8_t aRouterId) routeCount++; } - } - while (update); + } while (update); #if (OPENTHREAD_CONFIG_LOG_MLE && (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_DEBG)) @@ -1714,12 +1697,8 @@ void MleRouter::UpdateRoutes(const RouteTlv &aRoute, uint8_t aRouterId) continue; } - otLogDebgMle(GetInstance(), - "%x: %x %d %d %d %d", - GetRloc16(i), - GetRloc16(mRouters[i].GetNextHop()), - mRouters[i].GetCost(), - GetLinkCost(i), mRouters[i].GetLinkInfo().GetLinkQuality(), + otLogDebgMle(GetInstance(), "%x: %x %d %d %d %d", GetRloc16(i), GetRloc16(mRouters[i].GetNextHop()), + mRouters[i].GetCost(), GetLinkCost(i), mRouters[i].GetLinkInfo().GetLinkQuality(), mRouters[i].GetLinkQualityOut()); } @@ -1728,13 +1707,13 @@ void MleRouter::UpdateRoutes(const RouteTlv &aRoute, uint8_t aRouterId) otError MleRouter::HandleParentRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; const otThreadLinkInfo *linkInfo = static_cast(aMessageInfo.GetLinkInfo()); - Mac::ExtAddress macAddr; - VersionTlv version; - ScanMaskTlv scanMask; - ChallengeTlv challenge; - Child *child; + Mac::ExtAddress macAddr; + VersionTlv version; + ScanMaskTlv scanMask; + ChallengeTlv challenge; + Child * child; LogMleMessage("Receive Parent Request", aMessageInfo.GetPeerAddr()); @@ -1752,11 +1731,11 @@ otError MleRouter::HandleParentRequest(const Message &aMessage, const Ip6::Messa VerifyOrExit(GetLeaderAge() < mNetworkIdTimeout, error = OT_ERROR_DROP); // 3. Its current routing path cost to the Leader is infinite. - VerifyOrExit(mRole == OT_DEVICE_ROLE_LEADER || - GetLinkCost(GetLeaderId()) < kMaxRouteCost || - (mRole == OT_DEVICE_ROLE_CHILD && mRouters[GetLeaderId()].GetCost() + 1 < kMaxRouteCost) || - (mRouters[GetLeaderId()].GetCost() + GetLinkCost(mRouters[GetLeaderId()].GetNextHop()) < kMaxRouteCost), - error = OT_ERROR_DROP); + VerifyOrExit( + mRole == OT_DEVICE_ROLE_LEADER || GetLinkCost(GetLeaderId()) < kMaxRouteCost || + (mRole == OT_DEVICE_ROLE_CHILD && mRouters[GetLeaderId()].GetCost() + 1 < kMaxRouteCost) || + (mRouters[GetLeaderId()].GetCost() + GetLinkCost(mRouters[GetLeaderId()].GetNextHop()) < kMaxRouteCost), + error = OT_ERROR_DROP); aMessageInfo.GetPeerAddr().ToExtAddress(macAddr); @@ -1881,16 +1860,15 @@ void MleRouter::HandleStateUpdateTimer(void) { SendAdvertisement(); - mAdvertiseTimer.Start( - TimerMilli::SecToMsec(kReedAdvertiseInterval), - TimerMilli::SecToMsec(kReedAdvertiseInterval + kReedAdvertiseJitter), - TrickleTimer::kModePlainTimer); + mAdvertiseTimer.Start(TimerMilli::SecToMsec(kReedAdvertiseInterval), + TimerMilli::SecToMsec(kReedAdvertiseInterval + kReedAdvertiseJitter), + TrickleTimer::kModePlainTimer); } ExitNow(); } - // fall through + // fall through case OT_DEVICE_ROLE_ROUTER: // verify path to leader @@ -1962,8 +1940,8 @@ void MleRouter::HandleStateUpdateTimer(void) // update router state for (uint8_t i = 0; i <= kMaxRouterId; i++) { - Router &router = mRouters[i]; - uint32_t age = TimerMilli::GetNow() - router.GetLastHeard(); + Router & router = mRouters[i]; + uint32_t age = TimerMilli::GetNow() - router.GetLastHeard(); if (router.GetState() == Neighbor::kStateValid) { @@ -2008,8 +1986,7 @@ void MleRouter::HandleStateUpdateTimer(void) { if (router.IsAllocated()) { - if (!IsRouterIdValid(router.GetNextHop()) && - GetLinkCost(i) >= kMaxRouteCost && + if (!IsRouterIdValid(router.GetNextHop()) && GetLinkCost(i) >= kMaxRouteCost && age >= TimerMilli::SecToMsec(kMaxLeaderToRouterTimeout)) { otLogInfoMle(GetInstance(), "Router ID timeout expired (no route)"); @@ -2034,10 +2011,10 @@ exit: otError MleRouter::SendParentResponse(Child *aChild, const ChallengeTlv &aChallenge, bool aRoutersOnlyRequest) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Ip6::Address destination; - Message *message; - uint16_t delay; + Message * message; + uint16_t delay; VerifyOrExit((message = NewMleMessage()) != NULL, error = OT_ERROR_NO_BUFS); message->SetDirectTransmission(); @@ -2087,22 +2064,22 @@ exit: otError MleRouter::UpdateChildAddresses(const Message &aMessage, uint16_t aOffset, Child &aChild) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; AddressRegistrationEntry entry; - Ip6::Address address; - Lowpan::Context context; - Tlv tlv; - uint8_t registeredCount = 0; - uint8_t storedCount = 0; - uint16_t offset = 0; - uint16_t end = 0; - char stringBuffer[Ip6::Address::kIp6AddressStringSize]; + Ip6::Address address; + Lowpan::Context context; + Tlv tlv; + uint8_t registeredCount = 0; + uint8_t storedCount = 0; + uint16_t offset = 0; + uint16_t end = 0; + char stringBuffer[Ip6::Address::kIp6AddressStringSize]; VerifyOrExit(aMessage.Read(aOffset, sizeof(tlv), &tlv) == sizeof(tlv), error = OT_ERROR_PARSE); VerifyOrExit(tlv.GetLength() <= (aMessage.GetLength() - aOffset - sizeof(tlv)), error = OT_ERROR_PARSE); offset = aOffset + sizeof(tlv); - end = offset + tlv.GetLength(); + end = offset + tlv.GetLength(); aChild.ClearIp6Addresses(); while (offset < end) @@ -2147,7 +2124,6 @@ otError MleRouter::UpdateChildAddresses(const Message &aMessage, uint16_t aOffse { otLogWarnMle(GetInstance(), "Error %s adding IPv6 address %s to child 0x%04x", otThreadErrorToString(error), address.ToString(stringBuffer, sizeof(stringBuffer)), aChild.GetRloc16()); - } if (address.IsMulticast()) @@ -2178,7 +2154,6 @@ otError MleRouter::UpdateChildAddresses(const Message &aMessage, uint16_t aOffse } } - if (registeredCount == 0) { otLogInfoMle(GetInstance(), "Child 0x%04x has no registered IPv6 address", aChild.GetRloc16()); @@ -2186,8 +2161,8 @@ otError MleRouter::UpdateChildAddresses(const Message &aMessage, uint16_t aOffse else { otLogInfoMle(GetInstance(), "Child 0x%04x has %d registered IPv6 address%s, %d address%s stored", - aChild.GetRloc16(), registeredCount, (registeredCount == 1) ? "" : "es", - storedCount, (storedCount == 1) ? "" : "es"); + aChild.GetRloc16(), registeredCount, (registeredCount == 1) ? "" : "es", storedCount, + (storedCount == 1) ? "" : "es"); } error = OT_ERROR_NONE; @@ -2198,24 +2173,25 @@ exit: return error; } -otError MleRouter::HandleChildIdRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - uint32_t aKeySequence) +otError MleRouter::HandleChildIdRequest(const Message & aMessage, + const Ip6::MessageInfo &aMessageInfo, + uint32_t aKeySequence) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; const otThreadLinkInfo *linkInfo = static_cast(aMessageInfo.GetLinkInfo()); - Mac::ExtAddress macAddr; - ResponseTlv response; - LinkFrameCounterTlv linkFrameCounter; - MleFrameCounterTlv mleFrameCounter; - ModeTlv mode; - TimeoutTlv timeout; - TlvRequestTlv tlvRequest; - ActiveTimestampTlv activeTimestamp; - PendingTimestampTlv pendingTimestamp; - Child *child; - uint8_t numTlvs; - uint16_t addressRegistrationOffset = 0; + Mac::ExtAddress macAddr; + ResponseTlv response; + LinkFrameCounterTlv linkFrameCounter; + MleFrameCounterTlv mleFrameCounter; + ModeTlv mode; + TimeoutTlv timeout; + TlvRequestTlv tlvRequest; + ActiveTimestampTlv activeTimestamp; + PendingTimestampTlv pendingTimestamp; + Child * child; + uint8_t numTlvs; + uint16_t addressRegistrationOffset = 0; LogMleMessage("Receive Child ID Request", aMessageInfo.GetPeerAddr()); @@ -2232,7 +2208,7 @@ otError MleRouter::HandleChildIdRequest(const Message &aMessage, const Ip6::Mess // Response SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kResponse, sizeof(response), response)); VerifyOrExit(response.IsValid() && - memcmp(response.GetResponse(), child->GetChallenge(), child->GetChallengeSize()) == 0, + memcmp(response.GetResponse(), child->GetChallenge(), child->GetChallengeSize()) == 0, error = OT_ERROR_SECURITY); // Remove existing MLE messages @@ -2241,13 +2217,11 @@ otError MleRouter::HandleChildIdRequest(const Message &aMessage, const Ip6::Mess netif.GetMeshForwarder().RemoveMessages(*child, Message::kSubTypeMleDataResponse); // Link-Layer Frame Counter - SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kLinkFrameCounter, sizeof(linkFrameCounter), - linkFrameCounter)); + SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kLinkFrameCounter, sizeof(linkFrameCounter), linkFrameCounter)); VerifyOrExit(linkFrameCounter.IsValid(), error = OT_ERROR_PARSE); // MLE Frame Counter - if (Tlv::GetTlv(aMessage, Tlv::kMleFrameCounter, sizeof(mleFrameCounter), mleFrameCounter) == - OT_ERROR_NONE) + if (Tlv::GetTlv(aMessage, Tlv::kMleFrameCounter, sizeof(mleFrameCounter), mleFrameCounter) == OT_ERROR_NONE) { VerifyOrExit(mleFrameCounter.IsValid(), error = OT_ERROR_PARSE); } @@ -2266,8 +2240,7 @@ otError MleRouter::HandleChildIdRequest(const Message &aMessage, const Ip6::Mess // TLV Request SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kTlvRequest, sizeof(tlvRequest), tlvRequest)); - VerifyOrExit(tlvRequest.IsValid() && tlvRequest.GetLength() <= Child::kMaxRequestTlvs, - error = OT_ERROR_PARSE); + VerifyOrExit(tlvRequest.IsValid() && tlvRequest.GetLength() <= Child::kMaxRequestTlvs, error = OT_ERROR_PARSE); // Active Timestamp activeTimestamp.SetLength(0); @@ -2294,8 +2267,7 @@ otError MleRouter::HandleChildIdRequest(const Message &aMessage, const Ip6::Mess // Remove from router table for (int i = 0; i <= kMaxRouterId; i++) { - if (mRouters[i].GetState() != Neighbor::kStateInvalid && - mRouters[i].GetExtAddress() == macAddr) + if (mRouters[i].GetState() != Neighbor::kStateInvalid && mRouters[i].GetExtAddress() == macAddr) { RemoveNeighbor(mRouters[i]); break; @@ -2335,14 +2307,12 @@ otError MleRouter::HandleChildIdRequest(const Message &aMessage, const Ip6::Mess child->SetRequestTlv(numTlvs, tlvRequest.GetTlvs()[numTlvs]); } - if (activeTimestamp.GetLength() == 0 || - netif.GetActiveDataset().Compare(activeTimestamp) != 0) + if (activeTimestamp.GetLength() == 0 || netif.GetActiveDataset().Compare(activeTimestamp) != 0) { child->SetRequestTlv(numTlvs++, Tlv::kActiveDataset); } - if (pendingTimestamp.GetLength() == 0 || - netif.GetPendingDataset().Compare(pendingTimestamp) != 0) + if (pendingTimestamp.GetLength() == 0 || netif.GetPendingDataset().Compare(pendingTimestamp) != 0) { child->SetRequestTlv(numTlvs++, Tlv::kPendingDataset); } @@ -2369,22 +2339,23 @@ exit: return error; } -otError MleRouter::HandleChildUpdateRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - uint32_t aKeySequence) +otError MleRouter::HandleChildUpdateRequest(const Message & aMessage, + const Ip6::MessageInfo &aMessageInfo, + uint32_t aKeySequence) { static const uint8_t kMaxResponseTlvs = 10; - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Mac::ExtAddress macAddr; - ModeTlv mode; - ChallengeTlv challenge; - LeaderDataTlv leaderData; - TimeoutTlv timeout; - Child *child; - TlvRequestTlv tlvRequest; - uint8_t tlvs[kMaxResponseTlvs]; - uint8_t tlvslength = 0; - uint16_t addressRegistrationOffset = 0; + ModeTlv mode; + ChallengeTlv challenge; + LeaderDataTlv leaderData; + TimeoutTlv timeout; + Child * child; + TlvRequestTlv tlvRequest; + uint8_t tlvs[kMaxResponseTlvs]; + uint8_t tlvslength = 0; + uint16_t addressRegistrationOffset = 0; LogMleMessage("Receive Child Update Request from child", aMessageInfo.GetPeerAddr()); @@ -2451,8 +2422,8 @@ otError MleRouter::HandleChildUpdateRequest(const Message &aMessage, const Ip6:: // TLV Request if (Tlv::GetTlv(aMessage, Tlv::kTlvRequest, sizeof(tlvRequest), tlvRequest) == OT_ERROR_NONE) { - uint8_t tlv; - TlvRequestIterator iterator = TLVREQUESTTLV_ITERATOR_INIT; + uint8_t tlv; + TlvRequestIterator iterator = TLVREQUESTTLV_ITERATOR_INIT; VerifyOrExit(tlvRequest.IsValid() && tlvRequest.GetLength() <= (kMaxResponseTlvs - tlvslength), error = OT_ERROR_PARSE); @@ -2481,21 +2452,22 @@ exit: return error; } -otError MleRouter::HandleChildUpdateResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - uint32_t aKeySequence) +otError MleRouter::HandleChildUpdateResponse(const Message & aMessage, + const Ip6::MessageInfo &aMessageInfo, + uint32_t aKeySequence) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; const otThreadLinkInfo *linkInfo = static_cast(aMessageInfo.GetLinkInfo()); - Mac::ExtAddress macAddr; - SourceAddressTlv sourceAddress; - TimeoutTlv timeout; - ResponseTlv response; - StatusTlv status; - LinkFrameCounterTlv linkFrameCounter; - MleFrameCounterTlv mleFrameCounter; - LeaderDataTlv leaderData; - Child *child; - uint16_t addressRegistrationOffset = 0; + Mac::ExtAddress macAddr; + SourceAddressTlv sourceAddress; + TimeoutTlv timeout; + ResponseTlv response; + StatusTlv status; + LinkFrameCounterTlv linkFrameCounter; + MleFrameCounterTlv mleFrameCounter; + LeaderDataTlv leaderData; + Child * child; + uint16_t addressRegistrationOffset = 0; // Find Child aMessageInfo.GetPeerAddr().ToExtAddress(macAddr); @@ -2527,7 +2499,7 @@ otError MleRouter::HandleChildUpdateResponse(const Message &aMessage, const Ip6: if (Tlv::GetTlv(aMessage, Tlv::kResponse, sizeof(response), response) == OT_ERROR_NONE) { VerifyOrExit(response.IsValid() && - memcmp(response.GetResponse(), child->GetChallenge(), child->GetChallengeSize()) == 0, + memcmp(response.GetResponse(), child->GetChallenge(), child->GetChallengeSize()) == 0, error = OT_ERROR_SECURITY); } @@ -2596,13 +2568,13 @@ exit: otError MleRouter::HandleDataRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - TlvRequestTlv tlvRequest; - ActiveTimestampTlv activeTimestamp; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + TlvRequestTlv tlvRequest; + ActiveTimestampTlv activeTimestamp; PendingTimestampTlv pendingTimestamp; - uint8_t tlvs[4]; - uint8_t numTlvs; + uint8_t tlvs[4]; + uint8_t numTlvs; LogMleMessage("Receive Data Request", aMessageInfo.GetPeerAddr()); @@ -2630,14 +2602,12 @@ otError MleRouter::HandleDataRequest(const Message &aMessage, const Ip6::Message memcpy(tlvs, tlvRequest.GetTlvs(), tlvRequest.GetLength()); numTlvs = tlvRequest.GetLength(); - if (activeTimestamp.GetLength() == 0 || - netif.GetActiveDataset().Compare(activeTimestamp)) + if (activeTimestamp.GetLength() == 0 || netif.GetActiveDataset().Compare(activeTimestamp)) { tlvs[numTlvs++] = Tlv::kActiveDataset; } - if (pendingTimestamp.GetLength() == 0 || - netif.GetPendingDataset().Compare(pendingTimestamp)) + if (pendingTimestamp.GetLength() == 0 || netif.GetPendingDataset().Compare(pendingTimestamp)) { tlvs[numTlvs++] = Tlv::kPendingDataset; } @@ -2651,8 +2621,8 @@ exit: otError MleRouter::HandleNetworkDataUpdateRouter(void) { static const uint8_t tlvs[] = {Tlv::kNetworkData}; - Ip6::Address destination; - uint16_t delay; + Ip6::Address destination; + uint16_t delay; VerifyOrExit(mRole == OT_DEVICE_ROLE_ROUTER || mRole == OT_DEVICE_ROLE_LEADER); @@ -2677,7 +2647,7 @@ void MleRouter::SynchronizeChildNetworkData(void) for (uint8_t i = 0; i < mMaxChildrenAllowed; i++) { - Child &child = mChildren[i]; + Child & child = mChildren[i]; uint8_t version; if (child.GetState() != Neighbor::kStateValid || child.IsRxOnWhenIdle()) @@ -2709,7 +2679,7 @@ exit: #if OPENTHREAD_CONFIG_ENABLE_STEERING_DATA_SET_OOB otError MleRouter::SetSteeringData(const Mac::ExtAddress *aExtAddress) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Mac::ExtAddress nullExtAddr; Mac::ExtAddress allowAnyExtAddr; @@ -2745,14 +2715,14 @@ otError MleRouter::SetSteeringData(const Mac::ExtAddress *aExtAddress) otError MleRouter::HandleDiscoveryRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Tlv tlv; - MeshCoP::Tlv meshcopTlv; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Tlv tlv; + MeshCoP::Tlv meshcopTlv; MeshCoP::DiscoveryRequestTlv discoveryRequest; - MeshCoP::ExtendedPanIdTlv extPanId; - uint16_t offset; - uint16_t end; + MeshCoP::ExtendedPanIdTlv extPanId; + uint16_t offset; + uint16_t end; LogMleMessage("Receive Discovery Request", aMessageInfo.GetPeerAddr()); @@ -2785,7 +2755,7 @@ otError MleRouter::HandleDiscoveryRequest(const Message &aMessage, const Ip6::Me break; } else // if steering data is not set out of band, fall back to network data -#endif // OPENTHREAD_CONFIG_ENABLE_STEERING_DATA_SET_OOB +#endif // OPENTHREAD_CONFIG_ENABLE_STEERING_DATA_SET_OOB { VerifyOrExit(netif.GetNetworkDataLeader().IsJoiningEnabled()); } @@ -2821,17 +2791,17 @@ exit: otError MleRouter::SendDiscoveryResponse(const Ip6::Address &aDestination, uint16_t aPanId) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Message *message; - uint16_t startOffset; - Tlv tlv; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Message * message; + uint16_t startOffset; + Tlv tlv; MeshCoP::DiscoveryResponseTlv discoveryResponse; - MeshCoP::ExtendedPanIdTlv extPanId; - MeshCoP::NetworkNameTlv networkName; - MeshCoP::JoinerUdpPortTlv joinerUdpPort; - MeshCoP::Tlv *steeringData; - uint16_t delay; + MeshCoP::ExtendedPanIdTlv extPanId; + MeshCoP::NetworkNameTlv networkName; + MeshCoP::JoinerUdpPortTlv joinerUdpPort; + MeshCoP::Tlv * steeringData; + uint16_t delay; VerifyOrExit((message = NewMleMessage()) != NULL, error = OT_ERROR_NO_BUFS); message->SetSubType(Message::kSubTypeMleDiscoverResponse); @@ -2916,9 +2886,9 @@ exit: otError MleRouter::SendChildIdResponse(Child &aChild) { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Ip6::Address destination; - Message *message; + Message * message; VerifyOrExit((message = NewMleMessage()) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = AppendHeader(*message, Header::kCommandChildIdResponse)); @@ -2938,8 +2908,7 @@ otError MleRouter::SendChildIdResponse(Child &aChild) { mNextChildId = kMinChildId; } - } - while (FindChild(mNextChildId) != NULL); + } while (FindChild(mNextChildId) != NULL); // allocate Child ID aChild.SetRloc16(netif.GetMac().GetShortAddress() | mNextChildId); @@ -3004,10 +2973,10 @@ exit: otError MleRouter::SendChildUpdateRequest(Child &aChild) { static const uint8_t tlvs[] = {Tlv::kTimeout, Tlv::kAddressRegistration}; - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Ip6::Address destination; - Message *message; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Ip6::Address destination; + Message * message; if (!aChild.IsRxOnWhenIdle()) { @@ -3070,11 +3039,13 @@ exit: return error; } -otError MleRouter::SendChildUpdateResponse(Child *aChild, const Ip6::MessageInfo &aMessageInfo, - const uint8_t *aTlvs, uint8_t aTlvslength, - const ChallengeTlv *aChallenge) +otError MleRouter::SendChildUpdateResponse(Child * aChild, + const Ip6::MessageInfo &aMessageInfo, + const uint8_t * aTlvs, + uint8_t aTlvslength, + const ChallengeTlv * aChallenge) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Message *message; VerifyOrExit((message = NewMleMessage()) != NULL, error = OT_ERROR_NO_BUFS); @@ -3130,7 +3101,6 @@ otError MleRouter::SendChildUpdateResponse(Child *aChild, const Ip6::MessageInfo SuccessOrExit(error = SendMessage(*message, aMessageInfo.GetPeerAddr())); - if (aChild == NULL) { LogMleMessage("Send Child Update Response to child", aMessageInfo.GetPeerAddr()); @@ -3150,13 +3120,15 @@ exit: return OT_ERROR_NONE; } -otError MleRouter::SendDataResponse(const Ip6::Address &aDestination, const uint8_t *aTlvs, uint8_t aTlvsLength, - uint16_t aDelay) +otError MleRouter::SendDataResponse(const Ip6::Address &aDestination, + const uint8_t * aTlvs, + uint8_t aTlvsLength, + uint16_t aDelay) { - otError error = OT_ERROR_NONE; - Message *message = NULL; + otError error = OT_ERROR_NONE; + Message * message = NULL; Neighbor *neighbor; - bool stableOnly; + bool stableOnly; if (mRetrieveNewNetworkData) { @@ -3177,7 +3149,7 @@ otError MleRouter::SendDataResponse(const Ip6::Address &aDestination, const uint switch (aTlvs[i]) { case Tlv::kNetworkData: - neighbor = GetNeighbor(aDestination); + neighbor = GetNeighbor(aDestination); stableOnly = neighbor != NULL ? !neighbor->IsFullNetworkData() : false; SuccessOrExit(error = AppendNetworkData(*message, stableOnly)); break; @@ -3236,8 +3208,7 @@ Child *MleRouter::GetChild(const Mac::ExtAddress &aAddress) { for (int i = 0; i < mMaxChildrenAllowed; i++) { - if (mChildren[i].IsStateValidOrRestoring() && - mChildren[i].GetExtAddress() == aAddress) + if (mChildren[i].IsStateValidOrRestoring() && mChildren[i].GetExtAddress() == aAddress) { return &mChildren[i]; } @@ -3281,7 +3252,7 @@ Child *MleRouter::GetChildren(uint8_t *aNumChildren) bool MleRouter::IsMinimalChild(uint16_t aRloc16) { ThreadNetif &netif = GetNetif(); - bool rval = false; + bool rval = false; if (GetRouterId(aRloc16) == GetRouterId(netif.GetMac().GetShortAddress())) { @@ -3314,7 +3285,7 @@ exit: otError MleRouter::RemoveNeighbor(const Mac::Address &aAddress) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Neighbor *neighbor; VerifyOrExit((neighbor = GetNeighbor(aAddress)) != NULL, error = OT_ERROR_NOT_FOUND); @@ -3435,7 +3406,7 @@ Neighbor *MleRouter::GetNeighbor(uint16_t aAddress) if (IsActiveRouter(aAddress)) { uint8_t routerId = GetRouterId(aAddress); - Router *router = &mRouters[routerId]; + Router *router = &mRouters[routerId]; if (router->GetState() == Neighbor::kStateValid && router->GetRloc16() == aAddress) { @@ -3468,8 +3439,7 @@ Neighbor *MleRouter::GetNeighbor(const Mac::ExtAddress &aAddress) case OT_DEVICE_ROLE_LEADER: for (int i = 0; i < mMaxChildrenAllowed; i++) { - if (mChildren[i].IsStateValidOrRestoring() && - mChildren[i].GetExtAddress() == aAddress) + if (mChildren[i].IsStateValidOrRestoring() && mChildren[i].GetExtAddress() == aAddress) { ExitNow(rval = &mChildren[i]); } @@ -3482,8 +3452,7 @@ Neighbor *MleRouter::GetNeighbor(const Mac::ExtAddress &aAddress) continue; } - if (mRouters[i].GetState() == Neighbor::kStateValid && - mRouters[i].GetExtAddress() == aAddress) + if (mRouters[i].GetState() == Neighbor::kStateValid && mRouters[i].GetExtAddress() == aAddress) { ExitNow(rval = &mRouters[i]); } @@ -3524,16 +3493,15 @@ Neighbor *MleRouter::GetNeighbor(const Mac::Address &aAddress) Neighbor *MleRouter::GetNeighbor(const Ip6::Address &aAddress) { - Mac::Address macAddr; + Mac::Address macAddr; Lowpan::Context context; - Child *child; - Router *router; - Neighbor *rval = NULL; + Child * child; + Router * router; + Neighbor * rval = NULL; if (aAddress.IsLinkLocal()) { - if (aAddress.mFields.m16[4] == HostSwap16(0x0000) && - aAddress.mFields.m16[5] == HostSwap16(0x00ff) && + if (aAddress.mFields.m16[4] == HostSwap16(0x0000) && aAddress.mFields.m16[5] == HostSwap16(0x00ff) && aAddress.mFields.m16[6] == HostSwap16(0xfe00)) { macAddr.SetShort(HostSwap16(aAddress.mFields.m16[7])); @@ -3560,10 +3528,8 @@ Neighbor *MleRouter::GetNeighbor(const Ip6::Address &aAddress) continue; } - if (context.mContextId == 0 && - aAddress.mFields.m16[4] == HostSwap16(0x0000) && - aAddress.mFields.m16[5] == HostSwap16(0x00ff) && - aAddress.mFields.m16[6] == HostSwap16(0xfe00) && + if (context.mContextId == 0 && aAddress.mFields.m16[4] == HostSwap16(0x0000) && + aAddress.mFields.m16[5] == HostSwap16(0x00ff) && aAddress.mFields.m16[6] == HostSwap16(0xfe00) && aAddress.mFields.m16[7] == HostSwap16(child->GetRloc16())) { ExitNow(rval = child); @@ -3586,10 +3552,8 @@ Neighbor *MleRouter::GetNeighbor(const Ip6::Address &aAddress) continue; } - if (aAddress.mFields.m16[4] == HostSwap16(0x0000) && - aAddress.mFields.m16[5] == HostSwap16(0x00ff) && - aAddress.mFields.m16[6] == HostSwap16(0xfe00) && - aAddress.mFields.m16[7] == HostSwap16(router->GetRloc16())) + if (aAddress.mFields.m16[4] == HostSwap16(0x0000) && aAddress.mFields.m16[5] == HostSwap16(0x00ff) && + aAddress.mFields.m16[6] == HostSwap16(0xfe00) && aAddress.mFields.m16[7] == HostSwap16(router->GetRloc16())) { ExitNow(rval = router); } @@ -3611,10 +3575,9 @@ Neighbor *MleRouter::GetRxOnlyNeighborRouter(const Mac::Address &aAddress) if (IsActiveRouter(aAddress.GetShort())) { uint8_t routerId = GetRouterId(aAddress.GetShort()); - Router *router = &mRouters[routerId]; + Router *router = &mRouters[routerId]; - if (router->GetState() == Neighbor::kStateValid && - router->GetRloc16() == aAddress.GetShort()) + if (router->GetState() == Neighbor::kStateValid && router->GetRloc16() == aAddress.GetShort()) { ExitNow(rval = router); } @@ -3649,10 +3612,10 @@ exit: uint16_t MleRouter::GetNextHop(uint16_t aDestination) { - uint8_t destinationId = GetRouterId(aDestination); - uint8_t routeCost; - uint8_t linkCost; - uint16_t rval = Mac::kShortAddrInvalid; + uint8_t destinationId = GetRouterId(aDestination); + uint8_t routeCost; + uint8_t linkCost; + uint16_t rval = Mac::kShortAddrInvalid; const Router *router; const Router *nextHop; @@ -3670,7 +3633,7 @@ uint16_t MleRouter::GetNextHop(uint16_t aDestination) router = GetRouter(destinationId); VerifyOrExit(router != NULL); - linkCost = GetLinkCost(destinationId); + linkCost = GetLinkCost(destinationId); routeCost = GetRouteCost(aDestination); if ((routeCost + GetLinkCost(router->GetNextHop())) < linkCost) @@ -3692,8 +3655,8 @@ exit: uint8_t MleRouter::GetCost(uint16_t aRloc16) { uint8_t routerId = GetRouterId(aRloc16); - uint8_t cost = GetLinkCost(routerId); - Router *router = GetRouter(routerId); + uint8_t cost = GetLinkCost(routerId); + Router *router = GetRouter(routerId); uint8_t routeCost; VerifyOrExit(router != NULL && GetRouter(router->GetNextHop()) != NULL); @@ -3711,7 +3674,7 @@ exit: uint8_t MleRouter::GetRouteCost(uint16_t aRloc16) const { - uint8_t rval = kMaxRouteCost; + uint8_t rval = kMaxRouteCost; const Router *router; router = GetRouter(GetRouterId(aRloc16)); @@ -3738,7 +3701,7 @@ exit: void MleRouter::SetRouterId(uint8_t aRouterId) { - mRouterId = aRouterId; + mRouterId = aRouterId; mPreviousRouterId = mRouterId; } @@ -3779,7 +3742,7 @@ exit: otError MleRouter::GetChildInfoById(uint16_t aChildId, otChildInfo &aChildInfo) { otError error = OT_ERROR_NONE; - Child *child; + Child * child; if ((aChildId & ~kMaxChildId) != 0) { @@ -3804,8 +3767,9 @@ exit: return error; } -otError MleRouter::GetChildNextIp6Address(uint8_t aChildIndex, Child::Ip6AddressIterator &aIterator, - Ip6::Address &aAddress) +otError MleRouter::GetChildNextIp6Address(uint8_t aChildIndex, + Child::Ip6AddressIterator &aIterator, + Ip6::Address & aAddress) { otError error = OT_ERROR_NONE; @@ -3820,15 +3784,15 @@ exit: void MleRouter::RestoreChildren(void) { - otError error = OT_ERROR_NONE; - bool foundDuplicate = false; + otError error = OT_ERROR_NONE; + bool foundDuplicate = false; uint8_t index; - for (index = 0; ; index++) + for (index = 0;; index++) { - Child *child; + Child * child; Settings::ChildInfo childInfo; - uint16_t length; + uint16_t length; length = sizeof(childInfo); SuccessOrExit(otPlatSettingsGet(&GetInstance(), Settings::kKeyChildInfo, index, @@ -3878,7 +3842,7 @@ otError MleRouter::RemoveStoredChild(uint16_t aChildRloc16) for (uint8_t i = 0; i < kMaxChildren; i++) { Settings::ChildInfo childInfo; - uint16_t length = sizeof(childInfo); + uint16_t length = sizeof(childInfo); SuccessOrExit(error = otPlatSettingsGet(&GetInstance(), Settings::kKeyChildInfo, i, reinterpret_cast(&childInfo), &length)); @@ -3897,8 +3861,8 @@ exit: otError MleRouter::StoreChild(uint16_t aChildRloc16) { - otError error = OT_ERROR_NONE; - Child *child; + otError error = OT_ERROR_NONE; + Child * child; Settings::ChildInfo childInfo; VerifyOrExit((child = FindChild(GetChildId(aChildRloc16))) != NULL, error = OT_ERROR_NOT_FOUND); @@ -3907,9 +3871,9 @@ otError MleRouter::StoreChild(uint16_t aChildRloc16) memset(&childInfo, 0, sizeof(childInfo)); childInfo.mExtAddress = child->GetExtAddress(); - childInfo.mTimeout = child->GetTimeout(); - childInfo.mRloc16 = child->GetRloc16(); - childInfo.mMode = child->GetDeviceMode(); + childInfo.mTimeout = child->GetTimeout(); + childInfo.mRloc16 = child->GetRloc16(); + childInfo.mMode = child->GetDeviceMode(); error = otPlatSettingsAdd(&GetInstance(), Settings::kKeyChildInfo, reinterpret_cast(&childInfo), sizeof(childInfo)); @@ -3954,15 +3918,15 @@ otError MleRouter::GetChildInfo(Child &aChild, otChildInfo &aChildInfo) aChildInfo.mLastRssi = aChild.GetLinkInfo().GetLastRss(); #if OPENTHREAD_CONFIG_ENABLE_TX_ERROR_RATE_TRACKING - aChildInfo.mFrameErrorRate = aChild.GetLinkInfo().GetFrameErrorRate(); - aChildInfo.mMessageErrorRate = aChild.GetLinkInfo().GetMessageErrorRate(); + aChildInfo.mFrameErrorRate = aChild.GetLinkInfo().GetFrameErrorRate(); + aChildInfo.mMessageErrorRate = aChild.GetLinkInfo().GetMessageErrorRate(); #endif - aChildInfo.mRxOnWhenIdle = aChild.IsRxOnWhenIdle(); - aChildInfo.mSecureDataRequest = aChild.IsSecureDataRequest(); - aChildInfo.mFullFunction = aChild.IsFullThreadDevice(); - aChildInfo.mFullNetworkData = aChild.IsFullNetworkData(); - aChildInfo.mIsStateRestoring = aChild.IsStateRestoring(); + aChildInfo.mRxOnWhenIdle = aChild.IsRxOnWhenIdle(); + aChildInfo.mSecureDataRequest = aChild.IsSecureDataRequest(); + aChildInfo.mFullFunction = aChild.IsFullThreadDevice(); + aChildInfo.mFullNetworkData = aChild.IsFullNetworkData(); + aChildInfo.mIsStateRestoring = aChild.IsStateRestoring(); exit: return error; @@ -3995,8 +3959,7 @@ otError MleRouter::GetRouterInfo(uint16_t aRouterId, otRouterInfo &aRouterInfo) aRouterInfo.mPathCost = router->GetCost(); aRouterInfo.mLinkQualityIn = router->GetLinkInfo().GetLinkQuality(); aRouterInfo.mLinkQualityOut = router->GetLinkQualityOut(); - aRouterInfo.mAge = static_cast(TimerMilli::MsecToSec(TimerMilli::GetNow() - - router->GetLastHeard())); + aRouterInfo.mAge = static_cast(TimerMilli::MsecToSec(TimerMilli::GetNow() - router->GetLastHeard())); exit: return error; @@ -4004,9 +3967,9 @@ exit: otError MleRouter::GetNextNeighborInfo(otNeighborInfoIterator &aIterator, otNeighborInfo &aNeighInfo) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Neighbor *neighbor = NULL; - int16_t index; + int16_t index; memset(&aNeighInfo, 0, sizeof(aNeighInfo)); @@ -4018,7 +3981,7 @@ otError MleRouter::GetNextNeighborInfo(otNeighborInfoIterator &aIterator, otNeig { if (mChildren[index].GetState() == Neighbor::kStateValid) { - neighbor = &mChildren[index]; + neighbor = &mChildren[index]; aNeighInfo.mIsChild = true; index++; aIterator = index; @@ -4035,7 +3998,7 @@ otError MleRouter::GetNextNeighborInfo(otNeighborInfoIterator &aIterator, otNeig { if (mRouters[index].GetState() == Neighbor::kStateValid) { - neighbor = &mRouters[index]; + neighbor = &mRouters[index]; aNeighInfo.mIsChild = false; index++; aIterator = -index; @@ -4044,28 +4007,28 @@ otError MleRouter::GetNextNeighborInfo(otNeighborInfoIterator &aIterator, otNeig } aIterator = -index; - error = OT_ERROR_NOT_FOUND; + error = OT_ERROR_NOT_FOUND; exit: if (neighbor != NULL) { - aNeighInfo.mExtAddress = neighbor->GetExtAddress(); - aNeighInfo.mAge = TimerMilli::MsecToSec(TimerMilli::GetNow() - neighbor->GetLastHeard()); - aNeighInfo.mRloc16 = neighbor->GetRloc16(); + aNeighInfo.mExtAddress = neighbor->GetExtAddress(); + aNeighInfo.mAge = TimerMilli::MsecToSec(TimerMilli::GetNow() - neighbor->GetLastHeard()); + aNeighInfo.mRloc16 = neighbor->GetRloc16(); aNeighInfo.mLinkFrameCounter = neighbor->GetLinkFrameCounter(); - aNeighInfo.mMleFrameCounter = neighbor->GetMleFrameCounter(); - aNeighInfo.mLinkQualityIn = neighbor->GetLinkInfo().GetLinkQuality(); - aNeighInfo.mAverageRssi = neighbor->GetLinkInfo().GetAverageRss(); - aNeighInfo.mLastRssi = neighbor->GetLinkInfo().GetLastRss(); + aNeighInfo.mMleFrameCounter = neighbor->GetMleFrameCounter(); + aNeighInfo.mLinkQualityIn = neighbor->GetLinkInfo().GetLinkQuality(); + aNeighInfo.mAverageRssi = neighbor->GetLinkInfo().GetAverageRss(); + aNeighInfo.mLastRssi = neighbor->GetLinkInfo().GetLastRss(); #if OPENTHREAD_CONFIG_ENABLE_TX_ERROR_RATE_TRACKING - aNeighInfo.mFrameErrorRate = neighbor->GetLinkInfo().GetFrameErrorRate(); + aNeighInfo.mFrameErrorRate = neighbor->GetLinkInfo().GetFrameErrorRate(); aNeighInfo.mMessageErrorRate = neighbor->GetLinkInfo().GetMessageErrorRate(); #endif - aNeighInfo.mRxOnWhenIdle = neighbor->IsRxOnWhenIdle(); + aNeighInfo.mRxOnWhenIdle = neighbor->IsRxOnWhenIdle(); aNeighInfo.mSecureDataRequest = neighbor->IsSecureDataRequest(); - aNeighInfo.mFullFunction = neighbor->IsFullThreadDevice(); - aNeighInfo.mFullNetworkData = neighbor->IsFullNetworkData(); + aNeighInfo.mFullFunction = neighbor->IsFullThreadDevice(); + aNeighInfo.mFullNetworkData = neighbor->IsFullNetworkData(); } return error; @@ -4094,7 +4057,7 @@ exit: otError MleRouter::CheckReachability(uint16_t aMeshSource, uint16_t aMeshDest, Ip6::Header &aIp6Header) { - ThreadNetif &netif = GetNetif(); + ThreadNetif & netif = GetNetif(); Ip6::MessageInfo messageInfo; if (mRole == OT_DEVICE_ROLE_CHILD) @@ -4130,12 +4093,11 @@ otError MleRouter::CheckReachability(uint16_t aMeshSource, uint16_t aMeshDest, I return OT_ERROR_NONE; } - messageInfo.GetPeerAddr() = GetMeshLocal16(); + messageInfo.GetPeerAddr() = GetMeshLocal16(); messageInfo.GetPeerAddr().mFields.m16[7] = HostSwap16(aMeshSource); messageInfo.SetInterfaceId(netif.GetInterfaceId()); - netif.GetIp6().GetIcmp().SendError(Ip6::IcmpHeader::kTypeDstUnreach, - Ip6::IcmpHeader::kCodeDstUnreachNoRoute, + netif.GetIp6().GetIcmp().SendError(Ip6::IcmpHeader::kTypeDstUnreach, Ip6::IcmpHeader::kCodeDstUnreachNoRoute, messageInfo, aIp6Header); return OT_ERROR_DROP; @@ -4143,14 +4105,14 @@ otError MleRouter::CheckReachability(uint16_t aMeshSource, uint16_t aMeshDest, I otError MleRouter::SendAddressSolicit(ThreadStatusTlv::Status aStatus) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Coap::Header header; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Coap::Header header; ThreadExtMacAddressTlv macAddr64Tlv; - ThreadRloc16Tlv rlocTlv; - ThreadStatusTlv statusTlv; - Ip6::MessageInfo messageInfo; - Message *message = NULL; + ThreadRloc16Tlv rlocTlv; + ThreadStatusTlv statusTlv; + Ip6::MessageInfo messageInfo; + Message * message = NULL; VerifyOrExit(mAddressSolicitPending == false); @@ -4180,8 +4142,8 @@ otError MleRouter::SendAddressSolicit(ThreadStatusTlv::Status aStatus) messageInfo.SetSockAddr(GetMeshLocal16()); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo, - &MleRouter::HandleAddressSolicitResponse, this)); + SuccessOrExit( + error = netif.GetCoap().SendMessage(*message, messageInfo, &MleRouter::HandleAddressSolicitResponse, this)); mAddressSolicitPending = true; LogMleMessage("Send Address Solicit", messageInfo.GetPeerAddr()); @@ -4198,13 +4160,13 @@ exit: otError MleRouter::SendAddressRelease(void) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Coap::Header header; - ThreadRloc16Tlv rlocTlv; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Coap::Header header; + ThreadRloc16Tlv rlocTlv; ThreadExtMacAddressTlv macAddr64Tlv; - Ip6::MessageInfo messageInfo; - Message *message; + Ip6::MessageInfo messageInfo; + Message * message; header.Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); header.SetToken(Coap::Header::kDefaultTokenLength); @@ -4238,25 +4200,29 @@ exit: return error; } -void MleRouter::HandleAddressSolicitResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError aResult) +void MleRouter::HandleAddressSolicitResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aResult) { - static_cast(aContext)->HandleAddressSolicitResponse(static_cast(aHeader), - static_cast(aMessage), - static_cast(aMessageInfo), - aResult); + static_cast(aContext)->HandleAddressSolicitResponse( + static_cast(aHeader), static_cast(aMessage), + static_cast(aMessageInfo), aResult); } -void MleRouter::HandleAddressSolicitResponse(Coap::Header *aHeader, Message *aMessage, - const Ip6::MessageInfo *aMessageInfo, otError aResult) +void MleRouter::HandleAddressSolicitResponse(Coap::Header * aHeader, + Message * aMessage, + const Ip6::MessageInfo *aMessageInfo, + otError aResult) { OT_UNUSED_VARIABLE(aMessageInfo); - ThreadStatusTlv statusTlv; - ThreadRloc16Tlv rlocTlv; + ThreadStatusTlv statusTlv; + ThreadRloc16Tlv rlocTlv; ThreadRouterMaskTlv routerMaskTlv; - uint8_t routerId; - Router *router; + uint8_t routerId; + Router * router; mAddressSolicitPending = false; @@ -4287,7 +4253,7 @@ void MleRouter::HandleAddressSolicitResponse(Coap::Header *aHeader, Message *aMe SuccessOrExit(ThreadTlv::GetTlv(*aMessage, ThreadTlv::kRloc16, sizeof(rlocTlv), rlocTlv)); VerifyOrExit(rlocTlv.IsValid()); routerId = GetRouterId(rlocTlv.GetRloc16()); - router = GetRouter(routerId); + router = GetRouter(routerId); VerifyOrExit(router != NULL); SuccessOrExit(ThreadTlv::GetTlv(*aMessage, ThreadTlv::kRouterMask, sizeof(routerMaskTlv), routerMaskTlv)); @@ -4314,7 +4280,7 @@ void MleRouter::HandleAddressSolicitResponse(Coap::Header *aHeader, Message *aMe router->SetCost(0); // copy router id information - mRouterIdSequence = routerMaskTlv.GetIdSequence(); + mRouterIdSequence = routerMaskTlv.GetIdSequence(); mRouterIdSequenceLastUpdated = TimerMilli::GetNow(); for (uint8_t i = 0; i <= kMaxRouterId; i++) @@ -4372,22 +4338,24 @@ exit: return; } -void MleRouter::HandleAddressSolicit(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void MleRouter::HandleAddressSolicit(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleAddressSolicit( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleAddressSolicit(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void MleRouter::HandleAddressSolicit(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; ThreadExtMacAddressTlv macAddr64Tlv; - ThreadRloc16Tlv rlocTlv; - ThreadStatusTlv statusTlv; - uint8_t routerId = kInvalidRouterId; - Router *router = NULL; + ThreadRloc16Tlv rlocTlv; + ThreadStatusTlv statusTlv; + uint8_t routerId = kInvalidRouterId; + Router * router = NULL; VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && aHeader.GetCode() == OT_COAP_CODE_POST, error = OT_ERROR_PARSE); @@ -4403,8 +4371,7 @@ void MleRouter::HandleAddressSolicit(Coap::Header &aHeader, Message &aMessage, c // see if allocation already exists for (uint8_t i = 0; i <= kMaxRouterId; i++) { - if (mRouters[i].IsAllocated() && - mRouters[i].GetExtAddress() == macAddr64Tlv.GetMacAddr()) + if (mRouters[i].IsAllocated() && mRouters[i].GetExtAddress() == macAddr64Tlv.GetMacAddr()) { ExitNow(routerId = i); } @@ -4431,12 +4398,11 @@ void MleRouter::HandleAddressSolicit(Coap::Header &aHeader, Message &aMessage, c // specific Router ID requested VerifyOrExit(rlocTlv.IsValid(), error = OT_ERROR_PARSE); routerId = GetRouterId(rlocTlv.GetRloc16()); - router = GetRouter(routerId); + router = GetRouter(routerId); if (router != NULL) { - if (router->IsAllocated() && - router->GetExtAddress() != macAddr64Tlv.GetMacAddr()) + if (router->IsAllocated() && router->GetExtAddress() != macAddr64Tlv.GetMacAddr()) { // requested Router ID is allocated to another device routerId = kInvalidRouterId; @@ -4482,16 +4448,17 @@ exit: } } -void MleRouter::SendAddressSolicitResponse(const Coap::Header &aRequestHeader, uint8_t aRouterId, +void MleRouter::SendAddressSolicitResponse(const Coap::Header & aRequestHeader, + uint8_t aRouterId, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Coap::Header responseHeader; - ThreadStatusTlv statusTlv; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Coap::Header responseHeader; + ThreadStatusTlv statusTlv; ThreadRouterMaskTlv routerMaskTlv; - ThreadRloc16Tlv rlocTlv; - Message *message; + ThreadRloc16Tlv rlocTlv; + Message * message; responseHeader.SetDefaultResponseHeader(aRequestHeader); responseHeader.SetPayloadMarker(); @@ -4535,24 +4502,24 @@ exit: } } -void MleRouter::HandleAddressRelease(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void MleRouter::HandleAddressRelease(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleAddressRelease( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleAddressRelease(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } -void MleRouter::HandleAddressRelease(Coap::Header &aHeader, Message &aMessage, - const Ip6::MessageInfo &aMessageInfo) +void MleRouter::HandleAddressRelease(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadRloc16Tlv rlocTlv; + ThreadRloc16Tlv rlocTlv; ThreadExtMacAddressTlv macAddr64Tlv; - uint8_t routerId; - Router *router; + uint8_t routerId; + Router * router; - VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && - aHeader.GetCode() == OT_COAP_CODE_POST); + VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && aHeader.GetCode() == OT_COAP_CODE_POST); LogMleMessage("Receive Address Release", aMessageInfo.GetPeerAddr()); @@ -4563,7 +4530,7 @@ void MleRouter::HandleAddressRelease(Coap::Header &aHeader, Message &aMessage, VerifyOrExit(macAddr64Tlv.IsValid()); routerId = GetRouterId(rlocTlv.GetRloc16()); - router = GetRouter(routerId); + router = GetRouter(routerId); VerifyOrExit(router != NULL && router->GetExtAddress() == macAddr64Tlv.GetMacAddr()); @@ -4580,10 +4547,10 @@ exit: void MleRouter::FillConnectivityTlv(ConnectivityTlv &aTlv) { ConnectivityTlv &tlv = aTlv; - uint8_t cost; - uint8_t linkQuality; - uint8_t numChildren = 0; - int8_t parentPriority = kParentPriorityMedium; + uint8_t cost; + uint8_t linkQuality; + uint8_t numChildren = 0; + int8_t parentPriority = kParentPriorityMedium; if (mParentPriority != kParentPriorityUnspecified) { @@ -4704,7 +4671,7 @@ void MleRouter::FillConnectivityTlv(ConnectivityTlv &aTlv) otError MleRouter::AppendConnectivity(Message &aMessage) { - otError error; + otError error; ConnectivityTlv tlv; tlv.Init(); @@ -4718,23 +4685,22 @@ exit: otError MleRouter::AppendChildAddresses(Message &aMessage, Child &aChild) { - ThreadNetif &netif = GetNetif(); - otError error; - Ip6::Address address; + ThreadNetif & netif = GetNetif(); + otError error; + Ip6::Address address; Child::Ip6AddressIterator iterator; - Tlv tlv; - AddressRegistrationEntry entry; - Lowpan::Context context; - uint8_t length = 0; - uint16_t startOffset = aMessage.GetLength(); + Tlv tlv; + AddressRegistrationEntry entry; + Lowpan::Context context; + uint8_t length = 0; + uint16_t startOffset = aMessage.GetLength(); tlv.SetType(Tlv::kAddressRegistration); SuccessOrExit(error = aMessage.Append(&tlv, sizeof(tlv))); while (aChild.GetNextIp6Address(GetInstance(), iterator, address) == OT_ERROR_NONE) { - if (address.IsMulticast() || - netif.GetNetworkDataLeader().GetContext(address, context) != OT_ERROR_NONE) + if (address.IsMulticast() || netif.GetNetworkDataLeader().GetContext(address, context) != OT_ERROR_NONE) { // uncompressed entry entry.SetUncompressed(); @@ -4760,7 +4726,6 @@ exit: void MleRouter::FillRouteTlv(RouteTlv &aTlv) { - uint8_t routeCount = 0; uint8_t linkCost; uint8_t cost; @@ -4819,7 +4784,7 @@ void MleRouter::FillRouteTlv(RouteTlv &aTlv) otError MleRouter::AppendRoute(Message &aMessage) { - otError error; + otError error; RouteTlv tlv; tlv.Init(); FillRouteTlv(tlv); @@ -4845,10 +4810,10 @@ bool MleRouter::HasMinDowngradeNeighborRouters(void) bool MleRouter::HasOneNeighborwithComparableConnectivity(const RouteTlv &aRoute, uint8_t aRouterId) { - bool rval = true; + bool rval = true; uint8_t localLinkQuality = 0; - uint8_t peerLinkQuality = 0; - uint8_t routerCount = 0; + uint8_t peerLinkQuality = 0; + uint8_t routerCount = 0; // process local neighbor routers for (uint8_t i = 0; i <= kMaxRouterId; i++) @@ -5010,8 +4975,8 @@ otError MleRouter::SetAssignParentPriority(int8_t aParentPriority) { otError error = OT_ERROR_NONE; - VerifyOrExit(aParentPriority <= kParentPriorityHigh && - aParentPriority >= kParentPriorityUnspecified, error = OT_ERROR_INVALID_ARGS); + VerifyOrExit(aParentPriority <= kParentPriorityHigh && aParentPriority >= kParentPriorityUnspecified, + error = OT_ERROR_INVALID_ARGS); mParentPriority = aParentPriority; @@ -5054,7 +5019,7 @@ void MleRouter::SignalChildUpdated(otThreadChildTableEvent aEvent, Child &aChild if (mChildTableChangedCallback != NULL) { otChildInfo childInfo; - otError error; + otError error; error = GetChildInfo(aChild, childInfo); assert(error == OT_ERROR_NONE); @@ -5097,8 +5062,8 @@ exit: bool MleRouter::IsSleepyChildSubscribed(const Ip6::Address &aAddress, Child &aChild) { - bool rval = false; - Ip6::Address address; + bool rval = false; + Ip6::Address address; Child::Ip6AddressIterator iterator; VerifyOrExit(aChild.IsStateValidOrRestoring() && !aChild.IsRxOnWhenIdle()); @@ -5115,8 +5080,7 @@ exit: return rval; } -} // namespace Mle -} // namespace ot +} // namespace Mle +} // namespace ot #endif // OPENTHREAD_FTD - diff --git a/src/core/thread/mle_router_ftd.hpp b/src/core/thread/mle_router_ftd.hpp index 019d371f8..8cc22954f 100644 --- a/src/core/thread/mle_router_ftd.hpp +++ b/src/core/thread/mle_router_ftd.hpp @@ -73,7 +73,7 @@ class NetworkDataLeader; * This class implements MLE functionality required by the Thread Router and Leader roles. * */ -class MleRouter: public Mle +class MleRouter : public Mle { friend class Mle; @@ -146,11 +146,11 @@ public: uint8_t GetActiveRouterCount(void) const; /** - * This method returns the number of active neighbor routers. - * - * @returns The number of active neighbor routers. - * - */ + * This method returns the number of active neighbor routers. + * + * @returns The number of active neighbor routers. + * + */ uint8_t GetActiveNeighborRouterCount(void) const; /** @@ -635,8 +635,10 @@ public: * @retval -1 If partition B is preferred. * */ - static int ComparePartitions(bool aSingletonA, const LeaderDataTlv &aLeaderDataA, - bool aSingletonB, const LeaderDataTlv &aleaderDataB); + static int ComparePartitions(bool aSingletonA, + const LeaderDataTlv &aLeaderDataA, + bool aSingletonB, + const LeaderDataTlv &aleaderDataB); /** * This method checks if the destination is reachable. @@ -688,12 +690,12 @@ public: void FillRouteTlv(RouteTlv &aTlv); /** - * This method generates an MLE Child Update Request message to be sent to the parent. - * - * @retval OT_ERROR_NONE Successfully generated an MLE Child Update Request message. - * @retval OT_ERROR_NO_BUFS Insufficient buffers to generate the MLE Child Update Request message. - * - */ + * This method generates an MLE Child Update Request message to be sent to the parent. + * + * @retval OT_ERROR_NONE Successfully generated an MLE Child Update Request message. + * @retval OT_ERROR_NO_BUFS Insufficient buffers to generate the MLE Child Update Request message. + * + */ otError SendChildUpdateRequest(void) { return Mle::SendChildUpdateRequest(); } #if OPENTHREAD_CONFIG_ENABLE_STEERING_DATA_SET_OOB @@ -788,8 +790,8 @@ private: enum { kDiscoveryMaxJitter = 250u, ///< Maximum jitter time used to delay Discovery Responses in milliseconds. - kStateUpdatePeriod = 1000u, ///< State update period in milliseconds. - kUnsolicitedDataResponseJitter = 500u, ///< Maximum delay before unsolicited Data Response in milliseconds. + kStateUpdatePeriod = 1000u, ///< State update period in milliseconds. + kUnsolicitedDataResponseJitter = 500u, ///< Maximum delay before unsolicited Data Response in milliseconds. }; otError AppendConnectivity(Message &aMessage); @@ -803,59 +805,80 @@ private: otError HandleChildStart(AttachMode aMode); otError HandleLinkRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); otError HandleLinkAccept(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, uint32_t aKeySequence); - otError HandleLinkAccept(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, uint32_t aKeySequence, - bool request); - otError HandleLinkAcceptAndRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - uint32_t aKeySequence); + otError HandleLinkAccept(const Message & aMessage, + const Ip6::MessageInfo &aMessageInfo, + uint32_t aKeySequence, + bool request); + otError HandleLinkAcceptAndRequest(const Message & aMessage, + const Ip6::MessageInfo &aMessageInfo, + uint32_t aKeySequence); otError HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); otError HandleParentRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - otError HandleChildIdRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - uint32_t aKeySequence); - otError HandleChildUpdateRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - uint32_t aKeySequence); - otError HandleChildUpdateResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - uint32_t aKeySequence); + otError HandleChildIdRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, uint32_t aKeySequence); + otError HandleChildUpdateRequest(const Message & aMessage, + const Ip6::MessageInfo &aMessageInfo, + uint32_t aKeySequence); + otError HandleChildUpdateResponse(const Message & aMessage, + const Ip6::MessageInfo &aMessageInfo, + uint32_t aKeySequence); otError HandleDataRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); otError HandleNetworkDataUpdateRouter(void); otError HandleDiscoveryRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); otError ProcessRouteTlv(const RouteTlv &aRoute); - void StopAdvertiseTimer(void); - void ResetAdvertiseInterval(void); + void StopAdvertiseTimer(void); + void ResetAdvertiseInterval(void); otError SendAddressSolicit(ThreadStatusTlv::Status aStatus); otError SendAddressRelease(void); - void SendAddressSolicitResponse(const Coap::Header &aRequest, uint8_t aRouterId, - const Ip6::MessageInfo &aMessageInfo); + void SendAddressSolicitResponse(const Coap::Header & aRequest, + uint8_t aRouterId, + const Ip6::MessageInfo &aMessageInfo); otError SendAdvertisement(void); otError SendLinkRequest(Neighbor *aNeighbor); - otError SendLinkAccept(const Ip6::MessageInfo &aMessageInfo, Neighbor *aNeighbor, - const TlvRequestTlv &aTlvRequest, const ChallengeTlv &aChallenge); + otError SendLinkAccept(const Ip6::MessageInfo &aMessageInfo, + Neighbor * aNeighbor, + const TlvRequestTlv & aTlvRequest, + const ChallengeTlv & aChallenge); otError SendParentResponse(Child *aChild, const ChallengeTlv &aChallenge, bool aRoutersOnlyRequest); otError SendChildIdResponse(Child &aChild); otError SendChildUpdateRequest(Child &aChild); - otError SendChildUpdateResponse(Child *aChild, const Ip6::MessageInfo &aMessageInfo, - const uint8_t *aTlvs, uint8_t aTlvsLength, const ChallengeTlv *challenge); - otError SendDataResponse(const Ip6::Address &aDestination, const uint8_t *aTlvs, uint8_t aTlvsLength, - uint16_t aDelay); + otError SendChildUpdateResponse(Child * aChild, + const Ip6::MessageInfo &aMessageInfo, + const uint8_t * aTlvs, + uint8_t aTlvsLength, + const ChallengeTlv * challenge); + otError SendDataResponse(const Ip6::Address &aDestination, + const uint8_t * aTlvs, + uint8_t aTlvsLength, + uint16_t aDelay); otError SendDiscoveryResponse(const Ip6::Address &aDestination, uint16_t aPanId); otError SetStateRouter(uint16_t aRloc16); otError SetStateLeader(uint16_t aRloc16); - void StopLeader(void); - void SynchronizeChildNetworkData(void); + void StopLeader(void); + void SynchronizeChildNetworkData(void); otError UpdateChildAddresses(const Message &aMessage, uint16_t aOffset, Child &aChild); - void UpdateRoutes(const RouteTlv &aTlv, uint8_t aRouterId); + void UpdateRoutes(const RouteTlv &aTlv, uint8_t aRouterId); - static void HandleAddressSolicitResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError result); - void HandleAddressSolicitResponse(Coap::Header *aHeader, Message *aMessage, - const Ip6::MessageInfo *aMessageInfo, otError result); - static void HandleAddressRelease(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleAddressSolicitResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError result); + void HandleAddressSolicitResponse(Coap::Header * aHeader, + Message * aMessage, + const Ip6::MessageInfo *aMessageInfo, + otError result); + static void HandleAddressRelease(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleAddressRelease(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - static void HandleAddressSolicit(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + void HandleAddressRelease(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + static void HandleAddressSolicit(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleAddressSolicit(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleAddressSolicit(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); static uint8_t LinkQualityToCost(uint8_t aLinkQuality); @@ -867,71 +890,70 @@ private: Child *FindChild(uint16_t aChildId); Child *FindChild(const Mac::ExtAddress &aMacAddr); - void SetChildStateToValid(Child &aChild); - bool HasChildren(void); - void RemoveChildren(void); - bool HasMinDowngradeNeighborRouters(void); - bool HasOneNeighborwithComparableConnectivity(const RouteTlv &aRoute, uint8_t aRouterId); - bool HasSmallNumberOfChildren(void); + void SetChildStateToValid(Child &aChild); + bool HasChildren(void); + void RemoveChildren(void); + bool HasMinDowngradeNeighborRouters(void); + bool HasOneNeighborwithComparableConnectivity(const RouteTlv &aRoute, uint8_t aRouterId); + bool HasSmallNumberOfChildren(void); uint8_t GetMinDowngradeNeighborRouters(void); uint8_t AllocateRouterId(void); uint8_t AllocateRouterId(uint8_t aRouterId); - bool InRouterIdMask(uint8_t aRouterId); + bool InRouterIdMask(uint8_t aRouterId); static bool HandleAdvertiseTimer(TrickleTimer &aTimer); - bool HandleAdvertiseTimer(void); + bool HandleAdvertiseTimer(void); static void HandleStateUpdateTimer(Timer &aTimer); - void HandleStateUpdateTimer(void); + void HandleStateUpdateTimer(void); void SignalChildUpdated(otThreadChildTableEvent aEvent, Child &aChild); TrickleTimer mAdvertiseTimer; - TimerMilli mStateUpdateTimer; + TimerMilli mStateUpdateTimer; Coap::Resource mAddressSolicit; Coap::Resource mAddressRelease; - uint8_t mRouterIdSequence; + uint8_t mRouterIdSequence; uint32_t mRouterIdSequenceLastUpdated; - Router mRouters[kMaxRouterId + 1]; - uint8_t mMaxChildrenAllowed; - Child mChildren[kMaxChildren]; + Router mRouters[kMaxRouterId + 1]; + uint8_t mMaxChildrenAllowed; + Child mChildren[kMaxChildren]; otThreadChildTableCallback mChildTableChangedCallback; - uint8_t mChallengeTimeout; - uint8_t mChallenge[8]; + uint8_t mChallengeTimeout; + uint8_t mChallenge[8]; uint16_t mNextChildId; - uint8_t mNetworkIdTimeout; - uint8_t mRouterUpgradeThreshold; - uint8_t mRouterDowngradeThreshold; - uint8_t mLeaderWeight; - uint32_t mFixedLeaderPartitionId; ///< only for certification testing - bool mRouterRoleEnabled : 1; - bool mAddressSolicitPending : 1; + uint8_t mNetworkIdTimeout; + uint8_t mRouterUpgradeThreshold; + uint8_t mRouterDowngradeThreshold; + uint8_t mLeaderWeight; + uint32_t mFixedLeaderPartitionId; ///< only for certification testing + bool mRouterRoleEnabled : 1; + bool mAddressSolicitPending : 1; - uint8_t mRouterId; - uint8_t mPreviousRouterId; + uint8_t mRouterId; + uint8_t mPreviousRouterId; uint32_t mPreviousPartitionId; - uint8_t mRouterSelectionJitter; ///< The variable to save the assigned jitter value. - uint8_t mRouterSelectionJitterTimeout; ///< The Timeout prior to request/release Router ID. + uint8_t mRouterSelectionJitter; ///< The variable to save the assigned jitter value. + uint8_t mRouterSelectionJitterTimeout; ///< The Timeout prior to request/release Router ID. - int8_t mParentPriority; ///< The assigned parent priority value, -2 means not assigned. + int8_t mParentPriority; ///< The assigned parent priority value, -2 means not assigned. #if OPENTHREAD_CONFIG_ENABLE_STEERING_DATA_SET_OOB MeshCoP::SteeringDataTlv mSteeringData; #endif // OPENTHREAD_CONFIG_ENABLE_STEERING_DATA_SET_OOB - }; -} // namespace Mle +} // namespace Mle /** * @} */ -} // namespace ot +} // namespace ot -#endif // MLE_ROUTER_FTD_HPP_ +#endif // MLE_ROUTER_FTD_HPP_ diff --git a/src/core/thread/mle_router_mtd.hpp b/src/core/thread/mle_router_mtd.hpp index b50678a62..37e1ed61d 100644 --- a/src/core/thread/mle_router_mtd.hpp +++ b/src/core/thread/mle_router_mtd.hpp @@ -45,12 +45,15 @@ namespace ot { namespace Mle { -class MleRouter: public Mle +class MleRouter : public Mle { friend class Mle; public: - explicit MleRouter(Instance &aInstance) : Mle(aInstance) { } + explicit MleRouter(Instance &aInstance) + : Mle(aInstance) + { + } bool IsSingleton(void) { return false; } @@ -64,8 +67,8 @@ public: uint32_t GetLeaderAge(void) const { return 0; } uint32_t GetPreviousPartitionId(void) const { return 0; } - void SetPreviousPartitionId(uint32_t) { } - void SetRouterId(uint8_t) { } + void SetPreviousPartitionId(uint32_t) {} + void SetRouterId(uint8_t) {} uint16_t GetNextHop(uint16_t aDestination) const { return Mle::GetNextHop(aDestination); } @@ -86,8 +89,10 @@ public: uint8_t GetChildIndex(const Child &) { return 0; } - Child *GetChildren(uint8_t *aNumChildren) { - if (aNumChildren != NULL) { + Child *GetChildren(uint8_t *aNumChildren) + { + if (aNumChildren != NULL) + { *aNumChildren = 0; } @@ -96,20 +101,26 @@ public: bool IsMinimalChild(uint16_t) { return false; } - void RestoreChildren(void) { } - otError RemoveStoredChild(uint16_t) {return OT_ERROR_NOT_IMPLEMENTED; } - otError StoreChild(uint16_t) {return OT_ERROR_NOT_IMPLEMENTED; } + void RestoreChildren(void) {} + otError RemoveStoredChild(uint16_t) { return OT_ERROR_NOT_IMPLEMENTED; } + otError StoreChild(uint16_t) { return OT_ERROR_NOT_IMPLEMENTED; } Neighbor *GetNeighbor(uint16_t aAddress) { return Mle::GetNeighbor(aAddress); } Neighbor *GetNeighbor(const Mac::ExtAddress &aAddress) { return Mle::GetNeighbor(aAddress); } Neighbor *GetNeighbor(const Mac::Address &aAddress) { return Mle::GetNeighbor(aAddress); } Neighbor *GetNeighbor(const Ip6::Address &aAddress) { return Mle::GetNeighbor(aAddress); } - Neighbor *GetRxOnlyNeighborRouter(const Mac::Address &aAddress) { OT_UNUSED_VARIABLE(aAddress); return NULL; } + Neighbor *GetRxOnlyNeighborRouter(const Mac::Address &aAddress) + { + OT_UNUSED_VARIABLE(aAddress); + return NULL; + } otError GetNextNeighborInfo(otNeighborInfoIterator &, otNeighborInfo &) { return OT_ERROR_NOT_IMPLEMENTED; } - Router *GetRouters(uint8_t *aNumRouters) { - if (aNumRouters != NULL) { + Router *GetRouters(uint8_t *aNumRouters) + { + if (aNumRouters != NULL) + { *aNumRouters = 0; } @@ -118,16 +129,17 @@ public: static int ComparePartitions(bool, const LeaderDataTlv &, bool, const LeaderDataTlv &) { return 0; } - void ResolveRoutingLoops(uint16_t, uint16_t) { } + void ResolveRoutingLoops(uint16_t, uint16_t) {} - otError CheckReachability(uint16_t aMeshSource, uint16_t aMeshDest, Ip6::Header &aIp6Header) { + otError CheckReachability(uint16_t aMeshSource, uint16_t aMeshDest, Ip6::Header &aIp6Header) + { return Mle::CheckReachability(aMeshSource, aMeshDest, aIp6Header); } static bool IsRouterIdValid(uint8_t aRouterId) { return aRouterId <= kMaxRouterId; } - void FillConnectivityTlv(ConnectivityTlv &) { } - void FillRouteTlv(RouteTlv &) { } + void FillConnectivityTlv(ConnectivityTlv &) {} + void FillRouteTlv(RouteTlv &) {} otError SendChildUpdateRequest(void) { return Mle::SendChildUpdateRequest(); } @@ -156,13 +168,17 @@ private: otError HandleDataRequest(const Message &, const Ip6::MessageInfo &) { return OT_ERROR_DROP; } otError HandleNetworkDataUpdateRouter(void) { return OT_ERROR_NONE; } otError HandleDiscoveryRequest(const Message &, const Ip6::MessageInfo &) { return OT_ERROR_DROP; } - void HandlePartitionChange(void) { } + void HandlePartitionChange(void) {} - void StopAdvertiseTimer(void) { } - otError ProcessRouteTlv(const RouteTlv &aRoute) { OT_UNUSED_VARIABLE(aRoute); return OT_ERROR_NONE; } + void StopAdvertiseTimer(void) {} + otError ProcessRouteTlv(const RouteTlv &aRoute) + { + OT_UNUSED_VARIABLE(aRoute); + return OT_ERROR_NONE; + } }; -} // namespace Mle -} // namespace ot +} // namespace Mle +} // namespace ot -#endif // MLE_ROUTER_MTD_HPP_ +#endif // MLE_ROUTER_MTD_HPP_ diff --git a/src/core/thread/mle_tlvs.hpp b/src/core/thread/mle_tlvs.hpp index f10588abd..caaa41a8d 100644 --- a/src/core/thread/mle_tlvs.hpp +++ b/src/core/thread/mle_tlvs.hpp @@ -54,9 +54,9 @@ namespace ot { namespace Mle { -#define TLVREQUESTTLV_ITERATOR_INIT 0 ///< Initializer for TlvRequestTlvIterator. +#define TLVREQUESTTLV_ITERATOR_INIT 0 ///< Initializer for TlvRequestTlvIterator. -typedef uint8_t TlvRequestIterator; ///< Used to iterate through TlvRequestTlv. +typedef uint8_t TlvRequestIterator; ///< Used to iterate through TlvRequestTlv. /** * @addtogroup core-mle-tlvs @@ -82,33 +82,33 @@ public: */ enum Type { - kSourceAddress = 0, ///< Source Address TLV - kMode = 1, ///< Mode TLV - kTimeout = 2, ///< Timeout TLV - kChallenge = 3, ///< Challenge TLV - kResponse = 4, ///< Response TLV - kLinkFrameCounter = 5, ///< Link-Layer Frame Counter TLV - kLinkQuality = 6, ///< Link Quality TLV - kNetworkParameter = 7, ///< Network Parameter TLV - kMleFrameCounter = 8, ///< MLE Frame Counter TLV - kRoute = 9, ///< Route64 TLV - kAddress16 = 10, ///< Address16 TLV - kLeaderData = 11, ///< Leader Data TLV - kNetworkData = 12, ///< Network Data TLV - kTlvRequest = 13, ///< TLV Request TLV - kScanMask = 14, ///< Scan Mask TLV - kConnectivity = 15, ///< Connectivity TLV - kLinkMargin = 16, ///< Link Margin TLV - kStatus = 17, ///< Status TLV - kVersion = 18, ///< Version TLV - kAddressRegistration = 19, ///< Address Registration TLV - kChannel = 20, ///< Channel TLV - kPanId = 21, ///< PAN ID TLV - kActiveTimestamp = 22, ///< Active Timestamp TLV - kPendingTimestamp = 23, ///< Pending Timestamp TLV - kActiveDataset = 24, ///< Active Operational Dataset TLV - kPendingDataset = 25, ///< Pending Operational Dataset TLV - kDiscovery = 26, ///< Thread Discovery TLV + kSourceAddress = 0, ///< Source Address TLV + kMode = 1, ///< Mode TLV + kTimeout = 2, ///< Timeout TLV + kChallenge = 3, ///< Challenge TLV + kResponse = 4, ///< Response TLV + kLinkFrameCounter = 5, ///< Link-Layer Frame Counter TLV + kLinkQuality = 6, ///< Link Quality TLV + kNetworkParameter = 7, ///< Network Parameter TLV + kMleFrameCounter = 8, ///< MLE Frame Counter TLV + kRoute = 9, ///< Route64 TLV + kAddress16 = 10, ///< Address16 TLV + kLeaderData = 11, ///< Leader Data TLV + kNetworkData = 12, ///< Network Data TLV + kTlvRequest = 13, ///< TLV Request TLV + kScanMask = 14, ///< Scan Mask TLV + kConnectivity = 15, ///< Connectivity TLV + kLinkMargin = 16, ///< Link Margin TLV + kStatus = 17, ///< Status TLV + kVersion = 18, ///< Version TLV + kAddressRegistration = 19, ///< Address Registration TLV + kChannel = 20, ///< Channel TLV + kPanId = 21, ///< PAN ID TLV + kActiveTimestamp = 22, ///< Active Timestamp TLV + kPendingTimestamp = 23, ///< Pending Timestamp TLV + kActiveDataset = 24, ///< Active Operational Dataset TLV + kPendingDataset = 25, ///< Pending Operational Dataset TLV + kDiscovery = 26, ///< Thread Discovery TLV kInvalid = 255, }; @@ -140,7 +140,8 @@ public: * @retval OT_ERROR_NOT_FOUND Could not find the TLV with Type @p aType. * */ - static otError GetTlv(const Message &aMessage, Type aType, uint16_t aMaxLength, Tlv &aTlv) { + static otError GetTlv(const Message &aMessage, Type aType, uint16_t aMaxLength, Tlv &aTlv) + { return ot::Tlv::Get(aMessage, static_cast(aType), aMaxLength, aTlv); } @@ -155,7 +156,8 @@ public: * @retval OT_ERROR_NOT_FOUND Could not find the TLV with Type @p aType. * */ - static otError GetOffset(const Message &aMessage, Type aType, uint16_t &aOffset) { + static otError GetOffset(const Message &aMessage, Type aType, uint16_t &aOffset) + { return ot::Tlv::GetOffset(aMessage, static_cast(aType), aOffset); } @@ -166,14 +168,18 @@ public: * */ OT_TOOL_PACKED_BEGIN -class SourceAddressTlv: public Tlv +class SourceAddressTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kSourceAddress); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kSourceAddress); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -209,14 +215,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ModeTlv: public Tlv +class ModeTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kMode); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kMode); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -260,14 +270,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class TimeoutTlv: public Tlv +class TimeoutTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kTimeout); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kTimeout); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -303,19 +317,23 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ChallengeTlv: public Tlv +class ChallengeTlv : public Tlv { public: enum { - kMaxSize = 8, ///< Maximum size in bytes (Thread Specification). + kMaxSize = 8, ///< Maximum size in bytes (Thread Specification). }; /** * This method initializes the TLV. * */ - void Init(void) { SetType(kChallenge); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kChallenge); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -351,19 +369,23 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ResponseTlv: public Tlv +class ResponseTlv : public Tlv { public: enum { - kMaxSize = 8, ///< Maximum size in bytes (Thread Specification). + kMaxSize = 8, ///< Maximum size in bytes (Thread Specification). }; /** * This method initializes the TLV. * */ - void Init(void) { SetType(kResponse); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kResponse); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -399,14 +421,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class LinkFrameCounterTlv: public Tlv +class LinkFrameCounterTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kLinkFrameCounter); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kLinkFrameCounter); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -442,14 +468,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class RouteTlv: public Tlv +class RouteTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kRoute); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kRoute); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -458,7 +488,8 @@ public: * @retval FALSE If the TLV does not appear to be well-formed. * */ - bool IsValid(void) const { + bool IsValid(void) const + { return GetLength() >= sizeof(mRouterIdSequence) + sizeof(mRouterIdMask) && GetLength() <= sizeof(*this) - sizeof(Tlv); } @@ -494,7 +525,8 @@ public: * @retval FALSE If the Router ID bit is not set. * */ - bool IsRouterIdSet(uint8_t aRouterId) const { + bool IsRouterIdSet(uint8_t aRouterId) const + { return (mRouterIdMask[aRouterId / 8] & (0x80 >> (aRouterId % 8))) != 0; } @@ -520,9 +552,7 @@ public: * @param[in] aLength The Route Data Length value. * */ - void SetRouteDataLength(uint8_t aLength) { - SetLength(sizeof(mRouterIdSequence) + sizeof(mRouterIdMask) + aLength); - } + void SetRouteDataLength(uint8_t aLength) { SetLength(sizeof(mRouterIdSequence) + sizeof(mRouterIdMask) + aLength); } /** * This method returns the Route Cost value for a given Router ID. @@ -530,9 +560,7 @@ public: * @returns The Route Cost value for a given Router ID. * */ - uint8_t GetRouteCost(uint8_t aRouterId) const { - return mRouteData[aRouterId] & kRouteCostMask; - } + uint8_t GetRouteCost(uint8_t aRouterId) const { return mRouteData[aRouterId] & kRouteCostMask; } /** * This method sets the Route Cost value for a given Router ID. @@ -541,7 +569,8 @@ public: * @param[in] aRouteCost The Route Cost value. * */ - void SetRouteCost(uint8_t aRouterId, uint8_t aRouteCost) { + void SetRouteCost(uint8_t aRouterId, uint8_t aRouteCost) + { mRouteData[aRouterId] = (mRouteData[aRouterId] & ~kRouteCostMask) | aRouteCost; } @@ -551,7 +580,8 @@ public: * @returns The Link Quality In value for a given Router ID. * */ - uint8_t GetLinkQualityIn(uint8_t aRouterId) const { + uint8_t GetLinkQualityIn(uint8_t aRouterId) const + { return (mRouteData[aRouterId] & kLinkQualityInMask) >> kLinkQualityInOffset; } @@ -562,10 +592,10 @@ public: * @param[in] aLinkQuality The Link Quality In value for a given Router ID. * */ - void SetLinkQualityIn(uint8_t aRouterId, uint8_t aLinkQuality) { - mRouteData[aRouterId] = - (mRouteData[aRouterId] & ~kLinkQualityInMask) | - ((aLinkQuality << kLinkQualityInOffset) & kLinkQualityInMask); + void SetLinkQualityIn(uint8_t aRouterId, uint8_t aLinkQuality) + { + mRouteData[aRouterId] = (mRouteData[aRouterId] & ~kLinkQualityInMask) | + ((aLinkQuality << kLinkQualityInOffset) & kLinkQualityInMask); } /** @@ -574,7 +604,8 @@ public: * @returns The Link Quality Out value for a given Router ID. * */ - uint8_t GetLinkQualityOut(uint8_t aRouterId) const { + uint8_t GetLinkQualityOut(uint8_t aRouterId) const + { return (mRouteData[aRouterId] & kLinkQualityOutMask) >> kLinkQualityOutOffset; } @@ -585,21 +616,21 @@ public: * @param[in] aLinkQuality The Link Quality Out value for a given Router ID. * */ - void SetLinkQualityOut(uint8_t aRouterId, uint8_t aLinkQuality) { - mRouteData[aRouterId] = - (mRouteData[aRouterId] & ~kLinkQualityOutMask) | - ((aLinkQuality << kLinkQualityOutOffset) & kLinkQualityOutMask); + void SetLinkQualityOut(uint8_t aRouterId, uint8_t aLinkQuality) + { + mRouteData[aRouterId] = (mRouteData[aRouterId] & ~kLinkQualityOutMask) | + ((aLinkQuality << kLinkQualityOutOffset) & kLinkQualityOutMask); } private: enum { kLinkQualityOutOffset = 6, - kLinkQualityOutMask = 3 << kLinkQualityOutOffset, - kLinkQualityInOffset = 4, - kLinkQualityInMask = 3 << kLinkQualityInOffset, - kRouteCostOffset = 0, - kRouteCostMask = 0xf << kRouteCostOffset, + kLinkQualityOutMask = 3 << kLinkQualityOutOffset, + kLinkQualityInOffset = 4, + kLinkQualityInMask = 3 << kLinkQualityInOffset, + kRouteCostOffset = 0, + kRouteCostMask = 0xf << kRouteCostOffset, }; uint8_t mRouterIdSequence; uint8_t mRouterIdMask[BitVectorBytes(kMaxRouterId + 1)]; @@ -611,14 +642,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class MleFrameCounterTlv: public Tlv +class MleFrameCounterTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kMleFrameCounter); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kMleFrameCounter); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -654,14 +689,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class Address16Tlv: public Tlv +class Address16Tlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kAddress16); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kAddress16); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -697,14 +736,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class LeaderDataTlv: public Tlv +class LeaderDataTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kLeaderData); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kLeaderData); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -761,7 +804,7 @@ public: * @param[in] aVersion The Data Version value. * */ - void SetDataVersion(uint8_t aVersion) { mDataVersion = aVersion; } + void SetDataVersion(uint8_t aVersion) { mDataVersion = aVersion; } /** * This method returns the Stable Data Version value. @@ -797,10 +840,10 @@ public: private: uint32_t mPartitionId; - uint8_t mWeighting; - uint8_t mDataVersion; - uint8_t mStableDataVersion; - uint8_t mLeaderRouterId; + uint8_t mWeighting; + uint8_t mDataVersion; + uint8_t mStableDataVersion; + uint8_t mLeaderRouterId; } OT_TOOL_PACKED_END; /** @@ -808,14 +851,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class NetworkDataTlv: public Tlv +class NetworkDataTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kNetworkData); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kNetworkData); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -851,14 +898,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class TlvRequestTlv: public Tlv +class TlvRequestTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kTlvRequest); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kTlvRequest); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -884,13 +935,15 @@ public: * @retval OT_ERROR_NOT_FOUND No subsequent Tlv exists in TlvRequestTlv. * */ - otError GetNextTlv(TlvRequestIterator &aIterator, uint8_t &aTlv) { + otError GetNextTlv(TlvRequestIterator &aIterator, uint8_t &aTlv) + { otError error = OT_ERROR_NOT_FOUND; - if (aIterator < GetLength()) { - aTlv = mTlvs[aIterator]; + if (aIterator < GetLength()) + { + aTlv = mTlvs[aIterator]; aIterator = static_cast(aIterator + sizeof(uint8_t)); - error = OT_ERROR_NONE; + error = OT_ERROR_NONE; } return error; @@ -917,14 +970,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ScanMaskTlv: public Tlv +class ScanMaskTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kScanMask); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kScanMask); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -937,7 +994,7 @@ public: enum { - kRouterFlag = 1 << 7, + kRouterFlag = 1 << 7, kEndDeviceFlag = 1 << 6, }; @@ -998,14 +1055,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ConnectivityTlv: public Tlv +class ConnectivityTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kConnectivity); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kConnectivity); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1014,7 +1075,8 @@ public: * @retval FALSE If the TLV does not appear to be well-formed. * */ - bool IsValid(void) const { + bool IsValid(void) const + { return (GetLength() == sizeof(*this) - sizeof(Tlv) || GetLength() == sizeof(*this) - sizeof(Tlv) - sizeof(mSedBufferSize) - sizeof(mSedDatagramCount)); } @@ -1025,7 +1087,10 @@ public: * @returns The Parent Priority value. * */ - int8_t GetParentPriority(void) const { return (static_cast(mParentPriority & kParentPriorityMask)) >> kParentPriorityOffset; } + int8_t GetParentPriority(void) const + { + return (static_cast(mParentPriority & kParentPriorityMask)) >> kParentPriorityOffset; + } /** * This method sets the Parent Priority value. @@ -1033,7 +1098,8 @@ public: * @param[in] aParentPriority The Parent Priority value. * */ - void SetParentPriority(int8_t aParentPriority) { + void SetParentPriority(int8_t aParentPriority) + { mParentPriority = (aParentPriority << kParentPriorityOffset) & kParentPriorityMask; } @@ -1169,7 +1235,7 @@ private: enum { kParentPriorityOffset = 6, - kParentPriorityMask = 3 << kParentPriorityOffset, + kParentPriorityMask = 3 << kParentPriorityOffset, }; uint8_t mParentPriority; @@ -1181,21 +1247,25 @@ private: uint8_t mActiveRouters; uint16_t mSedBufferSize; uint8_t mSedDatagramCount; -} OT_TOOL_PACKED_END; +} OT_TOOL_PACKED_END; /** * This class implements Source Address TLV generation and parsing. * */ OT_TOOL_PACKED_BEGIN -class LinkMarginTlv: public Tlv +class LinkMarginTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kLinkMargin); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kLinkMargin); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1231,14 +1301,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class StatusTlv: public Tlv +class StatusTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kStatus); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kStatus); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1254,7 +1328,7 @@ public: */ enum Status { - kError = 1, ///< Error. + kError = 1, ///< Error. }; /** @@ -1282,14 +1356,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class VersionTlv: public Tlv +class VersionTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kVersion); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kVersion); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1404,13 +1482,13 @@ private: enum { kCompressed = 1 << 7, - kCidMask = 0xf, + kCidMask = 0xf, }; uint8_t mControl; union { - uint8_t mIid[Ip6::Address::kInterfaceIdentifierSize]; + uint8_t mIid[Ip6::Address::kInterfaceIdentifierSize]; Ip6::Address mIp6Address; } OT_TOOL_PACKED_FIELD; } OT_TOOL_PACKED_END; @@ -1420,14 +1498,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ChannelTlv: public Tlv +class ChannelTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kChannel); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kChannel); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1471,7 +1553,7 @@ public: void SetChannel(uint16_t aChannel) { mChannel = HostSwap16(aChannel); } private: - uint8_t mChannelPage; + uint8_t mChannelPage; uint16_t mChannel; } OT_TOOL_PACKED_END; @@ -1480,14 +1562,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class PanIdTlv: public Tlv +class PanIdTlv : public Tlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kPanId); SetLength(sizeof(*this) - sizeof(Tlv)); } + void Init(void) + { + SetType(kPanId); + SetLength(sizeof(*this) - sizeof(Tlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1530,7 +1616,8 @@ public: * This method initializes the TLV. * */ - void Init(void) { + void Init(void) + { SetType(Mle::Tlv::kActiveTimestamp); SetLength(sizeof(*this) - sizeof(Tlv)); Timestamp::Init(); @@ -1558,7 +1645,8 @@ public: * This method initializes the TLV. * */ - void Init(void) { + void Init(void) + { SetType(Mle::Tlv::kPendingTimestamp); SetLength(sizeof(*this) - sizeof(Tlv)); Timestamp::Init(); @@ -1579,9 +1667,8 @@ public: * */ -} // namespace Mle +} // namespace Mle +} // namespace ot -} // namespace ot - -#endif // MLE_TLVS_HPP_ +#endif // MLE_TLVS_HPP_ diff --git a/src/core/thread/network_data.cpp b/src/core/thread/network_data.cpp index 84fa1e083..9e177ea87 100644 --- a/src/core/thread/network_data.cpp +++ b/src/core/thread/network_data.cpp @@ -50,16 +50,15 @@ namespace ot { namespace NetworkData { -NetworkData::NetworkData(Instance &aInstance, bool aLocal): - InstanceLocator(aInstance), - mLocal(aLocal), - mLastAttemptWait(false), - mLastAttempt(0) +NetworkData::NetworkData(Instance &aInstance, bool aLocal) + : InstanceLocator(aInstance) + , mLocal(aLocal) + , mLastAttemptWait(false) + , mLastAttempt(0) { mLength = 0; } - void NetworkData::Clear(void) { mLength = 0; @@ -89,17 +88,18 @@ otError NetworkData::GetNextOnMeshPrefix(otNetworkDataIterator *aIterator, otBor return GetNextOnMeshPrefix(aIterator, Mac::kShortAddrBroadcast, aConfig); } -otError NetworkData::GetNextOnMeshPrefix(otNetworkDataIterator *aIterator, uint16_t aRloc16, - otBorderRouterConfig *aConfig) +otError NetworkData::GetNextOnMeshPrefix(otNetworkDataIterator *aIterator, + uint16_t aRloc16, + otBorderRouterConfig * aConfig) { - otError error = OT_ERROR_NOT_FOUND; + otError error = OT_ERROR_NOT_FOUND; NetworkDataIterator iterator(aIterator); - NetworkDataTlv *cur = reinterpret_cast(mTlvs + iterator.GetTlvOffset()); - NetworkDataTlv *end = reinterpret_cast(mTlvs + mLength); + NetworkDataTlv * cur = reinterpret_cast(mTlvs + iterator.GetTlvOffset()); + NetworkDataTlv * end = reinterpret_cast(mTlvs + mLength); for (; cur < end; cur = cur->GetNext(), iterator.SetSubTlvOffset(0), iterator.SetEntryIndex(0)) { - PrefixTlv *prefix; + PrefixTlv * prefix; NetworkDataTlv *subCur; NetworkDataTlv *subEnd; @@ -111,8 +111,8 @@ otError NetworkData::GetNextOnMeshPrefix(otNetworkDataIterator *aIterator, uint1 } prefix = static_cast(cur); - subCur = reinterpret_cast(reinterpret_cast(prefix->GetSubTlvs()) - + iterator.GetSubTlvOffset()); + subCur = reinterpret_cast(reinterpret_cast(prefix->GetSubTlvs()) + + iterator.GetSubTlvOffset()); subEnd = cur->GetNext(); for (; subCur < subEnd; subCur = subCur->GetNext(), iterator.SetEntryIndex(0)) @@ -137,15 +137,15 @@ otError NetworkData::GetNextOnMeshPrefix(otNetworkDataIterator *aIterator, uint1 memset(aConfig, 0, sizeof(*aConfig)); memcpy(&aConfig->mPrefix.mPrefix, prefix->GetPrefix(), BitVectorBytes(prefix->GetPrefixLength())); aConfig->mPrefix.mLength = prefix->GetPrefixLength(); - aConfig->mPreference = borderRouterEntry->GetPreference(); - aConfig->mPreferred = borderRouterEntry->IsPreferred(); - aConfig->mSlaac = borderRouterEntry->IsSlaac(); - aConfig->mDhcp = borderRouterEntry->IsDhcp(); - aConfig->mConfigure = borderRouterEntry->IsConfigure(); - aConfig->mDefaultRoute = borderRouterEntry->IsDefaultRoute(); - aConfig->mOnMesh = borderRouterEntry->IsOnMesh(); - aConfig->mStable = borderRouter->IsStable(); - aConfig->mRloc16 = borderRouterEntry->GetRloc(); + aConfig->mPreference = borderRouterEntry->GetPreference(); + aConfig->mPreferred = borderRouterEntry->IsPreferred(); + aConfig->mSlaac = borderRouterEntry->IsSlaac(); + aConfig->mDhcp = borderRouterEntry->IsDhcp(); + aConfig->mConfigure = borderRouterEntry->IsConfigure(); + aConfig->mDefaultRoute = borderRouterEntry->IsDefaultRoute(); + aConfig->mOnMesh = borderRouterEntry->IsOnMesh(); + aConfig->mStable = borderRouter->IsStable(); + aConfig->mRloc16 = borderRouterEntry->GetRloc(); iterator.SaveTlvOffset(cur, mTlvs); iterator.SaveSubTlvOffset(subCur, prefix->GetSubTlvs()); @@ -166,17 +166,18 @@ otError NetworkData::GetNextExternalRoute(otNetworkDataIterator *aIterator, otEx return GetNextExternalRoute(aIterator, Mac::kShortAddrBroadcast, aConfig); } -otError NetworkData::GetNextExternalRoute(otNetworkDataIterator *aIterator, uint16_t aRloc16, +otError NetworkData::GetNextExternalRoute(otNetworkDataIterator *aIterator, + uint16_t aRloc16, otExternalRouteConfig *aConfig) { - otError error = OT_ERROR_NOT_FOUND; + otError error = OT_ERROR_NOT_FOUND; NetworkDataIterator iterator(aIterator); - NetworkDataTlv *cur = reinterpret_cast(mTlvs + iterator.GetTlvOffset()); - NetworkDataTlv *end = reinterpret_cast(mTlvs + mLength); + NetworkDataTlv * cur = reinterpret_cast(mTlvs + iterator.GetTlvOffset()); + NetworkDataTlv * end = reinterpret_cast(mTlvs + mLength); for (; cur < end; cur = cur->GetNext(), iterator.SetSubTlvOffset(0), iterator.SetEntryIndex(0)) { - PrefixTlv *prefix; + PrefixTlv * prefix; NetworkDataTlv *subCur; NetworkDataTlv *subEnd; @@ -189,8 +190,8 @@ otError NetworkData::GetNextExternalRoute(otNetworkDataIterator *aIterator, uint prefix = static_cast(cur); - subCur = reinterpret_cast(reinterpret_cast(prefix->GetSubTlvs()) - + iterator.GetSubTlvOffset()); + subCur = reinterpret_cast(reinterpret_cast(prefix->GetSubTlvs()) + + iterator.GetSubTlvOffset()); subEnd = cur->GetNext(); for (; subCur < subEnd; subCur = subCur->GetNext(), iterator.SetEntryIndex(0)) @@ -213,12 +214,11 @@ otError NetworkData::GetNextExternalRoute(otNetworkDataIterator *aIterator, uint HasRouteEntry *hasRouteEntry = hasRoute->GetEntry(index); memset(aConfig, 0, sizeof(*aConfig)); - memcpy(&aConfig->mPrefix.mPrefix, prefix->GetPrefix(), - BitVectorBytes(prefix->GetPrefixLength())); - aConfig->mPrefix.mLength = prefix->GetPrefixLength(); - aConfig->mPreference = hasRouteEntry->GetPreference(); - aConfig->mStable = hasRoute->IsStable(); - aConfig->mRloc16 = hasRouteEntry->GetRloc(); + memcpy(&aConfig->mPrefix.mPrefix, prefix->GetPrefix(), BitVectorBytes(prefix->GetPrefixLength())); + aConfig->mPrefix.mLength = prefix->GetPrefixLength(); + aConfig->mPreference = hasRouteEntry->GetPreference(); + aConfig->mStable = hasRoute->IsStable(); + aConfig->mRloc16 = hasRouteEntry->GetRloc(); aConfig->mNextHopIsThisDevice = (hasRouteEntry->GetRloc() == GetNetif().GetMle().GetRloc16()); iterator.SaveTlvOffset(cur, mTlvs); @@ -241,17 +241,16 @@ otError NetworkData::GetNextService(otNetworkDataIterator *aIterator, otServiceC return GetNextService(aIterator, Mac::kShortAddrBroadcast, aConfig); } -otError NetworkData::GetNextService(otNetworkDataIterator *aIterator, uint16_t aRloc16, - otServiceConfig *aConfig) +otError NetworkData::GetNextService(otNetworkDataIterator *aIterator, uint16_t aRloc16, otServiceConfig *aConfig) { - otError error = OT_ERROR_NOT_FOUND; + otError error = OT_ERROR_NOT_FOUND; NetworkDataIterator iterator(aIterator); - NetworkDataTlv *cur = reinterpret_cast(mTlvs + iterator.GetTlvOffset()); - NetworkDataTlv *end = reinterpret_cast(mTlvs + mLength); + NetworkDataTlv * cur = reinterpret_cast(mTlvs + iterator.GetTlvOffset()); + NetworkDataTlv * end = reinterpret_cast(mTlvs + mLength); for (; cur < end; cur = cur->GetNext(), iterator.SetSubTlvOffset(0)) { - ServiceTlv *service; + ServiceTlv * service; NetworkDataTlv *subCur; NetworkDataTlv *subEnd; @@ -264,8 +263,8 @@ otError NetworkData::GetNextService(otNetworkDataIterator *aIterator, uint16_t a service = static_cast(cur); - subCur = reinterpret_cast(reinterpret_cast(service->GetSubTlvs()) - + iterator.GetSubTlvOffset()); + subCur = reinterpret_cast(reinterpret_cast(service->GetSubTlvs()) + + iterator.GetSubTlvOffset()); subEnd = cur->GetNext(); for (; subCur < subEnd; subCur = subCur->GetNext()) @@ -285,13 +284,13 @@ otError NetworkData::GetNextService(otNetworkDataIterator *aIterator, uint16_t a { memset(aConfig, 0, sizeof(*aConfig)); - aConfig->mServiceID = service->GetServiceID(); - aConfig->mEnterpriseNumber = service->GetEnterpriseNumber(); + aConfig->mServiceID = service->GetServiceID(); + aConfig->mEnterpriseNumber = service->GetEnterpriseNumber(); aConfig->mServiceDataLength = service->GetServiceDataLength(); memcpy(&aConfig->mServiceData, service->GetServiceData(), service->GetServiceDataLength()); - aConfig->mServerConfig.mStable = server->IsStable(); + aConfig->mServerConfig.mStable = server->IsStable(); aConfig->mServerConfig.mServerDataLength = server->GetServerDataLength(); memcpy(&aConfig->mServerConfig.mServerData, server->GetServerData(), server->GetServerDataLength()); aConfig->mServerConfig.mRloc16 = server->GetServer16(); @@ -318,14 +317,14 @@ exit: otError NetworkData::GetNextServiceId(otNetworkDataIterator *aIterator, uint16_t aRloc16, uint8_t *aServiceId) { - otError error = OT_ERROR_NOT_FOUND; + otError error = OT_ERROR_NOT_FOUND; NetworkDataIterator iterator(aIterator); - NetworkDataTlv *cur = reinterpret_cast(mTlvs + iterator.GetTlvOffset()); - NetworkDataTlv *end = reinterpret_cast(mTlvs + mLength); + NetworkDataTlv * cur = reinterpret_cast(mTlvs + iterator.GetTlvOffset()); + NetworkDataTlv * end = reinterpret_cast(mTlvs + mLength); for (; cur < end; cur = cur->GetNext(), iterator.SetSubTlvOffset(0)) { - ServiceTlv *service; + ServiceTlv * service; NetworkDataTlv *subCur; NetworkDataTlv *subEnd; @@ -338,8 +337,8 @@ otError NetworkData::GetNextServiceId(otNetworkDataIterator *aIterator, uint16_t service = static_cast(cur); - subCur = reinterpret_cast(reinterpret_cast(service->GetSubTlvs()) - + iterator.GetSubTlvOffset()); + subCur = reinterpret_cast(reinterpret_cast(service->GetSubTlvs()) + + iterator.GetSubTlvOffset()); subEnd = cur->GetNext(); for (; subCur < subEnd; subCur = subCur->GetNext()) @@ -383,14 +382,14 @@ exit: bool NetworkData::ContainsOnMeshPrefixes(NetworkData &aCompare, uint16_t aRloc16) { otNetworkDataIterator outerIterator = OT_NETWORK_DATA_ITERATOR_INIT; - otBorderRouterConfig outerConfig; - bool rval = true; + otBorderRouterConfig outerConfig; + bool rval = true; while (aCompare.GetNextOnMeshPrefix(&outerIterator, aRloc16, &outerConfig) == OT_ERROR_NONE) { otNetworkDataIterator innerIterator = OT_NETWORK_DATA_ITERATOR_INIT; - otBorderRouterConfig innerConfig; - otError error; + otBorderRouterConfig innerConfig; + otError error; while ((error = GetNextOnMeshPrefix(&innerIterator, aRloc16, &innerConfig)) == OT_ERROR_NONE) { @@ -414,13 +413,13 @@ bool NetworkData::ContainsExternalRoutes(NetworkData &aCompare, uint16_t aRloc16 { otNetworkDataIterator outerIterator = OT_NETWORK_DATA_ITERATOR_INIT; otExternalRouteConfig outerConfig; - bool rval = true; + bool rval = true; while (aCompare.GetNextExternalRoute(&outerIterator, aRloc16, &outerConfig) == OT_ERROR_NONE) { otNetworkDataIterator innerIterator = OT_NETWORK_DATA_ITERATOR_INIT; otExternalRouteConfig innerConfig; - otError error; + otError error; while ((error = GetNextExternalRoute(&innerIterator, aRloc16, &innerConfig)) == OT_ERROR_NONE) { @@ -444,22 +443,22 @@ exit: bool NetworkData::ContainsServices(NetworkData &aCompare, uint16_t aRloc16) { otNetworkDataIterator outerIterator = OT_NETWORK_DATA_ITERATOR_INIT; - otServiceConfig outerConfig; - bool rval = true; + otServiceConfig outerConfig; + bool rval = true; while (aCompare.GetNextService(&outerIterator, aRloc16, &outerConfig) == OT_ERROR_NONE) { otNetworkDataIterator innerIterator = OT_NETWORK_DATA_ITERATOR_INIT; - otServiceConfig innerConfig; - otError error; + otServiceConfig innerConfig; + otError error; while ((error = GetNextService(&innerIterator, aRloc16, &innerConfig)) == OT_ERROR_NONE) { if ((outerConfig.mEnterpriseNumber == innerConfig.mEnterpriseNumber) && - (outerConfig.mServiceDataLength == innerConfig.mServiceDataLength) - && (memcmp(outerConfig.mServiceData, innerConfig.mServiceData, outerConfig.mServiceDataLength) == 0) && - (outerConfig.mServerConfig.mStable == innerConfig.mServerConfig.mStable) - && (outerConfig.mServerConfig.mServerDataLength == innerConfig.mServerConfig.mServerDataLength) && + (outerConfig.mServiceDataLength == innerConfig.mServiceDataLength) && + (memcmp(outerConfig.mServiceData, innerConfig.mServiceData, outerConfig.mServiceDataLength) == 0) && + (outerConfig.mServerConfig.mStable == innerConfig.mServerConfig.mStable) && + (outerConfig.mServerConfig.mServerDataLength == innerConfig.mServerConfig.mServerDataLength) && (memcmp(outerConfig.mServerConfig.mServerData, innerConfig.mServerConfig.mServerData, outerConfig.mServerConfig.mServerDataLength) == 0)) { @@ -479,13 +478,13 @@ exit: bool NetworkData::ContainsService(uint8_t aServiceId, uint16_t aRloc16) { - bool rval = false; - NetworkDataTlv *cur = reinterpret_cast(mTlvs); - NetworkDataTlv *end = reinterpret_cast(mTlvs + mLength); + bool rval = false; + NetworkDataTlv *cur = reinterpret_cast(mTlvs); + NetworkDataTlv *end = reinterpret_cast(mTlvs + mLength); for (; cur < end; cur = cur->GetNext()) { - ServiceTlv *service; + ServiceTlv * service; NetworkDataTlv *subCur; NetworkDataTlv *subEnd; @@ -533,11 +532,11 @@ void NetworkData::RemoveTemporaryData(uint8_t *aData, uint8_t &aDataLength) { NetworkDataTlv *cur = reinterpret_cast(aData); NetworkDataTlv *end; - PrefixTlv *prefix; + PrefixTlv * prefix; #if OPENTHREAD_ENABLE_SERVICE ServiceTlv *service; #endif - uint8_t length; + uint8_t length; uint8_t *dst; uint8_t *src; @@ -560,8 +559,8 @@ void NetworkData::RemoveTemporaryData(uint8_t *aData, uint8_t &aDataLength) if (prefix->GetSubTlvsLength() == 0) { length = sizeof(NetworkDataTlv) + cur->GetLength(); - dst = reinterpret_cast(cur); - src = reinterpret_cast(cur->GetNext()); + dst = reinterpret_cast(cur); + src = reinterpret_cast(cur->GetNext()); memmove(dst, src, aDataLength - static_cast(src - aData)); aDataLength -= length; continue; @@ -581,8 +580,8 @@ void NetworkData::RemoveTemporaryData(uint8_t *aData, uint8_t &aDataLength) if (service->GetSubTlvsLength() == 0) { length = sizeof(NetworkDataTlv) + cur->GetLength(); - dst = reinterpret_cast(cur); - src = reinterpret_cast(cur->GetNext()); + dst = reinterpret_cast(cur); + src = reinterpret_cast(cur->GetNext()); memmove(dst, src, aDataLength - static_cast(src - aData)); aDataLength -= length; continue; @@ -600,8 +599,8 @@ void NetworkData::RemoveTemporaryData(uint8_t *aData, uint8_t &aDataLength) if (!cur->IsStable()) { length = sizeof(NetworkDataTlv) + cur->GetLength(); - dst = reinterpret_cast(cur); - src = reinterpret_cast(cur->GetNext()); + dst = reinterpret_cast(cur); + src = reinterpret_cast(cur->GetNext()); memmove(dst, src, aDataLength - static_cast(src - aData)); aDataLength -= length; continue; @@ -619,17 +618,17 @@ void NetworkData::RemoveTemporaryData(uint8_t *aData, uint8_t &aDataLength) void NetworkData::RemoveTemporaryData(uint8_t *aData, uint8_t &aDataLength, PrefixTlv &aPrefix) { - NetworkDataTlv *cur = aPrefix.GetSubTlvs(); - NetworkDataTlv *end; - BorderRouterTlv *borderRouter; - HasRouteTlv *hasRoute; - ContextTlv *context; + NetworkDataTlv * cur = aPrefix.GetSubTlvs(); + NetworkDataTlv * end; + BorderRouterTlv * borderRouter; + HasRouteTlv * hasRoute; + ContextTlv * context; BorderRouterEntry *borderRouterEntry; - HasRouteEntry *hasRouteEntry; - uint8_t length; - uint8_t contextId; - uint8_t *dst; - uint8_t *src; + HasRouteEntry * hasRouteEntry; + uint8_t length; + uint8_t contextId; + uint8_t * dst; + uint8_t * src; while (1) { @@ -700,8 +699,8 @@ void NetworkData::RemoveTemporaryData(uint8_t *aData, uint8_t &aDataLength, Pref { // remove temporary tlv length = sizeof(NetworkDataTlv) + cur->GetLength(); - dst = reinterpret_cast(cur); - src = reinterpret_cast(cur->GetNext()); + dst = reinterpret_cast(cur); + src = reinterpret_cast(cur->GetNext()); memmove(dst, src, aDataLength - static_cast(src - aData)); aPrefix.SetSubTlvsLength(aPrefix.GetSubTlvsLength() - length); aDataLength -= length; @@ -714,10 +713,10 @@ void NetworkData::RemoveTemporaryData(uint8_t *aData, uint8_t &aDataLength, Serv { NetworkDataTlv *cur = aService.GetSubTlvs(); NetworkDataTlv *end; - ServerTlv *server; - uint8_t length; - uint8_t *dst; - uint8_t *src; + ServerTlv * server; + uint8_t length; + uint8_t * dst; + uint8_t * src; while (1) { @@ -752,8 +751,8 @@ void NetworkData::RemoveTemporaryData(uint8_t *aData, uint8_t &aDataLength, Serv { // remove temporary tlv length = sizeof(NetworkDataTlv) + cur->GetLength(); - dst = reinterpret_cast(cur); - src = reinterpret_cast(cur->GetNext()); + dst = reinterpret_cast(cur); + src = reinterpret_cast(cur->GetNext()); memmove(dst, src, aDataLength - static_cast(src - aData)); aService.SetSubTlvsLength(aService.GetSubTlvsLength() - length); aDataLength -= length; @@ -765,8 +764,8 @@ void NetworkData::RemoveTemporaryData(uint8_t *aData, uint8_t &aDataLength, Serv BorderRouterTlv *NetworkData::FindBorderRouter(PrefixTlv &aPrefix) { BorderRouterTlv *rval = NULL; - NetworkDataTlv *cur = aPrefix.GetSubTlvs(); - NetworkDataTlv *end = aPrefix.GetNext(); + NetworkDataTlv * cur = aPrefix.GetSubTlvs(); + NetworkDataTlv * end = aPrefix.GetNext(); while (cur < end) { @@ -787,15 +786,14 @@ exit: BorderRouterTlv *NetworkData::FindBorderRouter(PrefixTlv &aPrefix, bool aStable) { BorderRouterTlv *rval = NULL; - NetworkDataTlv *cur = aPrefix.GetSubTlvs(); - NetworkDataTlv *end = aPrefix.GetNext(); + NetworkDataTlv * cur = aPrefix.GetSubTlvs(); + NetworkDataTlv * end = aPrefix.GetNext(); while (cur < end) { VerifyOrExit((cur + 1) <= end && cur->GetNext() <= end); - if (cur->GetType() == NetworkDataTlv::kTypeBorderRouter && - cur->IsStable() == aStable) + if (cur->GetType() == NetworkDataTlv::kTypeBorderRouter && cur->IsStable() == aStable) { ExitNow(rval = reinterpret_cast(cur)); } @@ -809,9 +807,9 @@ exit: HasRouteTlv *NetworkData::FindHasRoute(PrefixTlv &aPrefix) { - HasRouteTlv *rval = NULL; - NetworkDataTlv *cur = aPrefix.GetSubTlvs(); - NetworkDataTlv *end = aPrefix.GetNext(); + HasRouteTlv * rval = NULL; + NetworkDataTlv *cur = aPrefix.GetSubTlvs(); + NetworkDataTlv *end = aPrefix.GetNext(); while (cur < end) { @@ -831,16 +829,15 @@ exit: HasRouteTlv *NetworkData::FindHasRoute(PrefixTlv &aPrefix, bool aStable) { - HasRouteTlv *rval = NULL; - NetworkDataTlv *cur = aPrefix.GetSubTlvs(); - NetworkDataTlv *end = aPrefix.GetNext(); + HasRouteTlv * rval = NULL; + NetworkDataTlv *cur = aPrefix.GetSubTlvs(); + NetworkDataTlv *end = aPrefix.GetNext(); while (cur < end) { VerifyOrExit((cur + 1) <= end && cur->GetNext() <= end); - if (cur->GetType() == NetworkDataTlv::kTypeHasRoute && - cur->IsStable() == aStable) + if (cur->GetType() == NetworkDataTlv::kTypeHasRoute && cur->IsStable() == aStable) { ExitNow(rval = reinterpret_cast(cur)); } @@ -854,9 +851,9 @@ exit: ContextTlv *NetworkData::FindContext(PrefixTlv &aPrefix) { - ContextTlv *rval = NULL; - NetworkDataTlv *cur = aPrefix.GetSubTlvs(); - NetworkDataTlv *end = aPrefix.GetNext(); + ContextTlv * rval = NULL; + NetworkDataTlv *cur = aPrefix.GetSubTlvs(); + NetworkDataTlv *end = aPrefix.GetNext(); while (cur < end) { @@ -883,7 +880,7 @@ PrefixTlv *NetworkData::FindPrefix(const uint8_t *aPrefix, uint8_t aPrefixLength { NetworkDataTlv *cur = reinterpret_cast(aTlvs); NetworkDataTlv *end = reinterpret_cast(aTlvs + aTlvsLength); - PrefixTlv *compare; + PrefixTlv * compare; while (cur < end) { @@ -909,7 +906,7 @@ exit: int8_t NetworkData::PrefixMatch(const uint8_t *a, const uint8_t *b, uint8_t aLength) { - int8_t rval = 0; + int8_t rval = 0; uint8_t bytes = BitVectorBytes(aLength); uint8_t diff; @@ -937,18 +934,22 @@ int8_t NetworkData::PrefixMatch(const uint8_t *a, const uint8_t *b, uint8_t aLen } #if OPENTHREAD_ENABLE_SERVICE -ServiceTlv *NetworkData::FindService(uint32_t aEnterpriseNumber, const uint8_t *aServiceData, - uint8_t aServiceDataLength) +ServiceTlv *NetworkData::FindService(uint32_t aEnterpriseNumber, + const uint8_t *aServiceData, + uint8_t aServiceDataLength) { return FindService(aEnterpriseNumber, aServiceData, aServiceDataLength, mTlvs, mLength); } -ServiceTlv *NetworkData::FindService(uint32_t aEnterpriseNumber, const uint8_t *aServiceData, - uint8_t aServiceDataLength, uint8_t *aTlvs, uint8_t aTlvsLength) +ServiceTlv *NetworkData::FindService(uint32_t aEnterpriseNumber, + const uint8_t *aServiceData, + uint8_t aServiceDataLength, + uint8_t * aTlvs, + uint8_t aTlvsLength) { NetworkDataTlv *cur = reinterpret_cast(aTlvs); NetworkDataTlv *end = reinterpret_cast(aTlvs + aTlvsLength); - ServiceTlv *compare; + ServiceTlv * compare; while (cur < end) { @@ -958,8 +959,9 @@ ServiceTlv *NetworkData::FindService(uint32_t aEnterpriseNumber, const uint8_t * { compare = reinterpret_cast(cur); - if ((compare->GetEnterpriseNumber() == aEnterpriseNumber) && (compare->GetServiceDataLength() == aServiceDataLength) - && (memcmp(compare->GetServiceData(), aServiceData, aServiceDataLength) == 0)) + if ((compare->GetEnterpriseNumber() == aEnterpriseNumber) && + (compare->GetServiceDataLength() == aServiceDataLength) && + (memcmp(compare->GetServiceData(), aServiceData, aServiceDataLength) == 0)) { return compare; } @@ -975,9 +977,7 @@ exit: otError NetworkData::Insert(uint8_t *aStart, uint8_t aLength) { - assert(aLength + mLength <= sizeof(mTlvs) && - mTlvs <= aStart && - aStart <= mTlvs + mLength); + assert(aLength + mLength <= sizeof(mTlvs) && mTlvs <= aStart && aStart <= mTlvs + mLength); memmove(aStart + aLength, aStart, mLength - static_cast(aStart - mTlvs)); mLength += aLength; return OT_ERROR_NONE; @@ -985,9 +985,7 @@ otError NetworkData::Insert(uint8_t *aStart, uint8_t aLength) otError NetworkData::Remove(uint8_t *aStart, uint8_t aLength) { - assert(aLength <= mLength && - mTlvs <= aStart && - (aStart - mTlvs) + aLength <= mLength); + assert(aLength <= mLength && mTlvs <= aStart && (aStart - mTlvs) + aLength <= mLength); memmove(aStart, aStart + aLength, mLength - (static_cast(aStart - mTlvs) + aLength)); mLength -= aLength; return OT_ERROR_NONE; @@ -995,10 +993,10 @@ otError NetworkData::Remove(uint8_t *aStart, uint8_t aLength) otError NetworkData::SendServerDataNotification(uint16_t aRloc16) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Coap::Header header; - Message *message = NULL; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Coap::Header header; + Message * message = NULL; Ip6::MessageInfo messageInfo; VerifyOrExit(!mLastAttemptWait || static_cast(TimerMilli::GetNow() - mLastAttempt) < kDataResubmitDelay, @@ -1035,7 +1033,7 @@ otError NetworkData::SendServerDataNotification(uint16_t aRloc16) if (mLocal) { - mLastAttempt = TimerMilli::GetNow(); + mLastAttempt = TimerMilli::GetNow(); mLastAttemptWait = true; } @@ -1056,5 +1054,5 @@ void NetworkData::ClearResubmitDelayTimer(void) mLastAttemptWait = false; } -} // namespace NetworkData -} // namespace ot +} // namespace NetworkData +} // namespace ot diff --git a/src/core/thread/network_data.hpp b/src/core/thread/network_data.hpp index b8ce01902..a9a37f05d 100644 --- a/src/core/thread/network_data.hpp +++ b/src/core/thread/network_data.hpp @@ -86,12 +86,12 @@ namespace NetworkData { * This class implements Network Data processing. * */ -class NetworkData: public InstanceLocator +class NetworkData : public InstanceLocator { public: enum { - kMaxSize = 255, ///< Maximum size of Thread Network Data in bytes. + kMaxSize = 255, ///< Maximum size of Thread Network Data in bytes. }; /** @@ -171,8 +171,7 @@ public: * @retval OT_ERROR_NOT_FOUND No subsequent external route exists in the Thread Network Data. * */ - otError GetNextExternalRoute(otNetworkDataIterator *aIterator, uint16_t aRloc16, - otExternalRouteConfig *aConfig); + otError GetNextExternalRoute(otNetworkDataIterator *aIterator, uint16_t aRloc16, otExternalRouteConfig *aConfig); #if OPENTHREAD_ENABLE_SERVICE /** @@ -198,8 +197,7 @@ public: * @retval OT_ERROR_NOT_FOUND No subsequent service exists in the Thread Network Data. * */ - otError GetNextService(otNetworkDataIterator *aIterator, uint16_t aRloc16, - otServiceConfig *aConfig); + otError GetNextService(otNetworkDataIterator *aIterator, uint16_t aRloc16, otServiceConfig *aConfig); /** * This method provides the next service ID in the Thread Network Data for a given RLOC16. @@ -212,8 +210,7 @@ public: * @retval OT_ERROR_NOT_FOUND No subsequent service exists in the Thread Network Data. * */ - otError GetNextServiceId(otNetworkDataIterator *aIterator, uint16_t aRloc16, - uint8_t *aServiceId); + otError GetNextServiceId(otNetworkDataIterator *aIterator, uint16_t aRloc16, uint8_t *aServiceId); #endif /** @@ -378,8 +375,11 @@ protected: * @returns A pointer to the Service TLV is one is found or NULL if no matching Service TLV exists. * */ - ServiceTlv *FindService(uint32_t aEnterpriseNumber, const uint8_t *aServiceData, uint8_t aServiceDataLength, - uint8_t *aTlvs, uint8_t aTlvsLength); + ServiceTlv *FindService(uint32_t aEnterpriseNumber, + const uint8_t *aServiceData, + uint8_t aServiceDataLength, + uint8_t * aTlvs, + uint8_t aTlvsLength); #endif /** @@ -462,13 +462,13 @@ protected: */ otError SendServerDataNotification(uint16_t aRloc16); - uint8_t mTlvs[kMaxSize]; ///< The Network Data buffer. - uint8_t mLength; ///< The number of valid bytes in @var mTlvs. + uint8_t mTlvs[kMaxSize]; ///< The Network Data buffer. + uint8_t mLength; ///< The number of valid bytes in @var mTlvs. private: enum { - kDataResubmitDelay = 300000, ///< DATA_RESUBMIT_DELAY (milliseconds) + kDataResubmitDelay = 300000, ///< DATA_RESUBMIT_DELAY (milliseconds) }; class NetworkDataIterator @@ -482,21 +482,25 @@ private: }; public: - NetworkDataIterator(otNetworkDataIterator *aIterator): - mIteratorBuffer(reinterpret_cast(aIterator)) { } + NetworkDataIterator(otNetworkDataIterator *aIterator) + : mIteratorBuffer(reinterpret_cast(aIterator)) + { + } - uint8_t GetTlvOffset(void) const { return mIteratorBuffer[kTlvPosition]; } - uint8_t GetSubTlvOffset(void) const { return mIteratorBuffer[kSubTlvPosition]; } - uint8_t GetEntryIndex(void) const { return mIteratorBuffer[kEntryPosition]; } - void SetTlvOffset(uint8_t aOffset) { mIteratorBuffer[kTlvPosition] = aOffset; } + uint8_t GetTlvOffset(void) const { return mIteratorBuffer[kTlvPosition]; } + uint8_t GetSubTlvOffset(void) const { return mIteratorBuffer[kSubTlvPosition]; } + uint8_t GetEntryIndex(void) const { return mIteratorBuffer[kEntryPosition]; } + void SetTlvOffset(uint8_t aOffset) { mIteratorBuffer[kTlvPosition] = aOffset; } void SetSubTlvOffset(uint8_t aOffset) { mIteratorBuffer[kSubTlvPosition] = aOffset; } - void SetEntryIndex(uint8_t aIndex) { mIteratorBuffer[kEntryPosition] = aIndex; } + void SetEntryIndex(uint8_t aIndex) { mIteratorBuffer[kEntryPosition] = aIndex; } - void SaveTlvOffset(const NetworkDataTlv *aTlv, const uint8_t *aTlvs) { + void SaveTlvOffset(const NetworkDataTlv *aTlv, const uint8_t *aTlvs) + { SetTlvOffset(static_cast(reinterpret_cast(aTlv) - aTlvs)); } - void SaveSubTlvOffset(const NetworkDataTlv *aSubTlv, const NetworkDataTlv *aSubTlvs) { + void SaveSubTlvOffset(const NetworkDataTlv *aSubTlv, const NetworkDataTlv *aSubTlvs) + { SetSubTlvOffset(static_cast(reinterpret_cast(aSubTlv) - reinterpret_cast(aSubTlvs))); } @@ -505,17 +509,17 @@ private: uint8_t *mIteratorBuffer; }; - const bool mLocal; - bool mLastAttemptWait; - uint32_t mLastAttempt; + const bool mLocal; + bool mLastAttemptWait; + uint32_t mLastAttempt; }; -} // namespace NetworkData +} // namespace NetworkData /** * @} */ -} // namespace ot +} // namespace ot -#endif // NETWORK_DATA_HPP_ +#endif // NETWORK_DATA_HPP_ diff --git a/src/core/thread/network_data_leader.cpp b/src/core/thread/network_data_leader.cpp index 1954d2573..6414fb212 100644 --- a/src/core/thread/network_data_leader.cpp +++ b/src/core/thread/network_data_leader.cpp @@ -46,8 +46,8 @@ #include "common/message.hpp" #include "common/timer.hpp" #include "mac/mac_frame.hpp" -#include "thread/mle_router.hpp" #include "thread/lowpan.hpp" +#include "thread/mle_router.hpp" #include "thread/thread_netif.hpp" #include "thread/thread_tlvs.hpp" #include "thread/thread_uri_paths.hpp" @@ -57,39 +57,38 @@ using ot::Encoding::BigEndian::HostSwap16; namespace ot { namespace NetworkData { -LeaderBase::LeaderBase(Instance &aInstance): - NetworkData(aInstance, false) +LeaderBase::LeaderBase(Instance &aInstance) + : NetworkData(aInstance, false) { Reset(); } void LeaderBase::Reset(void) { - mVersion = static_cast(otPlatRandomGet()); + mVersion = static_cast(otPlatRandomGet()); mStableVersion = static_cast(otPlatRandomGet()); - mLength = 0; + mLength = 0; GetNotifier().SetFlags(OT_CHANGED_THREAD_NETDATA); } otError LeaderBase::GetContext(const Ip6::Address &aAddress, Lowpan::Context &aContext) { ThreadNetif &netif = GetNetif(); - PrefixTlv *prefix; - ContextTlv *contextTlv; + PrefixTlv * prefix; + ContextTlv * contextTlv; aContext.mPrefixLength = 0; if (PrefixMatch(netif.GetMle().GetMeshLocalPrefix(), aAddress.mFields.m8, 64) >= 0) { - aContext.mPrefix = netif.GetMle().GetMeshLocalPrefix(); + aContext.mPrefix = netif.GetMle().GetMeshLocalPrefix(); aContext.mPrefixLength = 64; - aContext.mContextId = 0; + aContext.mContextId = 0; aContext.mCompressFlag = true; } - for (NetworkDataTlv *cur = reinterpret_cast(mTlvs); - cur < reinterpret_cast(mTlvs + mLength); - cur = cur->GetNext()) + for (NetworkDataTlv *cur = reinterpret_cast(mTlvs); + cur < reinterpret_cast(mTlvs + mLength); cur = cur->GetNext()) { if (cur->GetType() != NetworkDataTlv::kTypePrefix) { @@ -112,9 +111,9 @@ otError LeaderBase::GetContext(const Ip6::Address &aAddress, Lowpan::Context &aC if (prefix->GetPrefixLength() > aContext.mPrefixLength) { - aContext.mPrefix = prefix->GetPrefix(); + aContext.mPrefix = prefix->GetPrefix(); aContext.mPrefixLength = prefix->GetPrefixLength(); - aContext.mContextId = contextTlv->GetContextId(); + aContext.mContextId = contextTlv->GetContextId(); aContext.mCompressFlag = contextTlv->IsCompress(); } } @@ -124,29 +123,28 @@ otError LeaderBase::GetContext(const Ip6::Address &aAddress, Lowpan::Context &aC otError LeaderBase::GetContext(uint8_t aContextId, Lowpan::Context &aContext) { - otError error = OT_ERROR_NOT_FOUND; - PrefixTlv *prefix; + otError error = OT_ERROR_NOT_FOUND; + PrefixTlv * prefix; ContextTlv *contextTlv; if (aContextId == 0) { - aContext.mPrefix = GetNetif().GetMle().GetMeshLocalPrefix(); + aContext.mPrefix = GetNetif().GetMle().GetMeshLocalPrefix(); aContext.mPrefixLength = 64; - aContext.mContextId = 0; + aContext.mContextId = 0; aContext.mCompressFlag = true; ExitNow(error = OT_ERROR_NONE); } - for (NetworkDataTlv *cur = reinterpret_cast(mTlvs); - cur < reinterpret_cast(mTlvs + mLength); - cur = cur->GetNext()) + for (NetworkDataTlv *cur = reinterpret_cast(mTlvs); + cur < reinterpret_cast(mTlvs + mLength); cur = cur->GetNext()) { if (cur->GetType() != NetworkDataTlv::kTypePrefix) { continue; } - prefix = static_cast(cur); + prefix = static_cast(cur); contextTlv = FindContext(*prefix); if (contextTlv == NULL) @@ -159,9 +157,9 @@ otError LeaderBase::GetContext(uint8_t aContextId, Lowpan::Context &aContext) continue; } - aContext.mPrefix = prefix->GetPrefix(); + aContext.mPrefix = prefix->GetPrefix(); aContext.mPrefixLength = prefix->GetPrefixLength(); - aContext.mContextId = contextTlv->GetContextId(); + aContext.mContextId = contextTlv->GetContextId(); aContext.mCompressFlag = contextTlv->IsCompress(); ExitNow(error = OT_ERROR_NONE); } @@ -173,18 +171,18 @@ exit: #if OPENTHREAD_ENABLE_DHCP6_SERVER || OPENTHREAD_ENABLE_DHCP6_CLIENT otError LeaderBase::GetRlocByContextId(uint8_t aContextId, uint16_t &aRloc16) { - otError error = OT_ERROR_NOT_FOUND; + otError error = OT_ERROR_NOT_FOUND; Lowpan::Context lowpanContext; if ((GetContext(aContextId, lowpanContext)) == OT_ERROR_NONE) { otNetworkDataIterator iterator = OT_NETWORK_DATA_ITERATOR_INIT; - otBorderRouterConfig config; + otBorderRouterConfig config; while (GetNextOnMeshPrefix(&iterator, &config) == OT_ERROR_NONE) { - if (otIp6PrefixMatch(&(config.mPrefix.mPrefix), - reinterpret_cast(lowpanContext.mPrefix)) >= config.mPrefix.mLength) + if (otIp6PrefixMatch(&(config.mPrefix.mPrefix), reinterpret_cast( + lowpanContext.mPrefix)) >= config.mPrefix.mLength) { aRloc16 = config.mRloc16; ExitNow(error = OT_ERROR_NONE); @@ -195,21 +193,20 @@ otError LeaderBase::GetRlocByContextId(uint8_t aContextId, uint16_t &aRloc16) exit: return error; } -#endif // OPENTHREAD_ENABLE_DHCP6_SERVER || OPENTHREAD_ENABLE_DHCP6_CLIENT +#endif // OPENTHREAD_ENABLE_DHCP6_SERVER || OPENTHREAD_ENABLE_DHCP6_CLIENT bool LeaderBase::IsOnMesh(const Ip6::Address &aAddress) { PrefixTlv *prefix; - bool rval = false; + bool rval = false; if (memcmp(aAddress.mFields.m8, GetNetif().GetMle().GetMeshLocalPrefix(), 8) == 0) { ExitNow(rval = true); } - for (NetworkDataTlv *cur = reinterpret_cast(mTlvs); - cur < reinterpret_cast(mTlvs + mLength); - cur = cur->GetNext()) + for (NetworkDataTlv *cur = reinterpret_cast(mTlvs); + cur < reinterpret_cast(mTlvs + mLength); cur = cur->GetNext()) { if (cur->GetType() != NetworkDataTlv::kTypePrefix) { @@ -235,15 +232,16 @@ exit: return rval; } -otError LeaderBase::RouteLookup(const Ip6::Address &aSource, const Ip6::Address &aDestination, - uint8_t *aPrefixMatch, uint16_t *aRloc16) +otError LeaderBase::RouteLookup(const Ip6::Address &aSource, + const Ip6::Address &aDestination, + uint8_t * aPrefixMatch, + uint16_t * aRloc16) { - otError error = OT_ERROR_NO_ROUTE; + otError error = OT_ERROR_NO_ROUTE; PrefixTlv *prefix; - for (NetworkDataTlv *cur = reinterpret_cast(mTlvs); - cur < reinterpret_cast(mTlvs + mLength); - cur = cur->GetNext()) + for (NetworkDataTlv *cur = reinterpret_cast(mTlvs); + cur < reinterpret_cast(mTlvs + mLength); cur = cur->GetNext()) { if (cur->GetType() != NetworkDataTlv::kTypePrefix) { @@ -275,22 +273,23 @@ exit: return error; } -otError LeaderBase::ExternalRouteLookup(uint8_t aDomainId, const Ip6::Address &aDestination, - uint8_t *aPrefixMatch, uint16_t *aRloc16) +otError LeaderBase::ExternalRouteLookup(uint8_t aDomainId, + const Ip6::Address &aDestination, + uint8_t * aPrefixMatch, + uint16_t * aRloc16) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NO_ROUTE; - PrefixTlv *prefix; - HasRouteTlv *hasRoute; - HasRouteEntry *entry; - HasRouteEntry *rvalRoute = NULL; - uint8_t rval_plen = 0; - int8_t plen; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NO_ROUTE; + PrefixTlv * prefix; + HasRouteTlv * hasRoute; + HasRouteEntry * entry; + HasRouteEntry * rvalRoute = NULL; + uint8_t rval_plen = 0; + int8_t plen; NetworkDataTlv *cur; NetworkDataTlv *subCur; - for (cur = reinterpret_cast(mTlvs); - cur < reinterpret_cast(mTlvs + mLength); + for (cur = reinterpret_cast(mTlvs); cur < reinterpret_cast(mTlvs + mLength); cur = cur->GetNext()) { if (cur->GetType() != NetworkDataTlv::kTypePrefix) @@ -323,8 +322,7 @@ otError LeaderBase::ExternalRouteLookup(uint8_t aDomainId, const Ip6::Address &a { entry = hasRoute->GetEntry(i); - if (rvalRoute == NULL || - entry->GetPreference() > rvalRoute->GetPreference() || + if (rvalRoute == NULL || entry->GetPreference() > rvalRoute->GetPreference() || (entry->GetPreference() == rvalRoute->GetPreference() && (entry->GetRloc() == netif.GetMle().GetRloc16() || (rvalRoute->GetRloc() != netif.GetMle().GetRloc16() && @@ -334,7 +332,6 @@ otError LeaderBase::ExternalRouteLookup(uint8_t aDomainId, const Ip6::Address &a rval_plen = static_cast(plen); } } - } } } @@ -359,9 +356,9 @@ otError LeaderBase::ExternalRouteLookup(uint8_t aDomainId, const Ip6::Address &a otError LeaderBase::DefaultRouteLookup(PrefixTlv &aPrefix, uint16_t *aRloc16) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NO_ROUTE; - BorderRouterTlv *borderRouter; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NO_ROUTE; + BorderRouterTlv * borderRouter; BorderRouterEntry *entry; BorderRouterEntry *route = NULL; @@ -383,8 +380,7 @@ otError LeaderBase::DefaultRouteLookup(PrefixTlv &aPrefix, uint16_t *aRloc16) continue; } - if (route == NULL || - entry->GetPreference() > route->GetPreference() || + if (route == NULL || entry->GetPreference() > route->GetPreference() || (entry->GetPreference() == route->GetPreference() && (entry->GetRloc() == netif.GetMle().GetRloc16() || (route->GetRloc() != netif.GetMle().GetRloc16() && @@ -408,10 +404,13 @@ otError LeaderBase::DefaultRouteLookup(PrefixTlv &aPrefix, uint16_t *aRloc16) return error; } -void LeaderBase::SetNetworkData(uint8_t aVersion, uint8_t aStableVersion, bool aStable, - const uint8_t *aData, uint8_t aDataLength) +void LeaderBase::SetNetworkData(uint8_t aVersion, + uint8_t aStableVersion, + bool aStable, + const uint8_t *aData, + uint8_t aDataLength) { - mVersion = aVersion; + mVersion = aVersion; mStableVersion = aStableVersion; memcpy(mTlvs, aData, aDataLength); mLength = aDataLength; @@ -428,8 +427,8 @@ void LeaderBase::SetNetworkData(uint8_t aVersion, uint8_t aStableVersion, bool a otError LeaderBase::SetCommissioningData(const uint8_t *aValue, uint8_t aValueLength) { - otError error = OT_ERROR_NONE; - uint8_t remaining = kMaxSize - mLength; + otError error = OT_ERROR_NONE; + uint8_t remaining = kMaxSize - mLength; CommissioningDataTlv *commissioningDataTlv; VerifyOrExit(sizeof(NetworkDataTlv) + aValueLength < remaining, error = OT_ERROR_NO_BUFS); @@ -473,10 +472,10 @@ exit: MeshCoP::Tlv *LeaderBase::GetCommissioningDataSubTlv(MeshCoP::Tlv::Type aType) { - MeshCoP::Tlv *rval = NULL; + MeshCoP::Tlv * rval = NULL; NetworkDataTlv *commissioningDataTlv; - MeshCoP::Tlv *cur; - MeshCoP::Tlv *end; + MeshCoP::Tlv * cur; + MeshCoP::Tlv * end; commissioningDataTlv = GetCommissioningData(); VerifyOrExit(commissioningDataTlv != NULL); @@ -499,7 +498,7 @@ exit: bool LeaderBase::IsJoiningEnabled(void) { MeshCoP::Tlv *steeringData; - bool rval = false; + bool rval = false; VerifyOrExit(GetCommissioningDataSubTlv(MeshCoP::Tlv::kBorderAgentLocator) != NULL); @@ -522,9 +521,8 @@ otError LeaderBase::RemoveCommissioningData(void) { otError error = OT_ERROR_NOT_FOUND; - for (NetworkDataTlv *cur = reinterpret_cast(mTlvs); - cur < reinterpret_cast(mTlvs + mLength); - cur = cur->GetNext()) + for (NetworkDataTlv *cur = reinterpret_cast(mTlvs); + cur < reinterpret_cast(mTlvs + mLength); cur = cur->GetNext()) { if (cur->GetType() == NetworkDataTlv::kTypeCommissioningData) { @@ -537,5 +535,5 @@ exit: return error; } -} // namespace NetworkData -} // namespace ot +} // namespace NetworkData +} // namespace ot diff --git a/src/core/thread/network_data_leader.hpp b/src/core/thread/network_data_leader.hpp index 4d41b793a..2503dd2d6 100644 --- a/src/core/thread/network_data_leader.hpp +++ b/src/core/thread/network_data_leader.hpp @@ -64,7 +64,7 @@ namespace NetworkData { * This class implements the Thread Network Data maintained by the Leader. * */ -class LeaderBase: public NetworkData +class LeaderBase : public NetworkData { public: /** @@ -144,8 +144,10 @@ public: * @retval OT_ERROR_NO_ROUTE No valid route was found. * */ - otError RouteLookup(const Ip6::Address &aSource, const Ip6::Address &aDestination, - uint8_t *aPrefixMatch, uint16_t *aRloc16); + otError RouteLookup(const Ip6::Address &aSource, + const Ip6::Address &aDestination, + uint8_t * aPrefixMatch, + uint16_t * aRloc16); /** * This method is used by non-Leader devices to set newly received Network Data from the Leader. @@ -157,8 +159,11 @@ public: * @param[in] aDataLength The length of the Network Data in bytes. * */ - void SetNetworkData(uint8_t aVersion, uint8_t aStableVersion, bool aStableOnly, const uint8_t *aData, - uint8_t aDataLength); + void SetNetworkData(uint8_t aVersion, + uint8_t aStableVersion, + bool aStableOnly, + const uint8_t *aData, + uint8_t aDataLength); /** * This method sends a Server Data Notification message to the Leader indicating an invalid RLOC16. @@ -223,17 +228,19 @@ public: * */ otError GetRlocByContextId(uint8_t aContextId, uint16_t &aRloc16); -#endif // OPENTHREAD_ENABLE_DHCP6_SERVER || OPENTHREAD_ENABLE_DHCP6_CLIENT +#endif // OPENTHREAD_ENABLE_DHCP6_SERVER || OPENTHREAD_ENABLE_DHCP6_CLIENT protected: - uint8_t mStableVersion; - uint8_t mVersion; + uint8_t mStableVersion; + uint8_t mVersion; private: otError RemoveCommissioningData(void); - otError ExternalRouteLookup(uint8_t aDomainId, const Ip6::Address &aDestination, - uint8_t *aPrefixMatch, uint16_t *aRloc16); + otError ExternalRouteLookup(uint8_t aDomainId, + const Ip6::Address &aDestination, + uint8_t * aPrefixMatch, + uint16_t * aRloc16); otError DefaultRouteLookup(PrefixTlv &aPrefix, uint16_t *aRloc16); }; @@ -241,8 +248,8 @@ private: * @} */ -} // namespace NetworkData -} // namespace ot +} // namespace NetworkData +} // namespace ot #if OPENTHREAD_MTD #include "network_data_leader_mtd.hpp" @@ -252,4 +259,4 @@ private: #error "Please define OPENTHREAD_MTD=1 or OPENTHREAD_FTD=1" #endif -#endif // NETWORK_DATA_LEADER_HPP_ +#endif // NETWORK_DATA_LEADER_HPP_ diff --git a/src/core/thread/network_data_leader_ftd.cpp b/src/core/thread/network_data_leader_ftd.cpp index fb358d8d6..8f3414b29 100644 --- a/src/core/thread/network_data_leader_ftd.cpp +++ b/src/core/thread/network_data_leader_ftd.cpp @@ -33,7 +33,6 @@ #if OPENTHREAD_FTD - #define WPP_NAME "network_data_leader_ftd.tmh" #include "network_data_leader.hpp" @@ -62,12 +61,12 @@ using ot::Encoding::BigEndian::HostSwap16; namespace ot { namespace NetworkData { -Leader::Leader(Instance &aInstance): - LeaderBase(aInstance), - mTimer(aInstance, &Leader::HandleTimer, this), - mServerData(OT_URI_PATH_SERVER_DATA, &Leader::HandleServerData, this), - mCommissioningDataGet(OT_URI_PATH_COMMISSIONER_GET, &Leader::HandleCommissioningGet, this), - mCommissioningDataSet(OT_URI_PATH_COMMISSIONER_SET, &Leader::HandleCommissioningSet, this) +Leader::Leader(Instance &aInstance) + : LeaderBase(aInstance) + , mTimer(aInstance, &Leader::HandleTimer, this) + , mServerData(OT_URI_PATH_SERVER_DATA, &Leader::HandleServerData, this) + , mCommissioningDataGet(OT_URI_PATH_COMMISSIONER_GET, &Leader::HandleCommissioningGet, this) + , mCommissioningDataSet(OT_URI_PATH_COMMISSIONER_SET, &Leader::HandleCommissioningSet, this) { Reset(); } @@ -77,7 +76,7 @@ void Leader::Reset(void) LeaderBase::Reset(); memset(mContextLastUsed, 0, sizeof(mContextLastUsed)); - mContextUsed = 0; + mContextUsed = 0; mContextIdReuseDelay = kContextIdReuseDelay; } @@ -129,7 +128,7 @@ otError Leader::SetContextIdReuseDelay(uint32_t aDelay) void Leader::RemoveBorderRouter(uint16_t aRloc16) { - bool rlocIn = false; + bool rlocIn = false; bool rlocStable = false; RlocLookup(aRloc16, rlocIn, rlocStable, mTlvs, mLength); @@ -149,19 +148,20 @@ exit: return; } -void Leader::HandleServerData(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void Leader::HandleServerData(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleServerData( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleServerData(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } -void Leader::HandleServerData(Coap::Header &aHeader, Message &aMessage, - const Ip6::MessageInfo &aMessageInfo) +void Leader::HandleServerData(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { ThreadNetworkDataTlv networkData; - ThreadRloc16Tlv rloc16; + ThreadRloc16Tlv rloc16; otLogInfoNetData(GetInstance(), "Received network data registration"); @@ -171,12 +171,11 @@ void Leader::HandleServerData(Coap::Header &aHeader, Message &aMessage, RemoveBorderRouter(rloc16.GetRloc16()); } - if (ThreadTlv::GetTlv(aMessage, ThreadTlv::kThreadNetworkData, sizeof(networkData), networkData) == - OT_ERROR_NONE) + if (ThreadTlv::GetTlv(aMessage, ThreadTlv::kThreadNetworkData, sizeof(networkData), networkData) == OT_ERROR_NONE) { VerifyOrExit(networkData.IsValid()); - RegisterNetworkData(HostSwap16(aMessageInfo.mPeerAddr.mFields.m16[7]), - networkData.GetTlvs(), networkData.GetLength()); + RegisterNetworkData(HostSwap16(aMessageInfo.mPeerAddr.mFields.m16[7]), networkData.GetTlvs(), + networkData.GetLength()); } SuccessOrExit(GetNetif().GetCoap().SendEmptyAck(aHeader, aMessageInfo)); @@ -187,23 +186,25 @@ exit: return; } -void Leader::HandleCommissioningSet(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void Leader::HandleCommissioningSet(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleCommissioningSet( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleCommissioningSet(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void Leader::HandleCommissioningSet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - uint16_t offset = aMessage.GetOffset(); - uint16_t length = aMessage.GetLength() - aMessage.GetOffset(); - uint8_t tlvs[NetworkData::kMaxSize]; - MeshCoP::StateTlv::State state = MeshCoP::StateTlv::kReject; - bool hasSessionId = false; - bool hasValidTlv = false; - uint16_t sessionId = 0; + uint16_t offset = aMessage.GetOffset(); + uint16_t length = aMessage.GetLength() - aMessage.GetOffset(); + uint8_t tlvs[NetworkData::kMaxSize]; + MeshCoP::StateTlv::State state = MeshCoP::StateTlv::kReject; + bool hasSessionId = false; + bool hasValidTlv = false; + uint16_t sessionId = 0; MeshCoP::Tlv *cur; MeshCoP::Tlv *end; @@ -239,7 +240,7 @@ void Leader::HandleCommissioningSet(Coap::Header &aHeader, Message &aMessage, co MeshCoP::CommissionerSessionIdTlv *tlv = static_cast(cur); VerifyOrExit(tlv->IsValid()); - sessionId = tlv->GetCommissionerSessionId(); + sessionId = tlv->GetCommissionerSessionId(); hasSessionId = true; } else @@ -258,8 +259,7 @@ void Leader::HandleCommissioningSet(Coap::Header &aHeader, Message &aMessage, co // Find Commissioning Data TLV for (NetworkDataTlv *netDataTlv = reinterpret_cast(mTlvs); - netDataTlv < reinterpret_cast(mTlvs + mLength); - netDataTlv = netDataTlv->GetNext()) + netDataTlv < reinterpret_cast(mTlvs + mLength); netDataTlv = netDataTlv->GetNext()) { if (netDataTlv->GetType() == NetworkDataTlv::kTypeCommissioningData) { @@ -297,20 +297,22 @@ exit: return; } -void Leader::HandleCommissioningGet(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void Leader::HandleCommissioningGet(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleCommissioningGet( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleCommissioningGet(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void Leader::HandleCommissioningGet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { MeshCoP::Tlv tlv; - uint16_t offset = aMessage.GetOffset(); - uint8_t tlvs[NetworkData::kMaxSize]; - uint8_t length = 0; + uint16_t offset = aMessage.GetOffset(); + uint8_t tlvs[NetworkData::kMaxSize]; + uint8_t length = 0; while (offset < aMessage.GetLength()) { @@ -329,16 +331,18 @@ void Leader::HandleCommissioningGet(Coap::Header &aHeader, Message &aMessage, co SendCommissioningGetResponse(aHeader, aMessageInfo, tlvs, length); } -void Leader::SendCommissioningGetResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, - uint8_t *aTlvs, uint8_t aLength) +void Leader::SendCommissioningGetResponse(const Coap::Header & aRequestHeader, + const Ip6::MessageInfo &aMessageInfo, + uint8_t * aTlvs, + uint8_t aLength) { ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Coap::Header responseHeader; - Message *message; - uint8_t index; - uint8_t *data = NULL; - uint8_t length = 0; + Message * message; + uint8_t index; + uint8_t * data = NULL; + uint8_t length = 0; responseHeader.SetDefaultResponseHeader(aRequestHeader); responseHeader.SetPayloadMarker(); @@ -346,13 +350,12 @@ void Leader::SendCommissioningGetResponse(const Coap::Header &aRequestHeader, co VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(netif.GetCoap(), responseHeader)) != NULL, error = OT_ERROR_NO_BUFS); - for (NetworkDataTlv *cur = reinterpret_cast(mTlvs); - cur < reinterpret_cast(mTlvs + mLength); - cur = cur->GetNext()) + for (NetworkDataTlv *cur = reinterpret_cast(mTlvs); + cur < reinterpret_cast(mTlvs + mLength); cur = cur->GetNext()) { if (cur->GetType() == NetworkDataTlv::kTypeCommissioningData) { - data = cur->GetValue(); + data = cur->GetValue(); length = cur->GetLength(); break; } @@ -368,9 +371,8 @@ void Leader::SendCommissioningGetResponse(const Coap::Header &aRequestHeader, co { for (index = 0; index < aLength; index++) { - for (MeshCoP::Tlv *cur = reinterpret_cast(data); - cur < reinterpret_cast(data + length); - cur = cur->GetNext()) + for (MeshCoP::Tlv *cur = reinterpret_cast(data); + cur < reinterpret_cast(data + length); cur = cur->GetNext()) { if (cur->GetType() == aTlvs[index]) { @@ -399,13 +401,14 @@ exit: } } -void Leader::SendCommissioningSetResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, +void Leader::SendCommissioningSetResponse(const Coap::Header & aRequestHeader, + const Ip6::MessageInfo & aMessageInfo, MeshCoP::StateTlv::State aState) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Coap::Header responseHeader; - Message *message; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Coap::Header responseHeader; + Message * message; MeshCoP::StateTlv state; responseHeader.SetDefaultResponseHeader(aRequestHeader); @@ -432,19 +435,19 @@ exit: otError Leader::RlocLookup(uint16_t aRloc16, bool &aIn, bool &aStable, uint8_t *aTlvs, uint8_t aTlvsLength) { - otError error = OT_ERROR_NONE; - NetworkDataTlv *cur = reinterpret_cast(aTlvs); - NetworkDataTlv *end = reinterpret_cast(aTlvs + aTlvsLength); - NetworkDataTlv *subCur; - NetworkDataTlv *subEnd; - PrefixTlv *prefix; - BorderRouterTlv *borderRouter; - HasRouteTlv *hasRoute; + otError error = OT_ERROR_NONE; + NetworkDataTlv * cur = reinterpret_cast(aTlvs); + NetworkDataTlv * end = reinterpret_cast(aTlvs + aTlvsLength); + NetworkDataTlv * subCur; + NetworkDataTlv * subEnd; + PrefixTlv * prefix; + BorderRouterTlv * borderRouter; + HasRouteTlv * hasRoute; BorderRouterEntry *borderRouterEntry; - HasRouteEntry *hasRouteEntry; + HasRouteEntry * hasRouteEntry; #if OPENTHREAD_ENABLE_SERVICE ServiceTlv *service; - ServerTlv *server; + ServerTlv * server; #endif while (cur < end) @@ -587,9 +590,9 @@ exit: bool Leader::IsStableUpdated(uint8_t *aTlvs, uint8_t aTlvsLength, uint8_t *aTlvsBase, uint8_t aTlvsBaseLength) { - bool rval = false; - NetworkDataTlv *cur = reinterpret_cast(aTlvs); - NetworkDataTlv *end = reinterpret_cast(aTlvs + aTlvsLength); + bool rval = false; + NetworkDataTlv *cur = reinterpret_cast(aTlvs); + NetworkDataTlv *end = reinterpret_cast(aTlvs + aTlvsLength); #if OPENTHREAD_ENABLE_SERVICE ServiceTlv *service; #endif @@ -602,15 +605,15 @@ bool Leader::IsStableUpdated(uint8_t *aTlvs, uint8_t aTlvsLength, uint8_t *aTlvs { case NetworkDataTlv::kTypePrefix: { - PrefixTlv *prefix = static_cast(cur); - ContextTlv *context = FindContext(*prefix); + PrefixTlv * prefix = static_cast(cur); + ContextTlv * context = FindContext(*prefix); BorderRouterTlv *borderRouter = FindBorderRouter(*prefix, true); - HasRouteTlv *hasRoute = FindHasRoute(*prefix, true); + HasRouteTlv * hasRoute = FindHasRoute(*prefix, true); if (cur->IsStable() && (!context || borderRouter)) { - PrefixTlv *prefixBase = FindPrefix(prefix->GetPrefix(), prefix->GetPrefixLength(), - aTlvsBase, aTlvsBaseLength); + PrefixTlv *prefixBase = + FindPrefix(prefix->GetPrefix(), prefix->GetPrefixLength(), aTlvsBase, aTlvsBaseLength); if (!prefixBase) { @@ -621,8 +624,7 @@ bool Leader::IsStableUpdated(uint8_t *aTlvs, uint8_t aTlvsLength, uint8_t *aTlvs { BorderRouterTlv *borderRouterBase = FindBorderRouter(*prefixBase, true); - if (!borderRouterBase || - memcmp(borderRouter, borderRouterBase, borderRouter->GetLength()) != 0) + if (!borderRouterBase || memcmp(borderRouter, borderRouterBase, borderRouter->GetLength()) != 0) { ExitNow(rval = true); } @@ -653,8 +655,7 @@ bool Leader::IsStableUpdated(uint8_t *aTlvs, uint8_t aTlvsLength, uint8_t *aTlvs NetworkDataTlv *endInner; ServiceTlv *serviceBase = FindService(service->GetEnterpriseNumber(), service->GetServiceData(), - service->GetServiceDataLength(), - aTlvsBase, aTlvsBaseLength); + service->GetServiceDataLength(), aTlvsBase, aTlvsBaseLength); if (!serviceBase || !serviceBase->IsStable()) { @@ -672,8 +673,8 @@ bool Leader::IsStableUpdated(uint8_t *aTlvs, uint8_t aTlvsLength, uint8_t *aTlvs { case NetworkDataTlv::kTypeServer: { - bool foundInBase = false; - ServerTlv *server = reinterpret_cast(curInner); + bool foundInBase = false; + ServerTlv *server = reinterpret_cast(curInner); NetworkDataTlv *curServerBase = service->GetSubTlvs(); NetworkDataTlv *endServerBase = service->GetNext(); @@ -682,9 +683,10 @@ bool Leader::IsStableUpdated(uint8_t *aTlvs, uint8_t aTlvsLength, uint8_t *aTlvs { ServerTlv *serverBase = reinterpret_cast(curServerBase); - if (curServerBase->IsStable() && (server->GetServer16() == serverBase->GetServer16()) - && (server->GetServerDataLength() == serverBase->GetServerDataLength()) - && (memcmp(server->GetServerData(), serverBase->GetServerData(), server->GetServerDataLength()) == 0)) + if (curServerBase->IsStable() && (server->GetServer16() == serverBase->GetServer16()) && + (server->GetServerDataLength() == serverBase->GetServerDataLength()) && + (memcmp(server->GetServerData(), serverBase->GetServerData(), + server->GetServerDataLength()) == 0)) { foundInBase = true; break; @@ -726,10 +728,10 @@ exit: otError Leader::RegisterNetworkData(uint16_t aRloc16, uint8_t *aTlvs, uint8_t aTlvsLength) { - otError error = OT_ERROR_NONE; - bool rlocIn = false; - bool rlocStable = false; - bool stableUpdated = false; + otError error = OT_ERROR_NONE; + bool rlocIn = false; + bool rlocStable = false; + bool stableUpdated = false; uint8_t oldTlvs[NetworkData::kMaxSize]; uint8_t oldTlvsLength = NetworkData::kMaxSize; @@ -737,8 +739,7 @@ otError Leader::RegisterNetworkData(uint16_t aRloc16, uint8_t *aTlvs, uint8_t aT if (rlocIn) { - if (IsStableUpdated(aTlvs, aTlvsLength, mTlvs, mLength) || - IsStableUpdated(mTlvs, mLength, aTlvs, aTlvsLength)) + if (IsStableUpdated(aTlvs, aTlvsLength, mTlvs, mLength) || IsStableUpdated(mTlvs, mLength, aTlvs, aTlvsLength)) { stableUpdated = true; } @@ -779,9 +780,9 @@ exit: otError Leader::AddNetworkData(uint8_t *aTlvs, uint8_t aTlvsLength, uint8_t *aOldTlvs, uint8_t aOldTlvsLength) { - otError error = OT_ERROR_NONE; - NetworkDataTlv *cur = reinterpret_cast(aTlvs); - NetworkDataTlv *end = reinterpret_cast(aTlvs + aTlvsLength); + otError error = OT_ERROR_NONE; + NetworkDataTlv *cur = reinterpret_cast(aTlvs); + NetworkDataTlv *end = reinterpret_cast(aTlvs + aTlvsLength); while (cur < end) { @@ -822,7 +823,7 @@ exit: otError Leader::AddPrefix(PrefixTlv &aPrefix) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; NetworkDataTlv *cur; NetworkDataTlv *end; @@ -858,7 +859,7 @@ exit: #if OPENTHREAD_ENABLE_SERVICE otError Leader::AddService(ServiceTlv &aService, uint8_t *aOldTlvs, uint8_t aOldTlvsLength) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; NetworkDataTlv *cur; NetworkDataTlv *end; @@ -890,10 +891,10 @@ exit: otError Leader::AddHasRoute(PrefixTlv &aPrefix, HasRouteTlv &aHasRoute) { - otError error = OT_ERROR_NONE; - PrefixTlv *dstPrefix = NULL; - HasRouteTlv *dstHasRoute = NULL; - uint16_t appendLength = 0; + otError error = OT_ERROR_NONE; + PrefixTlv * dstPrefix = NULL; + HasRouteTlv *dstHasRoute = NULL; + uint16_t appendLength = 0; VerifyOrExit(aHasRoute.GetNumEntries() > 0, error = OT_ERROR_PARSE); @@ -944,8 +945,7 @@ otError Leader::AddHasRoute(PrefixTlv &aPrefix, HasRouteTlv &aHasRoute) Insert(reinterpret_cast(dstHasRoute->GetNext()), sizeof(HasRouteEntry)); dstHasRoute->SetLength(dstHasRoute->GetLength() + sizeof(HasRouteEntry)); dstPrefix->SetLength(dstPrefix->GetLength() + sizeof(HasRouteEntry)); - memcpy(dstHasRoute->GetEntry(dstHasRoute->GetNumEntries() - 1), aHasRoute.GetEntry(0), - sizeof(HasRouteEntry)); + memcpy(dstHasRoute->GetEntry(dstHasRoute->GetNumEntries() - 1), aHasRoute.GetEntry(0), sizeof(HasRouteEntry)); exit: return error; @@ -954,17 +954,18 @@ exit: #if OPENTHREAD_ENABLE_SERVICE otError Leader::AddServer(ServiceTlv &aService, ServerTlv &aServer, uint8_t *aOldTlvs, uint8_t aOldTlvsLength) { - otError error = OT_ERROR_NONE; - ServiceTlv *dstService = NULL; - ServiceTlv *oldService = NULL; - ServerTlv *dstServer = NULL; - uint16_t appendLength = 0; - uint8_t serviceID = 0; - uint8_t serviceInsertLength = sizeof(ServiceTlv) + sizeof(uint8_t)/*mServiceDataLength*/ + + otError error = OT_ERROR_NONE; + ServiceTlv *dstService = NULL; + ServiceTlv *oldService = NULL; + ServerTlv * dstServer = NULL; + uint16_t appendLength = 0; + uint8_t serviceID = 0; + uint8_t serviceInsertLength = sizeof(ServiceTlv) + sizeof(uint8_t) /*mServiceDataLength*/ + ServiceTlv::GetEnterpriseNumberFieldLength(aService.GetEnterpriseNumber()) + aService.GetServiceDataLength(); - dstService = FindService(aService.GetEnterpriseNumber(), aService.GetServiceData(), aService.GetServiceDataLength()); + dstService = + FindService(aService.GetEnterpriseNumber(), aService.GetServiceData(), aService.GetServiceDataLength()); if (dstService == NULL) { @@ -978,22 +979,22 @@ otError Leader::AddServer(ServiceTlv &aService, ServerTlv &aServer, uint8_t *aOl if (dstService == NULL) { // Try to preserve old Service ID, if existing - oldService = FindService(aService.GetEnterpriseNumber(), aService.GetServiceData(), aService.GetServiceDataLength(), - aOldTlvs, aOldTlvsLength); + oldService = FindService(aService.GetEnterpriseNumber(), aService.GetServiceData(), + aService.GetServiceDataLength(), aOldTlvs, aOldTlvsLength); if (oldService != NULL) { - // The same service is not found in current data, but was in old data. So, it had to be just removed by RemoveRloc() - // Lets use the same ServiceID + // The same service is not found in current data, but was in old data. So, it had to be just removed by + // RemoveRloc() Lets use the same ServiceID serviceID = oldService->GetServiceID(); } else { uint8_t i; - // This seems like completely new service. Lets try to find new ServiceID for it. If all are taken, error out. - // Since we call FindServiceById() on mTlv, we need to execute this before Insert() call, otherwise we'll find - // uninitialized service as well. + // This seems like completely new service. Lets try to find new ServiceID for it. If all are taken, error + // out. Since we call FindServiceById() on mTlv, we need to execute this before Insert() call, otherwise + // we'll find uninitialized service as well. for (i = Mle::kServiceMinId; i <= Mle::kServiceMaxId; i++) { if (FindServiceById(i) == NULL) @@ -1038,9 +1039,9 @@ exit: ServiceTlv *Leader::FindServiceById(uint8_t aServiceId) { - NetworkDataTlv *cur = reinterpret_cast(mTlvs); - NetworkDataTlv *end = reinterpret_cast(mTlvs + mLength); - ServiceTlv *compare = NULL; + NetworkDataTlv *cur = reinterpret_cast(mTlvs); + NetworkDataTlv *end = reinterpret_cast(mTlvs + mLength); + ServiceTlv * compare = NULL; while (cur < end) { @@ -1066,18 +1067,18 @@ exit: otError Leader::AddBorderRouter(PrefixTlv &aPrefix, BorderRouterTlv &aBorderRouter) { - otError error = OT_ERROR_NONE; - PrefixTlv *dstPrefix = NULL; - ContextTlv *dstContext = NULL; + otError error = OT_ERROR_NONE; + PrefixTlv * dstPrefix = NULL; + ContextTlv * dstContext = NULL; BorderRouterTlv *dstBorderRouter = NULL; - int contextId = -1; - uint16_t appendLength = 0; + int contextId = -1; + uint16_t appendLength = 0; VerifyOrExit(aBorderRouter.GetNumEntries() > 0, error = OT_ERROR_PARSE); if ((dstPrefix = FindPrefix(aPrefix.GetPrefix(), aPrefix.GetPrefixLength())) != NULL) { - dstContext = FindContext(*dstPrefix); + dstContext = FindContext(*dstPrefix); dstBorderRouter = FindBorderRouter(*dstPrefix, aBorderRouter.IsStable()); } @@ -1184,9 +1185,9 @@ otError Leader::FreeContext(uint8_t aContextId) otError Leader::SendServerDataNotification(uint16_t aRloc16) { - otError error = OT_ERROR_NONE; - bool rlocIn = false; - bool rlocStable = false; + otError error = OT_ERROR_NONE; + bool rlocIn = false; + bool rlocStable = false; RlocLookup(aRloc16, rlocIn, rlocStable, mTlvs, mLength); @@ -1202,7 +1203,7 @@ otError Leader::RemoveRloc(uint16_t aRloc16) { NetworkDataTlv *cur = reinterpret_cast(mTlvs); NetworkDataTlv *end; - PrefixTlv *prefix; + PrefixTlv * prefix; #if OPENTHREAD_ENABLE_SERVICE ServiceTlv *service; #endif @@ -1269,7 +1270,7 @@ otError Leader::RemoveRloc(PrefixTlv &prefix, uint16_t aRloc16) { NetworkDataTlv *cur = prefix.GetSubTlvs(); NetworkDataTlv *end; - ContextTlv *context; + ContextTlv * context; while (1) { @@ -1344,8 +1345,8 @@ otError Leader::RemoveRloc(ServiceTlv &service, uint16_t aRloc16) { NetworkDataTlv *cur = service.GetSubTlvs(); NetworkDataTlv *end; - ServerTlv *server; - uint8_t removeLength; + ServerTlv * server; + uint8_t removeLength; while (1) { @@ -1432,7 +1433,7 @@ otError Leader::RemoveContext(uint8_t aContextId) { NetworkDataTlv *cur = reinterpret_cast(mTlvs); NetworkDataTlv *end; - PrefixTlv *prefix; + PrefixTlv * prefix; while (1) { @@ -1476,8 +1477,8 @@ otError Leader::RemoveContext(PrefixTlv &aPrefix, uint8_t aContextId) { NetworkDataTlv *cur = aPrefix.GetSubTlvs(); NetworkDataTlv *end; - ContextTlv *context; - uint8_t length; + ContextTlv * context; + uint8_t length; while (1) { @@ -1548,8 +1549,7 @@ void Leader::HandleTimer(void) } } -} // namespace NetworkData -} // namespace ot +} // namespace NetworkData +} // namespace ot #endif // OPENTHREAD_FTD - diff --git a/src/core/thread/network_data_leader_ftd.hpp b/src/core/thread/network_data_leader_ftd.hpp index 8fa96c6ae..188cdec91 100644 --- a/src/core/thread/network_data_leader_ftd.hpp +++ b/src/core/thread/network_data_leader_ftd.hpp @@ -64,7 +64,7 @@ namespace NetworkData { * This class implements the Thread Network Data maintained by the Leader. * */ -class Leader: public LeaderBase +class Leader : public LeaderBase { public: /** @@ -154,12 +154,14 @@ public: #endif private: - static void HandleServerData(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleServerData(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleServerData(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleServerData(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); static void HandleTimer(Timer &aTimer); - void HandleTimer(void); + void HandleTimer(void); otError RegisterNetworkData(uint16_t aRloc16, uint8_t *aTlvs, uint8_t aTlvsLength); @@ -172,7 +174,7 @@ private: otError AddService(ServiceTlv &aTlv, uint8_t *aOldTlvs, uint8_t aOldTlvsLength); #endif - int AllocateContext(void); + int AllocateContext(void); otError FreeContext(uint8_t aContextId); otError RemoveContext(uint8_t aContextId); @@ -189,19 +191,26 @@ private: otError RemoveRloc(PrefixTlv &aPrefix, BorderRouterTlv &aBorderRouter, uint16_t aRloc16); otError RlocLookup(uint16_t aRloc16, bool &aIn, bool &aStable, uint8_t *aTlvs, uint8_t aTlvsLength); - bool IsStableUpdated(uint8_t *aTlvs, uint8_t aTlvsLength, uint8_t *aTlvsBase, uint8_t aTlvsBaseLength); + bool IsStableUpdated(uint8_t *aTlvs, uint8_t aTlvsLength, uint8_t *aTlvsBase, uint8_t aTlvsBaseLength); - static void HandleCommissioningSet(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleCommissioningSet(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleCommissioningSet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleCommissioningSet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - static void HandleCommissioningGet(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleCommissioningGet(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleCommissioningGet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleCommissioningGet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - void SendCommissioningGetResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, - uint8_t *aTlvs, uint8_t aLength); - void SendCommissioningSetResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, + void SendCommissioningGetResponse(const Coap::Header & aRequestHeader, + const Ip6::MessageInfo &aMessageInfo, + uint8_t * aTlvs, + uint8_t aLength); + void SendCommissioningSetResponse(const Coap::Header & aRequestHeader, + const Ip6::MessageInfo & aMessageInfo, MeshCoP::StateTlv::State aState); /** @@ -210,17 +219,17 @@ private: */ enum { - kMinContextId = 1, ///< Minimum Context ID (0 is used for Mesh Local) - kNumContextIds = 15, ///< Maximum Context ID - kContextIdReuseDelay = 48 * 60 * 60, ///< CONTEXT_ID_REUSE_DELAY (seconds) - kStateUpdatePeriod = 1000, ///< State update period in milliseconds + kMinContextId = 1, ///< Minimum Context ID (0 is used for Mesh Local) + kNumContextIds = 15, ///< Maximum Context ID + kContextIdReuseDelay = 48 * 60 * 60, ///< CONTEXT_ID_REUSE_DELAY (seconds) + kStateUpdatePeriod = 1000, ///< State update period in milliseconds }; - uint16_t mContextUsed; - uint32_t mContextLastUsed[kNumContextIds]; - uint32_t mContextIdReuseDelay; + uint16_t mContextUsed; + uint32_t mContextLastUsed[kNumContextIds]; + uint32_t mContextIdReuseDelay; TimerMilli mTimer; - Coap::Resource mServerData; + Coap::Resource mServerData; Coap::Resource mCommissioningDataGet; Coap::Resource mCommissioningDataSet; @@ -230,7 +239,7 @@ private: * @} */ -} // namespace NetworkData -} // namespace ot +} // namespace NetworkData +} // namespace ot -#endif // NETWORK_DATA_LEADER_FTD_HPP_ +#endif // NETWORK_DATA_LEADER_FTD_HPP_ diff --git a/src/core/thread/network_data_leader_mtd.hpp b/src/core/thread/network_data_leader_mtd.hpp index 3fae524a6..4c4452b95 100644 --- a/src/core/thread/network_data_leader_mtd.hpp +++ b/src/core/thread/network_data_leader_mtd.hpp @@ -44,21 +44,24 @@ class ThreadNetif; namespace NetworkData { -class Leader: public LeaderBase +class Leader : public LeaderBase { public: - explicit Leader(Instance &aInstance) : LeaderBase(aInstance) { } + explicit Leader(Instance &aInstance) + : LeaderBase(aInstance) + { + } - void Start(void) { } - void Stop(void) { } + void Start(void) {} + void Stop(void) {} - void IncrementVersion(void) { } - void IncrementStableVersion(void) { } + void IncrementVersion(void) {} + void IncrementStableVersion(void) {} otError SendServerDataNotification(uint16_t) { return OT_ERROR_NOT_IMPLEMENTED; } }; -} // namespace NetworkData -} // namespace ot +} // namespace NetworkData +} // namespace ot -#endif // NETWORK_DATA_LEADER_MTD_HPP_ +#endif // NETWORK_DATA_LEADER_MTD_HPP_ diff --git a/src/core/thread/network_data_local.cpp b/src/core/thread/network_data_local.cpp index 0b9dc6c29..7e55b1026 100644 --- a/src/core/thread/network_data_local.cpp +++ b/src/core/thread/network_data_local.cpp @@ -45,21 +45,20 @@ namespace ot { namespace NetworkData { -Local::Local(Instance &aInstance): - NetworkData(aInstance, true), - mOldRloc(Mac::kShortAddrInvalid) +Local::Local(Instance &aInstance) + : NetworkData(aInstance, true) + , mOldRloc(Mac::kShortAddrInvalid) { } -otError Local::AddOnMeshPrefix(const uint8_t *aPrefix, uint8_t aPrefixLength, int8_t aPrf, - uint8_t aFlags, bool aStable) +otError Local::AddOnMeshPrefix(const uint8_t *aPrefix, uint8_t aPrefixLength, int8_t aPrf, uint8_t aFlags, bool aStable) { - otError error = OT_ERROR_NONE; - PrefixTlv *prefixTlv; + otError error = OT_ERROR_NONE; + PrefixTlv * prefixTlv; BorderRouterTlv *brTlv; - VerifyOrExit(Ip6::Address::PrefixMatch(aPrefix, GetNetif().GetMle().GetMeshLocalPrefix(), - (aPrefixLength + 7) / 8) < Ip6::Address::kMeshLocalPrefixLength, + VerifyOrExit(Ip6::Address::PrefixMatch(aPrefix, GetNetif().GetMle().GetMeshLocalPrefix(), (aPrefixLength + 7) / 8) < + Ip6::Address::kMeshLocalPrefixLength, error = OT_ERROR_INVALID_ARGS); RemoveOnMeshPrefix(aPrefix, aPrefixLength); @@ -93,7 +92,7 @@ exit: otError Local::RemoveOnMeshPrefix(const uint8_t *aPrefix, uint8_t aPrefixLength) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; PrefixTlv *tlv; VerifyOrExit((tlv = FindPrefix(aPrefix, aPrefixLength)) != NULL, error = OT_ERROR_NOT_FOUND); @@ -108,7 +107,7 @@ exit: otError Local::AddHasRoutePrefix(const uint8_t *aPrefix, uint8_t aPrefixLength, int8_t aPrf, bool aStable) { - PrefixTlv *prefixTlv; + PrefixTlv * prefixTlv; HasRouteTlv *hasRouteTlv; RemoveHasRoutePrefix(aPrefix, aPrefixLength); @@ -139,7 +138,7 @@ otError Local::AddHasRoutePrefix(const uint8_t *aPrefix, uint8_t aPrefixLength, otError Local::RemoveHasRoutePrefix(const uint8_t *aPrefix, uint8_t aPrefixLength) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; PrefixTlv *tlv; VerifyOrExit((tlv = FindPrefix(aPrefix, aPrefixLength)) != NULL, error = OT_ERROR_NOT_FOUND); @@ -153,16 +152,19 @@ exit: } #if OPENTHREAD_ENABLE_SERVICE -otError Local::AddService(uint32_t aEnterpriseNumber, const uint8_t *aServiceData, uint8_t aServiceDataLength, - bool aServerStable, const uint8_t *aServerData, uint8_t aServerDataLength) +otError Local::AddService(uint32_t aEnterpriseNumber, + const uint8_t *aServiceData, + uint8_t aServiceDataLength, + bool aServerStable, + const uint8_t *aServerData, + uint8_t aServerDataLength) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; ServiceTlv *serviceTlv; - ServerTlv *serverTlv; - uint8_t serviceTlvLength = (sizeof(ServiceTlv) - sizeof(NetworkDataTlv)) + aServiceDataLength + - sizeof(uint8_t)/*mServiceDataLength*/ + - ServiceTlv::GetEnterpriseNumberFieldLength(aEnterpriseNumber) + - aServerDataLength + sizeof(ServerTlv); + ServerTlv * serverTlv; + uint8_t serviceTlvLength = + (sizeof(ServiceTlv) - sizeof(NetworkDataTlv)) + aServiceDataLength + sizeof(uint8_t) /*mServiceDataLength*/ + + ServiceTlv::GetEnterpriseNumberFieldLength(aEnterpriseNumber) + aServerDataLength + sizeof(ServerTlv); RemoveService(aEnterpriseNumber, aServiceData, aServiceDataLength); @@ -194,13 +196,13 @@ otError Local::AddService(uint32_t aEnterpriseNumber, const uint8_t *aServiceDat otDumpDebgNetData(GetInstance(), "add service done", mTlvs, mLength); -//exit: + // exit: return error; } otError Local::RemoveService(uint32_t aEnterpriseNumber, const uint8_t *aServiceData, uint8_t aServiceDataLength) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; ServiceTlv *tlv; VerifyOrExit((tlv = FindService(aEnterpriseNumber, aServiceData, aServiceDataLength)) != NULL, @@ -216,9 +218,8 @@ exit: otError Local::UpdateRloc(void) { - for (NetworkDataTlv *cur = reinterpret_cast(mTlvs); - cur < reinterpret_cast(mTlvs + mLength); - cur = cur->GetNext()) + for (NetworkDataTlv *cur = reinterpret_cast(mTlvs); + cur < reinterpret_cast(mTlvs + mLength); cur = cur->GetNext()) { switch (cur->GetType()) { @@ -336,18 +337,16 @@ bool Local::IsServiceConsistent(void) otError Local::SendServerDataNotification(void) { - ThreadNetif &netif = GetNetif(); - Mle::MleRouter &mle = netif.GetMle(); - otError error = OT_ERROR_NONE; - uint16_t rloc = mle.GetRloc16(); + ThreadNetif & netif = GetNetif(); + Mle::MleRouter &mle = netif.GetMle(); + otError error = OT_ERROR_NONE; + uint16_t rloc = mle.GetRloc16(); #if OPENTHREAD_FTD // Don't send this Server Data Notification if the device is going to upgrade to Router - if ((mle.GetDeviceMode() & Mle::ModeTlv::kModeFFD) != 0 && - (mle.IsRouterRoleEnabled()) && - (mle.GetRole() < OT_DEVICE_ROLE_ROUTER) && - (mle.GetActiveRouterCount() < mle.GetRouterUpgradeThreshold())) + if ((mle.GetDeviceMode() & Mle::ModeTlv::kModeFFD) != 0 && (mle.IsRouterRoleEnabled()) && + (mle.GetRole() < OT_DEVICE_ROLE_ROUTER) && (mle.GetActiveRouterCount() < mle.GetRouterUpgradeThreshold())) { ExitNow(error = OT_ERROR_INVALID_STATE); } @@ -357,8 +356,8 @@ otError Local::SendServerDataNotification(void) UpdateRloc(); #if OPENTHREAD_ENABLE_SERVICE - VerifyOrExit(!IsOnMeshPrefixConsistent() || !IsExternalRouteConsistent() || - !IsServiceConsistent(), ClearResubmitDelayTimer()); + VerifyOrExit(!IsOnMeshPrefixConsistent() || !IsExternalRouteConsistent() || !IsServiceConsistent(), + ClearResubmitDelayTimer()); #else VerifyOrExit(!IsOnMeshPrefixConsistent() || !IsExternalRouteConsistent(), ClearResubmitDelayTimer()); #endif @@ -375,7 +374,7 @@ exit: return error; } -} // namespace NetworkData -} // namespace ot +} // namespace NetworkData +} // namespace ot #endif // OPENTHREAD_ENABLE_BORDER_ROUTER || OPENTHREAD_ENABLE_SERVICE diff --git a/src/core/thread/network_data_local.hpp b/src/core/thread/network_data_local.hpp index f50499a01..2c47cbb02 100644 --- a/src/core/thread/network_data_local.hpp +++ b/src/core/thread/network_data_local.hpp @@ -57,7 +57,7 @@ namespace NetworkData { * This class implements the Thread Network Data contributed by the local device. * */ -class Local: public NetworkData +class Local : public NetworkData { public: /** @@ -82,8 +82,7 @@ public: * @retval OT_ERROR_INVALID_ARGS The prefix is mesh local prefix. * */ - otError AddOnMeshPrefix(const uint8_t *aPrefix, uint8_t aPrefixLength, int8_t aPrf, uint8_t aFlags, - bool aStable); + otError AddOnMeshPrefix(const uint8_t *aPrefix, uint8_t aPrefixLength, int8_t aPrf, uint8_t aFlags, bool aStable); /** * This method removes a Border Router entry from the Thread Network Data. @@ -138,8 +137,12 @@ public: * @retval OT_ERROR_NO_BUFS Insufficient space to add the Service entry. * */ - otError AddService(uint32_t aEnterpriseNumber, const uint8_t *aServiceData, uint8_t aServiceDataLength, - bool aServerStable, const uint8_t *aServerData, uint8_t aServerDataLength); + otError AddService(uint32_t aEnterpriseNumber, + const uint8_t *aServiceData, + uint8_t aServiceDataLength, + bool aServerStable, + const uint8_t *aServerData, + uint8_t aServerDataLength); /** * This method removes a Service entry from the Thread Network local data. @@ -183,12 +186,12 @@ private: uint16_t mOldRloc; }; -} // namespace NetworkData +} // namespace NetworkData /** * @} */ -} // namespace ot +} // namespace ot -#endif // NETWORK_DATA_LOCAL_HPP_ +#endif // NETWORK_DATA_LOCAL_HPP_ diff --git a/src/core/thread/network_data_tlvs.hpp b/src/core/thread/network_data_tlvs.hpp index 20083b48c..f0330fee0 100644 --- a/src/core/thread/network_data_tlvs.hpp +++ b/src/core/thread/network_data_tlvs.hpp @@ -70,7 +70,11 @@ public: * This method initializes TLV. * */ - void Init(void) { mType = 0; mLength = 0; } + void Init(void) + { + mType = 0; + mLength = 0; + } /** * Thread Network Data Type values. @@ -78,13 +82,13 @@ public: */ enum Type { - kTypeHasRoute = 0, ///< Has Route TLV - kTypePrefix = 1, ///< Prefix TLV - kTypeBorderRouter = 2, ///< Border Router TLV - kTypeContext = 3, ///< Context TLV - kTypeCommissioningData = 4, ///< Commissioning Dataset TLV - kTypeService = 5, ///< Service TLV - kTypeServer = 6, ///< Server TLV + kTypeHasRoute = 0, ///< Has Route TLV + kTypePrefix = 1, ///< Prefix TLV + kTypeBorderRouter = 2, ///< Border Router TLV + kTypeContext = 3, ///< Context TLV + kTypeCommissioningData = 4, ///< Commissioning Dataset TLV + kTypeService = 5, ///< Service TLV + kTypeServer = 6, ///< Server TLV }; /** @@ -101,9 +105,7 @@ public: * @param[in] aType The Type value. * */ - void SetType(Type aType) { - mType = (mType & ~kTypeMask) | ((aType << kTypeOffset) & kTypeMask); - } + void SetType(Type aType) { mType = (mType & ~kTypeMask) | ((aType << kTypeOffset) & kTypeMask); } /** * This method returns the Length value. @@ -135,7 +137,8 @@ public: * @returns A pointer to the next Network Data TLV. * */ - NetworkDataTlv *GetNext(void) { + NetworkDataTlv *GetNext(void) + { return reinterpret_cast(reinterpret_cast(this) + sizeof(*this) + mLength); } @@ -164,7 +167,7 @@ private: enum { kTypeOffset = 1, - kTypeMask = 0x7f << kTypeOffset, + kTypeMask = 0x7f << kTypeOffset, kStableMask = 1 << 0, }; uint8_t mType; @@ -183,7 +186,11 @@ public: * This method initializes the header. * */ - void Init(void) { SetRloc(Mac::kShortAddrInvalid); mFlags = 0; } + void Init(void) + { + SetRloc(Mac::kShortAddrInvalid); + mFlags = 0; + } /** * This method returns the RLOC16 value. @@ -214,7 +221,8 @@ public: * @param[in] aPrf The Preference value. * */ - void SetPreference(int8_t aPrf) { + void SetPreference(int8_t aPrf) + { mFlags = (mFlags & ~kPreferenceMask) | ((aPrf << kPreferenceOffset) & kPreferenceMask); } @@ -222,11 +230,11 @@ private: enum { kPreferenceOffset = 6, - kPreferenceMask = 3 << kPreferenceOffset, + kPreferenceMask = 3 << kPreferenceOffset, }; uint16_t mRloc; - uint8_t mFlags; + uint8_t mFlags; } OT_TOOL_PACKED_END; /** @@ -234,14 +242,19 @@ private: * */ OT_TOOL_PACKED_BEGIN -class HasRouteTlv: public NetworkDataTlv +class HasRouteTlv : public NetworkDataTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { NetworkDataTlv::Init(); SetType(kTypeHasRoute); SetLength(0); } + void Init(void) + { + NetworkDataTlv::Init(); + SetType(kTypeHasRoute); + SetLength(0); + } /** * This method returns the number of HasRoute entries. @@ -259,7 +272,8 @@ public: * @returns A pointer to the i'th HasRoute entry. * */ - HasRouteEntry *GetEntry(uint8_t i) { + HasRouteEntry *GetEntry(uint8_t i) + { return reinterpret_cast(GetValue() + (i * sizeof(HasRouteEntry))); } } OT_TOOL_PACKED_END; @@ -269,7 +283,7 @@ public: * */ OT_TOOL_PACKED_BEGIN -class PrefixTlv: public NetworkDataTlv +class PrefixTlv : public NetworkDataTlv { public: /** @@ -280,10 +294,11 @@ public: * @param[in] aPrefix A pointer to the prefix. * */ - void Init(uint8_t aDomainId, uint8_t aPrefixLength, const uint8_t *aPrefix) { + void Init(uint8_t aDomainId, uint8_t aPrefixLength, const uint8_t *aPrefix) + { NetworkDataTlv::Init(); SetType(kTypePrefix); - mDomainId = aDomainId; + mDomainId = aDomainId; mPrefixLength = aPrefixLength; memcpy(GetPrefix(), aPrefix, BitVectorBytes(aPrefixLength)); SetSubTlvsLength(0); @@ -296,7 +311,8 @@ public: * @retval FALSE If the TLV does not appear to be well-formed. * */ - bool IsValid(void) const { + bool IsValid(void) const + { return ((GetLength() >= sizeof(*this) - sizeof(NetworkDataTlv)) && (GetLength() >= BitVectorBytes(mPrefixLength) + sizeof(*this) - sizeof(NetworkDataTlv))); } @@ -331,9 +347,9 @@ public: * @returns A pointer to the Sub-TLVs. * */ - NetworkDataTlv *GetSubTlvs(void) { - return reinterpret_cast(GetPrefix() + - BitVectorBytes(mPrefixLength)); + NetworkDataTlv *GetSubTlvs(void) + { + return reinterpret_cast(GetPrefix() + BitVectorBytes(mPrefixLength)); } /** @@ -342,7 +358,8 @@ public: * @returns The Sub-TLVs length in bytes. * */ - uint8_t GetSubTlvsLength(void) const { + uint8_t GetSubTlvsLength(void) const + { return GetLength() - (sizeof(*this) - sizeof(NetworkDataTlv) + BitVectorBytes(mPrefixLength)); } @@ -352,7 +369,8 @@ public: * @param[in] aLength The Sub-TLVs length in bytes. * */ - void SetSubTlvsLength(uint8_t aLength) { + void SetSubTlvsLength(uint8_t aLength) + { SetLength(sizeof(*this) - sizeof(NetworkDataTlv) + BitVectorBytes(mPrefixLength) + aLength); } @@ -372,20 +390,25 @@ public: enum { kPreferenceOffset = 6, - kPreferenceMask = 3 << kPreferenceOffset, - kPreferredFlag = 1 << 5, - kSlaacFlag = 1 << 4, - kDhcpFlag = 1 << 3, - kConfigureFlag = 1 << 2, + kPreferenceMask = 3 << kPreferenceOffset, + kPreferredFlag = 1 << 5, + kSlaacFlag = 1 << 4, + kDhcpFlag = 1 << 3, + kConfigureFlag = 1 << 2, kDefaultRouteFlag = 1 << 1, - kOnMeshFlag = 1 << 0, + kOnMeshFlag = 1 << 0, }; /** * This method initializes the TLV. * */ - void Init(void) { SetRloc(Mac::kShortAddrInvalid); mFlags = 0; mReserved = 0; } + void Init(void) + { + SetRloc(Mac::kShortAddrInvalid); + mFlags = 0; + mReserved = 0; + } /** * This method returns the RLOC16 value. @@ -432,7 +455,8 @@ public: * @param[in] aPrf The Preference value. * */ - void SetPreference(int8_t aPrf) { + void SetPreference(int8_t aPrf) + { mFlags = (mFlags & ~kPreferenceMask) | ((aPrf << kPreferenceOffset) & kPreferenceMask); } @@ -564,8 +588,8 @@ public: private: uint16_t mRloc; - uint8_t mFlags; - uint8_t mReserved; + uint8_t mFlags; + uint8_t mReserved; } OT_TOOL_PACKED_END; /** @@ -573,14 +597,19 @@ private: * */ OT_TOOL_PACKED_BEGIN -class BorderRouterTlv: public NetworkDataTlv +class BorderRouterTlv : public NetworkDataTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { NetworkDataTlv::Init(); SetType(kTypeBorderRouter); SetLength(0); } + void Init(void) + { + NetworkDataTlv::Init(); + SetType(kTypeBorderRouter); + SetLength(0); + } /** * This method returns the number of Border Router entries. @@ -598,7 +627,8 @@ public: * @returns A pointer to the i'th Border Router entry. * */ - BorderRouterEntry *GetEntry(uint8_t i) { + BorderRouterEntry *GetEntry(uint8_t i) + { return reinterpret_cast(GetValue() + (i * sizeof(BorderRouterEntry))); } } OT_TOOL_PACKED_END; @@ -608,14 +638,21 @@ public: * */ OT_TOOL_PACKED_BEGIN -class ContextTlv: public NetworkDataTlv +class ContextTlv : public NetworkDataTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { NetworkDataTlv::Init(); SetType(kTypeContext); SetLength(2); mFlags = 0; mContextLength = 0; } + void Init(void) + { + NetworkDataTlv::Init(); + SetType(kTypeContext); + SetLength(2); + mFlags = 0; + mContextLength = 0; + } /** * This method indicates whether or not the Compress flag is set. @@ -652,7 +689,8 @@ public: * @param[in] aContextId The Context ID value. * */ - void SetContextId(uint8_t aContextId) { + void SetContextId(uint8_t aContextId) + { mFlags = (mFlags & ~kContextIdMask) | ((aContextId << kContextIdOffset) & kContextIdMask); } @@ -675,9 +713,9 @@ public: private: enum { - kCompressFlag = 1 << 4, + kCompressFlag = 1 << 4, kContextIdOffset = 0, - kContextIdMask = 0xf << kContextIdOffset, + kContextIdMask = 0xf << kContextIdOffset, }; uint8_t mFlags; uint8_t mContextLength; @@ -688,14 +726,19 @@ private: * */ OT_TOOL_PACKED_BEGIN -class CommissioningDataTlv: public NetworkDataTlv +class CommissioningDataTlv : public NetworkDataTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { NetworkDataTlv::Init(); SetType(kTypeCommissioningData); SetLength(0); } + void Init(void) + { + NetworkDataTlv::Init(); + SetType(kTypeCommissioningData); + SetLength(0); + } } OT_TOOL_PACKED_END; /** @@ -703,14 +746,21 @@ public: * */ OT_TOOL_PACKED_BEGIN -class ServiceTlv: public NetworkDataTlv +class ServiceTlv : public NetworkDataTlv { public: /** * This method initializes the TLV. * Initial length is set to 2, to hold S_service_data_length field. */ - void Init(void) { NetworkDataTlv::Init(); SetType(kTypeService); SetLength(2); mTResSId = kTMask; SetServiceDataLength(0); } + void Init(void) + { + NetworkDataTlv::Init(); + SetType(kTypeService); + SetLength(2); + mTResSId = kTMask; + SetServiceDataLength(0); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -719,14 +769,14 @@ public: * @retval FALSE If the TLV does not appear to be well-formed. * */ - bool IsValid(void) { + bool IsValid(void) + { uint8_t length = GetLength(); return ((length >= (sizeof(*this) - sizeof(NetworkDataTlv))) && - (length >= ((sizeof(*this) - sizeof(NetworkDataTlv)) + - (IsThreadEnterprise() ? 0 : sizeof(uint32_t)) + sizeof(uint8_t))) && - (length >= ((sizeof(*this) - sizeof(NetworkDataTlv)) + - (IsThreadEnterprise() ? 0 : sizeof(uint32_t)) + sizeof(uint8_t) + - GetServiceDataLength()))); + (length >= ((sizeof(*this) - sizeof(NetworkDataTlv)) + (IsThreadEnterprise() ? 0 : sizeof(uint32_t)) + + sizeof(uint8_t))) && + (length >= ((sizeof(*this) - sizeof(NetworkDataTlv)) + (IsThreadEnterprise() ? 0 : sizeof(uint32_t)) + + sizeof(uint8_t) + GetServiceDataLength()))); } /** @@ -734,18 +784,14 @@ public: * * @returns length of the Service Data field in bytes. */ - uint8_t GetServiceDataLength(void) { - return *GetServiceDataLengthLocation(); - } + uint8_t GetServiceDataLength(void) { return *GetServiceDataLengthLocation(); } /** * This method sets Service Data length. * * @param aServiceDataLength desired length of the Service Data field in bytes. */ - void SetServiceDataLength(uint8_t aServiceDataLength) { - *GetServiceDataLengthLocation() = aServiceDataLength; - } + void SetServiceDataLength(uint8_t aServiceDataLength) { *GetServiceDataLengthLocation() = aServiceDataLength; } /** * This method returns a pointer to the Service Data. @@ -762,7 +808,8 @@ public: * @param aServiceData pointer to the service data to use * @param aServiceDataLength length of the provided service data in bytes */ - void SetServiceData(const uint8_t *aServiceData, uint8_t aServiceDataLength) { + void SetServiceData(const uint8_t *aServiceData, uint8_t aServiceDataLength) + { SetServiceDataLength(aServiceDataLength); memcpy(GetServiceData(), aServiceData, aServiceDataLength); @@ -773,11 +820,14 @@ public: * * @returns Enterprise Number */ - uint32_t GetEnterpriseNumber(void) { - if (IsThreadEnterprise()) { + uint32_t GetEnterpriseNumber(void) + { + if (IsThreadEnterprise()) + { return THREAD_ENTERPRISE_NUMBER; } - else { + else + { // This memory access most likely will not be aligned to 4 bytes return HostSwap32(*reinterpret_cast(GetEnterpriseNumberLocation())); } @@ -788,9 +838,7 @@ public: * * @returns Flag whether Enterprise Number is equal to THREAD_ENTERPRISE_NUMBER */ - bool IsThreadEnterprise(void) const { - return (mTResSId & kTMask) != 0; - } + bool IsThreadEnterprise(void) const { return (mTResSId & kTMask) != 0; } /** * This method sets Enterprise Number and updates the T flag. @@ -801,11 +849,14 @@ public: * * @param [in] aEnterpriseNumber Enterprise Number */ - void SetEnterpriseNumber(uint32_t aEnterpriseNumber) { - if (aEnterpriseNumber == THREAD_ENTERPRISE_NUMBER) { + void SetEnterpriseNumber(uint32_t aEnterpriseNumber) + { + if (aEnterpriseNumber == THREAD_ENTERPRISE_NUMBER) + { mTResSId |= kTMask; } - else { + else + { mTResSId &= ~kTMask; // This memory access most likely will not be aligned to 4 bytes @@ -818,11 +869,14 @@ public: * * @returns length of the S_enterprise_number field in bytes */ - static uint8_t GetEnterpriseNumberFieldLength(uint32_t aEnterpriseNumber) { - if (aEnterpriseNumber == THREAD_ENTERPRISE_NUMBER) { + static uint8_t GetEnterpriseNumberFieldLength(uint32_t aEnterpriseNumber) + { + if (aEnterpriseNumber == THREAD_ENTERPRISE_NUMBER) + { return 0; } - else { + else + { return (sizeof(aEnterpriseNumber)); } } @@ -832,16 +886,15 @@ public: * * @returns Service ID */ - uint8_t GetServiceID(void) const { - return (mTResSId & kSIdMask) >> kSIdOffset; - } + uint8_t GetServiceID(void) const { return (mTResSId & kSIdMask) >> kSIdOffset; } /** * This method sets Service ID. * * @param [in] aServiceID Service ID to be set. Expected range: 0x00-0x0f. */ - void SetServiceID(uint8_t aServiceID) { + void SetServiceID(uint8_t aServiceID) + { mTResSId = static_cast((mTResSId & ~kSIdMask) | (aServiceID << kSIdOffset)); } @@ -851,9 +904,10 @@ public: * @returns The Sub-TLVs length in bytes. * */ - uint8_t GetSubTlvsLength(void) { - return GetLength() - (sizeof(*this) - sizeof(NetworkDataTlv)) - (IsThreadEnterprise() ? 0 : sizeof(uint32_t)) - - sizeof(uint8_t)/* mServiceDataLength */ - GetServiceDataLength(); + uint8_t GetSubTlvsLength(void) + { + return GetLength() - (sizeof(*this) - sizeof(NetworkDataTlv)) - (IsThreadEnterprise() ? 0 : sizeof(uint32_t)) - + sizeof(uint8_t) /* mServiceDataLength */ - GetServiceDataLength(); } /** @@ -862,9 +916,10 @@ public: * @param[in] aLength The Sub-TLVs length in bytes. * */ - void SetSubTlvsLength(uint8_t aLength) { - SetLength(sizeof(*this) - sizeof(NetworkDataTlv) + (IsThreadEnterprise() ? 0 : sizeof(uint32_t)) - + sizeof(uint8_t)/* mServiceDataLength */ + GetServiceDataLength() + aLength); + void SetSubTlvsLength(uint8_t aLength) + { + SetLength(sizeof(*this) - sizeof(NetworkDataTlv) + (IsThreadEnterprise() ? 0 : sizeof(uint32_t)) + + sizeof(uint8_t) /* mServiceDataLength */ + GetServiceDataLength() + aLength); } /** @@ -873,8 +928,10 @@ public: * @returns A pointer to the Sub-TLVs. * */ - NetworkDataTlv *GetSubTlvs(void) { - return reinterpret_cast(GetServiceDataLengthLocation() + sizeof(uint8_t) + GetServiceDataLength()); + NetworkDataTlv *GetSubTlvs(void) + { + return reinterpret_cast(GetServiceDataLengthLocation() + sizeof(uint8_t) + + GetServiceDataLength()); } private: @@ -883,7 +940,8 @@ private: * * @returns pointer to service data length location */ - uint8_t *GetServiceDataLengthLocation(void) { + uint8_t *GetServiceDataLengthLocation(void) + { return GetEnterpriseNumberLocation() + (IsThreadEnterprise() ? 0 : sizeof(uint32_t)); } @@ -894,16 +952,14 @@ private: * * @returns pointer to enterprise number location */ - uint8_t *GetEnterpriseNumberLocation(void) { - return &mTResSId + sizeof(mTResSId); - } + uint8_t *GetEnterpriseNumberLocation(void) { return &mTResSId + sizeof(mTResSId); } enum { - kTOffset = 7, - kTMask = 0x1 << kTOffset, + kTOffset = 7, + kTMask = 0x1 << kTOffset, kSIdOffset = 0, - kSIdMask = 0xf << kSIdOffset, + kSIdMask = 0xf << kSIdOffset, }; uint8_t mTResSId; @@ -914,14 +970,19 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ServerTlv: public NetworkDataTlv +class ServerTlv : public NetworkDataTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { NetworkDataTlv::Init(); SetType(kTypeServer); SetLength(sizeof(*this) - sizeof(NetworkDataTlv)); } + void Init(void) + { + NetworkDataTlv::Init(); + SetType(kTypeServer); + SetLength(sizeof(*this) - sizeof(NetworkDataTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -930,9 +991,7 @@ public: * @retval FALSE If the TLV does not appear to be well-formed. * */ - bool IsValid(void) const { - return GetLength() >= (sizeof(*this) - sizeof(NetworkDataTlv)); - } + bool IsValid(void) const { return GetLength() >= (sizeof(*this) - sizeof(NetworkDataTlv)); } /** * This method returns the S_server_16 value. @@ -964,7 +1023,8 @@ public: * @param aServerData pointer to the server data to use * @param aServerDataLength length of the provided server data in bytes */ - void SetServerData(const uint8_t *aServerData, uint8_t aServerDataLength) { + void SetServerData(const uint8_t *aServerData, uint8_t aServerDataLength) + { SetLength(sizeof(*this) - sizeof(NetworkDataTlv) + aServerDataLength); memcpy(reinterpret_cast(this) + sizeof(*this), aServerData, aServerDataLength); } @@ -975,9 +1035,7 @@ public: * @returns The Server Data length in bytes. * */ - uint8_t GetServerDataLength(void) const { - return GetLength() - (sizeof(*this) - sizeof(NetworkDataTlv)); - } + uint8_t GetServerDataLength(void) const { return GetLength() - (sizeof(*this) - sizeof(NetworkDataTlv)); } private: uint16_t mServer16; @@ -988,7 +1046,7 @@ private: * */ -} // namespace NetworkData -} // namespace ot +} // namespace NetworkData +} // namespace ot -#endif // NETWORK_DATA_TLVS_HPP_ +#endif // NETWORK_DATA_TLVS_HPP_ diff --git a/src/core/thread/network_diagnostic.cpp b/src/core/thread/network_diagnostic.cpp index 0ef052937..eaf483898 100644 --- a/src/core/thread/network_diagnostic.cpp +++ b/src/core/thread/network_diagnostic.cpp @@ -40,17 +40,17 @@ #include "coap/coap_header.hpp" #include "common/code_utils.hpp" #include "common/debug.hpp" +#include "common/encoding.hpp" #include "common/instance.hpp" #include "common/logging.hpp" -#include "common/encoding.hpp" #include "mac/mac_frame.hpp" #include "net/netif.hpp" #include "thread/mesh_forwarder.hpp" #include "thread/mle_router.hpp" +#include "thread/network_diagnostic_tlvs.hpp" #include "thread/thread_netif.hpp" #include "thread/thread_tlvs.hpp" #include "thread/thread_uri_paths.hpp" -#include "thread/network_diagnostic_tlvs.hpp" using ot::Encoding::BigEndian::HostSwap16; @@ -60,14 +60,14 @@ namespace ot { namespace NetworkDiagnostic { -NetworkDiagnostic::NetworkDiagnostic(Instance &aInstance) : - InstanceLocator(aInstance), - mDiagnosticGetRequest(OT_URI_PATH_DIAGNOSTIC_GET_REQUEST, &NetworkDiagnostic::HandleDiagnosticGetRequest, this), - mDiagnosticGetQuery(OT_URI_PATH_DIAGNOSTIC_GET_QUERY, &NetworkDiagnostic::HandleDiagnosticGetQuery, this), - mDiagnosticGetAnswer(OT_URI_PATH_DIAGNOSTIC_GET_ANSWER, &NetworkDiagnostic::HandleDiagnosticGetAnswer, this), - mDiagnosticReset(OT_URI_PATH_DIAGNOSTIC_RESET, &NetworkDiagnostic::HandleDiagnosticReset, this), - mReceiveDiagnosticGetCallback(NULL), - mReceiveDiagnosticGetCallbackContext(NULL) +NetworkDiagnostic::NetworkDiagnostic(Instance &aInstance) + : InstanceLocator(aInstance) + , mDiagnosticGetRequest(OT_URI_PATH_DIAGNOSTIC_GET_REQUEST, &NetworkDiagnostic::HandleDiagnosticGetRequest, this) + , mDiagnosticGetQuery(OT_URI_PATH_DIAGNOSTIC_GET_QUERY, &NetworkDiagnostic::HandleDiagnosticGetQuery, this) + , mDiagnosticGetAnswer(OT_URI_PATH_DIAGNOSTIC_GET_ANSWER, &NetworkDiagnostic::HandleDiagnosticGetAnswer, this) + , mDiagnosticReset(OT_URI_PATH_DIAGNOSTIC_RESET, &NetworkDiagnostic::HandleDiagnosticReset, this) + , mReceiveDiagnosticGetCallback(NULL) + , mReceiveDiagnosticGetCallbackContext(NULL) { GetNetif().GetCoap().AddResource(mDiagnosticGetRequest); GetNetif().GetCoap().AddResource(mDiagnosticGetQuery); @@ -76,20 +76,21 @@ NetworkDiagnostic::NetworkDiagnostic(Instance &aInstance) : } void NetworkDiagnostic::SetReceiveDiagnosticGetCallback(otReceiveDiagnosticGetCallback aCallback, - void *aCallbackContext) + void * aCallbackContext) { - mReceiveDiagnosticGetCallback = aCallback; + mReceiveDiagnosticGetCallback = aCallback; mReceiveDiagnosticGetCallbackContext = aCallbackContext; } -otError NetworkDiagnostic::SendDiagnosticGet(const Ip6::Address &aDestination, const uint8_t aTlvTypes[], - uint8_t aCount) +otError NetworkDiagnostic::SendDiagnosticGet(const Ip6::Address &aDestination, + const uint8_t aTlvTypes[], + uint8_t aCount) { - ThreadNetif &netif = GetNetif(); - otError error; - Message *message = NULL; - Coap::Header header; - Ip6::MessageInfo messageInfo; + ThreadNetif & netif = GetNetif(); + otError error; + Message * message = NULL; + Coap::Header header; + Ip6::MessageInfo messageInfo; otCoapResponseHandler handler = NULL; if (aDestination.IsMulticast()) @@ -141,18 +142,21 @@ exit: return error; } -void NetworkDiagnostic::HandleDiagnosticGetResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError aResult) +void NetworkDiagnostic::HandleDiagnosticGetResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aResult) { - static_cast(aContext)->HandleDiagnosticGetResponse(*static_cast(aHeader), - *static_cast(aMessage), - *static_cast(aMessageInfo), - aResult); + static_cast(aContext)->HandleDiagnosticGetResponse( + *static_cast(aHeader), *static_cast(aMessage), + *static_cast(aMessageInfo), aResult); } -void NetworkDiagnostic::HandleDiagnosticGetResponse(Coap::Header &aHeader, Message &aMessage, +void NetworkDiagnostic::HandleDiagnosticGetResponse(Coap::Header & aHeader, + Message & aMessage, const Ip6::MessageInfo &aMessageInfo, - otError aResult) + otError aResult) { VerifyOrExit(aResult == OT_ERROR_NONE); VerifyOrExit(aHeader.GetCode() == OT_COAP_CODE_CHANGED); @@ -168,19 +172,21 @@ exit: return; } -void NetworkDiagnostic::HandleDiagnosticGetAnswer(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void NetworkDiagnostic::HandleDiagnosticGetAnswer(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleDiagnosticGetAnswer(*static_cast(aHeader), - *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleDiagnosticGetAnswer( + *static_cast(aHeader), *static_cast(aMessage), + *static_cast(aMessageInfo)); } -void NetworkDiagnostic::HandleDiagnosticGetAnswer(Coap::Header &aHeader, Message &aMessage, +void NetworkDiagnostic::HandleDiagnosticGetAnswer(Coap::Header & aHeader, + Message & aMessage, const Ip6::MessageInfo &aMessageInfo) { - VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && - aHeader.GetCode() == OT_COAP_CODE_POST); + VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && aHeader.GetCode() == OT_COAP_CODE_POST); otLogInfoNetDiag(GetInstance(), "Diagnostic get answer received"); @@ -199,10 +205,10 @@ exit: otError NetworkDiagnostic::AppendIp6AddressList(Message &aMessage) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; Ip6AddressListTlv tlv; - uint8_t count = 0; + uint8_t count = 0; tlv.Init(); @@ -226,13 +232,13 @@ exit: otError NetworkDiagnostic::AppendChildTable(Message &aMessage) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - uint8_t count = 0; - uint8_t timeout = 0; - uint8_t numChildren; - const Child *children = netif.GetMle().GetChildren(&numChildren); - ChildTableTlv tlv; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + uint8_t count = 0; + uint8_t timeout = 0; + uint8_t numChildren; + const Child * children = netif.GetMle().GetChildren(&numChildren); + ChildTableTlv tlv; ChildTableEntry entry; tlv.Init(); @@ -255,7 +261,10 @@ otError NetworkDiagnostic::AppendChildTable(Message &aMessage) { timeout = 0; - while (static_cast(1 << timeout) < children[i].GetTimeout()) { timeout++; } + while (static_cast(1 << timeout) < children[i].GetTimeout()) + { + timeout++; + } entry.SetReserved(0); entry.SetTimeout(timeout + 4); @@ -271,13 +280,14 @@ exit: return error; } -otError NetworkDiagnostic::FillRequestedTlvs(Message &aRequest, Message &aResponse, +otError NetworkDiagnostic::FillRequestedTlvs(Message & aRequest, + Message & aResponse, NetworkDiagnosticTlv &aNetworkDiagnosticTlv) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - uint16_t offset = 0; - uint8_t type; + ThreadNetif &netif = GetNetif(); + otError error = OT_ERROR_NONE; + uint16_t offset = 0; + uint8_t type; offset = aRequest.GetOffset() + sizeof(NetworkDiagnosticTlv); @@ -439,7 +449,9 @@ exit: return error; } -void NetworkDiagnostic::HandleDiagnosticGetQuery(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void NetworkDiagnostic::HandleDiagnosticGetQuery(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { static_cast(aContext)->HandleDiagnosticGetQuery( @@ -447,22 +459,24 @@ void NetworkDiagnostic::HandleDiagnosticGetQuery(void *aContext, otCoapHeader *a *static_cast(aMessageInfo)); } -void NetworkDiagnostic::HandleDiagnosticGetQuery(Coap::Header &aHeader, Message &aMessage, +void NetworkDiagnostic::HandleDiagnosticGetQuery(Coap::Header & aHeader, + Message & aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Message *message = NULL; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Message * message = NULL; NetworkDiagnosticTlv networkDiagnosticTlv; - Coap::Header header; - Ip6::MessageInfo messageInfo; + Coap::Header header; + Ip6::MessageInfo messageInfo; VerifyOrExit(aHeader.GetCode() == OT_COAP_CODE_POST, error = OT_ERROR_DROP); otLogInfoNetDiag(GetInstance(), "Received diagnostic get query"); - VerifyOrExit((aMessage.Read(aMessage.GetOffset(), sizeof(NetworkDiagnosticTlv), - &networkDiagnosticTlv) == sizeof(NetworkDiagnosticTlv)), error = OT_ERROR_DROP); + VerifyOrExit((aMessage.Read(aMessage.GetOffset(), sizeof(NetworkDiagnosticTlv), &networkDiagnosticTlv) == + sizeof(NetworkDiagnosticTlv)), + error = OT_ERROR_DROP); VerifyOrExit(networkDiagnosticTlv.GetType() == NetworkDiagnosticTlv::kTypeList, error = OT_ERROR_DROP); @@ -512,7 +526,9 @@ exit: } } -void NetworkDiagnostic::HandleDiagnosticGetRequest(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void NetworkDiagnostic::HandleDiagnosticGetRequest(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { static_cast(aContext)->HandleDiagnosticGetRequest( @@ -520,23 +536,25 @@ void NetworkDiagnostic::HandleDiagnosticGetRequest(void *aContext, otCoapHeader *static_cast(aMessageInfo)); } -void NetworkDiagnostic::HandleDiagnosticGetRequest(Coap::Header &aHeader, Message &aMessage, +void NetworkDiagnostic::HandleDiagnosticGetRequest(Coap::Header & aHeader, + Message & aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Message *message = NULL; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Message * message = NULL; NetworkDiagnosticTlv networkDiagnosticTlv; - Coap::Header header; - Ip6::MessageInfo messageInfo(aMessageInfo); + Coap::Header header; + Ip6::MessageInfo messageInfo(aMessageInfo); - VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && - aHeader.GetCode() == OT_COAP_CODE_POST, error = OT_ERROR_DROP); + VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && aHeader.GetCode() == OT_COAP_CODE_POST, + error = OT_ERROR_DROP); otLogInfoNetDiag(GetInstance(), "Received diagnostic get request"); - VerifyOrExit((aMessage.Read(aMessage.GetOffset(), sizeof(NetworkDiagnosticTlv), - &networkDiagnosticTlv) == sizeof(NetworkDiagnosticTlv)), error = OT_ERROR_DROP); + VerifyOrExit((aMessage.Read(aMessage.GetOffset(), sizeof(NetworkDiagnosticTlv), &networkDiagnosticTlv) == + sizeof(NetworkDiagnosticTlv)), + error = OT_ERROR_DROP); VerifyOrExit(networkDiagnosticTlv.GetType() == NetworkDiagnosticTlv::kTypeList, error = OT_ERROR_DROP); @@ -567,13 +585,14 @@ exit: } } -otError NetworkDiagnostic::SendDiagnosticReset(const Ip6::Address &aDestination, const uint8_t aTlvTypes[], - uint8_t aCount) +otError NetworkDiagnostic::SendDiagnosticReset(const Ip6::Address &aDestination, + const uint8_t aTlvTypes[], + uint8_t aCount) { - ThreadNetif &netif = GetNetif(); - otError error; - Message *message = NULL; - Coap::Header header; + ThreadNetif & netif = GetNetif(); + otError error; + Message * message = NULL; + Coap::Header header; Ip6::MessageInfo messageInfo; header.Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); @@ -615,7 +634,9 @@ exit: return error; } -void NetworkDiagnostic::HandleDiagnosticReset(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void NetworkDiagnostic::HandleDiagnosticReset(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { static_cast(aContext)->HandleDiagnosticReset( @@ -623,21 +644,21 @@ void NetworkDiagnostic::HandleDiagnosticReset(void *aContext, otCoapHeader *aHea *static_cast(aMessageInfo)); } -void NetworkDiagnostic::HandleDiagnosticReset(Coap::Header &aHeader, Message &aMessage, +void NetworkDiagnostic::HandleDiagnosticReset(Coap::Header & aHeader, + Message & aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - uint16_t offset = 0; - uint8_t type; + ThreadNetif & netif = GetNetif(); + uint16_t offset = 0; + uint8_t type; NetworkDiagnosticTlv networkDiagnosticTlv; otLogInfoNetDiag(GetInstance(), "Received diagnostic reset request"); - VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && - aHeader.GetCode() == OT_COAP_CODE_POST); + VerifyOrExit(aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE && aHeader.GetCode() == OT_COAP_CODE_POST); - VerifyOrExit((aMessage.Read(aMessage.GetOffset(), sizeof(NetworkDiagnosticTlv), - &networkDiagnosticTlv) == sizeof(NetworkDiagnosticTlv))); + VerifyOrExit((aMessage.Read(aMessage.GetOffset(), sizeof(NetworkDiagnosticTlv), &networkDiagnosticTlv) == + sizeof(NetworkDiagnosticTlv))); VerifyOrExit(networkDiagnosticTlv.GetType() == NetworkDiagnosticTlv::kTypeList); @@ -670,8 +691,8 @@ exit: return; } -} // namespace NetworkDiagnostic +} // namespace NetworkDiagnostic -} // namespace ot +} // namespace ot #endif // OPENTHREAD_FTD || OPENTHREAD_ENABLE_MTD_NETWORK_DIAGNOSTIC diff --git a/src/core/thread/network_diagnostic.hpp b/src/core/thread/network_diagnostic.hpp index 3e6f1d7b2..1e81d753e 100644 --- a/src/core/thread/network_diagnostic.hpp +++ b/src/core/thread/network_diagnostic.hpp @@ -63,7 +63,7 @@ class NetworkDiagnosticTlv; * This class implements the Network Diagnostic processing. * */ -class NetworkDiagnostic: public InstanceLocator +class NetworkDiagnostic : public InstanceLocator { public: /** @@ -104,31 +104,43 @@ public: otError SendDiagnosticReset(const Ip6::Address &aDestination, const uint8_t aTlvTypes[], uint8_t aCount); private: - otError AppendIp6AddressList(Message &aMessage); otError AppendChildTable(Message &aMessage); otError FillRequestedTlvs(Message &aRequest, Message &aResponse, NetworkDiagnosticTlv &aNetworkDiagnosticTlv); - static void HandleDiagnosticGetRequest(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleDiagnosticGetRequest(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); void HandleDiagnosticGetRequest(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - static void HandleDiagnosticGetQuery(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleDiagnosticGetQuery(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); void HandleDiagnosticGetQuery(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - static void HandleDiagnosticGetResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError aResult); - void HandleDiagnosticGetResponse(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - otError aResult); + static void HandleDiagnosticGetResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aResult); + void HandleDiagnosticGetResponse(Coap::Header & aHeader, + Message & aMessage, + const Ip6::MessageInfo &aMessageInfo, + otError aResult); - static void HandleDiagnosticGetAnswer(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleDiagnosticGetAnswer(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); void HandleDiagnosticGetAnswer(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - static void HandleDiagnosticReset(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleDiagnosticReset(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - void HandleDiagnosticReset(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + void HandleDiagnosticReset(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); Coap::Resource mDiagnosticGetRequest; Coap::Resource mDiagnosticGetQuery; @@ -136,7 +148,7 @@ private: Coap::Resource mDiagnosticReset; otReceiveDiagnosticGetCallback mReceiveDiagnosticGetCallback; - void *mReceiveDiagnosticGetCallbackContext; + void * mReceiveDiagnosticGetCallbackContext; }; /** @@ -144,6 +156,6 @@ private: */ } // namespace NetworkDiagnostic -} // namespace ot +} // namespace ot -#endif // NETWORK_DIAGNOSTIC_HPP_ +#endif // NETWORK_DIAGNOSTIC_HPP_ diff --git a/src/core/thread/network_diagnostic_tlvs.hpp b/src/core/thread/network_diagnostic_tlvs.hpp index 23dba5f02..1d7baf4ad 100644 --- a/src/core/thread/network_diagnostic_tlvs.hpp +++ b/src/core/thread/network_diagnostic_tlvs.hpp @@ -67,7 +67,7 @@ namespace NetworkDiagnostic { enum { kNumResetTlvTypes = 1, - kNumTlvTypes = 18, + kNumTlvTypes = 18, }; /** @@ -84,23 +84,23 @@ public: */ enum Type { - kExtMacAddress = 0, ///< Source Address TLV - kAddress16 = 1, ///< Address16 TLV - kMode = 2, ///< Mode TLV - kTimeout = 3, ///< Timeout TLV - kConnectivity = 4, ///< Connectivity TLV - kRoute = 5, ///< Routing-Table TLV - kLeaderData = 6, ///< Leader Data TLV - kNetworkData = 7, ///< Network Data TLV - kIp6AddressList = 8, ///< Ip6 Address List TLV - kMacCounters = 9, ///< Mac Counters TLV - kBatteryLevel = 14, ///< Battery Level TLV - kSupplyVoltage = 15, ///< Supply Voltage TLV - kChildTable = 16, ///< Child Table TLV - kChannelPages = 17, ///< Channel Pages TLV - kTypeList = 18, ///< Type List TLV - kMaxChildTimeout = 19, ///< Max Child Timeout TLV - kInvalid = 255, + kExtMacAddress = 0, ///< Source Address TLV + kAddress16 = 1, ///< Address16 TLV + kMode = 2, ///< Mode TLV + kTimeout = 3, ///< Timeout TLV + kConnectivity = 4, ///< Connectivity TLV + kRoute = 5, ///< Routing-Table TLV + kLeaderData = 6, ///< Leader Data TLV + kNetworkData = 7, ///< Network Data TLV + kIp6AddressList = 8, ///< Ip6 Address List TLV + kMacCounters = 9, ///< Mac Counters TLV + kBatteryLevel = 14, ///< Battery Level TLV + kSupplyVoltage = 15, ///< Supply Voltage TLV + kChildTable = 16, ///< Child Table TLV + kChannelPages = 17, ///< Channel Pages TLV + kTypeList = 18, ///< Type List TLV + kMaxChildTimeout = 19, ///< Max Child Timeout TLV + kInvalid = 255, }; /** @@ -131,7 +131,8 @@ public: * @retval OT_ERROR_NOT_FOUND Could not find the TLV with Type @p aType. * */ - static otError GetTlv(const Message &aMessage, Type aType, uint16_t aMaxLength, Tlv &aTlv) { + static otError GetTlv(const Message &aMessage, Type aType, uint16_t aMaxLength, Tlv &aTlv) + { return ot::Tlv::Get(aMessage, static_cast(aType), aMaxLength, aTlv); } @@ -146,7 +147,8 @@ public: * @retval OT_ERROR_NOT_FOUND Could not find the TLV with Type @p aType. * */ - static otError GetOffset(const Message &aMessage, Type aType, uint16_t &aOffset) { + static otError GetOffset(const Message &aMessage, Type aType, uint16_t &aOffset) + { return ot::Tlv::GetOffset(aMessage, static_cast(aType), aOffset); } @@ -156,14 +158,18 @@ public: * This class implements Extended Address TLV generation and parsing. * */ -class ExtMacAddressTlv: public NetworkDiagnosticTlv +class ExtMacAddressTlv : public NetworkDiagnosticTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kExtMacAddress); SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); } + void Init(void) + { + SetType(kExtMacAddress); + SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -199,14 +205,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class Address16Tlv: public NetworkDiagnosticTlv +class Address16Tlv : public NetworkDiagnosticTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kAddress16); SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); } + void Init(void) + { + SetType(kAddress16); + SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -242,14 +252,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ModeTlv: public NetworkDiagnosticTlv +class ModeTlv : public NetworkDiagnosticTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kMode); SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); } + void Init(void) + { + SetType(kMode); + SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -293,14 +307,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class TimeoutTlv: public NetworkDiagnosticTlv +class TimeoutTlv : public NetworkDiagnosticTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kTimeout); SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); } + void Init(void) + { + SetType(kTimeout); + SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -336,14 +354,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ConnectivityTlv: public NetworkDiagnosticTlv +class ConnectivityTlv : public NetworkDiagnosticTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kConnectivity); SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); } + void Init(void) + { + SetType(kConnectivity); + SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -352,9 +374,11 @@ public: * @retval FALSE If the TLV does not appear to be well-formed. * */ - bool IsValid(void) const { + bool IsValid(void) const + { return (GetLength() == sizeof(*this) - sizeof(NetworkDiagnosticTlv) || - GetLength() == sizeof(*this) - sizeof(NetworkDiagnosticTlv) - sizeof(mSedBufferSize) - sizeof(mSedDatagramCount)); + GetLength() == + sizeof(*this) - sizeof(NetworkDiagnosticTlv) - sizeof(mSedBufferSize) - sizeof(mSedDatagramCount)); } /** @@ -371,7 +395,8 @@ public: * @param[in] aParentPriority The Parent Priority value. * */ - void SetParentPriority(int8_t aParentPriority) { + void SetParentPriority(int8_t aParentPriority) + { mParentPriority = (aParentPriority << kParentPriorityOffset) & kParentPriorityMask; } @@ -507,7 +532,7 @@ private: enum { kParentPriorityOffset = 6, - kParentPriorityMask = 3 << kParentPriorityOffset, + kParentPriorityMask = 3 << kParentPriorityOffset, }; uint8_t mParentPriority; @@ -519,21 +544,25 @@ private: uint8_t mActiveRouters; uint16_t mSedBufferSize; uint8_t mSedDatagramCount; -} OT_TOOL_PACKED_END; +} OT_TOOL_PACKED_END; /** * This class implements Route TLV generation and parsing. * */ OT_TOOL_PACKED_BEGIN -class RouteTlv: public NetworkDiagnosticTlv +class RouteTlv : public NetworkDiagnosticTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kRoute); SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); } + void Init(void) + { + SetType(kRoute); + SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -542,7 +571,8 @@ public: * @retval FALSE If the TLV does not appear to be well-formed. * */ - bool IsValid(void) const { + bool IsValid(void) const + { return GetLength() >= sizeof(mRouterIdSequence) + sizeof(mRouterIdMask) && GetLength() <= sizeof(*this) - sizeof(NetworkDiagnosticTlv); } @@ -578,7 +608,8 @@ public: * @retval FALSE If the Router ID bit is not set. * */ - bool IsRouterIdSet(uint8_t aRouterId) const { + bool IsRouterIdSet(uint8_t aRouterId) const + { return (mRouterIdMask[aRouterId / 8] & (0x80 >> (aRouterId % 8))) != 0; } @@ -604,9 +635,7 @@ public: * @param[in] aLength The Route Data Length value. * */ - void SetRouteDataLength(uint8_t aLength) { - SetLength(sizeof(mRouterIdSequence) + sizeof(mRouterIdMask) + aLength); - } + void SetRouteDataLength(uint8_t aLength) { SetLength(sizeof(mRouterIdSequence) + sizeof(mRouterIdMask) + aLength); } /** * This method returns the Route Cost value for a given Router ID. @@ -614,9 +643,7 @@ public: * @returns The Route Cost value for a given Router ID. * */ - uint8_t GetRouteCost(uint8_t aRouterId) const { - return mRouteData[aRouterId] & kRouteCostMask; - } + uint8_t GetRouteCost(uint8_t aRouterId) const { return mRouteData[aRouterId] & kRouteCostMask; } /** * This method sets the Route Cost value for a given Router ID. @@ -625,7 +652,8 @@ public: * @param[in] aRouteCost The Route Cost value. * */ - void SetRouteCost(uint8_t aRouterId, uint8_t aRouteCost) { + void SetRouteCost(uint8_t aRouterId, uint8_t aRouteCost) + { mRouteData[aRouterId] = (mRouteData[aRouterId] & ~kRouteCostMask) | aRouteCost; } @@ -635,7 +663,8 @@ public: * @returns The Link Quality In value for a given Router ID. * */ - uint8_t GetLinkQualityIn(uint8_t aRouterId) const { + uint8_t GetLinkQualityIn(uint8_t aRouterId) const + { return (mRouteData[aRouterId] & kLinkQualityInMask) >> kLinkQualityInOffset; } @@ -646,10 +675,10 @@ public: * @param[in] aLinkQuality The Link Quality In value for a given Router ID. * */ - void SetLinkQualityIn(uint8_t aRouterId, uint8_t aLinkQuality) { - mRouteData[aRouterId] = - (mRouteData[aRouterId] & ~kLinkQualityInMask) | - ((aLinkQuality << kLinkQualityInOffset) & kLinkQualityInMask); + void SetLinkQualityIn(uint8_t aRouterId, uint8_t aLinkQuality) + { + mRouteData[aRouterId] = (mRouteData[aRouterId] & ~kLinkQualityInMask) | + ((aLinkQuality << kLinkQualityInOffset) & kLinkQualityInMask); } /** @@ -658,7 +687,8 @@ public: * @returns The Link Quality Out value for a given Router ID. * */ - uint8_t GetLinkQualityOut(uint8_t aRouterId) const { + uint8_t GetLinkQualityOut(uint8_t aRouterId) const + { return (mRouteData[aRouterId] & kLinkQualityOutMask) >> kLinkQualityOutOffset; } @@ -669,21 +699,21 @@ public: * @param[in] aLinkQuality The Link Quality Out value for a given Router ID. * */ - void SetLinkQualityOut(uint8_t aRouterId, uint8_t aLinkQuality) { - mRouteData[aRouterId] = - (mRouteData[aRouterId] & ~kLinkQualityOutMask) | - ((aLinkQuality << kLinkQualityOutOffset) & kLinkQualityOutMask); + void SetLinkQualityOut(uint8_t aRouterId, uint8_t aLinkQuality) + { + mRouteData[aRouterId] = (mRouteData[aRouterId] & ~kLinkQualityOutMask) | + ((aLinkQuality << kLinkQualityOutOffset) & kLinkQualityOutMask); } private: enum { kLinkQualityOutOffset = 6, - kLinkQualityOutMask = 3 << kLinkQualityOutOffset, - kLinkQualityInOffset = 4, - kLinkQualityInMask = 3 << kLinkQualityInOffset, - kRouteCostOffset = 0, - kRouteCostMask = 0xf << kRouteCostOffset, + kLinkQualityOutMask = 3 << kLinkQualityOutOffset, + kLinkQualityInOffset = 4, + kLinkQualityInMask = 3 << kLinkQualityInOffset, + kRouteCostOffset = 0, + kRouteCostMask = 0xf << kRouteCostOffset, }; uint8_t mRouterIdSequence; uint8_t mRouterIdMask[BitVectorBytes(Mle::kMaxRouterId)]; @@ -695,14 +725,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class LeaderDataTlv: public NetworkDiagnosticTlv +class LeaderDataTlv : public NetworkDiagnosticTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kLeaderData); SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); } + void Init(void) + { + SetType(kLeaderData); + SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -759,7 +793,7 @@ public: * @param[in] aVersion The Data Version value. * */ - void SetDataVersion(uint8_t aVersion) { mDataVersion = aVersion; } + void SetDataVersion(uint8_t aVersion) { mDataVersion = aVersion; } /** * This method returns the Stable Data Version value. @@ -795,10 +829,10 @@ public: private: uint32_t mPartitionId; - uint8_t mWeighting; - uint8_t mDataVersion; - uint8_t mStableDataVersion; - uint8_t mLeaderRouterId; + uint8_t mWeighting; + uint8_t mDataVersion; + uint8_t mStableDataVersion; + uint8_t mLeaderRouterId; } OT_TOOL_PACKED_END; /** @@ -806,14 +840,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class NetworkDataTlv: public NetworkDiagnosticTlv +class NetworkDataTlv : public NetworkDiagnosticTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kNetworkData); SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); } + void Init(void) + { + SetType(kNetworkData); + SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -849,19 +887,23 @@ private: * */ OT_TOOL_PACKED_BEGIN -class Ip6AddressListTlv: public NetworkDiagnosticTlv +class Ip6AddressListTlv : public NetworkDiagnosticTlv { public: enum { - kMaxSize = 8, ///< Maximum size in bytes (Thread Specification). + kMaxSize = 8, ///< Maximum size in bytes (Thread Specification). }; /** * This method initializes the TLV. * */ - void Init(void) { SetType(kIp6AddressList); SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); } + void Init(void) + { + SetType(kIp6AddressList); + SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -880,7 +922,8 @@ public: * @returns A reference to the IPv6 address. * */ - const Ip6::Address &GetIp6Address(uint8_t aIndex) const { + const Ip6::Address &GetIp6Address(uint8_t aIndex) const + { return *reinterpret_cast(GetValue() + (aIndex * sizeof(Ip6::Address))); } @@ -891,14 +934,18 @@ public: * */ OT_TOOL_PACKED_BEGIN -class MacCountersTlv: public NetworkDiagnosticTlv +class MacCountersTlv : public NetworkDiagnosticTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kMacCounters); SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); } + void Init(void) + { + SetType(kMacCounters); + SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -923,7 +970,10 @@ public: * @param[in] aIfInUnknownProtos The IfInUnknownProtos counter * */ - void SetIfInUnknownProtos(const uint32_t aIfInUnknownProtos) { mIfInUnknownProtos = HostSwap32(aIfInUnknownProtos); } + void SetIfInUnknownProtos(const uint32_t aIfInUnknownProtos) + { + mIfInUnknownProtos = HostSwap32(aIfInUnknownProtos); + } /** * This method returns the IfInErrors counter. @@ -986,7 +1036,10 @@ public: * @param[in] aIfInBroadcastPkts The IfInBroadcastPkts counter. * */ - void SetIfInBroadcastPkts(const uint32_t aIfInBroadcastPkts) { mIfInBroadcastPkts = HostSwap32(aIfInBroadcastPkts); } + void SetIfInBroadcastPkts(const uint32_t aIfInBroadcastPkts) + { + mIfInBroadcastPkts = HostSwap32(aIfInBroadcastPkts); + } /** * This method returns the IfInDiscards counter. @@ -1034,7 +1087,10 @@ public: * @param[in] aIfOutBroadcastPkts The IfOutBroadcastPkts counter. * */ - void SetIfOutBroadcastPkts(const uint32_t aIfOutBroadcastPkts) { mIfOutBroadcastPkts = HostSwap32(aIfOutBroadcastPkts); } + void SetIfOutBroadcastPkts(const uint32_t aIfOutBroadcastPkts) + { + mIfOutBroadcastPkts = HostSwap32(aIfOutBroadcastPkts); + } /** * This method returns the IfOutDiscards counter. @@ -1069,14 +1125,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class BatteryLevelTlv: public NetworkDiagnosticTlv +class BatteryLevelTlv : public NetworkDiagnosticTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kBatteryLevel); SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); } + void Init(void) + { + SetType(kBatteryLevel); + SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1107,20 +1167,23 @@ private: uint8_t mBatteryLevel; } OT_TOOL_PACKED_END; - /** * This class implements Supply Voltage TLV generation and parsing. * */ OT_TOOL_PACKED_BEGIN -class SupplyVoltageTlv: public NetworkDiagnosticTlv +class SupplyVoltageTlv : public NetworkDiagnosticTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kSupplyVoltage); SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); } + void Init(void) + { + SetType(kSupplyVoltage); + SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1163,9 +1226,11 @@ public: * Default constructor. * */ - ChildTableEntry(void): - mTimeoutRsvChildId(0), - mMode(0) {} + ChildTableEntry(void) + : mTimeoutRsvChildId(0) + , mMode(0) + { + } /** * This method returns the Timeout value. @@ -1181,7 +1246,8 @@ public: * @param[in] aTimeout The Timeout value. * */ - void SetTimeout(uint8_t aTimeout) { + void SetTimeout(uint8_t aTimeout) + { mTimeoutRsvChildId = HostSwap16((HostSwap16(mTimeoutRsvChildId) & ~kTimeoutMask) | ((aTimeout << kTimeoutOffset) & kTimeoutMask)); } @@ -1200,9 +1266,9 @@ public: * @param[in] aChildId The Child ID value. * */ - void SetChildId(uint16_t aChildId) { - mTimeoutRsvChildId = HostSwap16((HostSwap16(mTimeoutRsvChildId) & ~kChildIdMask) | - (aChildId & kChildIdMask)); + void SetChildId(uint16_t aChildId) + { + mTimeoutRsvChildId = HostSwap16((HostSwap16(mTimeoutRsvChildId) & ~kChildIdMask) | (aChildId & kChildIdMask)); } /** @@ -1235,7 +1301,8 @@ public: * @param[in] aReserved The Reserved value. * */ - void SetReserved(uint8_t aReserved) { + void SetReserved(uint8_t aReserved) + { mTimeoutRsvChildId = HostSwap16((HostSwap16(mTimeoutRsvChildId) & ~kReservedMask) | ((aReserved << kReservedOffset) & kReservedMask)); } @@ -1263,14 +1330,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ChildTableTlv: public NetworkDiagnosticTlv +class ChildTableTlv : public NetworkDiagnosticTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kChildTable); SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); } + void Init(void) + { + SetType(kChildTable); + SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1296,26 +1367,30 @@ public: * * @returns A reference to the Child Table entry. */ - ChildTableEntry &GetEntry(uint8_t aIndex) { + ChildTableEntry &GetEntry(uint8_t aIndex) + { return *reinterpret_cast(GetValue() + (aIndex * sizeof(ChildTableEntry))); } } OT_TOOL_PACKED_END; - /** * This class implements Channel Pages TLV generation and parsing. * */ OT_TOOL_PACKED_BEGIN -class ChannelPagesTlv: public NetworkDiagnosticTlv +class ChannelPagesTlv : public NetworkDiagnosticTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kChannelPages); SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); } + void Init(void) + { + SetType(kChannelPages); + SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1337,14 +1412,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class TypeListTlv: public NetworkDiagnosticTlv +class TypeListTlv : public NetworkDiagnosticTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kTypeList); SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); } + void Init(void) + { + SetType(kTypeList); + SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1368,14 +1447,18 @@ public: * */ OT_TOOL_PACKED_BEGIN -class MaxChildTimeoutTlv: public NetworkDiagnosticTlv +class MaxChildTimeoutTlv : public NetworkDiagnosticTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kMaxChildTimeout); SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); } + void Init(void) + { + SetType(kMaxChildTimeout); + SetLength(sizeof(*this) - sizeof(NetworkDiagnosticTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -1411,9 +1494,8 @@ private: * */ -} // namespace NetworkDiagnostic +} // namespace NetworkDiagnostic +} // namespace ot -} // namespace ot - -#endif // NETWORK_DIAGNOSTIC_TLVS_HPP_ +#endif // NETWORK_DIAGNOSTIC_TLVS_HPP_ diff --git a/src/core/thread/panid_query_server.cpp b/src/core/thread/panid_query_server.cpp index f14ae5984..587667cb9 100644 --- a/src/core/thread/panid_query_server.cpp +++ b/src/core/thread/panid_query_server.cpp @@ -26,7 +26,6 @@ * POSSIBILITY OF SUCH DAMAGE. */ - /** * @file * This file implements the PAN ID Query Server. @@ -51,29 +50,31 @@ namespace ot { -PanIdQueryServer::PanIdQueryServer(Instance &aInstance) : - InstanceLocator(aInstance), - mChannelMask(0), - mPanId(Mac::kPanIdBroadcast), - mTimer(aInstance, &PanIdQueryServer::HandleTimer, this), - mPanIdQuery(OT_URI_PATH_PANID_QUERY, &PanIdQueryServer::HandleQuery, this) +PanIdQueryServer::PanIdQueryServer(Instance &aInstance) + : InstanceLocator(aInstance) + , mChannelMask(0) + , mPanId(Mac::kPanIdBroadcast) + , mTimer(aInstance, &PanIdQueryServer::HandleTimer, this) + , mPanIdQuery(OT_URI_PATH_PANID_QUERY, &PanIdQueryServer::HandleQuery, this) { GetNetif().GetCoap().AddResource(mPanIdQuery); } -void PanIdQueryServer::HandleQuery(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void PanIdQueryServer::HandleQuery(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->HandleQuery( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->HandleQuery(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } void PanIdQueryServer::HandleQuery(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - MeshCoP::PanIdTlv panId; + MeshCoP::PanIdTlv panId; MeshCoP::ChannelMask0Tlv channelMask; - Ip6::MessageInfo responseInfo(aMessageInfo); + Ip6::MessageInfo responseInfo(aMessageInfo); VerifyOrExit(aHeader.GetCode() == OT_COAP_CODE_POST); @@ -83,9 +84,9 @@ void PanIdQueryServer::HandleQuery(Coap::Header &aHeader, Message &aMessage, con SuccessOrExit(MeshCoP::Tlv::GetTlv(aMessage, MeshCoP::Tlv::kPanId, sizeof(panId), panId)); VerifyOrExit(panId.IsValid()); - mChannelMask = channelMask.GetMask(); + mChannelMask = channelMask.GetMask(); mCommissioner = aMessageInfo.GetPeerAddr(); - mPanId = panId.GetPanId(); + mPanId = panId.GetPanId(); mTimer.Start(kScanDelay); if (aHeader.IsConfirmable() && !aMessageInfo.GetSockAddr().IsMulticast()) @@ -124,13 +125,13 @@ void PanIdQueryServer::HandleScanResult(Mac::Frame *aFrame) otError PanIdQueryServer::SendConflict(void) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Coap::Header header; + ThreadNetif & netif = GetNetif(); + otError error = OT_ERROR_NONE; + Coap::Header header; MeshCoP::ChannelMask0Tlv channelMask; - MeshCoP::PanIdTlv panId; - Ip6::MessageInfo messageInfo; - Message *message; + MeshCoP::PanIdTlv panId; + Ip6::MessageInfo messageInfo; + Message * message; header.Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); header.SetToken(Coap::Header::kDefaultTokenLength); @@ -175,4 +176,4 @@ void PanIdQueryServer::HandleTimer(void) mChannelMask = 0; } -} // namespace ot +} // namespace ot diff --git a/src/core/thread/panid_query_server.hpp b/src/core/thread/panid_query_server.hpp index e23063d0b..22e0a4872 100644 --- a/src/core/thread/panid_query_server.hpp +++ b/src/core/thread/panid_query_server.hpp @@ -56,7 +56,7 @@ class ThreadTargetTlv; * This class implements handling PANID Query Requests. * */ -class PanIdQueryServer: public InstanceLocator +class PanIdQueryServer : public InstanceLocator { public: /** @@ -68,25 +68,28 @@ public: private: enum { - kScanDelay = 1000, ///< SCAN_DELAY (milliseconds) + kScanDelay = 1000, ///< SCAN_DELAY (milliseconds) }; - static void HandleQuery(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, const otMessageInfo *aMessageInfo); - void HandleQuery(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + static void HandleQuery(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo); + void HandleQuery(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); static void HandleScanResult(void *aContext, Mac::Frame *aFrame); - void HandleScanResult(Mac::Frame *aFrame); + void HandleScanResult(Mac::Frame *aFrame); static void HandleTimer(Timer &aTimer); - void HandleTimer(void); + void HandleTimer(void); static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo); otError SendConflict(void); Ip6::Address mCommissioner; - uint32_t mChannelMask; - uint16_t mPanId; + uint32_t mChannelMask; + uint16_t mPanId; TimerMilli mTimer; @@ -97,6 +100,6 @@ private: * @} */ -} // namespace ot +} // namespace ot -#endif // PANID_QUERY_SERVER_HPP_ +#endif // PANID_QUERY_SERVER_HPP_ diff --git a/src/core/thread/src_match_controller.cpp b/src/core/thread/src_match_controller.cpp index f9fa9eb69..a983bba97 100644 --- a/src/core/thread/src_match_controller.cpp +++ b/src/core/thread/src_match_controller.cpp @@ -44,9 +44,9 @@ namespace ot { -SourceMatchController::SourceMatchController(Instance &aInstance) : - InstanceLocator(aInstance), - mEnabled(false) +SourceMatchController::SourceMatchController(Instance &aInstance) + : InstanceLocator(aInstance) + , mEnabled(false) { ClearTable(); } @@ -147,8 +147,8 @@ otError SourceMatchController::AddAddress(const Child &aChild) { error = otPlatRadioAddSrcMatchShortEntry(&GetInstance(), aChild.GetRloc16()); - otLogDebgMac(GetInstance(), "SrcAddrMatch - Adding short addr: 0x%04x -- %s (%d)", - aChild.GetRloc16(), otThreadErrorToString(error), error); + otLogDebgMac(GetInstance(), "SrcAddrMatch - Adding short addr: 0x%04x -- %s (%d)", aChild.GetRloc16(), + otThreadErrorToString(error), error); } else { @@ -184,8 +184,8 @@ void SourceMatchController::ClearEntry(Child &aChild) { error = otPlatRadioClearSrcMatchShortEntry(&GetInstance(), aChild.GetRloc16()); - otLogDebgMac(GetInstance(), "SrcAddrMatch - Clearing short address: 0x%04x -- %s (%d)", - aChild.GetRloc16(), otThreadErrorToString(error), error); + otLogDebgMac(GetInstance(), "SrcAddrMatch - Clearing short address: 0x%04x -- %s (%d)", aChild.GetRloc16(), + otThreadErrorToString(error), error); } else { @@ -219,7 +219,7 @@ otError SourceMatchController::AddPendingEntries(void) { otError error = OT_ERROR_NONE; uint8_t numChildren; - Child *child; + Child * child; child = GetNetif().GetMle().GetChildren(&numChildren); @@ -236,4 +236,4 @@ exit: return error; } -} // namespace ot +} // namespace ot diff --git a/src/core/thread/src_match_controller.hpp b/src/core/thread/src_match_controller.hpp index 45d44fe0e..21eb0df63 100644 --- a/src/core/thread/src_match_controller.hpp +++ b/src/core/thread/src_match_controller.hpp @@ -65,7 +65,7 @@ namespace ot { * address or an extended/long address can be added to the source address match table. * */ -class SourceMatchController: public InstanceLocator +class SourceMatchController : public InstanceLocator { public: /** @@ -191,6 +191,6 @@ private: * */ -} // namespace ot +} // namespace ot -#endif // SOURCE_MATCH_CONTROLLER_HPP_ +#endif // SOURCE_MATCH_CONTROLLER_HPP_ diff --git a/src/core/thread/thread_netif.cpp b/src/core/thread/thread_netif.cpp index 0028b9808..1cb6cfd02 100644 --- a/src/core/thread/thread_netif.cpp +++ b/src/core/thread/thread_netif.cpp @@ -49,67 +49,93 @@ using ot::Encoding::BigEndian::HostSwap16; namespace ot { -static const otMasterKey kThreadMasterKey = -{ - { - 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, - 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, - } -}; +static const otMasterKey kThreadMasterKey = {{ + 0x00, + 0x11, + 0x22, + 0x33, + 0x44, + 0x55, + 0x66, + 0x77, + 0x88, + 0x99, + 0xaa, + 0xbb, + 0xcc, + 0xdd, + 0xee, + 0xff, +}}; -ThreadNetif::ThreadNetif(Instance &aInstance): - Netif(aInstance, OT_NETIF_INTERFACE_ID_THREAD), - mCoap(aInstance), +ThreadNetif::ThreadNetif(Instance &aInstance) + : Netif(aInstance, OT_NETIF_INTERFACE_ID_THREAD) + , mCoap(aInstance) + , #if OPENTHREAD_ENABLE_DHCP6_CLIENT - mDhcp6Client(aInstance), -#endif // OPENTHREAD_ENABLE_DHCP6_CLIENT + mDhcp6Client(aInstance) + , +#endif // OPENTHREAD_ENABLE_DHCP6_CLIENT #if OPENTHREAD_ENABLE_DHCP6_SERVER - mDhcp6Server(aInstance), -#endif // OPENTHREAD_ENABLE_DHCP6_SERVER + mDhcp6Server(aInstance) + , +#endif // OPENTHREAD_ENABLE_DHCP6_SERVER #if OPENTHREAD_ENABLE_DNS_CLIENT - mDnsClient(aInstance.GetThreadNetif()), -#endif // OPENTHREAD_ENABLE_DNS_CLIENT - mActiveDataset(aInstance), - mPendingDataset(aInstance), - mKeyManager(aInstance), - mLowpan(aInstance), - mMac(aInstance), - mMeshForwarder(aInstance), - mMleRouter(aInstance), + mDnsClient(aInstance.GetThreadNetif()) + , +#endif // OPENTHREAD_ENABLE_DNS_CLIENT + mActiveDataset(aInstance) + , mPendingDataset(aInstance) + , mKeyManager(aInstance) + , mLowpan(aInstance) + , mMac(aInstance) + , mMeshForwarder(aInstance) + , mMleRouter(aInstance) + , #if OPENTHREAD_ENABLE_BORDER_ROUTER || OPENTHREAD_ENABLE_SERVICE - mNetworkDataLocal(aInstance), + mNetworkDataLocal(aInstance) + , #endif - mNetworkDataLeader(aInstance), + mNetworkDataLeader(aInstance) + , #if OPENTHREAD_FTD || OPENTHREAD_ENABLE_MTD_NETWORK_DIAGNOSTIC - mNetworkDiagnostic(aInstance), + mNetworkDiagnostic(aInstance) + , #endif - mIsUp(false), + mIsUp(false) + , #if OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD - mCommissioner(aInstance), -#endif // OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD + mCommissioner(aInstance) + , +#endif // OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD #if OPENTHREAD_ENABLE_DTLS - mDtls(aInstance), - mCoapSecure(aInstance), + mDtls(aInstance) + , mCoapSecure(aInstance) + , #endif #if OPENTHREAD_ENABLE_JOINER - mJoiner(aInstance), -#endif // OPENTHREAD_ENABLE_JOINER + mJoiner(aInstance) + , +#endif // OPENTHREAD_ENABLE_JOINER #if OPENTHREAD_ENABLE_JAM_DETECTION - mJamDetector(aInstance), + mJamDetector(aInstance) + , #endif // OPENTHREAD_ENABLE_JAM_DETECTTION #if OPENTHREAD_FTD #if OPENTHREAD_ENABLE_TMF_PROXY - mTmfProxy(mMleRouter.GetMeshLocal16(), mCoap), + mTmfProxy(mMleRouter.GetMeshLocal16(), mCoap) + , #endif // OPENTHREAD_ENABLE_TMF_PROXY - mJoinerRouter(aInstance), - mLeader(aInstance), - mAddressResolver(aInstance), -#endif // OPENTHREAD_FTD - mChildSupervisor(aInstance), - mSupervisionListener(aInstance), - mAnnounceBegin(aInstance), - mPanIdQuery(aInstance), - mEnergyScan(aInstance) + mJoinerRouter(aInstance) + , mLeader(aInstance) + , mAddressResolver(aInstance) + , +#endif // OPENTHREAD_FTD + mChildSupervisor(aInstance) + , mSupervisionListener(aInstance) + , mAnnounceBegin(aInstance) + , mPanIdQuery(aInstance) + , mEnergyScan(aInstance) { mKeyManager.SetMasterKey(kThreadMasterKey); @@ -163,15 +189,15 @@ otError ThreadNetif::Down(void) otError ThreadNetif::GetLinkAddress(Ip6::LinkAddress &address) const { - address.mType = Ip6::LinkAddress::kEui64; - address.mLength = sizeof(address.mExtAddress); + address.mType = Ip6::LinkAddress::kEui64; + address.mLength = sizeof(address.mExtAddress); address.mExtAddress = mMac.GetExtAddress(); return OT_ERROR_NONE; } otError ThreadNetif::RouteLookup(const Ip6::Address &aSource, const Ip6::Address &aDestination, uint8_t *aPrefixMatch) { - otError error; + otError error; uint16_t rloc; SuccessOrExit(error = mNetworkDataLeader.RouteLookup(aSource, aDestination, aPrefixMatch, &rloc)); @@ -200,14 +226,14 @@ bool ThreadNetif::IsTmfMessage(const Ip6::MessageInfo &aMessageInfo) // 1. The destination is a Mesh Local Address or a Link-Local Multicast Address or a Realm-Local Multicast Address, // and the source is a Mesh Local Address. // 2. Both the destination and the source are Link-Local Addresses. - VerifyOrExit(((mMleRouter.IsMeshLocalAddress(aMessageInfo.GetSockAddr()) || - aMessageInfo.GetSockAddr().IsLinkLocalMulticast() || - aMessageInfo.GetSockAddr().IsRealmLocalMulticast()) && - mMleRouter.IsMeshLocalAddress(aMessageInfo.GetPeerAddr())) || - (aMessageInfo.GetSockAddr().IsLinkLocal() && aMessageInfo.GetPeerAddr().IsLinkLocal()), - rval = false); + VerifyOrExit( + ((mMleRouter.IsMeshLocalAddress(aMessageInfo.GetSockAddr()) || + aMessageInfo.GetSockAddr().IsLinkLocalMulticast() || aMessageInfo.GetSockAddr().IsRealmLocalMulticast()) && + mMleRouter.IsMeshLocalAddress(aMessageInfo.GetPeerAddr())) || + (aMessageInfo.GetSockAddr().IsLinkLocal() && aMessageInfo.GetPeerAddr().IsLinkLocal()), + rval = false); exit: return rval; } -} // namespace ot +} // namespace ot diff --git a/src/core/thread/thread_netif.hpp b/src/core/thread/thread_netif.hpp index 01886226f..9e5422568 100644 --- a/src/core/thread/thread_netif.hpp +++ b/src/core/thread/thread_netif.hpp @@ -48,17 +48,17 @@ #if OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD #include "meshcop/commissioner.hpp" -#endif // OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD +#endif // OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD #include "meshcop/dataset_manager.hpp" #if OPENTHREAD_ENABLE_DTLS #include "meshcop/dtls.hpp" -#endif // OPENTHREAD_ENABLE_DTLS +#endif // OPENTHREAD_ENABLE_DTLS #if OPENTHREAD_ENABLE_JOINER #include "meshcop/joiner.hpp" -#endif // OPENTHREAD_ENABLE_JOINER +#endif // OPENTHREAD_ENABLE_JOINER #include "meshcop/joiner_router.hpp" #include "meshcop/leader.hpp" @@ -71,12 +71,12 @@ #include "thread/address_resolver.hpp" #include "thread/announce_begin_server.hpp" #include "thread/energy_scan_server.hpp" -#include "thread/network_diagnostic.hpp" #include "thread/key_manager.hpp" #include "thread/mesh_forwarder.hpp" #include "thread/mle.hpp" #include "thread/mle_router.hpp" #include "thread/network_data_local.hpp" +#include "thread/network_diagnostic.hpp" #include "thread/panid_query_server.hpp" #include "utils/child_supervision.hpp" @@ -95,7 +95,7 @@ namespace ot { * @{ */ -class ThreadNetif: public Ip6::Netif +class ThreadNetif : public Ip6::Netif { public: /** @@ -176,7 +176,7 @@ public: * */ Dhcp6::Dhcp6Client &GetDhcp6Client(void) { return mDhcp6Client; } -#endif // OPENTHREAD_ENABLE_DHCP6_CLIENT +#endif // OPENTHREAD_ENABLE_DHCP6_CLIENT #if OPENTHREAD_ENABLE_DHCP6_SERVER /** @@ -186,7 +186,7 @@ public: * */ Dhcp6::Dhcp6Server &GetDhcp6Server(void) { return mDhcp6Server; } -#endif // OPENTHREAD_ENABLE_DHCP6_SERVER +#endif // OPENTHREAD_ENABLE_DHCP6_SERVER #if OPENTHREAD_ENABLE_DNS_CLIENT /** @@ -196,7 +196,7 @@ public: * */ Dns::Client &GetDnsClient(void) { return mDnsClient; } -#endif // OPENTHREAD_ENABLE_DNS_CLIENT +#endif // OPENTHREAD_ENABLE_DNS_CLIENT /** * This method returns a reference to the CoAP object. @@ -262,7 +262,7 @@ public: * */ NetworkData::Local &GetNetworkDataLocal(void) { return mNetworkDataLocal; } -#endif // OPENTHREAD_ENABLE_BORDER_ROUTER || OPENTHREAD_ENABLE_SERVICE +#endif // OPENTHREAD_ENABLE_BORDER_ROUTER || OPENTHREAD_ENABLE_SERVICE /** * This method returns a reference to the network data leader object. @@ -312,7 +312,7 @@ public: * */ AddressResolver &GetAddressResolver(void) { return mAddressResolver; } -#endif // OPENTHREAD_FTD +#endif // OPENTHREAD_FTD /** * This method returns a reference to the announce begin server object. @@ -330,7 +330,7 @@ public: * */ MeshCoP::Commissioner &GetCommissioner(void) { return mCommissioner; } -#endif // OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD +#endif // OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD #if OPENTHREAD_ENABLE_DTLS /** @@ -348,7 +348,7 @@ public: * */ Coap::CoapSecure &GetCoapSecure(void) { return mCoapSecure; } -#endif // OPENTHREAD_ENABLE_DTLS +#endif // OPENTHREAD_ENABLE_DTLS #if OPENTHREAD_ENABLE_JOINER /** @@ -358,7 +358,7 @@ public: * */ MeshCoP::Joiner &GetJoiner(void) { return mJoiner; } -#endif // OPENTHREAD_ENABLE_JOINER +#endif // OPENTHREAD_ENABLE_JOINER #if OPENTHREAD_ENABLE_JAM_DETECTION /** @@ -389,27 +389,27 @@ public: Utils::ChildSupervisor &GetChildSupervisor(void) { return mChildSupervisor; } /** - * This method returns a reference to the supervision listener object. - * - * @returns A reference to the supervision listener object. - * - */ + * This method returns a reference to the supervision listener object. + * + * @returns A reference to the supervision listener object. + * + */ Utils::SupervisionListener &GetSupervisionListener(void) { return mSupervisionListener; } /** - * This method returns a reference to the energy scan server object. - * - * @returns A reference to the energy scan server object. - * - */ + * This method returns a reference to the energy scan server object. + * + * @returns A reference to the energy scan server object. + * + */ EnergyScanServer &GetEnergyScanServer(void) { return mEnergyScan; } /** - * This method returns a reference to the PAN ID query server object. - * - * @returns A reference to the PAN ID query server object. - * - */ + * This method returns a reference to the PAN ID query server object. + * + * @returns A reference to the PAN ID query server object. + * + */ PanIdQueryServer &GetPanIdQueryServer(void) { return mPanIdQuery; } /** @@ -427,24 +427,24 @@ private: Coap::Coap mCoap; #if OPENTHREAD_ENABLE_DHCP6_CLIENT Dhcp6::Dhcp6Client mDhcp6Client; -#endif // OPENTHREAD_ENABLE_DHCP6_CLIENT +#endif // OPENTHREAD_ENABLE_DHCP6_CLIENT #if OPENTHREAD_ENABLE_DHCP6_SERVER Dhcp6::Dhcp6Server mDhcp6Server; -#endif // OPENTHREAD_ENABLE_DHCP6_SERVER +#endif // OPENTHREAD_ENABLE_DHCP6_SERVER #if OPENTHREAD_ENABLE_DNS_CLIENT Dns::Client mDnsClient; -#endif // OPENTHREAD_ENABLE_DNS_CLIENT - MeshCoP::ActiveDataset mActiveDataset; +#endif // OPENTHREAD_ENABLE_DNS_CLIENT + MeshCoP::ActiveDataset mActiveDataset; MeshCoP::PendingDataset mPendingDataset; - Ip6::Filter mIp6Filter; - KeyManager mKeyManager; - Lowpan::Lowpan mLowpan; - Mac::Mac mMac; - MeshForwarder mMeshForwarder; - Mle::MleRouter mMleRouter; + Ip6::Filter mIp6Filter; + KeyManager mKeyManager; + Lowpan::Lowpan mLowpan; + Mac::Mac mMac; + MeshForwarder mMeshForwarder; + Mle::MleRouter mMleRouter; #if OPENTHREAD_ENABLE_BORDER_ROUTER || OPENTHREAD_ENABLE_SERVICE NetworkData::Local mNetworkDataLocal; -#endif // OPENTHREAD_ENABLE_BORDER_ROUTER || OPENTHREAD_ENABLE_SERVICE +#endif // OPENTHREAD_ENABLE_BORDER_ROUTER || OPENTHREAD_ENABLE_SERVICE NetworkData::Leader mNetworkDataLeader; #if OPENTHREAD_FTD || OPENTHREAD_ENABLE_MTD_NETWORK_DIAGNOSTIC NetworkDiagnostic::NetworkDiagnostic mNetworkDiagnostic; @@ -453,16 +453,16 @@ private: #if OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD MeshCoP::Commissioner mCommissioner; -#endif // OPENTHREAD_ENABLE_COMMISSIONER +#endif // OPENTHREAD_ENABLE_COMMISSIONER #if OPENTHREAD_ENABLE_DTLS - MeshCoP::Dtls mDtls; + MeshCoP::Dtls mDtls; Coap::CoapSecure mCoapSecure; -#endif// OPENTHREAD_ENABLE_DTLS +#endif // OPENTHREAD_ENABLE_DTLS #if OPENTHREAD_ENABLE_JOINER MeshCoP::Joiner mJoiner; -#endif // OPENTHREAD_ENABLE_JOINER +#endif // OPENTHREAD_ENABLE_JOINER #if OPENTHREAD_ENABLE_JAM_DETECTION Utils::JamDetector mJamDetector; @@ -474,21 +474,21 @@ private: #if OPENTHREAD_FTD MeshCoP::JoinerRouter mJoinerRouter; - MeshCoP::Leader mLeader; - AddressResolver mAddressResolver; -#endif // OPENTHREAD_FTD + MeshCoP::Leader mLeader; + AddressResolver mAddressResolver; +#endif // OPENTHREAD_FTD - Utils::ChildSupervisor mChildSupervisor; + Utils::ChildSupervisor mChildSupervisor; Utils::SupervisionListener mSupervisionListener; - AnnounceBeginServer mAnnounceBegin; - PanIdQueryServer mPanIdQuery; - EnergyScanServer mEnergyScan; + AnnounceBeginServer mAnnounceBegin; + PanIdQueryServer mPanIdQuery; + EnergyScanServer mEnergyScan; }; /** * @} */ -} // namespace ot +} // namespace ot -#endif // THREAD_NETIF_HPP_ +#endif // THREAD_NETIF_HPP_ diff --git a/src/core/thread/thread_tlvs.hpp b/src/core/thread/thread_tlvs.hpp index 7b9165e5f..f857b32df 100644 --- a/src/core/thread/thread_tlvs.hpp +++ b/src/core/thread/thread_tlvs.hpp @@ -108,7 +108,8 @@ public: * @retval OT_ERROR_NOT_FOUND Could not find the TLV with Type @p aType. * */ - static otError GetTlv(const Message &aMessage, Type aType, uint16_t aMaxLength, Tlv &aTlv) { + static otError GetTlv(const Message &aMessage, Type aType, uint16_t aMaxLength, Tlv &aTlv) + { return ot::Tlv::Get(aMessage, static_cast(aType), aMaxLength, aTlv); } @@ -119,14 +120,18 @@ public: * */ OT_TOOL_PACKED_BEGIN -class ThreadTargetTlv: public ThreadTlv +class ThreadTargetTlv : public ThreadTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kTarget); SetLength(sizeof(*this) - sizeof(ThreadTlv)); } + void Init(void) + { + SetType(kTarget); + SetLength(sizeof(*this) - sizeof(ThreadTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -162,14 +167,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ThreadExtMacAddressTlv: public ThreadTlv +class ThreadExtMacAddressTlv : public ThreadTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kExtMacAddress); SetLength(sizeof(*this) - sizeof(ThreadTlv)); } + void Init(void) + { + SetType(kExtMacAddress); + SetLength(sizeof(*this) - sizeof(ThreadTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -205,14 +214,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ThreadRloc16Tlv: public ThreadTlv +class ThreadRloc16Tlv : public ThreadTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kRloc16); SetLength(sizeof(*this) - sizeof(ThreadTlv)); } + void Init(void) + { + SetType(kRloc16); + SetLength(sizeof(*this) - sizeof(ThreadTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -248,14 +261,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ThreadMeshLocalEidTlv: public ThreadTlv +class ThreadMeshLocalEidTlv : public ThreadTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kMeshLocalEid); SetLength(sizeof(*this) - sizeof(ThreadTlv)); } + void Init(void) + { + SetType(kMeshLocalEid); + SetLength(sizeof(*this) - sizeof(ThreadTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -288,7 +305,8 @@ public: * @param[in] aExtAddress A reference to the MAC Extended Address. * */ - void SetIid(const Mac::ExtAddress &aExtAddress) { + void SetIid(const Mac::ExtAddress &aExtAddress) + { memcpy(mIid, aExtAddress.m8, sizeof(mIid)); mIid[0] ^= 0x2; } @@ -302,14 +320,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ThreadStatusTlv: public ThreadTlv +class ThreadStatusTlv : public ThreadTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kStatus); SetLength(sizeof(*this) - sizeof(ThreadTlv)); } + void Init(void) + { + SetType(kStatus); + SetLength(sizeof(*this) - sizeof(ThreadTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -326,11 +348,11 @@ public: */ enum Status { - kSuccess = 0, ///< Success. - kNoAddressAvailable = 1, ///< No address available. - kTooFewRouters = 2, ///< Address Solicit due to too few routers. - kHaveChildIdRequest = 3, ///< Address Solicit due to child ID request. - kParentPartitionChange = 4, ///< Address Solicit due to parent partition change + kSuccess = 0, ///< Success. + kNoAddressAvailable = 1, ///< No address available. + kTooFewRouters = 2, ///< Address Solicit due to too few routers. + kHaveChildIdRequest = 3, ///< Address Solicit due to child ID request. + kParentPartitionChange = 4, ///< Address Solicit due to parent partition change }; /** @@ -358,14 +380,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ThreadLastTransactionTimeTlv: public ThreadTlv +class ThreadLastTransactionTimeTlv : public ThreadTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kLastTransactionTime); SetLength(sizeof(*this) - sizeof(ThreadTlv)); } + void Init(void) + { + SetType(kLastTransactionTime); + SetLength(sizeof(*this) - sizeof(ThreadTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -396,19 +422,22 @@ private: uint32_t mTime; } OT_TOOL_PACKED_END; - /** * This class implements Router Mask TLV generation and parsing. * */ -class ThreadRouterMaskTlv: public ThreadTlv +class ThreadRouterMaskTlv : public ThreadTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kRouterMask); SetLength(sizeof(*this) - sizeof(ThreadTlv)); } + void Init(void) + { + SetType(kRouterMask); + SetLength(sizeof(*this) - sizeof(ThreadTlv)); + } /** * This method indicates whether or not the TLV appears to be well-formed. @@ -450,7 +479,8 @@ public: * @retval FALSE If the given Router ID is not set in the Assigned Router ID Mask. * */ - bool IsAssignedRouterIdSet(uint8_t aRouterId) const { + bool IsAssignedRouterIdSet(uint8_t aRouterId) const + { return (mAssignedRouterIdMask[aRouterId / 8] & (0x80 >> (aRouterId % 8))) != 0; } @@ -472,14 +502,18 @@ private: * */ OT_TOOL_PACKED_BEGIN -class ThreadNetworkDataTlv: public ThreadTlv +class ThreadNetworkDataTlv : public ThreadTlv { public: /** * This method initializes the TLV. * */ - void Init(void) { SetType(kThreadNetworkData); SetLength(0); } + void Init(void) + { + SetType(kThreadNetworkData); + SetLength(0); + } /** * This method overrides same method of the base class @@ -506,6 +540,6 @@ private: uint8_t mTlvs[kMaxSize]; } OT_TOOL_PACKED_END; -} // namespace ot +} // namespace ot -#endif // THREAD_TLVS_HPP_ +#endif // THREAD_TLVS_HPP_ diff --git a/src/core/thread/thread_uri_paths.hpp b/src/core/thread/thread_uri_paths.hpp index ac5687f9e..886b47a8c 100644 --- a/src/core/thread/thread_uri_paths.hpp +++ b/src/core/thread/thread_uri_paths.hpp @@ -42,7 +42,7 @@ namespace ot { * The URI Path for Address Query. * */ -#define OT_URI_PATH_ADDRESS_QUERY "a/aq" +#define OT_URI_PATH_ADDRESS_QUERY "a/aq" /** * @def OT_URI_PATH_ADDRESS_NOTIFY @@ -50,7 +50,7 @@ namespace ot { * The URI Path for Address Notify. * */ -#define OT_URI_PATH_ADDRESS_NOTIFY "a/an" +#define OT_URI_PATH_ADDRESS_NOTIFY "a/an" /** * @def OT_URI_PATH_ADDRESS_ERROR @@ -58,7 +58,7 @@ namespace ot { * The URI Path for Address Error. * */ -#define OT_URI_PATH_ADDRESS_ERROR "a/ae" +#define OT_URI_PATH_ADDRESS_ERROR "a/ae" /** * @def OT_URI_PATH_ADDRESS_RELEASE @@ -66,7 +66,7 @@ namespace ot { * The URI Path for Address Release. * */ -#define OT_URI_PATH_ADDRESS_RELEASE "a/ar" +#define OT_URI_PATH_ADDRESS_RELEASE "a/ar" /** * @def OT_URI_PATH_ADDRESS_SOLICIT @@ -74,7 +74,7 @@ namespace ot { * The URI Path for Address Solicit. * */ -#define OT_URI_PATH_ADDRESS_SOLICIT "a/as" +#define OT_URI_PATH_ADDRESS_SOLICIT "a/as" /** * @def OT_URI_PATH_ACTIVE_GET @@ -82,7 +82,7 @@ namespace ot { * The URI Path for MGMT_ACTIVE_GET * */ -#define OT_URI_PATH_ACTIVE_GET "c/ag" +#define OT_URI_PATH_ACTIVE_GET "c/ag" /** * @def OT_URI_PATH_ACTIVE_SET @@ -90,7 +90,7 @@ namespace ot { * The URI Path for MGMT_ACTIVE_SET * */ -#define OT_URI_PATH_ACTIVE_SET "c/as" +#define OT_URI_PATH_ACTIVE_SET "c/as" /** * @def OT_URI_PATH_DATASET_CHANGED @@ -98,7 +98,7 @@ namespace ot { * The URI Path for MGMT_DATASET_CHANGED * */ -#define OT_URI_PATH_DATASET_CHANGED "c/dc" +#define OT_URI_PATH_DATASET_CHANGED "c/dc" /** * @def OT_URI_PATH_ENERGY_SCAN @@ -106,7 +106,7 @@ namespace ot { * The URI Path for Energy Scan * */ -#define OT_URI_PATH_ENERGY_SCAN "c/es" +#define OT_URI_PATH_ENERGY_SCAN "c/es" /** * @def OT_URI_PATH_ENERGY_REPORT @@ -114,7 +114,7 @@ namespace ot { * The URI Path for Energy Report * */ -#define OT_URI_PATH_ENERGY_REPORT "c/er" +#define OT_URI_PATH_ENERGY_REPORT "c/er" /** * @def OT_URI_PATH_PENDING_GET @@ -122,7 +122,7 @@ namespace ot { * The URI Path for MGMT_PENDING_GET * */ -#define OT_URI_PATH_PENDING_GET "c/pg" +#define OT_URI_PATH_PENDING_GET "c/pg" /** * @def OT_URI_PATH_PENDING_SET @@ -130,7 +130,7 @@ namespace ot { * The URI Path for MGMT_PENDING_SET * */ -#define OT_URI_PATH_PENDING_SET "c/ps" +#define OT_URI_PATH_PENDING_SET "c/ps" /** * @def OT_URI_PATH_SERVER_DATA @@ -138,7 +138,7 @@ namespace ot { * The URI Path for Server Data Registration. * */ -#define OT_URI_PATH_SERVER_DATA "a/sd" +#define OT_URI_PATH_SERVER_DATA "a/sd" /** * @def OT_URI_PATH_ANNOUNCE_BEGIN @@ -146,7 +146,7 @@ namespace ot { * The URI Path for Announce Begin. * */ -#define OT_URI_PATH_ANNOUNCE_BEGIN "c/ab" +#define OT_URI_PATH_ANNOUNCE_BEGIN "c/ab" /** * @def OT_URI_PATH_RELAY_RX @@ -154,7 +154,7 @@ namespace ot { * The URI Path for Relay RX. * */ -#define OT_URI_PATH_RELAY_RX "c/rx" +#define OT_URI_PATH_RELAY_RX "c/rx" /** * @def OT_URI_PATH_RELAY_TX @@ -162,7 +162,7 @@ namespace ot { * The URI Path for Relay TX. * */ -#define OT_URI_PATH_RELAY_TX "c/tx" +#define OT_URI_PATH_RELAY_TX "c/tx" /** * @def OT_URI_PATH_JOINER_FINALIZE @@ -170,7 +170,7 @@ namespace ot { * The URI Path for Joiner Finalize * */ -#define OT_URI_PATH_JOINER_FINALIZE "c/jf" +#define OT_URI_PATH_JOINER_FINALIZE "c/jf" /** * @def OT_URI_PATH_JOINER_ENTRUST @@ -178,7 +178,7 @@ namespace ot { * The URI Path for Joiner Entrust * */ -#define OT_URI_PATH_JOINER_ENTRUST "c/je" +#define OT_URI_PATH_JOINER_ENTRUST "c/je" /** * @def OT_URI_PATH_LEADER_PETITION @@ -186,7 +186,7 @@ namespace ot { * The URI Path for Leader Petition * */ -#define OT_URI_PATH_LEADER_PETITION "c/lp" +#define OT_URI_PATH_LEADER_PETITION "c/lp" /** * @def OT_URI_PATH_LEADER_KEEP_ALIVE @@ -194,7 +194,7 @@ namespace ot { * The URI Path for Leader Keep Alive * */ -#define OT_URI_PATH_LEADER_KEEP_ALIVE "c/la" +#define OT_URI_PATH_LEADER_KEEP_ALIVE "c/la" /** * @def OT_URI_PATH_PANID_CONFLICT @@ -202,7 +202,7 @@ namespace ot { * The URI Path for PAN ID Conflict * */ -#define OT_URI_PATH_PANID_CONFLICT "c/pc" +#define OT_URI_PATH_PANID_CONFLICT "c/pc" /** * @def OT_URI_PATH_PANID_QUERY @@ -210,7 +210,7 @@ namespace ot { * The URI Path for PAN ID Query * */ -#define OT_URI_PATH_PANID_QUERY "c/pq" +#define OT_URI_PATH_PANID_QUERY "c/pq" /** * @def OT_URI_PATH_COMMISSIONER_GET @@ -218,7 +218,7 @@ namespace ot { * The URI Path for MGMT_COMMISSIONER_GET * */ -#define OT_URI_PATH_COMMISSIONER_GET "c/cg" +#define OT_URI_PATH_COMMISSIONER_GET "c/cg" /** * @def OT_URI_PATH_COMMISSIONER_SET @@ -226,7 +226,7 @@ namespace ot { * The URI Path for MGMT_COMMISSIONER_SET * */ -#define OT_URI_PATH_COMMISSIONER_SET "c/cs" +#define OT_URI_PATH_COMMISSIONER_SET "c/cs" /** * @def OT_URI_PATH_DIAGNOSTIC_GET_REQUEST @@ -242,7 +242,7 @@ namespace ot { * The URI Path for Network Diagnostic Get Query. * */ -#define OT_URI_PATH_DIAGNOSTIC_GET_QUERY "d/dq" +#define OT_URI_PATH_DIAGNOSTIC_GET_QUERY "d/dq" /** * @def OT_URI_PATH_DIAGNOSTIC_GET_ANSWER @@ -250,7 +250,7 @@ namespace ot { * The URI Path for Network Diagnostic Get Answer. * */ -#define OT_URI_PATH_DIAGNOSTIC_GET_ANSWER "d/da" +#define OT_URI_PATH_DIAGNOSTIC_GET_ANSWER "d/da" /** * @def OT_URI_PATH_DIAG_RST @@ -258,8 +258,8 @@ namespace ot { * The URI Path for Network Diagnostic Reset. * */ -#define OT_URI_PATH_DIAGNOSTIC_RESET "d/dr" +#define OT_URI_PATH_DIAGNOSTIC_RESET "d/dr" -} // namespace ot +} // namespace ot -#endif // THREAD_URIS_HPP_ +#endif // THREAD_URIS_HPP_ diff --git a/src/core/thread/tmf_proxy.cpp b/src/core/thread/tmf_proxy.cpp index 955f58b61..3640ea0ab 100644 --- a/src/core/thread/tmf_proxy.cpp +++ b/src/core/thread/tmf_proxy.cpp @@ -37,8 +37,8 @@ #include -#include "common/instance.hpp" #include "coap/coap_header.hpp" +#include "common/instance.hpp" #include "net/ip6_address.hpp" #include "thread/thread_tlvs.hpp" #include "thread/thread_uri_paths.hpp" @@ -47,12 +47,12 @@ namespace ot { -TmfProxy::TmfProxy(const Ip6::Address &aMeshLocal16, Coap::Coap &aCoap): - mRelayReceive(OT_URI_PATH_RELAY_RX, &TmfProxy::HandleRelayReceive, this), - mStreamHandler(NULL), - mContext(NULL), - mMeshLocal16(aMeshLocal16), - mCoap(aCoap) +TmfProxy::TmfProxy(const Ip6::Address &aMeshLocal16, Coap::Coap &aCoap) + : mRelayReceive(OT_URI_PATH_RELAY_RX, &TmfProxy::HandleRelayReceive, this) + , mStreamHandler(NULL) + , mContext(NULL) + , mMeshLocal16(aMeshLocal16) + , mCoap(aCoap) { } @@ -64,7 +64,7 @@ otError TmfProxy::Start(otTmfProxyStreamHandler aStreamHandler, void *aContext) mCoap.AddResource(mRelayReceive); mStreamHandler = aStreamHandler; - mContext = aContext; + mContext = aContext; exit: return error; @@ -89,16 +89,21 @@ bool TmfProxy::IsEnabled(void) const return mStreamHandler != NULL; } -void TmfProxy::HandleRelayReceive(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, +void TmfProxy::HandleRelayReceive(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo) { - static_cast(aContext)->DeliverMessage( - *static_cast(aHeader), *static_cast(aMessage), - *static_cast(aMessageInfo)); + static_cast(aContext)->DeliverMessage(*static_cast(aHeader), + *static_cast(aMessage), + *static_cast(aMessageInfo)); } -void TmfProxy::HandleResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError aResult) +void TmfProxy::HandleResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aResult) { VerifyOrExit(aResult == OT_ERROR_NONE); @@ -109,10 +114,9 @@ exit: return; } -void TmfProxy::DeliverMessage(Coap::Header &aHeader, Message &aMessage, - const Ip6::MessageInfo &aMessageInfo) +void TmfProxy::DeliverMessage(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; uint16_t rloc; uint16_t port; Message *message = NULL; @@ -136,7 +140,7 @@ exit: otError TmfProxy::Send(Message &aMessage, uint16_t aLocator, uint16_t aPort) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Ip6::MessageInfo messageInfo; VerifyOrExit(mStreamHandler != NULL, error = OT_ERROR_INVALID_STATE); @@ -166,6 +170,6 @@ exit: return error; } -} // namespace ot +} // namespace ot #endif // OPENTHREAD_FTD && OPENTHREAD_ENABLE_TMF_PROXY diff --git a/src/core/thread/tmf_proxy.hpp b/src/core/thread/tmf_proxy.hpp index 67d0fbe87..83319eaeb 100644 --- a/src/core/thread/tmf_proxy.hpp +++ b/src/core/thread/tmf_proxy.hpp @@ -97,24 +97,27 @@ public: bool IsEnabled(void) const; private: - - static void HandleRelayReceive(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, + static void HandleRelayReceive(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, const otMessageInfo *aMessageInfo); - static void HandleResponse(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, - const otMessageInfo *aMessageInfo, otError aResult); + static void HandleResponse(void * aContext, + otCoapHeader * aHeader, + otMessage * aMessage, + const otMessageInfo *aMessageInfo, + otError aResult); void DeliverMessage(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - - Coap::Resource mRelayReceive; + Coap::Resource mRelayReceive; otTmfProxyStreamHandler mStreamHandler; - void *mContext; + void * mContext; const Ip6::Address &mMeshLocal16; - Coap::Coap &mCoap; + Coap::Coap & mCoap; }; -} // namespace ot +} // namespace ot -#endif // TMF_PROXY_HPP_ +#endif // TMF_PROXY_HPP_ diff --git a/src/core/thread/topology.cpp b/src/core/thread/topology.cpp index ca3062ee1..dad951dfe 100644 --- a/src/core/thread/topology.cpp +++ b/src/core/thread/topology.cpp @@ -95,7 +95,7 @@ exit: otError Child::GetNextIp6Address(Instance &aInstance, Ip6AddressIterator &aIterator, Ip6::Address &aAddress) const { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; otChildIp6AddressIterator index; // Index zero corresponds to the Mesh Local IPv6 address (if any). @@ -150,7 +150,7 @@ exit: otError Child::RemoveIp6Address(Instance &aInstance, const Ip6::Address &aAddress) { - otError error = OT_ERROR_NOT_FOUND; + otError error = OT_ERROR_NOT_FOUND; uint16_t index; VerifyOrExit(!aAddress.IsUnspecified(), error = OT_ERROR_INVALID_ARGS); @@ -238,4 +238,4 @@ const Mac::Address &Child::GetMacAddress(Mac::Address &aMacAddress) const return aMacAddress; } -} // namespace ot +} // namespace ot diff --git a/src/core/thread/topology.hpp b/src/core/thread/topology.hpp index c426f4bbd..0705bfb03 100644 --- a/src/core/thread/topology.hpp +++ b/src/core/thread/topology.hpp @@ -61,14 +61,14 @@ public: */ enum State { - kStateInvalid, ///< Neighbor link is invalid - kStateRestored, ///< Neighbor is restored from non-volatile memory - kStateParentRequest, ///< Received an MLE Parent Request message - kStateParentResponse, ///< Received an MLE Parent Response message - kStateChildIdRequest, ///< Received an MLE Child ID Request message - kStateLinkRequest, ///< Sent an MLE Link Request message - kStateChildUpdateRequest, ///< Sent an MLE Child Update Request message (trying to restore the child) - kStateValid, ///< Link is valid + kStateInvalid, ///< Neighbor link is invalid + kStateRestored, ///< Neighbor is restored from non-volatile memory + kStateParentRequest, ///< Received an MLE Parent Request message + kStateParentResponse, ///< Received an MLE Parent Response message + kStateChildIdRequest, ///< Received an MLE Child ID Request message + kStateLinkRequest, ///< Sent an MLE Link Request message + kStateChildUpdateRequest, ///< Sent an MLE Child Update Request message (trying to restore the child) + kStateValid, ///< Link is valid }; /** @@ -329,28 +329,28 @@ public: uint8_t GetChallengeSize(void) const { return sizeof(mValidPending.mPending.mChallenge); } private: - Mac::ExtAddress mMacAddr; ///< The IEEE 802.15.4 Extended Address - uint32_t mLastHeard; ///< Time when last heard. + Mac::ExtAddress mMacAddr; ///< The IEEE 802.15.4 Extended Address + uint32_t mLastHeard; ///< Time when last heard. union { struct { - uint32_t mLinkFrameCounter; ///< The Link Frame Counter - uint32_t mMleFrameCounter; ///< The MLE Frame Counter + uint32_t mLinkFrameCounter; ///< The Link Frame Counter + uint32_t mMleFrameCounter; ///< The MLE Frame Counter } mValid; struct { - uint8_t mChallenge[Mle::ChallengeTlv::kMaxSize]; ///< The challenge value + uint8_t mChallenge[Mle::ChallengeTlv::kMaxSize]; ///< The challenge value } mPending; } mValidPending; - uint32_t mKeySequence; ///< Current key sequence - uint16_t mRloc16; ///< The RLOC16 - uint8_t mState : 3; ///< The link state - uint8_t mMode : 4; ///< The MLE device mode - bool mDataRequest : 1; ///< Indicates whether or not a Data Poll was received - uint8_t mLinkFailures; ///< Consecutive link failure count - LinkQualityInfo mLinkInfo; ///< Link quality info (contains average RSS, link margin and link quality) + uint32_t mKeySequence; ///< Current key sequence + uint16_t mRloc16; ///< The RLOC16 + uint8_t mState : 3; ///< The link state + uint8_t mMode : 4; ///< The MLE device mode + bool mDataRequest : 1; ///< Indicates whether or not a Data Poll was received + uint8_t mLinkFailures; ///< Consecutive link failure count + LinkQualityInfo mLinkInfo; ///< Link quality info (contains average RSS, link margin and link quality) }; /** @@ -362,7 +362,7 @@ class Child : public Neighbor public: enum { - kMaxRequestTlvs = 5, + kMaxRequestTlvs = 5, }; /** @@ -374,14 +374,16 @@ public: friend class Child; public: - /** * This constructor initializes the iterator object. * * After initialization a call to `GetNextIp6Address()` would start at the first IPv6 address entry in the list. * */ - Ip6AddressIterator(void): mIndex(0) { } + Ip6AddressIterator(void) + : mIndex(0) + { + } /** * This method resets the iterator. @@ -737,7 +739,8 @@ public: void SetRequestTlv(uint8_t aIndex, uint8_t aType) { mRequestTlvs[aIndex] = aType; } /** - * This method gets the mac address of child (either rloc16 or extended address depending on `UseShortAddress` flag). + * This method gets the mac address of child (either rloc16 or extended address depending on `UseShortAddress` + * flag). * * @param[out] aMacAddress A reference to a mac address object to which the child's address is copied. * @@ -771,7 +774,6 @@ public: #endif // #if OPENTHREAD_ENABLE_CHILD_SUPERVISION private: - #if OPENTHREAD_CONFIG_IP_ADDRS_PER_CHILD < 2 #error OPENTHREAD_CONFIG_IP_ADDRS_PER_CHILD should be at least set to 2. #endif @@ -781,10 +783,10 @@ private: kNumIp6Addresses = OPENTHREAD_CONFIG_IP_ADDRS_PER_CHILD - 1, }; - uint8_t mMeshLocalIid[Ip6::Address::kInterfaceIdentifierSize]; ///< IPv6 address IID for mesh-local address - Ip6::Address mIp6Address[kNumIp6Addresses]; ///< Registered IPv6 addresses + uint8_t mMeshLocalIid[Ip6::Address::kInterfaceIdentifierSize]; ///< IPv6 address IID for mesh-local address + Ip6::Address mIp6Address[kNumIp6Addresses]; ///< Registered IPv6 addresses - uint32_t mTimeout; ///< Child timeout + uint32_t mTimeout; ///< Child timeout union { @@ -792,22 +794,21 @@ private: uint8_t mAttachChallenge[Mle::ChallengeTlv::kMaxSize]; ///< The challenge value }; - uint32_t mIndirectFrameCounter; ///< Frame counter for current indirect message (used fore retx). - Message *mIndirectMessage; ///< Current indirect message. - uint16_t mIndirectFragmentOffset : 15; ///< 6LoWPAN fragment offset for the indirect message. - bool mIndirectTxSuccess : 1; ///< Indicates tx success/failure of current indirect message. - uint8_t mIndirectKeyId; ///< Key Id for current indirect message (used for retx). - uint8_t mIndirectTxAttempts; ///< Number of data poll triggered tx attempts. - uint8_t mIndirectDsn; ///< MAC level Data Sequence Number (DSN) for retx attempts. - uint8_t mNetworkDataVersion; ///< Current Network Data version - uint16_t mQueuedMessageCount : 13; ///< Number of queued indirect messages for the child. - bool mUseShortAddress : 1; ///< Indicates whether to use short or extended address. - bool mSourceMatchPending : 1; ///< Indicates whether or not pending to add to src match table. + uint32_t mIndirectFrameCounter; ///< Frame counter for current indirect message (used fore retx). + Message *mIndirectMessage; ///< Current indirect message. + uint16_t mIndirectFragmentOffset : 15; ///< 6LoWPAN fragment offset for the indirect message. + bool mIndirectTxSuccess : 1; ///< Indicates tx success/failure of current indirect message. + uint8_t mIndirectKeyId; ///< Key Id for current indirect message (used for retx). + uint8_t mIndirectTxAttempts; ///< Number of data poll triggered tx attempts. + uint8_t mIndirectDsn; ///< MAC level Data Sequence Number (DSN) for retx attempts. + uint8_t mNetworkDataVersion; ///< Current Network Data version + uint16_t mQueuedMessageCount : 13; ///< Number of queued indirect messages for the child. + bool mUseShortAddress : 1; ///< Indicates whether to use short or extended address. + bool mSourceMatchPending : 1; ///< Indicates whether or not pending to add to src match table. #if OPENTHREAD_ENABLE_CHILD_SUPERVISION - uint16_t mSecondsSinceSupervision; ///< Number of seconds since last supervision of the child. -#endif // OPENTHREAD_ENABLE_CHILD_SUPERVISION - + uint16_t mSecondsSinceSupervision; ///< Number of seconds since last supervision of the child. +#endif // OPENTHREAD_ENABLE_CHILD_SUPERVISION }; /** @@ -898,13 +899,13 @@ public: void SetReclaimDelay(bool aReclaimDelay) { mReclaimDelay = aReclaimDelay; } private: - uint8_t mNextHop; ///< The next hop towards this router - uint8_t mLinkQualityOut : 2; ///< The link quality out for this router - uint8_t mCost : 4; ///< The cost to this router via neighbor router - bool mAllocated : 1; ///< Indicates whether or not this entry is allocated - bool mReclaimDelay : 1; ///< Indicates whether or not this entry is waiting to be reclaimed + uint8_t mNextHop; ///< The next hop towards this router + uint8_t mLinkQualityOut : 2; ///< The link quality out for this router + uint8_t mCost : 4; ///< The cost to this router via neighbor router + bool mAllocated : 1; ///< Indicates whether or not this entry is allocated + bool mReclaimDelay : 1; ///< Indicates whether or not this entry is waiting to be reclaimed }; -} // namespace ot +} // namespace ot -#endif // TOPOLOGY_HPP_ +#endif // TOPOLOGY_HPP_ diff --git a/src/core/utils/channel_manager.cpp b/src/core/utils/channel_manager.cpp index 5f3c908ef..e9440f75d 100644 --- a/src/core/utils/channel_manager.cpp +++ b/src/core/utils/channel_manager.cpp @@ -46,15 +46,15 @@ namespace ot { namespace Utils { -ChannelManager::ChannelManager(Instance &aInstance): - InstanceLocator(aInstance), - mSupportedChannels(kDefaultSupprotedChannelMask), - mActiveTimestamp(0), - mNotifierCallback(&ChannelManager::HandleStateChanged, this), - mDelay(kMinimumDelay), - mChannel(0), - mState(kStateIdle), - mTimer(aInstance, &ChannelManager::HandleTimer, this) +ChannelManager::ChannelManager(Instance &aInstance) + : InstanceLocator(aInstance) + , mSupportedChannels(kDefaultSupprotedChannelMask) + , mActiveTimestamp(0) + , mNotifierCallback(&ChannelManager::HandleStateChanged, this) + , mDelay(kMinimumDelay) + , mChannel(0) + , mState(kStateIdle) + , mTimer(aInstance, &ChannelManager::HandleTimer, this) { } @@ -74,8 +74,8 @@ otError ChannelManager::RequestChannelChange(uint8_t aChannel) ExitNow(error = OT_ERROR_INVALID_ARGS); } - mState = kStateChangeRequested; - mChannel = aChannel; + mState = kStateChangeRequested; + mChannel = aChannel; mActiveTimestamp = 0; mTimer.Start((otPlatRandomGet() % kRequestStartJitterInterval) + 1); @@ -97,12 +97,12 @@ exit: void ChannelManager::PreparePendingDataset(void) { - ThreadNetif &netif = GetInstance().GetThreadNetif(); - uint64_t pendingTimestamp = 0; - uint64_t pendingActiveTimestamp = 0; - uint32_t delayInMs = TimerMilli::SecToMsec(static_cast(mDelay)); + ThreadNetif & netif = GetInstance().GetThreadNetif(); + uint64_t pendingTimestamp = 0; + uint64_t pendingActiveTimestamp = 0; + uint32_t delayInMs = TimerMilli::SecToMsec(static_cast(mDelay)); otOperationalDataset dataset; - otError error; + otError error; VerifyOrExit(mState == kStateChangeRequested); @@ -128,9 +128,8 @@ void ChannelManager::PreparePendingDataset(void) // should match and delay should be less than the requested // delay). - if (dataset.mIsChannelSet && (mChannel == dataset.mChannel) && - dataset.mIsDelaySet && (dataset.mDelay <= delayInMs) && - dataset.mIsActiveTimestampSet) + if (dataset.mIsChannelSet && (mChannel == dataset.mChannel) && dataset.mIsDelaySet && + (dataset.mDelay <= delayInMs) && dataset.mIsActiveTimestampSet) { // We save the active timestamp to later check and ensure it // is ahead of current ActiveDataset timestamp. @@ -202,19 +201,19 @@ void ChannelManager::PreparePendingDataset(void) } else { - mActiveTimestamp = dataset.mActiveTimestamp + 1 + (otPlatRandomGet() % kMaxTimestampIncrease); + mActiveTimestamp = dataset.mActiveTimestamp + 1 + (otPlatRandomGet() % kMaxTimestampIncrease); } - dataset.mActiveTimestamp = mActiveTimestamp; + dataset.mActiveTimestamp = mActiveTimestamp; dataset.mIsActiveTimestampSet = true; - dataset.mChannel = mChannel; + dataset.mChannel = mChannel; dataset.mIsChannelSet = true; - dataset.mPendingTimestamp = pendingTimestamp; + dataset.mPendingTimestamp = pendingTimestamp; dataset.mIsPendingTimestampSet = true; - dataset.mDelay = delayInMs; + dataset.mDelay = delayInMs; dataset.mIsDelaySet = true; error = netif.GetPendingDataset().SendSetRequest(dataset, NULL, 0); @@ -254,7 +253,7 @@ void ChannelManager::HandleTimer(void) otLogInfoUtil(GetInstance(), "ChannelManager: Timed out waiting for change to %d, trying again.", mChannel); mState = kStateChangeRequested; - // fall through + // fall through case kStateChangeRequested: PreparePendingDataset(); @@ -281,7 +280,7 @@ exit: return; } -} // namespace Utils -} // namespace ot +} // namespace Utils +} // namespace ot #endif // #if OPENTHREAD_ENABLE_CHANNEL_MANAGER diff --git a/src/core/utils/channel_manager.hpp b/src/core/utils/channel_manager.hpp index 3d5117d9e..0a355cfd4 100644 --- a/src/core/utils/channel_manager.hpp +++ b/src/core/utils/channel_manager.hpp @@ -36,8 +36,8 @@ #include "openthread-core-config.h" -#include #include +#include #include "common/locator.hpp" #include "common/notifier.hpp" @@ -143,7 +143,8 @@ public: * @param[in] aChannelMask A channel mask. * */ - void SetSupportedChannels(uint32_t aChannelMask) { + void SetSupportedChannels(uint32_t aChannelMask) + { mSupportedChannels = (aChannelMask & OT_RADIO_SUPPORTED_CHANNELS); } @@ -152,9 +153,9 @@ private: { kDefaultSupprotedChannelMask = OT_RADIO_SUPPORTED_CHANNELS, kMaxTimestampIncrease = 128, - kPendingDatasetTxRetryInterval = 20000, // in ms - kChangeCheckWaitInterval = 30000, // in ms - kRequestStartJitterInterval = 10000, // in ms + kPendingDatasetTxRetryInterval = 20000, // in ms + kChangeCheckWaitInterval = 30000, // in ms + kRequestStartJitterInterval = 10000, // in ms }; enum State @@ -165,10 +166,10 @@ private: }; static void HandleTimer(Timer &aTimer); - void HandleTimer(void); + void HandleTimer(void); static void HandleStateChanged(Notifier::Callback &aCallback, uint32_t aChangedFlags); - void HandleStateChanged(uint32_t aChangedFlags); - void PreparePendingDataset(void); + void HandleStateChanged(uint32_t aChangedFlags); + void PreparePendingDataset(void); uint32_t mSupportedChannels; uint64_t mActiveTimestamp; @@ -184,7 +185,7 @@ private: class ChannelManager { public: - explicit ChannelManager(Instance &) { } + explicit ChannelManager(Instance &) {} }; #endif // OPENTHREAD_FTD @@ -195,7 +196,7 @@ public: * */ -} // namespace Utils -} // namespace ot +} // namespace Utils +} // namespace ot -#endif // CHANNEL_MANAGER_HPP_ +#endif // CHANNEL_MANAGER_HPP_ diff --git a/src/core/utils/channel_monitor.cpp b/src/core/utils/channel_monitor.cpp index 670a69915..e5b7fa127 100644 --- a/src/core/utils/channel_monitor.cpp +++ b/src/core/utils/channel_monitor.cpp @@ -42,19 +42,18 @@ namespace ot { namespace Utils { -const uint32_t ChannelMonitor::mScanChannelMasks[kNumChannelMasks] = -{ +const uint32_t ChannelMonitor::mScanChannelMasks[kNumChannelMasks] = { OT_CHANNEL_11_MASK | OT_CHANNEL_15_MASK | OT_CHANNEL_19_MASK | OT_CHANNEL_23_MASK, OT_CHANNEL_12_MASK | OT_CHANNEL_16_MASK | OT_CHANNEL_20_MASK | OT_CHANNEL_24_MASK, OT_CHANNEL_13_MASK | OT_CHANNEL_17_MASK | OT_CHANNEL_21_MASK | OT_CHANNEL_25_MASK, OT_CHANNEL_14_MASK | OT_CHANNEL_18_MASK | OT_CHANNEL_22_MASK | OT_CHANNEL_26_MASK, }; -ChannelMonitor::ChannelMonitor(Instance &aInstance): - InstanceLocator(aInstance), - mChannelMaskIndex(0), - mSampleCount(0), - mTimer(aInstance, &ChannelMonitor::HandleTimer, this) +ChannelMonitor::ChannelMonitor(Instance &aInstance) + : InstanceLocator(aInstance) + , mChannelMaskIndex(0) + , mSampleCount(0) + , mTimer(aInstance, &ChannelMonitor::HandleTimer, this) { memset(mChannelQuality, 0, sizeof(mChannelQuality)); } @@ -75,7 +74,7 @@ void ChannelMonitor::Stop(void) void ChannelMonitor::Clear(void) { mChannelMaskIndex = 0; - mSampleCount = 0; + mSampleCount = 0; memset(mChannelQuality, 0, sizeof(mChannelQuality)); otLogDebgUtil(GetInstance(), "ChannelMonitor: Clearing data"); @@ -95,7 +94,7 @@ exit: void ChannelMonitor::RestartTimer(void) { uint16_t interval = kTimerInterval; - int16_t jitter; + int16_t jitter; jitter = (otPlatRandomGet() % (2 * kMaxJitterInterval)) - kMaxJitterInterval; @@ -150,8 +149,8 @@ void ChannelMonitor::HandleEnergyScanResult(otEnergyScanResult *aResult) else { uint8_t channelIndex = (aResult->mChannel - OT_RADIO_CHANNEL_MIN); - uint32_t newAverage = mChannelQuality[channelIndex]; - uint32_t newValue = 0; + uint32_t newAverage = mChannelQuality[channelIndex]; + uint32_t newValue = 0; uint32_t weight; assert(channelIndex < kNumChannels); @@ -194,15 +193,14 @@ void ChannelMonitor::LogResults(void) otLogInfoUtil( GetInstance(), "ChannelMonitor: %u [%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x]", - mSampleCount, - mChannelQuality[0] >> 8, mChannelQuality[1] >> 8, mChannelQuality[2] >> 8, mChannelQuality[3] >> 8, - mChannelQuality[4] >> 8, mChannelQuality[5] >> 8, mChannelQuality[6] >> 8, mChannelQuality[7] >> 8, - mChannelQuality[8] >> 8, mChannelQuality[9] >> 8, mChannelQuality[10] >> 8, mChannelQuality[11] >> 8, - mChannelQuality[12] >> 8, mChannelQuality[13] >> 8, mChannelQuality[14] >> 8, mChannelQuality[15] >> 8 - ); + mSampleCount, mChannelQuality[0] >> 8, mChannelQuality[1] >> 8, mChannelQuality[2] >> 8, + mChannelQuality[3] >> 8, mChannelQuality[4] >> 8, mChannelQuality[5] >> 8, mChannelQuality[6] >> 8, + mChannelQuality[7] >> 8, mChannelQuality[8] >> 8, mChannelQuality[9] >> 8, mChannelQuality[10] >> 8, + mChannelQuality[11] >> 8, mChannelQuality[12] >> 8, mChannelQuality[13] >> 8, mChannelQuality[14] >> 8, + mChannelQuality[15] >> 8); } -} // namespace Utils -} // namespace ot +} // namespace Utils +} // namespace ot #endif // #if OPENTHREAD_ENABLE_CHANNEL_MONITOR diff --git a/src/core/utils/channel_monitor.hpp b/src/core/utils/channel_monitor.hpp index ad238ebde..1b9096e70 100644 --- a/src/core/utils/channel_monitor.hpp +++ b/src/core/utils/channel_monitor.hpp @@ -36,8 +36,8 @@ #include "openthread-core-config.h" -#include #include +#include #include "common/locator.hpp" #include "common/timer.hpp" @@ -65,13 +65,13 @@ namespace Utils { * When Channel Monitoring is active, every `kSampleInterval`, a zero-duration Energy Scan is performed on every * channel collecting a single RSSI sample per channel. The RSSI samples are compared with a pre-specified RSSI * threshold `kRssiThreshold`. As an indicator of channel quality, the `ChannelMonitor` maintains and provides the - * average rate/percentage of RSSI samples that are above the threshold within (approximately) a specified sample window. + * average rate/percentage of RSSI samples that are above the threshold within (approximately) a specified sample + * window. * */ class ChannelMonitor : public InstanceLocator { public: - enum { /** @@ -157,25 +157,25 @@ public: private: enum { - kNumChannels = (OT_RADIO_CHANNEL_MAX - OT_RADIO_CHANNEL_MIN + 1), - kNumChannelMasks = 4, - kTimerInterval = (kSampleInterval / kNumChannelMasks), - kMaxJitterInterval = 4096, + kNumChannels = (OT_RADIO_CHANNEL_MAX - OT_RADIO_CHANNEL_MIN + 1), + kNumChannelMasks = 4, + kTimerInterval = (kSampleInterval / kNumChannelMasks), + kMaxJitterInterval = 4096, kMaxQualityIndicator = 0xffff, }; - void RestartTimer(void); + void RestartTimer(void); static void HandleTimer(Timer &aTimer); - void HandleTimer(void); + void HandleTimer(void); static void HandleEnergyScanResult(void *aContext, otEnergyScanResult *aResult); - void HandleEnergyScanResult(otEnergyScanResult *aResult); - void LogResults(void); + void HandleEnergyScanResult(otEnergyScanResult *aResult); + void LogResults(void); static const uint32_t mScanChannelMasks[kNumChannelMasks]; - uint8_t mChannelMaskIndex : 2; - uint32_t mSampleCount : 30; - uint16_t mChannelQuality[kNumChannels]; + uint8_t mChannelMaskIndex : 2; + uint32_t mSampleCount : 30; + uint16_t mChannelQuality[kNumChannels]; TimerMilli mTimer; }; @@ -186,7 +186,7 @@ private: * */ -} // namespace Utils -} // namespace ot +} // namespace Utils +} // namespace ot -#endif // CHANNEL_MONITOR_HPP_ +#endif // CHANNEL_MONITOR_HPP_ diff --git a/src/core/utils/child_supervision.cpp b/src/core/utils/child_supervision.cpp index 9206d503d..e1a6e90fc 100644 --- a/src/core/utils/child_supervision.cpp +++ b/src/core/utils/child_supervision.cpp @@ -49,10 +49,10 @@ namespace Utils { #if OPENTHREAD_FTD -ChildSupervisor::ChildSupervisor(Instance &aInstance) : - InstanceLocator(aInstance), - mSupervisionInterval(kDefaultSupervisionInterval), - mTimer(aInstance, &ChildSupervisor::HandleTimer, this) +ChildSupervisor::ChildSupervisor(Instance &aInstance) + : InstanceLocator(aInstance) + , mSupervisionInterval(kDefaultSupervisionInterval) + , mTimer(aInstance, &ChildSupervisor::HandleTimer, this) { } @@ -79,7 +79,7 @@ void ChildSupervisor::SetSupervisionInterval(uint16_t aInterval) Child *ChildSupervisor::GetDestination(const Message &aMessage) const { - Child *child = NULL; + Child * child = NULL; uint8_t childIndex; uint8_t numChildren; @@ -96,9 +96,9 @@ exit: void ChildSupervisor::SendMessage(Child &aChild) { - ThreadNetif &netif = GetNetif(); - Message *message = NULL; - uint8_t childIndex; + ThreadNetif &netif = GetNetif(); + Message * message = NULL; + uint8_t childIndex; VerifyOrExit(aChild.GetIndirectMessageCount() == 0); @@ -138,7 +138,7 @@ void ChildSupervisor::HandleTimer(Timer &aTimer) void ChildSupervisor::HandleTimer(void) { - Child *child; + Child * child; uint8_t numChildren; VerifyOrExit(mSupervisionInterval != 0); @@ -168,10 +168,10 @@ exit: #endif // #if OPENTHREAD_FTD -SupervisionListener::SupervisionListener(Instance &aInstance) : - InstanceLocator(aInstance), - mTimeout(0), - mTimer(aInstance, &SupervisionListener::HandleTimer, this) +SupervisionListener::SupervisionListener(Instance &aInstance) + : InstanceLocator(aInstance) + , mTimeout(0) + , mTimer(aInstance, &SupervisionListener::HandleTimer, this) { SetTimeout(kDefaultTimeout); } @@ -201,7 +201,7 @@ void SupervisionListener::UpdateOnReceive(const Mac::Address &aSourceAddress, bo // If listener is enabled and device is a child and it received a secure frame from its parent, restart the timer. - VerifyOrExit(mTimer.IsRunning() && aIsSecure && (netif.GetMle().GetRole() == OT_DEVICE_ROLE_CHILD) && + VerifyOrExit(mTimer.IsRunning() && aIsSecure && (netif.GetMle().GetRole() == OT_DEVICE_ROLE_CHILD) && (netif.GetMle().GetNeighbor(aSourceAddress) == netif.GetMle().GetParent())); RestartTimer(); diff --git a/src/core/utils/child_supervision.hpp b/src/core/utils/child_supervision.hpp index 9366693b5..8b36bccd6 100644 --- a/src/core/utils/child_supervision.hpp +++ b/src/core/utils/child_supervision.hpp @@ -86,7 +86,7 @@ namespace Utils { * This class implements a child supervisor. * */ -class ChildSupervisor: public InstanceLocator +class ChildSupervisor : public InstanceLocator { public: /** @@ -150,30 +150,30 @@ public: private: enum { - kDefaultSupervisionInterval = OPENTHREAD_CONFIG_CHILD_SUPERVISION_INTERVAL, // (seconds) - kOneSecond = 1000, // One second interval (in ms). + kDefaultSupervisionInterval = OPENTHREAD_CONFIG_CHILD_SUPERVISION_INTERVAL, // (seconds) + kOneSecond = 1000, // One second interval (in ms). }; - void SendMessage(Child &aChild); + void SendMessage(Child &aChild); static void HandleTimer(Timer &aTimer); - void HandleTimer(void); + void HandleTimer(void); - uint16_t mSupervisionInterval; - TimerMilli mTimer; + uint16_t mSupervisionInterval; + TimerMilli mTimer; }; -#else // #if OPENTHREAD_ENABLE_CHILD_SUPERVISION && OPENTHREAD_FTD +#else // #if OPENTHREAD_ENABLE_CHILD_SUPERVISION && OPENTHREAD_FTD class ChildSupervisor { public: - explicit ChildSupervisor(otInstance &) { } - void Start(void) { } - void Stop(void) { } - void SetSupervisionInterval(uint16_t) { } + explicit ChildSupervisor(otInstance &) {} + void Start(void) {} + void Stop(void) {} + void SetSupervisionInterval(uint16_t) {} uint16_t GetSupervisionInterval(void) const { return 0; } - Child *GetDestination(const Message &) const { return NULL; } - void UpdateOnSend(Child &) { } + Child * GetDestination(const Message &) const { return NULL; } + void UpdateOnSend(Child &) {} }; #endif // #if OPENTHREAD_ENABLE_CHILD_SUPERVISION && OPENTHREAD_FTD @@ -184,7 +184,7 @@ public: * This class implements a child supervision listener. * */ -class SupervisionListener: public InstanceLocator +class SupervisionListener : public InstanceLocator { public: /** @@ -228,7 +228,7 @@ public: * @returns The check timeout interval (in seconds) or zero if the supervision check on the child is disabled. * */ - uint16_t GetTimeout(void) const { return mTimeout; } + uint16_t GetTimeout(void) const { return mTimeout; } /** * This method updates the supervision listener state. It informs the listener of a received frame. @@ -242,14 +242,14 @@ public: private: enum { - kDefaultTimeout = OPENTHREAD_CONFIG_SUPERVISION_CHECK_TIMEOUT, // (seconds) + kDefaultTimeout = OPENTHREAD_CONFIG_SUPERVISION_CHECK_TIMEOUT, // (seconds) }; - void RestartTimer(void); + void RestartTimer(void); static void HandleTimer(Timer &aTimer); - void HandleTimer(void); + void HandleTimer(void); - uint16_t mTimeout; + uint16_t mTimeout; TimerMilli mTimer; }; @@ -258,12 +258,12 @@ private: class SupervisionListener { public: - SupervisionListener(otInstance &) { } - void Start(void) { } - void Stop(void) { } - void SetTimeout(uint16_t) { } - uint16_t GetTimeout(void) const { return 0; } - void UpdateOnReceive(const Mac::Address &, bool) { } + SupervisionListener(otInstance &) {} + void Start(void) {} + void Stop(void) {} + void SetTimeout(uint16_t) {} + uint16_t GetTimeout(void) const { return 0; } + void UpdateOnReceive(const Mac::Address &, bool) {} }; #endif // #if OPENTHREAD_ENABLE_CHILD_SUPERVISION @@ -276,4 +276,4 @@ public: } // namespace Utils } // namespace ot -#endif // CHILD_SUPERVISION_HPP_ +#endif // CHILD_SUPERVISION_HPP_ diff --git a/src/core/utils/jam_detector.cpp b/src/core/utils/jam_detector.cpp index 047b035f4..0aa7b064d 100644 --- a/src/core/utils/jam_detector.cpp +++ b/src/core/utils/jam_detector.cpp @@ -46,20 +46,20 @@ namespace ot { namespace Utils { -JamDetector::JamDetector(Instance &aInstance) : - InstanceLocator(aInstance), - mHandler(NULL), - mContext(NULL), - mRssiThreshold(kDefaultRssiThreshold), - mTimer(aInstance, &JamDetector::HandleTimer, this), - mHistoryBitmap(0), - mCurSecondStartTime(0), - mSampleInterval(0), - mWindow(kMaxWindow), - mBusyPeriod(kMaxWindow), - mEnabled(false), - mAlwaysAboveThreshold(false), - mJamState(false) +JamDetector::JamDetector(Instance &aInstance) + : InstanceLocator(aInstance) + , mHandler(NULL) + , mContext(NULL) + , mRssiThreshold(kDefaultRssiThreshold) + , mTimer(aInstance, &JamDetector::HandleTimer, this) + , mHistoryBitmap(0) + , mCurSecondStartTime(0) + , mSampleInterval(0) + , mWindow(kMaxWindow) + , mBusyPeriod(kMaxWindow) + , mEnabled(false) + , mAlwaysAboveThreshold(false) + , mJamState(false) { } @@ -75,11 +75,11 @@ otError JamDetector::Start(Handler aHandler, void *aContext) mEnabled = true; - mCurSecondStartTime = TimerMilli::GetNow(); + mCurSecondStartTime = TimerMilli::GetNow(); mAlwaysAboveThreshold = true; - mHistoryBitmap = 0; - mJamState = false; - mSampleInterval = kMaxSampleInterval; + mHistoryBitmap = 0; + mJamState = false; + mSampleInterval = kMaxSampleInterval; mTimer.Start(kMinSampleInterval); @@ -93,7 +93,7 @@ otError JamDetector::Stop(void) VerifyOrExit(mEnabled, error = OT_ERROR_ALREADY); - mEnabled = false; + mEnabled = false; mJamState = false; mTimer.Stop(); @@ -143,7 +143,7 @@ void JamDetector::HandleTimer(Timer &aTimer) void JamDetector::HandleTimer(void) { int8_t rssi; - bool didExceedThreshold = true; + bool didExceedThreshold = true; VerifyOrExit(mEnabled); @@ -215,9 +215,9 @@ void JamDetector::UpdateHistory(bool aDidExceedThreshold) void JamDetector::UpdateJamState(void) { - uint8_t numJammedSeconds = 0; - uint64_t bitmap = mHistoryBitmap; - bool oldJamState = mJamState; + uint8_t numJammedSeconds = 0; + uint64_t bitmap = mHistoryBitmap; + bool oldJamState = mJamState; // Clear all history bits beyond the current window size bitmap &= (static_cast(1) << mWindow) - 1; @@ -239,7 +239,7 @@ void JamDetector::UpdateJamState(void) } } -} // namespace Utils -} // namespace ot +} // namespace Utils +} // namespace ot #endif // OPENTHREAD_ENABLE_JAM_DETECTION diff --git a/src/core/utils/jam_detector.hpp b/src/core/utils/jam_detector.hpp index 823b972cd..68a0ac910 100644 --- a/src/core/utils/jam_detector.hpp +++ b/src/core/utils/jam_detector.hpp @@ -46,10 +46,9 @@ class ThreadNetif; namespace Utils { -class JamDetector: public InstanceLocator +class JamDetector : public InstanceLocator { public: - /** * This function pointer is called if jam state changes (assuming jamming detection is enabled). * @@ -175,35 +174,35 @@ public: private: static void HandleTimer(Timer &aTimer); - void HandleTimer(void); - void UpdateHistory(bool aThresholdExceeded); - void UpdateJamState(void); + void HandleTimer(void); + void UpdateHistory(bool aThresholdExceeded); + void UpdateJamState(void); private: enum { - kMaxWindow = 63, // Max window size - kDefaultRssiThreshold = 0, + kMaxWindow = 63, // Max window size + kDefaultRssiThreshold = 0, - kMaxSampleInterval = 256, // in ms - kMinSampleInterval = 2, // in ms - kMaxRandomDelay = 4, // in ms - kOneSecondInterval = 1000 // in ms + kMaxSampleInterval = 256, // in ms + kMinSampleInterval = 2, // in ms + kMaxRandomDelay = 4, // in ms + kOneSecondInterval = 1000 // in ms }; - Handler mHandler; // Handler/callback to inform about jamming state - void *mContext; // Context for handler/callback - int8_t mRssiThreshold; // RSSI threshold for jam detection - TimerMilli mTimer; // RSSI sample timer - uint64_t mHistoryBitmap; // History bitmap, each bit correspond to 1 sec interval - uint32_t mCurSecondStartTime; // Start time for current 1 sec interval - uint16_t mSampleInterval; // Current sample interval - uint8_t mWindow : 6; // Window (in sec) to monitor jamming - uint8_t mBusyPeriod : 6; // BusyPeriod (in sec) with mWindow to alert jamming - bool mEnabled : 1; // If jam detection is enabled - bool mAlwaysAboveThreshold : 1; // State for current 1 sec interval - bool mJamState : 1; // Current jam state + Handler mHandler; // Handler/callback to inform about jamming state + void * mContext; // Context for handler/callback + int8_t mRssiThreshold; // RSSI threshold for jam detection + TimerMilli mTimer; // RSSI sample timer + uint64_t mHistoryBitmap; // History bitmap, each bit correspond to 1 sec interval + uint32_t mCurSecondStartTime; // Start time for current 1 sec interval + uint16_t mSampleInterval; // Current sample interval + uint8_t mWindow : 6; // Window (in sec) to monitor jamming + uint8_t mBusyPeriod : 6; // BusyPeriod (in sec) with mWindow to alert jamming + bool mEnabled : 1; // If jam detection is enabled + bool mAlwaysAboveThreshold : 1; // State for current 1 sec interval + bool mJamState : 1; // Current jam state }; /** @@ -211,7 +210,7 @@ private: * */ -} // namespace Utils -} // namespace ot +} // namespace Utils +} // namespace ot -#endif // JAM_DETECTOR_HPP_ +#endif // JAM_DETECTOR_HPP_ diff --git a/src/core/utils/slaac_address.cpp b/src/core/utils/slaac_address.cpp index aede1501c..fae760333 100644 --- a/src/core/utils/slaac_address.cpp +++ b/src/core/utils/slaac_address.cpp @@ -46,17 +46,20 @@ namespace ot { namespace Utils { -void Slaac::UpdateAddresses(otInstance *aInstance, otNetifAddress *aAddresses, uint32_t aNumAddresses, - IidCreator aIidCreator, void *aContext) +void Slaac::UpdateAddresses(otInstance * aInstance, + otNetifAddress *aAddresses, + uint32_t aNumAddresses, + IidCreator aIidCreator, + void * aContext) { otNetworkDataIterator iterator; - otBorderRouterConfig config; + otBorderRouterConfig config; // remove addresses for (size_t i = 0; i < aNumAddresses; i++) { otNetifAddress *address = &aAddresses[i]; - bool found = false; + bool found = false; if (!address->mValid) { @@ -131,8 +134,8 @@ void Slaac::UpdateAddresses(otInstance *aInstance, otNetifAddress *aAddresses, u memcpy(&address->mAddress, &config.mPrefix.mPrefix, 8); address->mPrefixLength = config.mPrefix.mLength; - address->mPreferred = config.mPreferred; - address->mValid = true; + address->mPreferred = config.mPreferred; + address->mValid = true; if (aIidCreator(aInstance, address, aContext) != OT_ERROR_NONE) { @@ -174,10 +177,10 @@ exit: otError SemanticallyOpaqueIidGenerator::CreateIidOnce(otInstance *aInstance, otNetifAddress *aAddress) { - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Crypto::Sha256 sha256; - uint8_t hash[Crypto::Sha256::kHashSize]; - Ip6::Address *address = static_cast(&aAddress->mAddress); + uint8_t hash[Crypto::Sha256::kHashSize]; + Ip6::Address * address = static_cast(&aAddress->mAddress); sha256.Start(); @@ -199,8 +202,8 @@ otError SemanticallyOpaqueIidGenerator::CreateIidOnce(otInstance *aInstance, otN sha256.Finish(hash); - memcpy(&aAddress->mAddress.mFields.m8[OT_IP6_ADDRESS_SIZE - OT_IP6_IID_SIZE], - &hash[sizeof(hash) - OT_IP6_IID_SIZE], OT_IP6_IID_SIZE); + memcpy(&aAddress->mAddress.mFields.m8[OT_IP6_ADDRESS_SIZE - OT_IP6_IID_SIZE], &hash[sizeof(hash) - OT_IP6_IID_SIZE], + OT_IP6_IID_SIZE); VerifyOrExit(!IsAddressRegistered(aInstance, aAddress), error = OT_ERROR_IP6_ADDRESS_CREATION_FAILURE); VerifyOrExit(!address->IsIidReserved(), error = OT_ERROR_IP6_ADDRESS_CREATION_FAILURE); @@ -211,7 +214,7 @@ exit: bool SemanticallyOpaqueIidGenerator::IsAddressRegistered(otInstance *aInstance, otNetifAddress *aCreatedAddress) { - bool result = false; + bool result = false; const otNetifAddress *address = otIp6GetUnicastAddresses(aInstance); while (address != NULL) @@ -229,6 +232,5 @@ exit: return result; } - -} // namespace Slaac -} // namespace ot +} // namespace Utils +} // namespace ot diff --git a/src/core/utils/slaac_address.hpp b/src/core/utils/slaac_address.hpp index 22f2f140a..124caaf81 100644 --- a/src/core/utils/slaac_address.hpp +++ b/src/core/utils/slaac_address.hpp @@ -69,7 +69,7 @@ public: * @retval OT_ERROR_FAILED if creating IID failed. * */ - typedef otError(*IidCreator)(otInstance *aInstance, otNetifAddress *aAddress, void *aContext); + typedef otError (*IidCreator)(otInstance *aInstance, otNetifAddress *aAddress, void *aContext); /** * This function update addresses that shall be automatically created using SLAAC. @@ -81,8 +81,11 @@ public: * @param[in] aContext A pointer to IID creator-specific context data. * */ - static void UpdateAddresses(otInstance *aInstance, otNetifAddress *aAddresses, uint32_t aNumAddresses, - IidCreator aIidCreator, void *aContext); + static void UpdateAddresses(otInstance * aInstance, + otNetifAddress *aAddresses, + uint32_t aNumAddresses, + IidCreator aIidCreator, + void * aContext); /** * This function creates randomly generated IPv6 IID for given IPv6 address. @@ -100,7 +103,7 @@ public: * This class implements the Method for Generating Semantically Opaque IIDs with IPv6 SLAAC (RFC 7217). * */ -class SemanticallyOpaqueIidGenerator: public otSemanticallyOpaqueIidGeneratorData +class SemanticallyOpaqueIidGenerator : public otSemanticallyOpaqueIidGeneratorData { public: /** @@ -157,8 +160,7 @@ private: * @} */ -} // namespace Slaac -} // namespace ot - -#endif // SLAAC_ADDRESS_HPP_ +} // namespace Utils +} // namespace ot +#endif // SLAAC_ADDRESS_HPP_ diff --git a/src/core/utils/wrap_stdbool.h b/src/core/utils/wrap_stdbool.h index 3548e650f..dc131af2c 100644 --- a/src/core/utils/wrap_stdbool.h +++ b/src/core/utils/wrap_stdbool.h @@ -63,5 +63,4 @@ typedef _Bool bool; #endif // HAVE_STDBOOL_H - #endif // WRAP_STDBOOL_H diff --git a/src/core/utils/wrap_string.h b/src/core/utils/wrap_string.h index b9073bf08..c1d047049 100644 --- a/src/core/utils/wrap_string.h +++ b/src/core/utils/wrap_string.h @@ -40,37 +40,34 @@ /* system provided string.h */ #include - /* These are C functions */ #if defined(__cplusplus) -#define WRAP_EXTERN_C extern "C" +#define WRAP_EXTERN_C extern "C" #else -#define WRAP_EXTERN_C extern +#define WRAP_EXTERN_C extern #endif /* Prototypes for our missing function replacements */ /* See: https://www.freebsd.org/cgi/man.cgi?query=strlcpy */ -WRAP_EXTERN_C size_t missing_strlcpy(char *dst, const char *src, size_t dstsize); +WRAP_EXTERN_C size_t missing_strlcpy(char *dst, const char *src, size_t dstsize); /* See: https://www.freebsd.org/cgi/man.cgi?query=strlcat */ -WRAP_EXTERN_C size_t missing_strlcat(char *dst, const char *src, size_t dstsize); +WRAP_EXTERN_C size_t missing_strlcat(char *dst, const char *src, size_t dstsize); /* See: https://www.freebsd.org/cgi/man.cgi?query=strnlen */ WRAP_EXTERN_C size_t missing_strnlen(const char *s, size_t maxlen); #undef WRAP_EXTERN_C - - #if (!HAVE_STRNLEN) -#define strnlen( S, N ) missing_strnlen( S, N ) +#define strnlen(S, N) missing_strnlen(S, N) #endif #if (!HAVE_STRLCPY) -#define strlcpy( D, S, N ) missing_strlcpy( D, S, N ) +#define strlcpy(D, S, N) missing_strlcpy(D, S, N) #endif #if (!HAVE_STRLCAT) -#define strlcat( D, S, N ) missing_strlcat( D, S, N ) +#define strlcat(D, S, N) missing_strlcat(D, S, N) #endif -#endif // WRAP_STRING_H +#endif // WRAP_STRING_H diff --git a/tests/fuzz/fuzzer_platform.c b/tests/fuzz/fuzzer_platform.c index 2814a63c5..bd3e72a15 100644 --- a/tests/fuzz/fuzzer_platform.c +++ b/tests/fuzz/fuzzer_platform.c @@ -257,10 +257,10 @@ uint32_t otPlatRandomGet(void) uint64_t tmpstate; tmpstate = (uint64_t)33614 * (uint64_t)sRandomState; - q = tmpstate & 0xffffffff; - q = q >> 1; - p = tmpstate >> 32; - mlcg = p + q; + q = tmpstate & 0xffffffff; + q = q >> 1; + p = tmpstate >> 32; + mlcg = p + q; if (mlcg & 0x80000000) { @@ -306,8 +306,7 @@ otError otPlatSettingsAbandonChange(otInstance *aInstance) return OT_ERROR_NONE; } -otError otPlatSettingsGet(otInstance *aInstance, uint16_t aKey, int aIndex, uint8_t *aValue, - uint16_t *aValueLength) +otError otPlatSettingsGet(otInstance *aInstance, uint16_t aKey, int aIndex, uint8_t *aValue, uint16_t *aValueLength) { (void)aInstance; (void)aKey; diff --git a/tests/fuzz/ip6_send.cpp b/tests/fuzz/ip6_send.cpp index ec639a5d7..3c4125f46 100644 --- a/tests/fuzz/ip6_send.cpp +++ b/tests/fuzz/ip6_send.cpp @@ -45,9 +45,9 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) const otPanId panId = 0xdead; otInstance *instance = NULL; - otMessage *message = NULL; - otError error = OT_ERROR_NONE; - bool isSecure; + otMessage * message = NULL; + otError error = OT_ERROR_NONE; + bool isSecure; VerifyOrExit(size > 0); diff --git a/tests/fuzz/radio_receive_done.cpp b/tests/fuzz/radio_receive_done.cpp index 2e20e2859..2a16b473c 100644 --- a/tests/fuzz/radio_receive_done.cpp +++ b/tests/fuzz/radio_receive_done.cpp @@ -45,9 +45,9 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { const otPanId panId = 0xdead; - otInstance *instance = NULL; + otInstance * instance = NULL; otRadioFrame frame; - uint8_t *buf = NULL; + uint8_t * buf = NULL; VerifyOrExit(size <= OT_RADIO_FRAME_MAX_SIZE); @@ -62,9 +62,9 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) buf = static_cast(malloc(size)); memset(&frame, 0, sizeof(frame)); - frame.mPsdu = buf; + frame.mPsdu = buf; frame.mChannel = 11; - frame.mLength = static_cast(size); + frame.mLength = static_cast(size); memcpy(buf, data, frame.mLength); diff --git a/tests/unit/test_aes.cpp b/tests/unit/test_aes.cpp index c9222fec9..f6eda4b44 100644 --- a/tests/unit/test_aes.cpp +++ b/tests/unit/test_aes.cpp @@ -41,49 +41,30 @@ */ void TestMacBeaconFrame(void) { - uint8_t key[] = - { - 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, - 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, + uint8_t key[] = { + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, }; - uint8_t test[] = - { - 0x08, 0xD0, 0x84, 0x21, 0x43, 0x01, 0x00, 0x00, - 0x00, 0x00, 0x48, 0xDE, 0xAC, 0x02, 0x05, 0x00, - 0x00, 0x00, 0x55, 0xCF, 0x00, 0x00, 0x51, 0x52, - 0x53, 0x54, 0x22, 0x3B, 0xC1, 0xEC, 0x84, 0x1A, - 0xB5, 0x53 - }; + uint8_t test[] = {0x08, 0xD0, 0x84, 0x21, 0x43, 0x01, 0x00, 0x00, 0x00, 0x00, 0x48, 0xDE, + 0xAC, 0x02, 0x05, 0x00, 0x00, 0x00, 0x55, 0xCF, 0x00, 0x00, 0x51, 0x52, + 0x53, 0x54, 0x22, 0x3B, 0xC1, 0xEC, 0x84, 0x1A, 0xB5, 0x53}; - uint8_t encrypted[] = - { - 0x08, 0xD0, 0x84, 0x21, 0x43, 0x01, 0x00, 0x00, - 0x00, 0x00, 0x48, 0xDE, 0xAC, 0x02, 0x05, 0x00, - 0x00, 0x00, 0x55, 0xCF, 0x00, 0x00, 0x51, 0x52, - 0x53, 0x54, 0x22, 0x3B, 0xC1, 0xEC, 0x84, 0x1A, - 0xB5, 0x53 - }; + uint8_t encrypted[] = {0x08, 0xD0, 0x84, 0x21, 0x43, 0x01, 0x00, 0x00, 0x00, 0x00, 0x48, 0xDE, + 0xAC, 0x02, 0x05, 0x00, 0x00, 0x00, 0x55, 0xCF, 0x00, 0x00, 0x51, 0x52, + 0x53, 0x54, 0x22, 0x3B, 0xC1, 0xEC, 0x84, 0x1A, 0xB5, 0x53}; - uint8_t decrypted[] = - { - 0x08, 0xD0, 0x84, 0x21, 0x43, 0x01, 0x00, 0x00, - 0x00, 0x00, 0x48, 0xDE, 0xAC, 0x02, 0x05, 0x00, - 0x00, 0x00, 0x55, 0xCF, 0x00, 0x00, 0x51, 0x52, - 0x53, 0x54, 0x22, 0x3B, 0xC1, 0xEC, 0x84, 0x1A, - 0xB5, 0x53 - }; + uint8_t decrypted[] = {0x08, 0xD0, 0x84, 0x21, 0x43, 0x01, 0x00, 0x00, 0x00, 0x00, 0x48, 0xDE, + 0xAC, 0x02, 0x05, 0x00, 0x00, 0x00, 0x55, 0xCF, 0x00, 0x00, 0x51, 0x52, + 0x53, 0x54, 0x22, 0x3B, 0xC1, 0xEC, 0x84, 0x1A, 0xB5, 0x53}; - otInstance *instance = testInitInstance(); + otInstance * instance = testInitInstance(); ot::Crypto::AesCcm aesCcm; - uint32_t headerLength = sizeof(test) - 8; - uint32_t payloadLength = 0; - uint8_t tagLength = 8; + uint32_t headerLength = sizeof(test) - 8; + uint32_t payloadLength = 0; + uint8_t tagLength = 8; - uint8_t nonce[] = - { - 0xAC, 0xDE, 0x48, 0x00, 0x00, 0x00, 0x00, 0x01, - 0x00, 0x00, 0x00, 0x05, 0x02, + uint8_t nonce[] = { + 0xAC, 0xDE, 0x48, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05, 0x02, }; VerifyOrQuit(instance != NULL, "Null OpenThread instance"); @@ -93,15 +74,13 @@ void TestMacBeaconFrame(void) aesCcm.Header(test, headerLength); aesCcm.Finalize(test + headerLength, &tagLength); - VerifyOrQuit(memcmp(test, encrypted, sizeof(encrypted)) == 0, - "TestMacBeaconFrame encrypt failed"); + VerifyOrQuit(memcmp(test, encrypted, sizeof(encrypted)) == 0, "TestMacBeaconFrame encrypt failed"); aesCcm.Init(headerLength, payloadLength, tagLength, nonce, sizeof(nonce)); aesCcm.Header(test, headerLength); aesCcm.Finalize(test + headerLength, &tagLength); - VerifyOrQuit(memcmp(test, decrypted, sizeof(decrypted)) == 0, - "TestMacBeaconFrame decrypt failed"); + VerifyOrQuit(memcmp(test, decrypted, sizeof(decrypted)) == 0, "TestMacBeaconFrame decrypt failed"); testFreeInstance(instance); } @@ -111,46 +90,33 @@ void TestMacBeaconFrame(void) */ void TestMacCommandFrame() { - uint8_t key[] = - { - 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, - 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, + uint8_t key[] = { + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, }; - uint8_t test[] = - { - 0x2B, 0xDC, 0x84, 0x21, 0x43, 0x02, 0x00, 0x00, - 0x00, 0x00, 0x48, 0xDE, 0xAC, 0xFF, 0xFF, 0x01, - 0x00, 0x00, 0x00, 0x00, 0x48, 0xDE, 0xAC, 0x06, - 0x05, 0x00, 0x00, 0x00, 0x01, 0xCE, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + uint8_t test[] = { + 0x2B, 0xDC, 0x84, 0x21, 0x43, 0x02, 0x00, 0x00, 0x00, 0x00, 0x48, 0xDE, 0xAC, + 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x48, 0xDE, 0xAC, 0x06, 0x05, 0x00, + 0x00, 0x00, 0x01, 0xCE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; uint32_t headerLength = 29, payloadLength = 1; - uint8_t tagLength = 8; + uint8_t tagLength = 8; - uint8_t encrypted[] = - { - 0x2B, 0xDC, 0x84, 0x21, 0x43, 0x02, 0x00, 0x00, - 0x00, 0x00, 0x48, 0xDE, 0xAC, 0xFF, 0xFF, 0x01, - 0x00, 0x00, 0x00, 0x00, 0x48, 0xDE, 0xAC, 0x06, - 0x05, 0x00, 0x00, 0x00, 0x01, 0xD8, 0x4F, 0xDE, - 0x52, 0x90, 0x61, 0xF9, 0xC6, 0xF1, + uint8_t encrypted[] = { + 0x2B, 0xDC, 0x84, 0x21, 0x43, 0x02, 0x00, 0x00, 0x00, 0x00, 0x48, 0xDE, 0xAC, + 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x48, 0xDE, 0xAC, 0x06, 0x05, 0x00, + 0x00, 0x00, 0x01, 0xD8, 0x4F, 0xDE, 0x52, 0x90, 0x61, 0xF9, 0xC6, 0xF1, }; - uint8_t decrypted[] = - { - 0x2B, 0xDC, 0x84, 0x21, 0x43, 0x02, 0x00, 0x00, - 0x00, 0x00, 0x48, 0xDE, 0xAC, 0xFF, 0xFF, 0x01, - 0x00, 0x00, 0x00, 0x00, 0x48, 0xDE, 0xAC, 0x06, - 0x05, 0x00, 0x00, 0x00, 0x01, 0xCE, 0x4F, 0xDE, - 0x52, 0x90, 0x61, 0xF9, 0xC6, 0xF1, + uint8_t decrypted[] = { + 0x2B, 0xDC, 0x84, 0x21, 0x43, 0x02, 0x00, 0x00, 0x00, 0x00, 0x48, 0xDE, 0xAC, + 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x48, 0xDE, 0xAC, 0x06, 0x05, 0x00, + 0x00, 0x00, 0x01, 0xCE, 0x4F, 0xDE, 0x52, 0x90, 0x61, 0xF9, 0xC6, 0xF1, }; - uint8_t nonce[] = - { - 0xAC, 0xDE, 0x48, 0x00, 0x00, 0x00, 0x00, 0x01, - 0x00, 0x00, 0x00, 0x05, 0x06, + uint8_t nonce[] = { + 0xAC, 0xDE, 0x48, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05, 0x06, }; ot::Crypto::AesCcm aesCcm; @@ -159,16 +125,14 @@ void TestMacCommandFrame() aesCcm.Header(test, headerLength); aesCcm.Payload(test + headerLength, test + headerLength, payloadLength, true); aesCcm.Finalize(test + headerLength + payloadLength, &tagLength); - VerifyOrQuit(memcmp(test, encrypted, sizeof(encrypted)) == 0, - "TestMacCommandFrame encrypt failed\n"); + VerifyOrQuit(memcmp(test, encrypted, sizeof(encrypted)) == 0, "TestMacCommandFrame encrypt failed\n"); aesCcm.Init(headerLength, payloadLength, tagLength, nonce, sizeof(nonce)); aesCcm.Header(test, headerLength); aesCcm.Payload(test + headerLength, test + headerLength, payloadLength, false); aesCcm.Finalize(test + headerLength + payloadLength, &tagLength); - VerifyOrQuit(memcmp(test, decrypted, sizeof(decrypted)) == 0, - "TestMacCommandFrame decrypt failed\n"); + VerifyOrQuit(memcmp(test, decrypted, sizeof(decrypted)) == 0, "TestMacCommandFrame decrypt failed\n"); } #ifdef ENABLE_TEST_MAIN diff --git a/tests/unit/test_child.cpp b/tests/unit/test_child.cpp index 7eeb9637f..56ab72a2f 100644 --- a/tests/unit/test_child.cpp +++ b/tests/unit/test_child.cpp @@ -31,8 +31,8 @@ #include #include -#include "common/instance.hpp" #include "test_util.h" +#include "common/instance.hpp" #include "thread/topology.hpp" namespace ot { @@ -47,10 +47,10 @@ enum void VerifyChildIp6Addresses(const Child &aChild, uint8_t aAddressListLength, const Ip6::Address aAddressList[]) { Child::Ip6AddressIterator iterator; - Ip6::Address address; - bool addressObserved[kMaxChildIp6Addresses]; - bool addressIsMeshLocal[kMaxChildIp6Addresses]; - bool hasMeshLocal = false; + Ip6::Address address; + bool addressObserved[kMaxChildIp6Addresses]; + bool addressIsMeshLocal[kMaxChildIp6Addresses]; + bool hasMeshLocal = false; for (uint8_t index = 0; index < aAddressListLength; index++) { @@ -75,7 +75,7 @@ void VerifyChildIp6Addresses(const Child &aChild, uint8_t aAddressListLength, co { if (address == aAddressList[index]) { - addressIsInList = true; + addressIsInList = true; addressObserved[index] = true; break; } @@ -106,20 +106,16 @@ void VerifyChildIp6Addresses(const Child &aChild, uint8_t aAddressListLength, co void TestChildIp6Address(void) { - Child child; + Child child; Ip6::Address addresses[kMaxChildIp6Addresses]; - uint8_t numAddresses; - const char *ip6Addresses[] = - { + uint8_t numAddresses; + const char * ip6Addresses[] = { "fd00:1234::1234", "fd6b:e251:52fb:0:12e6:b94c:1c28:c56a", "fd00:1234::204c:3d7c:98f6:9a1b", }; - const uint8_t meshLocalIid[] = - { - 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 - }; + const uint8_t meshLocalIid[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}; sInstance = testInitInstance(); VerifyOrQuit(sInstance != NULL, "Null instance"); @@ -241,7 +237,7 @@ void TestChildIp6Address(void) { Ip6::Address updatedAddressList[kMaxChildIp6Addresses]; - uint8_t updatedListIndex = 0; + uint8_t updatedListIndex = 0; for (uint8_t index = 0; index < numAddresses; index++) { @@ -260,7 +256,7 @@ void TestChildIp6Address(void) testFreeInstance(sInstance); } -} // namespace ot +} // namespace ot #ifdef ENABLE_TEST_MAIN int main(void) diff --git a/tests/unit/test_heap.cpp b/tests/unit/test_heap.cpp index f00e00835..f91eac959 100644 --- a/tests/unit/test_heap.cpp +++ b/tests/unit/test_heap.cpp @@ -79,13 +79,13 @@ void TestAllocateRandomly(size_t aSizeLimit, unsigned int aSeed) { struct Node { - Node *mNext; + Node * mNext; size_t mSize; }; ot::Crypto::Heap heap; - Node head; - size_t nnodes = 0; + Node head; + size_t nnodes = 0; srand(aSeed); @@ -104,7 +104,7 @@ void TestAllocateRandomly(size_t aSizeLimit, unsigned int aSeed) } VerifyOrQuit(last->mNext->mNext == NULL, "TestAllocateRandomly memory not initialized to zero!\n"); - last = last->mNext; + last = last->mNext; last->mSize = size; ++nnodes; @@ -134,8 +134,7 @@ void TestAllocateRandomly(size_t aSizeLimit, unsigned int aSeed) --nnodes; } - } - while (true); + } while (true); last = head.mNext; diff --git a/tests/unit/test_hmac_sha256.cpp b/tests/unit/test_hmac_sha256.cpp index 0401e9215..dd9f7449a 100644 --- a/tests/unit/test_hmac_sha256.cpp +++ b/tests/unit/test_hmac_sha256.cpp @@ -42,17 +42,14 @@ void TestHmacSha256(void) { const char *key; const char *data; - uint8_t hash[ot::Crypto::HmacSha256::kHashSize]; - } tests[] = - { + uint8_t hash[ot::Crypto::HmacSha256::kHashSize]; + } tests[] = { { "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b", "Hi There", { - 0xb0, 0x34, 0x4c, 0x61, 0xd8, 0xdb, 0x38, 0x53, - 0x5c, 0xa8, 0xaf, 0xce, 0xaf, 0x0b, 0xf1, 0x2b, - 0x88, 0x1d, 0xc2, 0x00, 0xc9, 0x83, 0x3d, 0xa7, - 0x26, 0xe9, 0x37, 0x6c, 0x2e, 0x32, 0xcf, 0xf7, + 0xb0, 0x34, 0x4c, 0x61, 0xd8, 0xdb, 0x38, 0x53, 0x5c, 0xa8, 0xaf, 0xce, 0xaf, 0x0b, 0xf1, 0x2b, + 0x88, 0x1d, 0xc2, 0x00, 0xc9, 0x83, 0x3d, 0xa7, 0x26, 0xe9, 0x37, 0x6c, 0x2e, 0x32, 0xcf, 0xf7, }, }, { @@ -67,7 +64,7 @@ void TestHmacSha256(void) // Make sure hmac is destructed before freeing instance. { ot::Crypto::HmacSha256 hmac; - uint8_t hash[ot::Crypto::HmacSha256::kHashSize]; + uint8_t hash[ot::Crypto::HmacSha256::kHashSize]; VerifyOrQuit(instance != NULL, "Null OpenThread instance"); @@ -77,8 +74,7 @@ void TestHmacSha256(void) hmac.Update(reinterpret_cast(tests[i].data), static_cast(strlen(tests[i].data))); hmac.Finish(hash); - VerifyOrQuit(memcmp(hash, tests[i].hash, sizeof(tests[i].hash)) == 0, - "HMAC-SHA-256 failed\n"); + VerifyOrQuit(memcmp(hash, tests[i].hash, sizeof(tests[i].hash)) == 0, "HMAC-SHA-256 failed\n"); } } diff --git a/tests/unit/test_link_quality.cpp b/tests/unit/test_link_quality.cpp index d82895f98..0fb70b718 100644 --- a/tests/unit/test_link_quality.cpp +++ b/tests/unit/test_link_quality.cpp @@ -38,32 +38,32 @@ namespace ot { enum { - kMaxRssValue = 0, - kMinRssValue = -128, + kMaxRssValue = 0, + kMinRssValue = -128, - kStringBuffferSize = 80, + kStringBuffferSize = 80, - kRssAverageMaxDiff = 16, - kNumRssAdds = 300, + kRssAverageMaxDiff = 16, + kNumRssAdds = 300, kRawAverageBitShift = 3, kRawAverageMultiple = (1 << kRawAverageBitShift), kRawAverageBitMask = (1 << kRawAverageBitShift) - 1, }; -#define MIN_RSS(_rss1, _rss2) (((_rss1) < (_rss2)) ? (_rss1) : (_rss2)) -#define MAX_RSS(_rss1, _rss2) (((_rss1) < (_rss2)) ? (_rss2) : (_rss1)) -#define ABS(value) (((value) >= 0) ? (value) : -(value)) +#define MIN_RSS(_rss1, _rss2) (((_rss1) < (_rss2)) ? (_rss1) : (_rss2)) +#define MAX_RSS(_rss1, _rss2) (((_rss1) < (_rss2)) ? (_rss2) : (_rss1)) +#define ABS(value) (((value) >= 0) ? (value) : -(value)) // This struct contains RSS values and test data for checking link quality info calss. struct RssTestData { - const int8_t *mRssList; // Array of RSS values. - size_t mRssListSize; // Size of RSS list. - uint8_t mExpectedLinkQuality; // Expected final link quality value. + const int8_t *mRssList; // Array of RSS values. + size_t mRssListSize; // Size of RSS list. + uint8_t mExpectedLinkQuality; // Expected final link quality value. }; -int8_t sNoiseFloor = -100; // dBm +int8_t sNoiseFloor = -100; // dBm // Check and verify the raw average RSS value to match the value from GetAverage(). void VerifyRawRssValue(int8_t aAverage, uint16_t aRawValue) @@ -95,8 +95,8 @@ void PrintOutcome(LinkQualityInfo &aLinkInfo) void TestLinkQualityData(RssTestData aRssData) { LinkQualityInfo linkInfo; - int8_t rss, ave, min, max; - size_t i; + int8_t rss, ave, min, max; + size_t i; printf("- - - - - - - - - - - - - - - - - -\n"); min = kMinRssValue; @@ -124,7 +124,7 @@ void TestLinkQualityData(RssTestData aRssData) // Check and verify the raw average RSS value to match the value from GetAverage(). void VerifyRawRssValue(RssAverager &aRssAverager) { - int8_t average = aRssAverager.GetAverage(); + int8_t average = aRssAverager.GetAverage(); uint16_t rawValue = aRssAverager.GetRaw(); if (average != OT_RADIO_RSSI_INVALID) @@ -150,7 +150,6 @@ void PrintOutcome(RssAverager &aRssAverager) printf(" -> PASS\n"); } - int8_t GetRandomRss(void) { uint32_t value; @@ -161,12 +160,12 @@ int8_t GetRandomRss(void) void TestRssAveraging(void) { - RssAverager rssAverager; - int8_t rss, rss2, ave; - int16_t diff; - size_t i, j, k; - const int8_t rssValues[] = { kMinRssValue, -70, -40, -41, -10, kMaxRssValue}; - int16_t sum; + RssAverager rssAverager; + int8_t rss, rss2, ave; + int16_t diff; + size_t i, j, k; + const int8_t rssValues[] = {kMinRssValue, -70, -40, -41, -10, kMaxRssValue}; + int16_t sum; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Values after initialization/reset. @@ -184,8 +183,7 @@ void TestRssAveraging(void) rss = -70; printf("AddRss(%d): ", rss); rssAverager.Add(rss); - VerifyOrQuit(rssAverager.GetAverage() == rss, - "TestLinkQualityInfo - GetAverage() failed after a single AddRss()."); + VerifyOrQuit(rssAverager.GetAverage() == rss, "TestLinkQualityInfo - GetAverage() failed after a single AddRss()."); VerifyRawRssValue(rssAverager); PrintOutcome(rssAverager); @@ -219,7 +217,6 @@ void TestRssAveraging(void) } PrintOutcome(rssAverager); - } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -316,8 +313,7 @@ void TestRssAveraging(void) "TestLinkQualityInfo failed - GetAverage() is larger than min value."); diff = ave; diff -= (rss + rss2) >> 1; - VerifyOrQuit(ABS(diff) <= kRssAverageMaxDiff, - "TestLinkQualityInfo failed - GetAverage() is incorrect"); + VerifyOrQuit(ABS(diff) <= kRssAverageMaxDiff, "TestLinkQualityInfo failed - GetAverage() is incorrect"); VerifyRawRssValue(rssAverager); } @@ -356,36 +352,32 @@ void TestRssAveraging(void) void TestLinkQualityCalculations(void) { - const int8_t rssList1[] = { -81, -80, -79, -78, -76, -80, -77, -75, -77, -76, -77, -74}; - const RssTestData rssData1 = - { - rssList1, // mRssList - sizeof(rssList1), // mRssListSize - 3 // mExpectedLinkQuality + const int8_t rssList1[] = {-81, -80, -79, -78, -76, -80, -77, -75, -77, -76, -77, -74}; + const RssTestData rssData1 = { + rssList1, // mRssList + sizeof(rssList1), // mRssListSize + 3 // mExpectedLinkQuality }; - const int8_t rssList2[] = { -90, -80, -85 }; - const RssTestData rssData2 = - { - rssList2, // mRssList - sizeof(rssList2), // mRssListSize - 2 // mExpectedLinkQuality + const int8_t rssList2[] = {-90, -80, -85}; + const RssTestData rssData2 = { + rssList2, // mRssList + sizeof(rssList2), // mRssListSize + 2 // mExpectedLinkQuality }; - const int8_t rssList3[] = { -95, -96, -98, -99, -100, -100, -98, -99, -100, -100, -100, -100, -100 }; - const RssTestData rssData3 = - { - rssList3, // mRssList - sizeof(rssList3), // mRssListSize - 0 // mExpectedLinkQuality + const int8_t rssList3[] = {-95, -96, -98, -99, -100, -100, -98, -99, -100, -100, -100, -100, -100}; + const RssTestData rssData3 = { + rssList3, // mRssList + sizeof(rssList3), // mRssListSize + 0 // mExpectedLinkQuality }; - const int8_t rssList4[] = { -75, -100, -100, -100, -100, -100, -95, -92, -93, -94, -93, -93 }; - const RssTestData rssData4 = - { - rssList4, // mRssList - sizeof(rssList4), // mRssListSize - 1 // mExpectedLinkQuality + const int8_t rssList4[] = {-75, -100, -100, -100, -100, -100, -95, -92, -93, -94, -93, -93}; + const RssTestData rssData4 = { + rssList4, // mRssList + sizeof(rssList4), // mRssListSize + 1 // mExpectedLinkQuality }; TestLinkQualityData(rssData1); @@ -397,13 +389,13 @@ void TestLinkQualityCalculations(void) void TestSuccessRateTracker(void) { SuccessRateTracker rateTracker; - uint16_t sampleCount; + uint16_t sampleCount; const uint16_t kMaxSamples = 5000; - const uint16_t kMaxRate = SuccessRateTracker::kMaxRateValue; - const double kMaxError = 1.0; // Max permitted error in percentage - const uint16_t kWeightLimit[] = { 64, 128, 256, 300, 512, 810, 900 }; + const uint16_t kMaxRate = SuccessRateTracker::kMaxRateValue; + const double kMaxError = 1.0; // Max permitted error in percentage + const uint16_t kWeightLimit[] = {64, 128, 256, 300, 512, 810, 900}; printf("\nTesting SuccessRateTracker\n"); @@ -429,7 +421,8 @@ void TestSuccessRateTracker(void) rateTracker.AddSample(false, sampleCount); VerifyOrQuit(rateTracker.GetSuccessRate() == 0, "SuccessRateTracker: rate incorrect all failure case"); - VerifyOrQuit(rateTracker.GetFailureRate() == kMaxRate, "SuccessRateTracker: rate incorrect in all failure case"); + VerifyOrQuit(rateTracker.GetFailureRate() == kMaxRate, + "SuccessRateTracker: rate incorrect in all failure case"); } // Adding success/failure at different rates and checking the RateTracker rate for every sample @@ -437,8 +430,8 @@ void TestSuccessRateTracker(void) for (uint16_t testRound = 0; testRound < sizeof(kWeightLimit) / sizeof(kWeightLimit[0]) * 2; testRound++) { uint16_t weightLimit; - bool reverseLogic; - double maxDiff = 0; + bool reverseLogic; + double maxDiff = 0; // Reverse the logic (add success instead of failure) on even test rounds reverseLogic = ((testRound % 2) == 0); @@ -456,10 +449,10 @@ void TestSuccessRateTracker(void) for (sampleCount = 1; sampleCount < kMaxSamples; sampleCount++) { - double expectedRate; - double failureRate; - double diff; - bool isSuccess = ((sampleCount % period) == 0); + double expectedRate; + double failureRate; + double diff; + bool isSuccess = ((sampleCount % period) == 0); uint16_t weight; if (reverseLogic) @@ -483,8 +476,8 @@ void TestSuccessRateTracker(void) // Calculate the failure rate from rateTracker and expected rate. - failureRate = static_cast(rateTracker.GetFailureRate()) * 100.0 / kMaxRate; // in percent - expectedRate = static_cast(failureCount) * 100.0 / sampleCount; // in percent + failureRate = static_cast(rateTracker.GetFailureRate()) * 100.0 / kMaxRate; // in percent + expectedRate = static_cast(failureCount) * 100.0 / sampleCount; // in percent diff = failureRate - expectedRate; diff = ABS(diff); @@ -502,7 +495,7 @@ void TestSuccessRateTracker(void) } } -} // namespace ot +} // namespace ot #ifdef ENABLE_TEST_MAIN int main(void) diff --git a/tests/unit/test_lowpan.cpp b/tests/unit/test_lowpan.cpp index 267412fdb..ebad97c4f 100644 --- a/tests/unit/test_lowpan.cpp +++ b/tests/unit/test_lowpan.cpp @@ -36,9 +36,9 @@ using ot::Encoding::BigEndian::HostSwap16; namespace ot { -ot::Instance *sInstance; -Ip6::Ip6 *sIp6; -ThreadNetif *sThreadNetif; +ot::Instance * sInstance; +Ip6::Ip6 * sIp6; +ThreadNetif * sThreadNetif; Lowpan::Lowpan *sLowpan; void TestIphcVector::GetCompressedStream(uint8_t *aIphc, uint16_t &aIphcLength) @@ -85,8 +85,7 @@ void TestIphcVector::GetUncompressedStream(Message &aMessage) if (mExtHeader.mLength) { - SuccessOrQuit(aMessage.Append(mExtHeader.mData, mExtHeader.mLength), - "6lo: Message::Append failed"); + SuccessOrQuit(aMessage.Append(mExtHeader.mData, mExtHeader.mLength), "6lo: Message::Append failed"); } if (mIpTunneledHeader.GetPayloadLength()) @@ -114,21 +113,16 @@ static void Init() sThreadNetif->GetMle().SetMeshLocalPrefix(meshLocalPrefix); // Emulate global prefixes with contextes. - uint8_t mockNetworkData[] = - { + uint8_t mockNetworkData[] = { // Prefix 2001:2:0:1::/64 - 0x03, 0x0e, // Prefix TLV - 0x00, 0x40, - 0x20, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, - 0x07, 0x02, // 6LoWPAN Context ID TLV - 0x11, 0x40, // Context ID = 1, C = TRUE + 0x03, 0x0e, // Prefix TLV + 0x00, 0x40, 0x20, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x07, 0x02, // 6LoWPAN Context ID TLV + 0x11, 0x40, // Context ID = 1, C = TRUE // Prefix 2001:2:0:2::/64 - 0x03, 0x0e, // Prefix TLV - 0x00, 0x40, - 0x20, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, - 0x07, 0x02, // 6LoWPAN Context ID TLV - 0x02, 0x40 // Context ID = 2, C = FALSE + 0x03, 0x0e, // Prefix TLV + 0x00, 0x40, 0x20, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x07, 0x02, // 6LoWPAN Context ID TLV + 0x02, 0x40 // Context ID = 2, C = FALSE }; sThreadNetif->GetNetworkDataLeader().SetNetworkData(0, 0, true, mockNetworkData, sizeof(mockNetworkData)); @@ -148,9 +142,9 @@ static void Init() static void Test(TestIphcVector &aVector, bool aCompress, bool aDecompress) { Message *message = NULL; - uint8_t result[512]; - uint8_t iphc[512]; - uint8_t ip6[512]; + uint8_t result[512]; + uint8_t iphc[512]; + uint8_t ip6[512]; uint16_t iphcLength; uint16_t ip6Length; @@ -181,15 +175,12 @@ static void Test(TestIphcVector &aVector, bool aCompress, bool aDecompress) aVector.GetUncompressedStream(*message); - int compressBytes = sLowpan->Compress(*message, aVector.mMacSource, aVector.mMacDestination, - result); + int compressBytes = sLowpan->Compress(*message, aVector.mMacSource, aVector.mMacDestination, result); if (aVector.mError == OT_ERROR_NONE) { // Append payload to the LOWPAN_IPHC. - message->Read(message->GetOffset(), - message->GetLength() - message->GetOffset(), - result + compressBytes); + message->Read(message->GetOffset(), message->GetLength() - message->GetOffset(), result + compressBytes); printf("Resulted LOWPAN_IPHC compressed frame: \n"); otTestPrintHex(result, compressBytes + message->GetLength() - message->GetOffset()); @@ -197,8 +188,7 @@ static void Test(TestIphcVector &aVector, bool aCompress, bool aDecompress) VerifyOrQuit(compressBytes == aVector.mIphcHeader.mLength, "6lo: Lowpan::Compress failed"); VerifyOrQuit(message->GetOffset() == aVector.mPayloadOffset, "6lo: Lowpan::Compress failed"); - VerifyOrQuit(memcmp(iphc, result, iphcLength) == 0, - "6lo: Lowpan::Compress failed"); + VerifyOrQuit(memcmp(iphc, result, iphcLength) == 0, "6lo: Lowpan::Compress failed"); } else { @@ -214,8 +204,8 @@ static void Test(TestIphcVector &aVector, bool aCompress, bool aDecompress) VerifyOrQuit((message = sInstance->GetMessagePool().New(Message::kTypeIp6, 0)) != NULL, "6lo: Ip6::NewMessage failed"); - int decompressedBytes = sLowpan->Decompress(*message, aVector.mMacSource, aVector.mMacDestination, - iphc, iphcLength, 0); + int decompressedBytes = + sLowpan->Decompress(*message, aVector.mMacSource, aVector.mMacDestination, iphc, iphcLength, 0); message->Read(0, message->GetLength(), result); @@ -249,18 +239,18 @@ static void Test(TestIphcVector &aVector, bool aCompress, bool aDecompress) /*************************************************************************************************** * @section Test constants. **************************************************************************************************/ -static const uint8_t sTestMacSourceDefaultLong[] = {0x00, 0x00, 0x5e, 0xef, 0x10, 0x22, 0x11, 0x00}; +static const uint8_t sTestMacSourceDefaultLong[] = {0x00, 0x00, 0x5e, 0xef, 0x10, 0x22, 0x11, 0x00}; static const uint8_t sTestMacDestinationDefaultLong[] = {0x00, 0x00, 0x5e, 0xef, 0x10, 0xaa, 0xbb, 0xcc}; -static uint16_t sTestMacSourceDefaultShort = 0x0000; +static uint16_t sTestMacSourceDefaultShort = 0x0000; static uint16_t sTestMacDestinationDefaultShort = 0xc003; -static uint16_t sTestMacDestinationBroadcast = 0xffff; +static uint16_t sTestMacDestinationBroadcast = 0xffff; static const uint8_t sTestPayloadDefault[] = {0x80, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06}; /*************************************************************************************************** -* @section Test cases. -**************************************************************************************************/ + * @section Test cases. + **************************************************************************************************/ static void TestFullyCompressableLongAddresses(void) { @@ -271,8 +261,7 @@ static void TestFullyCompressableLongAddresses(void) testVector.SetMacDestination(sTestMacDestinationDefaultLong); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fe80::200:5eef:1022:1100", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, "fe80::200:5eef:1022:1100", "fe80::200:5eef:10aa:bbcc"); // Set LOWPAN_IPHC header. @@ -297,8 +286,7 @@ static void TestFullyCompressableShortAddresses(void) testVector.SetMacDestination(sTestMacDestinationDefaultShort); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fe80::ff:fe00:0000", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, "fe80::ff:fe00:0000", "fe80::ff:fe00:c003"); // Set LOWPAN_IPHC header. @@ -323,8 +311,7 @@ static void TestFullyCompressableShortLongAddresses(void) testVector.SetMacDestination(sTestMacDestinationDefaultLong); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fe80::ff:fe00:0000", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, "fe80::ff:fe00:0000", "fe80::200:5eef:10aa:bbcc"); // Set LOWPAN_IPHC header. @@ -349,8 +336,7 @@ static void TestFullyCompressableLongShortAddresses(void) testVector.SetMacDestination(sTestMacDestinationDefaultShort); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fe80::200:5eef:1022:1100", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, "fe80::200:5eef:1022:1100", "fe80::ff:fe00:c003"); // Set LOWPAN_IPHC header. @@ -375,9 +361,7 @@ static void TestSourceUnspecifiedAddress(void) testVector.SetMacDestination(sTestMacDestinationDefaultShort); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "::", - "fe80::ff:fe00:c003"); + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, "::", "fe80::ff:fe00:c003"); // Set LOWPAN_IPHC header. uint8_t iphc[] = {0x7a, 0x43, 0x3a}; @@ -402,16 +386,12 @@ static void TestSource128bitDestination128bitAddresses(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "2001:2:0:3:aaaa:bbbb:cccc:dddd", - "2001:2:0:4::"); + "2001:2:0:3:aaaa:bbbb:cccc:dddd", "2001:2:0:4::"); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7a, 0x00, 0x3a, 0x20, 0x01, 0x00, 0x02, 0x00, - 0x00, 0x00, 0x03, 0xaa, 0xaa, 0xbb, 0xbb, 0xcc, - 0xcc, 0xdd, 0xdd, 0x20, 0x01, 0x00, 0x02, 0x00, - 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00 - }; + uint8_t iphc[] = {0x7a, 0x00, 0x3a, 0x20, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0xaa, + 0xaa, 0xbb, 0xbb, 0xcc, 0xcc, 0xdd, 0xdd, 0x20, 0x01, 0x00, 0x02, 0x00, + 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -432,15 +412,12 @@ static void TestSource64bitDestination64bitLongAddresses(void) testVector.SetMacDestination(sTestMacDestinationDefaultLong); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fe80::200:5eef:1022:1101", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, "fe80::200:5eef:1022:1101", "fe80::200:5eef:10aa:bbcd"); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7a, 0x11, 0x3a, 0x02, 0x00, 0x5e, 0xef, 0x10, - 0x22, 0x11, 0x01, 0x02, 0x00, 0x5e, 0xef, 0x10, - 0xaa, 0xbb, 0xcd - }; + uint8_t iphc[] = {0x7a, 0x11, 0x3a, 0x02, 0x00, 0x5e, 0xef, 0x10, 0x22, 0x11, + 0x01, 0x02, 0x00, 0x5e, 0xef, 0x10, 0xaa, 0xbb, 0xcd}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -461,15 +438,12 @@ static void TestSource64bitDestination64bitShortAddresses(void) testVector.SetMacDestination(sTestMacDestinationDefaultShort); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fe80::200:5eef:1022:1101", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, "fe80::200:5eef:1022:1101", "fe80::200:5eef:10aa:bbcd"); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7a, 0x11, 0x3a, 0x02, 0x00, 0x5e, 0xef, 0x10, - 0x22, 0x11, 0x01, 0x02, 0x00, 0x5e, 0xef, 0x10, - 0xaa, 0xbb, 0xcd - }; + uint8_t iphc[] = {0x7a, 0x11, 0x3a, 0x02, 0x00, 0x5e, 0xef, 0x10, 0x22, 0x11, + 0x01, 0x02, 0x00, 0x5e, 0xef, 0x10, 0xaa, 0xbb, 0xcd}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -490,8 +464,7 @@ static void TestSource16bitDestination16bitAddresses(void) testVector.SetMacDestination(sTestMacDestinationDefaultShort); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fe80::ff:fe00:0001", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, "fe80::ff:fe00:0001", "fe80::ff:fe00:c004"); // Set LOWPAN_IPHC header. @@ -516,8 +489,7 @@ static void TestSourceCompressedDestination16bitAddresses(void) testVector.SetMacDestination(sTestMacDestinationDefaultLong); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fe80::200:5eef:1022:1100", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, "fe80::200:5eef:1022:1100", "fe80::ff:fe00:beaf"); // Set LOWPAN_IPHC header. @@ -542,15 +514,12 @@ static void TestSourceCompressedDestination128bitAddresses(void) testVector.SetMacDestination(sTestMacDestinationDefaultLong); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fe80::200:5eef:1022:1100", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, "fe80::200:5eef:1022:1100", "2001:2:0:4::"); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7a, 0x30, 0x3a, 0x20, 0x01, 0x00, 0x02, 0x00, - 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00 - }; + uint8_t iphc[] = {0x7a, 0x30, 0x3a, 0x20, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -562,7 +531,6 @@ static void TestSourceCompressedDestination128bitAddresses(void) Test(testVector, true, true); } - static void TestMulticast128bitAddress(void) { TestIphcVector testVector("Multicast address inline"); @@ -572,15 +540,12 @@ static void TestMulticast128bitAddress(void) testVector.SetMacDestination(sTestMacDestinationBroadcast); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fe80::200:5eef:1022:1100", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, "fe80::200:5eef:1022:1100", "ff05::100:0030:0001"); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7a, 0x38, 0x3a, 0xff, 0x05, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, - 0x30, 0x00, 0x01 - }; + uint8_t iphc[] = {0x7a, 0x38, 0x3a, 0xff, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x30, 0x00, 0x01}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -601,14 +566,11 @@ static void TestMulticast48bitAddress(void) testVector.SetMacDestination(sTestMacDestinationBroadcast); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fe80::200:5eef:1022:1100", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, "fe80::200:5eef:1022:1100", "ff05::1:0030:0001"); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7a, 0x39, 0x3a, 0x05, 0x01, 0x00, 0x30, 0x00, - 0x01 - }; + uint8_t iphc[] = {0x7a, 0x39, 0x3a, 0x05, 0x01, 0x00, 0x30, 0x00, 0x01}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -629,14 +591,11 @@ static void TestMulticast32bitAddress(void) testVector.SetMacDestination(sTestMacDestinationBroadcast); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fe80::200:5eef:1022:1100", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, "fe80::200:5eef:1022:1100", "ff03::fc"); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7a, 0x1a, 0x3a, 0x02, 0x00, 0x5e, 0xef, 0x10, - 0x22, 0x11, 0x00, 0x03, 0x00, 0x00, 0xfc - }; + uint8_t iphc[] = {0x7a, 0x1a, 0x3a, 0x02, 0x00, 0x5e, 0xef, 0x10, 0x22, 0x11, 0x00, 0x03, 0x00, 0x00, 0xfc}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -657,8 +616,7 @@ static void TestMulticast8bitAddress(void) testVector.SetMacDestination(sTestMacDestinationBroadcast); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fe80::200:5eef:1022:1100", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, "fe80::200:5eef:1022:1100", "ff02::2"); // Set LOWPAN_IPHC header. @@ -684,14 +642,11 @@ static void TestStatefulSource64bitDestination64bitContext0(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fd00:cafe:face:1234:abcd:ef01:2345:6789", - "fd00:cafe:face:1234:c31d:a702:0d41:beef"); + "fd00:cafe:face:1234:abcd:ef01:2345:6789", "fd00:cafe:face:1234:c31d:a702:0d41:beef"); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7a, 0x55, 0x3a, 0xab, 0xcd, 0xef, 0x01, 0x23, - 0x45, 0x67, 0x89, 0xc3, 0x1d, 0xa7, 0x02, 0x0d, - 0x41, 0xbe, 0xef - }; + uint8_t iphc[] = {0x7a, 0x55, 0x3a, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, + 0x89, 0xc3, 0x1d, 0xa7, 0x02, 0x0d, 0x41, 0xbe, 0xef}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -713,14 +668,11 @@ static void TestStatefulSource64bitDestination64bitContext0IfContextInLine(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fd00:cafe:face:1234:abcd:ef01:2345:6789", - "fd00:cafe:face:1234:c31d:a702:0d41:beef"); + "fd00:cafe:face:1234:abcd:ef01:2345:6789", "fd00:cafe:face:1234:c31d:a702:0d41:beef"); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7a, 0xd5, 0x00, 0x3a, 0xab, 0xcd, 0xef, 0x01, 0x23, - 0x45, 0x67, 0x89, 0xc3, 0x1d, 0xa7, 0x02, 0x0d, - 0x41, 0xbe, 0xef - }; + uint8_t iphc[] = {0x7a, 0xd5, 0x00, 0x3a, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, + 0x67, 0x89, 0xc3, 0x1d, 0xa7, 0x02, 0x0d, 0x41, 0xbe, 0xef}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -742,8 +694,7 @@ static void TestStatefulSource16bitDestination16bitContext0(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fd00:cafe:face:1234::ff:fe00:fffc", - "fd00:cafe:face:1234::ff:fe00:fffe"); + "fd00:cafe:face:1234::ff:fe00:fffc", "fd00:cafe:face:1234::ff:fe00:fffe"); // Set LOWPAN_IPHC header. uint8_t iphc[] = {0x7a, 0x66, 0x3a, 0xff, 0xfc, 0xff, 0xfe}; @@ -768,8 +719,7 @@ static void TestStatefulCompressableLongAddressesContext0(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fd00:cafe:face:1234:0200:5eef:1022:1100", - "fd00:cafe:face:1234:0200:5eef:10aa:bbcc"); + "fd00:cafe:face:1234:0200:5eef:1022:1100", "fd00:cafe:face:1234:0200:5eef:10aa:bbcc"); // Set LOWPAN_IPHC header. uint8_t iphc[] = {0x7a, 0x77, 0x3a}; @@ -794,8 +744,7 @@ static void TestStatefulCompressableShortAddressesContext0(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fd00:cafe:face:1234::ff:fe00:0000", - "fd00:cafe:face:1234::ff:fe00:c003"); + "fd00:cafe:face:1234::ff:fe00:0000", "fd00:cafe:face:1234::ff:fe00:c003"); // Set LOWPAN_IPHC header. uint8_t iphc[] = {0x7a, 0x77, 0x3a}; @@ -820,8 +769,7 @@ static void TestStatefulCompressableLongShortAddressesContext0(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fd00:cafe:face:1234:0200:5eef:1022:1100", - "fd00:cafe:face:1234::ff:fe00:c003"); + "fd00:cafe:face:1234:0200:5eef:1022:1100", "fd00:cafe:face:1234::ff:fe00:c003"); // Set LOWPAN_IPHC header. uint8_t iphc[] = {0x7a, 0x77, 0x3a}; @@ -846,15 +794,11 @@ static void TestStatefulSource64bitDestination128bitContext1(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "2001:2:0:1:abcd:ef01:2345:6789", - "2001:2:0:3:c31d:a702:0d41:beef"); + "2001:2:0:1:abcd:ef01:2345:6789", "2001:2:0:3:c31d:a702:0d41:beef"); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7a, 0xd0, 0x10, 0x3a, 0xab, 0xcd, 0xef, 0x01, 0x23, - 0x45, 0x67, 0x89, 0x20, 0x01, 0x00, 0x02, 0x00, 0x00, - 0x00, 0x03, 0xc3, 0x1d, 0xa7, 0x02, 0x0d, 0x41, 0xbe, - 0xef - }; + uint8_t iphc[] = {0x7a, 0xd0, 0x10, 0x3a, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0x20, 0x01, + 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0xc3, 0x1d, 0xa7, 0x02, 0x0d, 0x41, 0xbe, 0xef}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -876,14 +820,11 @@ static void TestStatefulSource64bitDestination64bitContext1(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "2001:2:0:1:abcd:ef01:2345:6789", - "2001:2:0:1:c31d:a702:0d41:beef"); + "2001:2:0:1:abcd:ef01:2345:6789", "2001:2:0:1:c31d:a702:0d41:beef"); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7a, 0xd5, 0x11, 0x3a, 0xab, 0xcd, 0xef, 0x01, 0x23, - 0x45, 0x67, 0x89, 0xc3, 0x1d, 0xa7, 0x02, 0x0d, 0x41, - 0xbe, 0xef - }; + uint8_t iphc[] = {0x7a, 0xd5, 0x11, 0x3a, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, + 0x67, 0x89, 0xc3, 0x1d, 0xa7, 0x02, 0x0d, 0x41, 0xbe, 0xef}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -905,16 +846,12 @@ static void TestStatefulSourceDestinationInlineContext2CIDFalse(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "2001:2:0:2:abcd:ef01:2345:6789", - "2001:2:0:2:c31d:a702:0d41:beef"); + "2001:2:0:2:abcd:ef01:2345:6789", "2001:2:0:2:c31d:a702:0d41:beef"); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7a, 0x00, 0x3a, 0x20, 0x01, 0x00, 0x02, 0x00, - 0x00, 0x00, 0x02, 0xab, 0xcd, 0xef, 0x01, 0x23, - 0x45, 0x67, 0x89, 0x20, 0x01, 0x00, 0x02, 0x00, - 0x00, 0x00, 0x02, 0xc3, 0x1d, 0xa7, 0x02, 0x0d, - 0x41, 0xbe, 0xef - }; + uint8_t iphc[] = {0x7a, 0x00, 0x3a, 0x20, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0xab, + 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0x20, 0x01, 0x00, 0x02, 0x00, + 0x00, 0x00, 0x02, 0xc3, 0x1d, 0xa7, 0x02, 0x0d, 0x41, 0xbe, 0xef}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -936,13 +873,10 @@ static void TestStatefulMulticastDestination48bitContext0(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fd00:cafe:face:1234:0200:5eef:1022:1100", - "ff33:0040:fd00:cafe:face:1234:0000:0001"); + "fd00:cafe:face:1234:0200:5eef:1022:1100", "ff33:0040:fd00:cafe:face:1234:0000:0001"); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7a, 0x7c, 0x3a, 0x33, 0x00, 0x00, 0x00, 0x00, - 0x01 - }; + uint8_t iphc[] = {0x7a, 0x7c, 0x3a, 0x33, 0x00, 0x00, 0x00, 0x00, 0x01}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -963,8 +897,7 @@ static void TestTrafficClassFlowLabel3Bytes(void) testVector.SetMacDestination(sTestMacDestinationDefaultLong); // Setup IPv6 header. - testVector.SetIpHeader(0x6011ac59, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fe80::200:5eef:1022:1100", + testVector.SetIpHeader(0x6011ac59, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, "fe80::200:5eef:1022:1100", "fe80::200:5eef:10aa:bbcc"); // Set LOWPAN_IPHC header. @@ -989,8 +922,7 @@ static void TestTrafficClassFlowLabel1Byte(void) testVector.SetMacDestination(sTestMacDestinationDefaultLong); // Setup IPv6 header. - testVector.SetIpHeader(0x60d00000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fe80::200:5eef:1022:1100", + testVector.SetIpHeader(0x60d00000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, "fe80::200:5eef:1022:1100", "fe80::200:5eef:10aa:bbcc"); // Set LOWPAN_IPHC header. @@ -1015,8 +947,7 @@ static void TestTrafficClassFlowLabel1ByteEcnOnly(void) testVector.SetMacDestination(sTestMacDestinationDefaultLong); // Setup IPv6 header. - testVector.SetIpHeader(0x60100000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fe80::200:5eef:1022:1100", + testVector.SetIpHeader(0x60100000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, "fe80::200:5eef:1022:1100", "fe80::200:5eef:10aa:bbcc"); // Set LOWPAN_IPHC header. @@ -1041,8 +972,7 @@ static void TestTrafficClassFlowLabelInline(void) testVector.SetMacDestination(sTestMacDestinationDefaultLong); // Setup IPv6 header. - testVector.SetIpHeader(0x6ea12345, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, - "fe80::200:5eef:1022:1100", + testVector.SetIpHeader(0x6ea12345, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 64, "fe80::200:5eef:1022:1100", "fe80::200:5eef:10aa:bbcc"); // Set LOWPAN_IPHC header. @@ -1067,8 +997,7 @@ static void TestHopLimit1(void) testVector.SetMacDestination(sTestMacDestinationDefaultShort); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 1, - "fe80::ff:fe00:0000", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 1, "fe80::ff:fe00:0000", "fe80::ff:fe00:c003"); // Set LOWPAN_IPHC header. @@ -1093,8 +1022,7 @@ static void TestHopLimit255(void) testVector.SetMacDestination(sTestMacDestinationDefaultShort); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 255, - "fe80::ff:fe00:0000", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 255, "fe80::ff:fe00:0000", "fe80::ff:fe00:c003"); // Set LOWPAN_IPHC header. @@ -1119,8 +1047,7 @@ static void TestHopLimitInline(void) testVector.SetMacDestination(sTestMacDestinationDefaultShort); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 63, - "fe80::ff:fe00:0000", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 63, "fe80::ff:fe00:0000", "fe80::ff:fe00:c003"); // Set LOWPAN_IPHC header. @@ -1145,8 +1072,7 @@ static void TestUdpSourceDestinationInline(void) testVector.SetMacDestination(sTestMacDestinationDefaultLong); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 8, Ip6::kProtoUdp, 64, - "fe80::200:5eef:1022:1100", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 8, Ip6::kProtoUdp, 64, "fe80::200:5eef:1022:1100", "fe80::200:5eef:10aa:bbcc"); // Setup UDP header. @@ -1174,8 +1100,7 @@ static void TestUdpSourceInlineDestination8bit(void) testVector.SetMacDestination(sTestMacDestinationDefaultLong); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 8, Ip6::kProtoUdp, 64, - "fe80::200:5eef:1022:1100", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 8, Ip6::kProtoUdp, 64, "fe80::200:5eef:1022:1100", "fe80::200:5eef:10aa:bbcc"); // Setup UDP header. @@ -1203,8 +1128,7 @@ static void TestUdpSource8bitDestinationInline(void) testVector.SetMacDestination(sTestMacDestinationDefaultLong); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 8, Ip6::kProtoUdp, 64, - "fe80::200:5eef:1022:1100", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 8, Ip6::kProtoUdp, 64, "fe80::200:5eef:1022:1100", "fe80::200:5eef:10aa:bbcc"); // Setup UDP header. @@ -1232,8 +1156,7 @@ static void TestUdpFullyCompressed(void) testVector.SetMacDestination(sTestMacDestinationDefaultLong); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 8, Ip6::kProtoUdp, 64, - "fe80::200:5eef:1022:1100", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 8, Ip6::kProtoUdp, 64, "fe80::200:5eef:1022:1100", "fe80::200:5eef:10aa:bbcc"); // Setup UDP header. @@ -1261,8 +1184,7 @@ static void TestUdpFullyCompressedMulticast(void) testVector.SetMacDestination(sTestMacDestinationDefaultLong); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 8, Ip6::kProtoUdp, 64, - "fe80::200:5eef:1022:1100", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 8, Ip6::kProtoUdp, 64, "fe80::200:5eef:1022:1100", "ff02::1"); // Setup UDP header. @@ -1290,8 +1212,7 @@ static void TestUdpWithoutNhc(void) testVector.SetMacDestination(sTestMacDestinationDefaultShort); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoUdp, 64, - "fe80::ff:fe00:0000", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoUdp, 64, "fe80::ff:fe00:0000", "fe80::ff:fe00:c003"); // Set LOWPAN_IPHC header. @@ -1317,17 +1238,14 @@ static void TestExtensionHeaderHopByHopNoPadding(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 8, Ip6::kProtoHopOpts, 64, - "fd00:cafe:face:1234::ff:fe00:0000", - "ff03::1"); + "fd00:cafe:face:1234::ff:fe00:0000", "ff03::1"); // Setup extension header. uint8_t extHeader[] = {0x3a, 0x00, 0x6d, 0x04, 0x60, 0x11, 0x00, 0x0c}; testVector.SetExtHeader(extHeader, sizeof(extHeader)); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0x01, 0xe0, 0x3a, - 0x06, 0x6d, 0x04, 0x60, 0x11, 0x00, 0x0c - }; + uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0x01, 0xe0, 0x3a, 0x06, 0x6d, 0x04, 0x60, 0x11, 0x00, 0x0c}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -1349,17 +1267,14 @@ static void TestExtensionHeaderHopByHopPad1(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 8, Ip6::kProtoHopOpts, 64, - "fd00:cafe:face:1234::ff:fe00:0000", - "ff03::1"); + "fd00:cafe:face:1234::ff:fe00:0000", "ff03::1"); // Setup extension header. uint8_t extHeader[] = {0x3a, 0x00, 0x6d, 0x03, 0x60, 0x11, 0x00, 0x00}; testVector.SetExtHeader(extHeader, sizeof(extHeader)); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0x01, 0xe0, 0x3a, - 0x05, 0x6d, 0x03, 0x60, 0x11, 0x00 - }; + uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0x01, 0xe0, 0x3a, 0x05, 0x6d, 0x03, 0x60, 0x11, 0x00}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -1381,17 +1296,14 @@ static void TestExtensionHeaderHopByHopPadN2(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 8, Ip6::kProtoHopOpts, 64, - "fd00:cafe:face:1234::ff:fe00:0000", - "ff03::1"); + "fd00:cafe:face:1234::ff:fe00:0000", "ff03::1"); // Setup extension header. uint8_t extHeader[] = {0x3a, 0x00, 0x6d, 0x02, 0x60, 0x11, 0x01, 0x00}; testVector.SetExtHeader(extHeader, sizeof(extHeader)); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0x01, 0xe0, 0x3a, - 0x04, 0x6d, 0x02, 0x60, 0x11 - }; + uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0x01, 0xe0, 0x3a, 0x04, 0x6d, 0x02, 0x60, 0x11}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -1413,17 +1325,14 @@ static void TestExtensionHeaderHopByHopPadN3(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 8, Ip6::kProtoHopOpts, 64, - "fd00:cafe:face:1234::ff:fe00:0000", - "ff03::1"); + "fd00:cafe:face:1234::ff:fe00:0000", "ff03::1"); // Setup extension header. uint8_t extHeader[] = {0x3a, 0x00, 0x6d, 0x01, 0x60, 0x01, 0x01, 0x00}; testVector.SetExtHeader(extHeader, sizeof(extHeader)); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0x01, 0xe0, 0x3a, - 0x03, 0x6d, 0x01, 0x60 - }; + uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0x01, 0xe0, 0x3a, 0x03, 0x6d, 0x01, 0x60}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -1445,17 +1354,14 @@ static void TestExtensionHeaderHopByHopPadN4(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 8, Ip6::kProtoHopOpts, 64, - "fd00:cafe:face:1234::ff:fe00:0000", - "ff03::1"); + "fd00:cafe:face:1234::ff:fe00:0000", "ff03::1"); // Setup extension header. uint8_t extHeader[] = {0x3a, 0x00, 0x6d, 0x00, 0x01, 0x02, 0x00, 0x00}; testVector.SetExtHeader(extHeader, sizeof(extHeader)); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0x01, 0xe0, 0x3a, - 0x02, 0x6d, 0x00 - }; + uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0x01, 0xe0, 0x3a, 0x02, 0x6d, 0x00}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -1477,20 +1383,16 @@ static void TestExtensionHeaderHopByHopPadN5(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 16, Ip6::kProtoHopOpts, 64, - "fd00:cafe:face:1234::ff:fe00:0000", - "ff03::1"); + "fd00:cafe:face:1234::ff:fe00:0000", "ff03::1"); // Setup extension header. uint8_t extHeader[] = {0x3a, 0x01, 0x6d, 0x07, 0x01, 0x02, 0x01, 0x00, - 0x00, 0x00, 0x33, 0x01, 0x03, 0x00, 0x00, 0x00 - }; + 0x00, 0x00, 0x33, 0x01, 0x03, 0x00, 0x00, 0x00}; testVector.SetExtHeader(extHeader, sizeof(extHeader)); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0x01, 0xe0, 0x3a, - 0x09, 0x6d, 0x07, 0x01, 0x02, 0x01, 0x00, 0x00, - 0x00, 0x33 - }; + uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0x01, 0xe0, 0x3a, 0x09, + 0x6d, 0x07, 0x01, 0x02, 0x01, 0x00, 0x00, 0x00, 0x33}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -1512,22 +1414,16 @@ static void TestExtensionHeaderHopByHopPadN6(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 24, Ip6::kProtoHopOpts, 64, - "fd00:cafe:face:1234::ff:fe00:0000", - "ff03::1"); + "fd00:cafe:face:1234::ff:fe00:0000", "ff03::1"); // Setup extension header. - uint8_t extHeader[] = {0x3a, 0x02, 0x6d, 0x0e, 0x01, 0x02, 0x01, 0x00, - 0x00, 0x00, 0x33, 0x01, 0x03, 0x00, 0x00, 0x00, - 0x11, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00 - }; + uint8_t extHeader[] = {0x3a, 0x02, 0x6d, 0x0e, 0x01, 0x02, 0x01, 0x00, 0x00, 0x00, 0x33, 0x01, + 0x03, 0x00, 0x00, 0x00, 0x11, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00}; testVector.SetExtHeader(extHeader, sizeof(extHeader)); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0x01, 0xe0, 0x3a, - 0x10, 0x6d, 0x0e, 0x01, 0x02, 0x01, 0x00, 0x00, - 0x00, 0x33, 0x01, 0x03, 0x00, 0x00, 0x00, 0x11, - 0x00 - }; + uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0x01, 0xe0, 0x3a, 0x10, 0x6d, 0x0e, 0x01, 0x02, + 0x01, 0x00, 0x00, 0x00, 0x33, 0x01, 0x03, 0x00, 0x00, 0x00, 0x11, 0x00}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -1549,21 +1445,16 @@ static void TestExtensionHeaderHopByHopPadN7(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 24, Ip6::kProtoHopOpts, 64, - "fd00:cafe:face:1234::ff:fe00:0000", - "ff03::1"); + "fd00:cafe:face:1234::ff:fe00:0000", "ff03::1"); // Setup extension header. - uint8_t extHeader[] = {0x3a, 0x02, 0x6d, 0x0d, 0x01, 0x02, 0x01, 0x00, - 0x00, 0x00, 0x33, 0x01, 0x03, 0x00, 0x00, 0x00, - 0x11, 0x01, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00 - }; + uint8_t extHeader[] = {0x3a, 0x02, 0x6d, 0x0d, 0x01, 0x02, 0x01, 0x00, 0x00, 0x00, 0x33, 0x01, + 0x03, 0x00, 0x00, 0x00, 0x11, 0x01, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00}; testVector.SetExtHeader(extHeader, sizeof(extHeader)); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0x01, 0xe0, 0x3a, - 0x0f, 0x6d, 0x0d, 0x01, 0x02, 0x01, 0x00, 0x00, - 0x00, 0x33, 0x01, 0x03, 0x00, 0x00, 0x00, 0x11 - }; + uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0x01, 0xe0, 0x3a, 0x0f, 0x6d, 0x0d, 0x01, + 0x02, 0x01, 0x00, 0x00, 0x00, 0x33, 0x01, 0x03, 0x00, 0x00, 0x00, 0x11}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -1585,8 +1476,7 @@ static void TestExtensionHeaderHopByHopPadN2UdpFullyCompressed(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 16, Ip6::kProtoHopOpts, 64, - "fd00:cafe:face:1234::ff:fe00:0000", - "ff03::1"); + "fd00:cafe:face:1234::ff:fe00:0000", "ff03::1"); // Setup extension header. uint8_t extHeader[] = {0x11, 0x00, 0x6d, 0x02, 0x60, 0x11, 0x01, 0x00}; @@ -1596,9 +1486,7 @@ static void TestExtensionHeaderHopByHopPadN2UdpFullyCompressed(void) testVector.SetUDPHeader(61616, 61631, sizeof(sTestPayloadDefault) + 8, 0xface); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0x01, 0xe1, 0x04, - 0x6d, 0x02, 0x60, 0x11, 0xf3, 0x0f, 0xfa, 0xce - }; + uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0x01, 0xe1, 0x04, 0x6d, 0x02, 0x60, 0x11, 0xf3, 0x0f, 0xfa, 0xce}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -1620,8 +1508,7 @@ static void TestIpInIpHopByHopPadN2UdpSourceDestinationInline(void) // Setup IPv6 header. testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 56, Ip6::kProtoHopOpts, 64, - "fd00:cafe:face:1234::ff:fe00:0000", - "ff03::fc"); + "fd00:cafe:face:1234::ff:fe00:0000", "ff03::fc"); // Setup extension header. uint8_t extHeader[] = {0x29, 0x00, 0x6d, 0x02, 0x00, 0x11, 0x01, 0x00}; @@ -1629,18 +1516,14 @@ static void TestIpInIpHopByHopPadN2UdpSourceDestinationInline(void) // Setup IPv6 tunneled header. testVector.SetIpTunneledHeader(0x60000000, sizeof(sTestPayloadDefault) + 8, Ip6::kProtoUdp, 64, - "fd00:cafe:face:1234::ff:fe00:0000", - "ff05::1"); + "fd00:cafe:face:1234::ff:fe00:0000", "ff05::1"); // Setup UDP header. testVector.SetUDPHeader(5683, 5684, sizeof(sTestPayloadDefault) + 8, 0xbeef); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0xfc, 0xe1, 0x04, - 0x6d, 0x02, 0x00, 0x11, 0xee, 0x7e, 0x7a, 0x05, - 0x00, 0x00, 0x01, 0xf0, 0x16, 0x33, 0x16, 0x34, - 0xbe, 0xef - }; + uint8_t iphc[] = {0x7e, 0x7a, 0x03, 0x00, 0x00, 0xfc, 0xe1, 0x04, 0x6d, 0x02, 0x00, 0x11, 0xee, + 0x7e, 0x7a, 0x05, 0x00, 0x00, 0x01, 0xf0, 0x16, 0x33, 0x16, 0x34, 0xbe, 0xef}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -1661,19 +1544,15 @@ static void TestIpInIpWithoutExtensionHeader(void) testVector.SetMacDestination(sTestMacDestinationDefaultLong); // Setup IPv6 header. - testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 40, Ip6::kProtoIp6, 64, - "fe80::200:5eef:1022:1100", + testVector.SetIpHeader(0x60000000, sizeof(sTestPayloadDefault) + 40, Ip6::kProtoIp6, 64, "fe80::200:5eef:1022:1100", "ff03::1"); // Setup IPv6 tunneled header. testVector.SetIpTunneledHeader(0x60000000, sizeof(sTestPayloadDefault), Ip6::kProtoIcmp6, 1, - "fe80::200:5eef:1022:1100", - "fe80::200:5eef:10aa:bbcc"); + "fe80::200:5eef:1022:1100", "fe80::200:5eef:10aa:bbcc"); // Set LOWPAN_IPHC header. - uint8_t iphc[] = {0x7e, 0x3a, 0x03, 0x00, 0x00, 0x01, 0xee, 0x79, - 0x33, 0x3a - }; + uint8_t iphc[] = {0x7e, 0x3a, 0x03, 0x00, 0x00, 0x01, 0xee, 0x79, 0x33, 0x3a}; testVector.SetIphcHeader(iphc, sizeof(iphc)); // Set payload and error. @@ -1866,9 +1745,9 @@ void TestLowpanIphc(void) VerifyOrQuit(sInstance != NULL, "NULL instance"); - sIp6 = &sInstance->GetIp6(); + sIp6 = &sInstance->GetIp6(); sThreadNetif = &sInstance->GetThreadNetif(); - sLowpan = &sThreadNetif->GetLowpan(); + sLowpan = &sThreadNetif->GetLowpan(); Init(); @@ -1953,7 +1832,7 @@ void TestLowpanIphc(void) testFreeInstance(sInstance); } -} // namespace ot +} // namespace ot #ifdef ENABLE_TEST_MAIN int main(void) diff --git a/tests/unit/test_lowpan.hpp b/tests/unit/test_lowpan.hpp index 6d4e58408..5bed5c94b 100644 --- a/tests/unit/test_lowpan.hpp +++ b/tests/unit/test_lowpan.hpp @@ -29,7 +29,6 @@ #ifndef TEST_LOWPAN_HPP #define TEST_LOWPAN_HPP - #include #include "common/instance.hpp" @@ -46,13 +45,13 @@ class TestIphcVector public: enum { - kContextUnused = 255, + kContextUnused = 255, kPayloadMaxLength = 512 }; struct Payload { - uint8_t mData[kPayloadMaxLength]; + uint8_t mData[kPayloadMaxLength]; uint16_t mLength; }; @@ -60,9 +59,10 @@ public: * Default constructor for the object. * */ - TestIphcVector(const char *aTestName) { + TestIphcVector(const char *aTestName) + { memset(this, 0, sizeof(*this)); - mTestName = aTestName; + mTestName = aTestName; mSrcContext.mContextId = kContextUnused; mDstContext.mContextId = kContextUnused; } @@ -73,9 +73,7 @@ public: * @param aAddress Pointer to the long MAC address. * */ - void SetMacSource(const uint8_t *aAddress) { - mMacSource.SetExtended(aAddress, /* reverse */ false); - } + void SetMacSource(const uint8_t *aAddress) { mMacSource.SetExtended(aAddress, /* reverse */ false); } /** * This method sets short MAC source address. @@ -83,9 +81,7 @@ public: * @param aAddress Short MAC address. * */ - void SetMacSource(uint16_t aAddress) { - mMacSource.SetShort(aAddress); - } + void SetMacSource(uint16_t aAddress) { mMacSource.SetShort(aAddress); } /** * This method sets long MAC destination address. @@ -93,9 +89,7 @@ public: * @param aAddress Pointer to the long MAC address. * */ - void SetMacDestination(const uint8_t *aAddress) { - mMacDestination.SetExtended(aAddress, /* reverse */ false); - } + void SetMacDestination(const uint8_t *aAddress) { mMacDestination.SetExtended(aAddress, /* reverse */ false); } /** * This method sets short MAC destination address. @@ -103,9 +97,7 @@ public: * @param aAddress Short MAC address. * */ - void SetMacDestination(uint16_t aAddress) { - mMacDestination.SetShort(aAddress); - } + void SetMacDestination(uint16_t aAddress) { mMacDestination.SetShort(aAddress); } /** * This method initializes IPv6 Header. @@ -118,9 +110,13 @@ public: * @param aDestination String represents IPv6 destination address. * */ - void SetIpHeader(uint32_t aVersionClassFlow, uint16_t aPayloadLength, - Ip6::IpProto aNextHeader, uint8_t aHopLimit, - const char *aSource, const char *aDestination) { + void SetIpHeader(uint32_t aVersionClassFlow, + uint16_t aPayloadLength, + Ip6::IpProto aNextHeader, + uint8_t aHopLimit, + const char * aSource, + const char * aDestination) + { mIpHeader.Init(aVersionClassFlow); mIpHeader.SetPayloadLength(aPayloadLength); mIpHeader.SetNextHeader(aNextHeader); @@ -140,9 +136,13 @@ public: * @param aDestination String represents IPv6 destination address. * */ - void SetIpTunneledHeader(uint32_t aVersionClassFlow, uint16_t aPayloadLength, - Ip6::IpProto aNextHeader, uint8_t aHopLimit, - const char *aSource, const char *aDestination) { + void SetIpTunneledHeader(uint32_t aVersionClassFlow, + uint16_t aPayloadLength, + Ip6::IpProto aNextHeader, + uint8_t aHopLimit, + const char * aSource, + const char * aDestination) + { mIpTunneledHeader.Init(aVersionClassFlow); mIpTunneledHeader.SetPayloadLength(aPayloadLength); mIpTunneledHeader.SetNextHeader(aNextHeader); @@ -158,7 +158,8 @@ public: * @param aExtHeaderLength Length of the extension header data. * */ - void SetExtHeader(const uint8_t *aExtHeader, uint16_t aExtHeaderLength) { + void SetExtHeader(const uint8_t *aExtHeader, uint16_t aExtHeaderLength) + { memcpy(mExtHeader.mData, aExtHeader, aExtHeaderLength); mExtHeader.mLength = aExtHeaderLength; } @@ -172,8 +173,8 @@ public: * @param aChecksum Value of the checksum field. * */ - void SetUDPHeader(uint16_t aSource, uint16_t aDestination, uint16_t aLength, - uint16_t aChecksum) { + void SetUDPHeader(uint16_t aSource, uint16_t aDestination, uint16_t aLength, uint16_t aChecksum) + { mUdpHeader.SetSourcePort(aSource); mUdpHeader.SetDestinationPort(aDestination); mUdpHeader.SetLength(aLength); @@ -187,7 +188,8 @@ public: * @param aIphcLength Length of the LOWPAN_IPHC header. * */ - void SetIphcHeader(const uint8_t *aIphc, uint16_t aIphcLength) { + void SetIphcHeader(const uint8_t *aIphc, uint16_t aIphcLength) + { memcpy(mIphcHeader.mData, aIphc, aIphcLength); mIphcHeader.mLength = aIphcLength; } @@ -207,7 +209,8 @@ public: * @param aLength Length of the payload data. * */ - void SetPayload(const uint8_t *aPayload, uint16_t aLength) { + void SetPayload(const uint8_t *aPayload, uint16_t aLength) + { memcpy(mPayload.mData, aPayload, aLength); mPayload.mLength = aLength; } @@ -261,20 +264,20 @@ public: * This fields represent compressed IPv6 packet. * */ - Payload mIphcHeader; - uint16_t mPayloadOffset; - Lowpan::Context mSrcContext; - Lowpan::Context mDstContext; + Payload mIphcHeader; + uint16_t mPayloadOffset; + Lowpan::Context mSrcContext; + Lowpan::Context mDstContext; /** * General purpose fields. * */ - Payload mPayload; - otError mError; - const char *mTestName; + Payload mPayload; + otError mError; + const char *mTestName; }; -} // namespace ot +} // namespace ot #endif // TEST_LOWPAN_HPP diff --git a/tests/unit/test_mac_frame.cpp b/tests/unit/test_mac_frame.cpp index d1bd74f77..39e98abfb 100644 --- a/tests/unit/test_mac_frame.cpp +++ b/tests/unit/test_mac_frame.cpp @@ -41,50 +41,46 @@ void TestMacHeader(void) static const struct { uint16_t fcf; - uint8_t secCtl; - uint8_t headerLength; - } tests[] = - { - { Mac::Frame::kFcfDstAddrNone | Mac::Frame::kFcfSrcAddrNone, 0, 3 }, - { Mac::Frame::kFcfDstAddrNone | Mac::Frame::kFcfSrcAddrShort, 0, 7 }, - { Mac::Frame::kFcfDstAddrNone | Mac::Frame::kFcfSrcAddrExt, 0, 13 }, - { Mac::Frame::kFcfDstAddrShort | Mac::Frame::kFcfSrcAddrNone, 0, 7 }, - { Mac::Frame::kFcfDstAddrExt | Mac::Frame::kFcfSrcAddrNone, 0, 13 }, - { Mac::Frame::kFcfDstAddrShort | Mac::Frame::kFcfSrcAddrShort, 0, 11 }, - { Mac::Frame::kFcfDstAddrShort | Mac::Frame::kFcfSrcAddrExt, 0, 17 }, - { Mac::Frame::kFcfDstAddrExt | Mac::Frame::kFcfSrcAddrShort, 0, 17 }, - { Mac::Frame::kFcfDstAddrExt | Mac::Frame::kFcfSrcAddrExt, 0, 23 }, + uint8_t secCtl; + uint8_t headerLength; + } tests[] = { + {Mac::Frame::kFcfDstAddrNone | Mac::Frame::kFcfSrcAddrNone, 0, 3}, + {Mac::Frame::kFcfDstAddrNone | Mac::Frame::kFcfSrcAddrShort, 0, 7}, + {Mac::Frame::kFcfDstAddrNone | Mac::Frame::kFcfSrcAddrExt, 0, 13}, + {Mac::Frame::kFcfDstAddrShort | Mac::Frame::kFcfSrcAddrNone, 0, 7}, + {Mac::Frame::kFcfDstAddrExt | Mac::Frame::kFcfSrcAddrNone, 0, 13}, + {Mac::Frame::kFcfDstAddrShort | Mac::Frame::kFcfSrcAddrShort, 0, 11}, + {Mac::Frame::kFcfDstAddrShort | Mac::Frame::kFcfSrcAddrExt, 0, 17}, + {Mac::Frame::kFcfDstAddrExt | Mac::Frame::kFcfSrcAddrShort, 0, 17}, + {Mac::Frame::kFcfDstAddrExt | Mac::Frame::kFcfSrcAddrExt, 0, 23}, - { Mac::Frame::kFcfDstAddrShort | Mac::Frame::kFcfSrcAddrShort | Mac::Frame::kFcfPanidCompression, 0, 9 }, - { Mac::Frame::kFcfDstAddrShort | Mac::Frame::kFcfSrcAddrExt | Mac::Frame::kFcfPanidCompression, 0, 15 }, - { Mac::Frame::kFcfDstAddrExt | Mac::Frame::kFcfSrcAddrShort | Mac::Frame::kFcfPanidCompression, 0, 15 }, - { Mac::Frame::kFcfDstAddrExt | Mac::Frame::kFcfSrcAddrExt | Mac::Frame::kFcfPanidCompression, 0, 21 }, + {Mac::Frame::kFcfDstAddrShort | Mac::Frame::kFcfSrcAddrShort | Mac::Frame::kFcfPanidCompression, 0, 9}, + {Mac::Frame::kFcfDstAddrShort | Mac::Frame::kFcfSrcAddrExt | Mac::Frame::kFcfPanidCompression, 0, 15}, + {Mac::Frame::kFcfDstAddrExt | Mac::Frame::kFcfSrcAddrShort | Mac::Frame::kFcfPanidCompression, 0, 15}, + {Mac::Frame::kFcfDstAddrExt | Mac::Frame::kFcfSrcAddrExt | Mac::Frame::kFcfPanidCompression, 0, 21}, - { - Mac::Frame::kFcfDstAddrShort | Mac::Frame::kFcfSrcAddrShort | Mac::Frame::kFcfPanidCompression | - Mac::Frame::kFcfSecurityEnabled, Mac::Frame::kSecMic32 | Mac::Frame::kKeyIdMode1, 15 - }, - { - Mac::Frame::kFcfDstAddrShort | Mac::Frame::kFcfSrcAddrShort | Mac::Frame::kFcfPanidCompression | - Mac::Frame::kFcfSecurityEnabled, Mac::Frame::kSecMic32 | Mac::Frame::kKeyIdMode2, 19 - }, + {Mac::Frame::kFcfDstAddrShort | Mac::Frame::kFcfSrcAddrShort | Mac::Frame::kFcfPanidCompression | + Mac::Frame::kFcfSecurityEnabled, + Mac::Frame::kSecMic32 | Mac::Frame::kKeyIdMode1, 15}, + {Mac::Frame::kFcfDstAddrShort | Mac::Frame::kFcfSrcAddrShort | Mac::Frame::kFcfPanidCompression | + Mac::Frame::kFcfSecurityEnabled, + Mac::Frame::kSecMic32 | Mac::Frame::kKeyIdMode2, 19}, }; for (unsigned i = 0; i < sizeof(tests) / sizeof(tests[0]); i++) { - uint8_t psdu[Mac::Frame::kMTU]; + uint8_t psdu[Mac::Frame::kMTU]; Mac::Frame frame; frame.mPsdu = psdu; frame.InitMacHeader(tests[i].fcf, tests[i].secCtl); printf("%d\n", frame.GetHeaderLength()); - VerifyOrQuit(frame.GetHeaderLength() == tests[i].headerLength, - "MacHeader test failed\n"); + VerifyOrQuit(frame.GetHeaderLength() == tests[i].headerLength, "MacHeader test failed\n"); } } -} // namespace ot +} // namespace ot #ifdef ENABLE_TEST_MAIN int main(void) diff --git a/tests/unit/test_message.cpp b/tests/unit/test_message.cpp index af656bd62..377c25b73 100644 --- a/tests/unit/test_message.cpp +++ b/tests/unit/test_message.cpp @@ -38,11 +38,11 @@ void TestMessage(void) { - ot::Instance *instance; + ot::Instance * instance; ot::MessagePool *messagePool; - ot::Message *message; - uint8_t writeBuffer[1024]; - uint8_t readBuffer[1024]; + ot::Message * message; + uint8_t writeBuffer[1024]; + uint8_t readBuffer[1024]; instance = static_cast(testInitInstance()); VerifyOrQuit(instance != NULL, "Null OpenThread instance\n"); @@ -54,18 +54,12 @@ void TestMessage(void) writeBuffer[i] = static_cast(random()); } - VerifyOrQuit((message = messagePool->New(ot::Message::kTypeIp6, 0)) != NULL, - "Message::New failed\n"); - SuccessOrQuit(message->SetLength(sizeof(writeBuffer)), - "Message::SetLength failed\n"); - VerifyOrQuit(message->Write(0, sizeof(writeBuffer), writeBuffer) == sizeof(writeBuffer), - "Message::Write failed\n"); - VerifyOrQuit(message->Read(0, sizeof(readBuffer), readBuffer) == sizeof(readBuffer), - "Message::Read failed\n"); - VerifyOrQuit(memcmp(writeBuffer, readBuffer, sizeof(writeBuffer)) == 0, - "Message compare failed\n"); - VerifyOrQuit(message->GetLength() == 1024, - "Message::GetLength failed\n"); + VerifyOrQuit((message = messagePool->New(ot::Message::kTypeIp6, 0)) != NULL, "Message::New failed\n"); + SuccessOrQuit(message->SetLength(sizeof(writeBuffer)), "Message::SetLength failed\n"); + VerifyOrQuit(message->Write(0, sizeof(writeBuffer), writeBuffer) == sizeof(writeBuffer), "Message::Write failed\n"); + VerifyOrQuit(message->Read(0, sizeof(readBuffer), readBuffer) == sizeof(readBuffer), "Message::Read failed\n"); + VerifyOrQuit(memcmp(writeBuffer, readBuffer, sizeof(writeBuffer)) == 0, "Message compare failed\n"); + VerifyOrQuit(message->GetLength() == 1024, "Message::GetLength failed\n"); message->Free(); testFreeInstance(instance); diff --git a/tests/unit/test_message_queue.cpp b/tests/unit/test_message_queue.cpp index fd7c0e3ab..d0186d970 100644 --- a/tests/unit/test_message_queue.cpp +++ b/tests/unit/test_message_queue.cpp @@ -40,15 +40,15 @@ #include "test_util.h" -#define kNumTestMessages 5 +#define kNumTestMessages 5 -static ot::Instance *sInstance; +static ot::Instance * sInstance; static ot::MessagePool *sMessagePool; // This function verifies the content of the message queue to match the passed in messages void VerifyMessageQueueContent(ot::MessageQueue &aMessageQueue, int aExpectedLength, ...) { - va_list args; + va_list args; ot::Message *message; ot::Message *msgArg; @@ -80,9 +80,9 @@ void VerifyMessageQueueContent(ot::MessageQueue &aMessageQueue, int aExpectedLen void TestMessageQueue(void) { ot::MessageQueue messageQueue; - ot::Message *msg[kNumTestMessages]; - otError error; - uint16_t msgCount, bufferCount; + ot::Message * msg[kNumTestMessages]; + otError error; + uint16_t msgCount, bufferCount; sInstance = testInitInstance(); VerifyOrQuit(sInstance != NULL, "Null instance"); @@ -187,8 +187,7 @@ void TestMessageQueue(void) error = messageQueue.Enqueue(*msg[0]); VerifyOrQuit(error == OT_ERROR_ALREADY, "Enqueuing an already queued message did not fail as expected.\n"); error = messageQueue.Dequeue(*msg[1]); - VerifyOrQuit(error == OT_ERROR_NOT_FOUND, - "Dequeuing a message not in the queue did not fail as expected.\n"); + VerifyOrQuit(error == OT_ERROR_NOT_FOUND, "Dequeuing a message not in the queue did not fail as expected.\n"); testFreeInstance(sInstance); } @@ -196,7 +195,7 @@ void TestMessageQueue(void) // This function verifies the content of the message queue to match the passed in messages void VerifyMessageQueueContentUsingOtApi(otMessageQueue *aQueue, int aExpectedLength, ...) { - va_list args; + va_list args; otMessage *message; otMessage *msgArg; @@ -209,10 +208,7 @@ void VerifyMessageQueueContentUsingOtApi(otMessageQueue *aQueue, int aExpectedLe } else { - for (message = otMessageQueueGetHead(aQueue); - message != NULL; - message = otMessageQueueGetNext(aQueue, message) - ) + for (message = otMessageQueueGetHead(aQueue); message != NULL; message = otMessageQueueGetNext(aQueue, message)) { VerifyOrQuit(aExpectedLength != 0, "MessageQueue contains more entries than expected\n"); @@ -231,9 +227,9 @@ void VerifyMessageQueueContentUsingOtApi(otMessageQueue *aQueue, int aExpectedLe // This test checks all the OpenThread C APIs for `otMessageQueue` void TestMessageQueueOtApis(void) { - otMessage *msg[kNumTestMessages]; - otError error; - otMessage *message; + otMessage * msg[kNumTestMessages]; + otError error; + otMessage * message; otMessageQueue queue, queue2; sInstance = testInitInstance(); @@ -273,8 +269,7 @@ void TestMessageQueueOtApis(void) error = otMessageQueueEnqueue(&queue, msg[2]); VerifyOrQuit(error == OT_ERROR_ALREADY, "Enqueuing an already queued message did not fail as expected.\n"); error = otMessageQueueDequeue(&queue, msg[0]); - VerifyOrQuit(error == OT_ERROR_NOT_FOUND, - "Dequeuing a message not in the queue did not fail as expected.\n"); + VerifyOrQuit(error == OT_ERROR_NOT_FOUND, "Dequeuing a message not in the queue did not fail as expected.\n"); // Check the failure cases for otMessageQueueGetNext() message = otMessageQueueGetNext(&queue, NULL); diff --git a/tests/unit/test_ncp_buffer.cpp b/tests/unit/test_ncp_buffer.cpp index 9b2163ad1..4ac0b0457 100644 --- a/tests/unit/test_ncp_buffer.cpp +++ b/tests/unit/test_ncp_buffer.cpp @@ -46,9 +46,9 @@ namespace Ncp { // Test related constants: enum { - kTestBufferSize = 800, + kTestBufferSize = 800, kTestIterationAttemps = 10000, - kTagArraySize = 1000, + kTagArraySize = 1000, }; // Messages used for building frames... @@ -59,19 +59,19 @@ static const uint8_t sMysteryText[] = "4871(\\):|(3$}{4|/4/2%14(\\)"; static const uint8_t sHexText[] = "0123456789abcdef"; static ot::Instance *sInstance; -static MessagePool *sMessagePool; +static MessagePool * sMessagePool; struct CallbackContext { - uint32_t mFrameAddedCount; // Number of times FrameAddedCallback is invoked. - uint32_t mFrameRemovedCount; // Number of times FrameRemovedCallback is invoked. + uint32_t mFrameAddedCount; // Number of times FrameAddedCallback is invoked. + uint32_t mFrameRemovedCount; // Number of times FrameRemovedCallback is invoked. }; CallbackContext sContext; enum { - kNumPrios = 2, // Number of priority levels. + kNumPrios = 2, // Number of priority levels. kTestFrame1Size = sizeof(sMottoText) + sizeof(sMysteryText) + sizeof(sMottoText) + sizeof(sHelloText), kTestFrame2Size = sizeof(sMysteryText) + sizeof(sHelloText) + sizeof(sOpenThreadText), @@ -80,9 +80,9 @@ enum }; NcpFrameBuffer::FrameTag sTagHistoryArray[kNumPrios][kTagArraySize]; -uint32_t sTagHistoryHead[kNumPrios] = {0}; -uint32_t sTagHistoryTail[kNumPrios] = {0}; -NcpFrameBuffer::FrameTag sExpectedRemovedTag = NcpFrameBuffer::kInvalidTag; +uint32_t sTagHistoryHead[kNumPrios] = {0}; +uint32_t sTagHistoryTail[kNumPrios] = {0}; +NcpFrameBuffer::FrameTag sExpectedRemovedTag = NcpFrameBuffer::kInvalidTag; void ClearTagHistory(void) { @@ -112,7 +112,8 @@ void VerifyAndRemoveTagFromHistory(NcpFrameBuffer::FrameTag aTag, NcpFrameBuffer uint8_t priority = static_cast(aPriority); VerifyOrQuit(sTagHistoryHead[priority] != sTagHistoryTail[priority], "Tag history is empty,"); - VerifyOrQuit(aTag == sTagHistoryArray[priority][sTagHistoryHead[priority]], "Removed tag does not match the added one"); + VerifyOrQuit(aTag == sTagHistoryArray[priority][sTagHistoryHead[priority]], + "Removed tag does not match the added one"); if (++sTagHistoryHead[priority] == kTagArraySize) { @@ -126,8 +127,10 @@ void VerifyAndRemoveTagFromHistory(NcpFrameBuffer::FrameTag aTag, NcpFrameBuffer } } -void FrameAddedCallback(void *aContext, NcpFrameBuffer::FrameTag aTag, NcpFrameBuffer::Priority aPriority, - NcpFrameBuffer *aNcpBuffer) +void FrameAddedCallback(void * aContext, + NcpFrameBuffer::FrameTag aTag, + NcpFrameBuffer::Priority aPriority, + NcpFrameBuffer * aNcpBuffer) { CallbackContext *callbackContext = reinterpret_cast(aContext); @@ -141,8 +144,10 @@ void FrameAddedCallback(void *aContext, NcpFrameBuffer::FrameTag aTag, NcpFrameB callbackContext->mFrameAddedCount++; } -void FrameRemovedCallback(void *aContext, NcpFrameBuffer::FrameTag aTag, NcpFrameBuffer::Priority aPriority, - NcpFrameBuffer *aNcpBuffer) +void FrameRemovedCallback(void * aContext, + NcpFrameBuffer::FrameTag aTag, + NcpFrameBuffer::Priority aPriority, + NcpFrameBuffer * aNcpBuffer) { CallbackContext *callbackContext = reinterpret_cast(aContext); @@ -160,12 +165,12 @@ void DumpBuffer(const char *aTextMessage, uint8_t *aBuffer, uint16_t aBufferLeng { enum { - kBytesPerLine = 32, // Number of bytes per line. + kBytesPerLine = 32, // Number of bytes per line. }; - char charBuff[kBytesPerLine + 1]; + char charBuff[kBytesPerLine + 1]; uint16_t counter; - uint8_t byte; + uint8_t byte; printf("\n%s - len = %u\n ", aTextMessage, aBufferLength); @@ -210,7 +215,7 @@ void ReadAndVerifyContent(NcpFrameBuffer &aNcpBuffer, const uint8_t *aContentBuf void WriteTestFrame1(NcpFrameBuffer &aNcpBuffer, NcpFrameBuffer::Priority aPriority) { - Message *message; + Message * message; CallbackContext oldContext; message = sMessagePool->New(Message::kTypeIp6, 0); @@ -253,8 +258,8 @@ void VerifyAndRemoveFrame1(NcpFrameBuffer &aNcpBuffer) void WriteTestFrame2(NcpFrameBuffer &aNcpBuffer, NcpFrameBuffer::Priority aPriority) { - Message *message1; - Message *message2; + Message * message1; + Message * message2; CallbackContext oldContext = sContext; message1 = sMessagePool->New(Message::kTypeIp6, 0); @@ -299,7 +304,7 @@ void VerifyAndRemoveFrame2(NcpFrameBuffer &aNcpBuffer) void WriteTestFrame3(NcpFrameBuffer &aNcpBuffer, NcpFrameBuffer::Priority aPriority) { - Message *message1; + Message * message1; CallbackContext oldContext = sContext; message1 = sMessagePool->New(Message::kTypeIp6, 0); @@ -368,16 +373,16 @@ void VerifyAndRemoveFrame4(NcpFrameBuffer &aNcpBuffer) // This function implements the NcpFrameBuffer tests void TestNcpFrameBuffer(void) { - unsigned i, j; - uint8_t buffer[kTestBufferSize]; + unsigned i, j; + uint8_t buffer[kTestBufferSize]; NcpFrameBuffer ncpBuffer(buffer, kTestBufferSize); - Message *message; - uint8_t readBuffer[16]; - uint16_t readLen, readOffset; + Message * message; + uint8_t readBuffer[16]; + uint16_t readLen, readOffset; NcpFrameBuffer::WritePosition pos1, pos2; - sInstance = testInitInstance(); + sInstance = testInitInstance(); sMessagePool = &sInstance->GetMessagePool(); for (i = 0; i < sizeof(buffer); i++) @@ -385,7 +390,7 @@ void TestNcpFrameBuffer(void) buffer[i] = 0; } - sContext.mFrameAddedCount = 0; + sContext.mFrameAddedCount = 0; sContext.mFrameRemovedCount = 0; ClearTagHistory(); @@ -571,8 +576,7 @@ void TestNcpFrameBuffer(void) ncpBuffer.InFrameFeedMessage(message); // Start writing a new frame in middle of an unfinished frame. Ensure the first one is discarded. - WriteTestFrame1(ncpBuffer, - frame1IsHighPriority ? NcpFrameBuffer::kPriorityHigh : NcpFrameBuffer::kPriorityLow); + WriteTestFrame1(ncpBuffer, frame1IsHighPriority ? NcpFrameBuffer::kPriorityHigh : NcpFrameBuffer::kPriorityLow); // Note that message will not be freed by the NCP buffer since the frame associated with it was discarded and // not yet finished/ended. @@ -598,7 +602,6 @@ void TestNcpFrameBuffer(void) VerifyAndRemoveFrame1(ncpBuffer); } - VerifyOrQuit(ncpBuffer.IsEmpty() == true, "IsEmpty() is incorrect when buffer is empty."); } @@ -618,7 +621,8 @@ void TestNcpFrameBuffer(void) VerifyOrQuit(ncpBuffer.OutFrameHasEnded() == true, "OutFrameHasEnded() is incorrect when no data in buffer."); VerifyOrQuit(ncpBuffer.OutFrameRemove() == OT_ERROR_NOT_FOUND, "Remove() returned incorrect error status when buffer is empty."); - VerifyOrQuit(ncpBuffer.OutFrameGetLength() == 0, "OutFrameGetLength() returned non-zero length when buffer is empty."); + VerifyOrQuit(ncpBuffer.OutFrameGetLength() == 0, + "OutFrameGetLength() returned non-zero length when buffer is empty."); WriteTestFrame1(ncpBuffer, NcpFrameBuffer::kPriorityLow); VerifyAndRemoveFrame1(ncpBuffer); @@ -627,7 +631,8 @@ void TestNcpFrameBuffer(void) VerifyOrQuit(ncpBuffer.OutFrameHasEnded() == true, "OutFrameHasEnded() is incorrect when no data in buffer."); VerifyOrQuit(ncpBuffer.OutFrameRemove() == OT_ERROR_NOT_FOUND, "Remove() returned incorrect error status when buffer is empty."); - VerifyOrQuit(ncpBuffer.OutFrameGetLength() == 0, "OutFrameGetLength() returned non-zero length when buffer is empty."); + VerifyOrQuit(ncpBuffer.OutFrameGetLength() == 0, + "OutFrameGetLength() returned non-zero length when buffer is empty."); printf(" -- PASS\n"); @@ -811,13 +816,13 @@ void TestNcpFrameBuffer(void) for (j = 0; j < kTestIterationAttemps; j++) { - uint16_t index; - bool addExtra = ((j % 7) != 0); + uint16_t index; + bool addExtra = ((j % 7) != 0); NcpFrameBuffer::Priority priority; printf("*"); priority = ((j % 3) == 0) ? NcpFrameBuffer::kPriorityHigh : NcpFrameBuffer::kPriorityLow; - index = static_cast(j % sizeof(sHexText)); + index = static_cast(j % sizeof(sHexText)); SuccessOrQuit(ncpBuffer.InFrameBegin(priority), "InFrameBegin() failed"); SuccessOrQuit(ncpBuffer.InFrameFeedData(sHexText, index), "InFrameFeedData() failed."); SuccessOrQuit(ncpBuffer.InFrameGetPosition(pos1), "InFrameGetPosition() failed"); @@ -831,7 +836,8 @@ void TestNcpFrameBuffer(void) SuccessOrQuit(ncpBuffer.InFrameOverwrite(pos1, sHexText + index, sizeof(sHexText) - index), "InFrameOverwrite() failed."); - VerifyOrQuit(ncpBuffer.InFrameGetDistance(pos1) == sizeof(sHexText) - index + (addExtra ? sizeof(sHelloText) : 0), + VerifyOrQuit(ncpBuffer.InFrameGetDistance(pos1) == + sizeof(sHexText) - index + (addExtra ? sizeof(sHelloText) : 0), "InFrameGetDistance() failed"); SuccessOrQuit(ncpBuffer.InFrameEnd(), "InFrameEnd() failed."); VerifyOrQuit(ncpBuffer.InFrameGetPosition(pos2) == OT_ERROR_INVALID_STATE, "GetPosition failed."); @@ -856,13 +862,13 @@ void TestNcpFrameBuffer(void) for (j = 0; j < kTestIterationAttemps; j++) { - uint16_t index; - bool addExtra = ((j % 7) != 0); + uint16_t index; + bool addExtra = ((j % 7) != 0); NcpFrameBuffer::Priority priority; printf("*"); priority = ((j % 3) == 0) ? NcpFrameBuffer::kPriorityHigh : NcpFrameBuffer::kPriorityLow; - index = static_cast(j % sizeof(sHexText)); + index = static_cast(j % sizeof(sHexText)); SuccessOrQuit(ncpBuffer.InFrameBegin(priority), "InFrameBegin() failed"); SuccessOrQuit(ncpBuffer.InFrameFeedData(sHexText, index), "InFrameFeedData() failed."); SuccessOrQuit(ncpBuffer.InFrameGetPosition(pos1), "InFrameGetPosition() failed"); @@ -883,11 +889,9 @@ void TestNcpFrameBuffer(void) SuccessOrQuit(ncpBuffer.InFrameReset(pos1), "InFrameReset() failed."); SuccessOrQuit(ncpBuffer.InFrameFeedData(sHexText + index, sizeof(sHexText) - index), "InFrameOverwrite() failed."); - } - VerifyOrQuit(ncpBuffer.InFrameGetDistance(pos1) == sizeof(sHexText) - index, - "InFrameGetDistance() failed"); + VerifyOrQuit(ncpBuffer.InFrameGetDistance(pos1) == sizeof(sHexText) - index, "InFrameGetDistance() failed"); SuccessOrQuit(ncpBuffer.InFrameEnd(), "InFrameEnd() failed."); SuccessOrQuit(ncpBuffer.OutFrameBegin(), "OutFrameBegin() failed"); ReadAndVerifyContent(ncpBuffer, sHexText, sizeof(sHexText)); @@ -913,16 +917,16 @@ void TestNcpFrameBuffer(void) enum { - kFuzTestBufferSize = 2000, // Size of the buffer used during fuzz testing - kFuzTestIterationAttempts = 500000, // Number of iterations to run - kLensArraySize = 500, // Size of "Lengths" array. - kMaxFrameLen = 400, // Maximum frame length - kReadProbability = 50, // Probability (in percent) to randomly choose to read vs write frame - kHighPriorityProbablity = 20, // Probability (in percent) to write a high priority frame - kUseTrueRandomNumberGenerator = 1, // To use true random number generator or not. + kFuzTestBufferSize = 2000, // Size of the buffer used during fuzz testing + kFuzTestIterationAttempts = 500000, // Number of iterations to run + kLensArraySize = 500, // Size of "Lengths" array. + kMaxFrameLen = 400, // Maximum frame length + kReadProbability = 50, // Probability (in percent) to randomly choose to read vs write frame + kHighPriorityProbablity = 20, // Probability (in percent) to write a high priority frame + kUseTrueRandomNumberGenerator = 1, // To use true random number generator or not. }; -uint8_t sFrameBuffer[kNumPrios][kFuzTestBufferSize]; +uint8_t sFrameBuffer[kNumPrios][kFuzTestBufferSize]; uint32_t sFrameBufferTailIndex[kNumPrios] = {0}; uint32_t GetRandom(uint32_t max) @@ -943,11 +947,11 @@ uint32_t GetRandom(uint32_t max) otError WriteRandomFrame(uint32_t aLength, NcpFrameBuffer &aNcpBuffer, NcpFrameBuffer::Priority aPriority) { - otError error; - uint8_t byte; - uint8_t priority = static_cast(aPriority); + otError error; + uint8_t byte; + uint8_t priority = static_cast(aPriority); CallbackContext oldContext = sContext; - uint32_t tail = sFrameBufferTailIndex[priority]; + uint32_t tail = sFrameBufferTailIndex[priority]; SuccessOrExit(error = aNcpBuffer.InFrameBegin(aPriority)); @@ -993,18 +997,17 @@ otError ReadRandomFrame(uint32_t aLength, NcpFrameBuffer &aNcpBuffer, uint8_t pr return OT_ERROR_NONE; } - // This runs a fuzz test of NCP buffer void TestFuzzNcpFrameBuffer(void) { - uint8_t buffer[kFuzTestBufferSize]; + uint8_t buffer[kFuzTestBufferSize]; NcpFrameBuffer ncpBuffer(buffer, kFuzTestBufferSize); - uint32_t lensArray[kNumPrios][kLensArraySize]; // Keeps track of length of written frames so far + uint32_t lensArray[kNumPrios][kLensArraySize]; // Keeps track of length of written frames so far uint32_t lensArrayStart[kNumPrios]; uint32_t lensArrayCount[kNumPrios]; - sInstance = testInitInstance(); + sInstance = testInitInstance(); sMessagePool = &sInstance->GetMessagePool(); memset(buffer, 0, sizeof(buffer)); @@ -1013,7 +1016,7 @@ void TestFuzzNcpFrameBuffer(void) memset(lensArrayStart, 0, sizeof(lensArrayStart)); memset(lensArrayCount, 0, sizeof(lensArrayCount)); - sContext.mFrameAddedCount = 0; + sContext.mFrameAddedCount = 0; sContext.mFrameRemovedCount = 0; ClearTagHistory(); @@ -1041,12 +1044,12 @@ void TestFuzzNcpFrameBuffer(void) if (shouldRead) { uint32_t len; - uint8_t priority; + uint8_t priority; - priority = (lensArrayCount[NcpFrameBuffer::kPriorityHigh] != 0) ? - NcpFrameBuffer::kPriorityHigh : NcpFrameBuffer::kPriorityLow; + priority = (lensArrayCount[NcpFrameBuffer::kPriorityHigh] != 0) ? NcpFrameBuffer::kPriorityHigh + : NcpFrameBuffer::kPriorityLow; - len = lensArray[priority][lensArrayStart[priority]]; + len = lensArray[priority][lensArrayStart[priority]]; lensArrayStart[priority] = (lensArrayStart[priority] + 1) % kLensArraySize; lensArrayCount[priority]--; @@ -1056,7 +1059,7 @@ void TestFuzzNcpFrameBuffer(void) } else { - uint32_t len = GetRandom(kMaxFrameLen) + 1; + uint32_t len = GetRandom(kMaxFrameLen) + 1; NcpFrameBuffer::Priority priority; if (GetRandom(100) < kHighPriorityProbablity) @@ -1086,7 +1089,6 @@ void TestFuzzNcpFrameBuffer(void) VerifyOrQuit(ncpBuffer.IsEmpty() == true, "IsEmpty failed."); printf("EMPTY "); } - } printf("\n -- PASS\n"); @@ -1094,8 +1096,8 @@ void TestFuzzNcpFrameBuffer(void) testFreeInstance(sInstance); } -} // namespace Ncp -} // namespace ot +} // namespace Ncp +} // namespace ot #ifdef ENABLE_TEST_MAIN int main(void) diff --git a/tests/unit/test_network_data.cpp b/tests/unit/test_network_data.cpp index 6356165cb..e097557f1 100644 --- a/tests/unit/test_network_data.cpp +++ b/tests/unit/test_network_data.cpp @@ -36,11 +36,12 @@ namespace ot { -class TestNetworkData: public NetworkData::NetworkData +class TestNetworkData : public NetworkData::NetworkData { public: - TestNetworkData(ot::Instance *aInstance, const uint8_t *aTlvs, uint8_t aTlvsLength): - NetworkData::NetworkData(*aInstance, false) { + TestNetworkData(ot::Instance *aInstance, const uint8_t *aTlvs, uint8_t aTlvsLength) + : NetworkData::NetworkData(*aInstance, false) + { memcpy(mTlvs, aTlvs, aTlvsLength); mLength = aTlvsLength; } @@ -55,8 +56,8 @@ void PrintExternalRouteConfig(const otExternalRouteConfig &aConfig) printf("%02x", aConfig.mPrefix.mPrefix.mFields.m8[i]); } - printf(", length:%d, rloc16:%04x, preference:%d, stable:%d, nexthop:%d", aConfig.mPrefix.mLength, - aConfig.mRloc16, aConfig.mPreference, aConfig.mStable, aConfig.mNextHopIsThisDevice); + printf(", length:%d, rloc16:%04x, preference:%d, stable:%d, nexthop:%d", aConfig.mPrefix.mLength, aConfig.mRloc16, + aConfig.mPreference, aConfig.mStable, aConfig.mNextHopIsThisDevice); } // Returns true if the two given otExternalRouteConfig match (intentionally ignoring mNextHopIsThisDevice). @@ -64,15 +65,13 @@ bool CompareExternalRouteConfig(const otExternalRouteConfig &aConfig1, const otE { return (memcmp(aConfig1.mPrefix.mPrefix.mFields.m8, aConfig2.mPrefix.mPrefix.mFields.m8, sizeof(aConfig1.mPrefix.mPrefix)) == 0) && - (aConfig1.mPrefix.mLength == aConfig2.mPrefix.mLength) && - (aConfig1.mRloc16 == aConfig2.mRloc16) && - (aConfig1.mPreference == aConfig2.mPreference) && - (aConfig1.mStable == aConfig2.mStable); + (aConfig1.mPrefix.mLength == aConfig2.mPrefix.mLength) && (aConfig1.mRloc16 == aConfig2.mRloc16) && + (aConfig1.mPreference == aConfig2.mPreference) && (aConfig1.mStable == aConfig2.mStable); } void TestNetworkDataIterator(void) { - ot::Instance *instance; + ot::Instance * instance; otNetworkDataIterator iter = OT_NETWORK_DATA_ITERATOR_INIT; otExternalRouteConfig config; @@ -80,35 +79,27 @@ void TestNetworkDataIterator(void) VerifyOrQuit(instance != NULL, "Null OpenThread instance\n"); { - const uint8_t kNetworkData[] = - { - 0x08, 0x04, 0x0B, 0x02, 0x00, 0x00, 0x03, 0x14, 0x00, 0x40, 0xFD, 0x00, 0x12, 0x34, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x03, 0xC8, 0x00, 0x40, 0x01, 0x03, 0x54, 0x00, 0x00 - }; + const uint8_t kNetworkData[] = {0x08, 0x04, 0x0B, 0x02, 0x00, 0x00, 0x03, 0x14, 0x00, 0x40, + 0xFD, 0x00, 0x12, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, + 0xC8, 0x00, 0x40, 0x01, 0x03, 0x54, 0x00, 0x00}; - otExternalRouteConfig routes[] = - { + otExternalRouteConfig routes[] = { { - { - {{{ 0xfd, 0x00, 0x12, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }}}, - 64 - }, + {{{{0xfd, 0x00, 0x12, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}}, + 64}, 0xc800, 1, false, false, }, { - { - {{{ 0xfd, 0x00, 0x12, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }}}, - 64 - }, + {{{{0xfd, 0x00, 0x12, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}}, + 64}, 0x5400, 0, true, false, - } - }; + }}; TestNetworkData netData(instance, kNetworkData, sizeof(kNetworkData)); @@ -127,67 +118,38 @@ void TestNetworkDataIterator(void) } { - const uint8_t kNetworkData[] = - { + const uint8_t kNetworkData[] = { 0x08, 0x04, 0x0B, 0x02, 0x00, 0x00, 0x03, 0x1E, 0x00, 0x40, 0xFD, 0x00, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x07, 0x02, 0x11, 0x40, 0x00, 0x03, 0x10, 0x00, 0x40, 0x01, 0x03, 0x54, 0x00, 0x00, 0x05, 0x04, 0x54, 0x00, 0x31, 0x00, 0x02, 0x0F, 0x00, 0x40, 0xFD, 0x00, 0xAB, 0xBA, 0xCD, 0xDC, 0x00, 0x00, 0x00, 0x03, 0x10, 0x00, - 0x00, 0x03, 0x0E, 0x00, 0x20, 0xFD, 0x00, 0xAB, 0xBA, 0x01, 0x06, 0x54, 0x00, 0x00, 0x04, 0x00, 0x00 - }; + 0x00, 0x03, 0x0E, 0x00, 0x20, 0xFD, 0x00, 0xAB, 0xBA, 0x01, 0x06, 0x54, 0x00, 0x00, 0x04, 0x00, 0x00}; - otExternalRouteConfig routes[] = - { - { - { - {{{ 0xfd, 0x00, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }}}, - 64 - }, - 0x1000, - 1, - false, - false - }, - { - { - {{{ 0xfd, 0x00, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }}}, - 64 - }, - 0x5400, - 0, - true, - false - }, - { - { - {{{ 0xfd, 0x00, 0xab, 0xba, 0xcd, 0xdc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }}}, - 64 - }, - 0x1000, - 0, - false, - false - }, - { - { - {{{ 0xfd, 0x00, 0xab, 0xba, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }}}, - 32 - }, - 0x5400, - 0, - true, - false - }, - { - { - {{{ 0xfd, 0x00, 0xab, 0xba, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }}}, - 32 - }, - 0x0400, - 0, - true, - false - } - }; + otExternalRouteConfig routes[] = { + {{{{{0xfd, 0x00, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}}, 64}, + 0x1000, + 1, + false, + false}, + {{{{{0xfd, 0x00, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}}, 64}, + 0x5400, + 0, + true, + false}, + {{{{{0xfd, 0x00, 0xab, 0xba, 0xcd, 0xdc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}}, 64}, + 0x1000, + 0, + false, + false}, + {{{{{0xfd, 0x00, 0xab, 0xba, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}}, 32}, + 0x5400, + 0, + true, + false}, + {{{{{0xfd, 0x00, 0xab, 0xba, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}}, 32}, + 0x0400, + 0, + true, + false}}; TestNetworkData netData(instance, kNetworkData, sizeof(kNetworkData)); @@ -208,7 +170,7 @@ void TestNetworkDataIterator(void) testFreeInstance(instance); } -} // namespace ot +} // namespace ot #ifdef ENABLE_TEST_MAIN int main(void) diff --git a/tests/unit/test_platform.cpp b/tests/unit/test_platform.cpp index c84f9c43c..268c156e7 100644 --- a/tests/unit/test_platform.cpp +++ b/tests/unit/test_platform.cpp @@ -31,8 +31,8 @@ #if _WIN32 __forceinline int gettimeofday(struct timeval *tv, struct timezone *) { - DWORD tick = GetTickCount(); - tv->tv_sec = (long)(tick / 1000); + DWORD tick = GetTickCount(); + tv->tv_sec = (long)(tick / 1000); tv->tv_usec = (long)(tick * 1000); return 0; } @@ -40,41 +40,41 @@ __forceinline int gettimeofday(struct timeval *tv, struct timezone *) #include #endif -bool g_testPlatAlarmSet = false; -uint32_t g_testPlatAlarmNext = 0; -testPlatAlarmStop g_testPlatAlarmStop = NULL; -testPlatAlarmStartAt g_testPlatAlarmStartAt = NULL; -testPlatAlarmGetNow g_testPlatAlarmGetNow = NULL; +bool g_testPlatAlarmSet = false; +uint32_t g_testPlatAlarmNext = 0; +testPlatAlarmStop g_testPlatAlarmStop = NULL; +testPlatAlarmStartAt g_testPlatAlarmStartAt = NULL; +testPlatAlarmGetNow g_testPlatAlarmGetNow = NULL; -otRadioCaps g_testPlatRadioCaps = OT_RADIO_CAPS_NONE; -testPlatRadioSetPanId g_testPlatRadioSetPanId = NULL; +otRadioCaps g_testPlatRadioCaps = OT_RADIO_CAPS_NONE; +testPlatRadioSetPanId g_testPlatRadioSetPanId = NULL; testPlatRadioSetExtendedAddress g_testPlatRadioSetExtendedAddress = NULL; -testPlatRadioIsEnabled g_testPlatRadioIsEnabled = NULL; -testPlatRadioEnable g_testPlatRadioEnable = NULL; -testPlatRadioDisable g_testPlatRadioDisable = NULL; -testPlatRadioSetShortAddress g_testPlatRadioSetShortAddress = NULL; -testPlatRadioReceive g_testPlatRadioReceive = NULL; -testPlatRadioTransmit g_testPlatRadioTransmit = NULL; -testPlatRadioGetTransmitBuffer g_testPlatRadioGetTransmitBuffer = NULL; +testPlatRadioIsEnabled g_testPlatRadioIsEnabled = NULL; +testPlatRadioEnable g_testPlatRadioEnable = NULL; +testPlatRadioDisable g_testPlatRadioDisable = NULL; +testPlatRadioSetShortAddress g_testPlatRadioSetShortAddress = NULL; +testPlatRadioReceive g_testPlatRadioReceive = NULL; +testPlatRadioTransmit g_testPlatRadioTransmit = NULL; +testPlatRadioGetTransmitBuffer g_testPlatRadioGetTransmitBuffer = NULL; void testPlatResetToDefaults(void) { - g_testPlatAlarmSet = false; - g_testPlatAlarmNext = 0; - g_testPlatAlarmStop = NULL; + g_testPlatAlarmSet = false; + g_testPlatAlarmNext = 0; + g_testPlatAlarmStop = NULL; g_testPlatAlarmStartAt = NULL; - g_testPlatAlarmGetNow = NULL; + g_testPlatAlarmGetNow = NULL; - g_testPlatRadioCaps = OT_RADIO_CAPS_NONE; - g_testPlatRadioSetPanId = NULL; + g_testPlatRadioCaps = OT_RADIO_CAPS_NONE; + g_testPlatRadioSetPanId = NULL; g_testPlatRadioSetExtendedAddress = NULL; - g_testPlatRadioSetShortAddress = NULL; - g_testPlatRadioIsEnabled = NULL; - g_testPlatRadioEnable = NULL; - g_testPlatRadioDisable = NULL; - g_testPlatRadioReceive = NULL; - g_testPlatRadioTransmit = NULL; - g_testPlatRadioGetTransmitBuffer = NULL; + g_testPlatRadioSetShortAddress = NULL; + g_testPlatRadioIsEnabled = NULL; + g_testPlatRadioEnable = NULL; + g_testPlatRadioDisable = NULL; + g_testPlatRadioReceive = NULL; + g_testPlatRadioTransmit = NULL; + g_testPlatRadioGetTransmitBuffer = NULL; } ot::Instance *testInitInstance(void) @@ -82,8 +82,8 @@ ot::Instance *testInitInstance(void) otInstance *instance = NULL; #if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES - size_t instanceBufferLength = 0; - uint8_t *instanceBuffer = NULL; + size_t instanceBufferLength = 0; + uint8_t *instanceBuffer = NULL; // Call to query the buffer size (void)otInstanceInit(NULL, &instanceBufferLength); @@ -116,460 +116,459 @@ bool sDiagMode = false; extern "C" { #if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES - void *otPlatCAlloc(size_t aNum, size_t aSize) - { - return calloc(aNum, aSize); - } +void *otPlatCAlloc(size_t aNum, size_t aSize) +{ + return calloc(aNum, aSize); +} - void otPlatFree(void *aPtr) - { - free(aPtr); - } +void otPlatFree(void *aPtr) +{ + free(aPtr); +} #endif - void otTaskletsSignalPending(otInstance *) +void otTaskletsSignalPending(otInstance *) +{ +} + +// +// Alarm +// + +void otPlatAlarmMilliStop(otInstance *aInstance) +{ + if (g_testPlatAlarmStop) { + g_testPlatAlarmStop(aInstance); } - - // - // Alarm - // - - void otPlatAlarmMilliStop(otInstance *aInstance) + else { - if (g_testPlatAlarmStop) - { - g_testPlatAlarmStop(aInstance); - } - else - { - g_testPlatAlarmSet = false; - } + g_testPlatAlarmSet = false; } +} - void otPlatAlarmMilliStartAt(otInstance *aInstance, uint32_t aT0, uint32_t aDt) +void otPlatAlarmMilliStartAt(otInstance *aInstance, uint32_t aT0, uint32_t aDt) +{ + if (g_testPlatAlarmStartAt) { - if (g_testPlatAlarmStartAt) - { - g_testPlatAlarmStartAt(aInstance, aT0, aDt); - } - else - { - g_testPlatAlarmSet = true; - g_testPlatAlarmNext = aT0 + aDt; - } + g_testPlatAlarmStartAt(aInstance, aT0, aDt); } - - uint32_t otPlatAlarmMilliGetNow(void) + else { - if (g_testPlatAlarmGetNow) - { - return g_testPlatAlarmGetNow(); - } - else - { - struct timeval tv; - gettimeofday(&tv, NULL); - return (uint32_t)((tv.tv_sec * 1000) + (tv.tv_usec / 1000) + 123456); - } + g_testPlatAlarmSet = true; + g_testPlatAlarmNext = aT0 + aDt; } +} - void otPlatAlarmMicroStop(otInstance *aInstance) +uint32_t otPlatAlarmMilliGetNow(void) +{ + if (g_testPlatAlarmGetNow) { - if (g_testPlatAlarmStop) - { - g_testPlatAlarmStop(aInstance); - } - else - { - g_testPlatAlarmSet = false; - } + return g_testPlatAlarmGetNow(); } - - void otPlatAlarmMicroStartAt(otInstance *aInstance, uint32_t aT0, uint32_t aDt) + else { - if (g_testPlatAlarmStartAt) - { - g_testPlatAlarmStartAt(aInstance, aT0, aDt); - } - else - { - g_testPlatAlarmSet = true; - g_testPlatAlarmNext = aT0 + aDt; - } + struct timeval tv; + gettimeofday(&tv, NULL); + return (uint32_t)((tv.tv_sec * 1000) + (tv.tv_usec / 1000) + 123456); } +} - uint32_t otPlatAlarmMicroGetNow(void) +void otPlatAlarmMicroStop(otInstance *aInstance) +{ + if (g_testPlatAlarmStop) { - if (g_testPlatAlarmGetNow) - { - return g_testPlatAlarmGetNow(); - } - else - { - struct timeval tv; - gettimeofday(&tv, NULL); - return (uint32_t)((tv.tv_sec * 1000000) + tv.tv_usec + 123456); - } + g_testPlatAlarmStop(aInstance); } - - // - // Radio - // - - void otPlatRadioGetIeeeEui64(otInstance *, uint8_t *) + else { + g_testPlatAlarmSet = false; } +} - void otPlatRadioSetPanId(otInstance *aInstance, uint16_t aPanId) +void otPlatAlarmMicroStartAt(otInstance *aInstance, uint32_t aT0, uint32_t aDt) +{ + if (g_testPlatAlarmStartAt) { - if (g_testPlatRadioSetPanId) - { - g_testPlatRadioSetPanId(aInstance, aPanId); - } + g_testPlatAlarmStartAt(aInstance, aT0, aDt); } - - void otPlatRadioSetExtendedAddress(otInstance *aInstance, const otExtAddress *aExtAddr) + else { - if (g_testPlatRadioSetExtendedAddress) - { - g_testPlatRadioSetExtendedAddress(aInstance, aExtAddr); - } + g_testPlatAlarmSet = true; + g_testPlatAlarmNext = aT0 + aDt; } +} - void otPlatRadioSetShortAddress(otInstance *aInstance, uint16_t aShortAddr) +uint32_t otPlatAlarmMicroGetNow(void) +{ + if (g_testPlatAlarmGetNow) { - if (g_testPlatRadioSetShortAddress) - { - g_testPlatRadioSetShortAddress(aInstance, aShortAddr); - } + return g_testPlatAlarmGetNow(); } - - void otPlatRadioSetPromiscuous(otInstance *, bool) + else { + struct timeval tv; + gettimeofday(&tv, NULL); + return (uint32_t)((tv.tv_sec * 1000000) + tv.tv_usec + 123456); } +} - bool otPlatRadioIsEnabled(otInstance *aInstance) +// +// Radio +// + +void otPlatRadioGetIeeeEui64(otInstance *, uint8_t *) +{ +} + +void otPlatRadioSetPanId(otInstance *aInstance, uint16_t aPanId) +{ + if (g_testPlatRadioSetPanId) { - if (g_testPlatRadioIsEnabled) - { - return g_testPlatRadioIsEnabled(aInstance); - } - else - { - return true; - } + g_testPlatRadioSetPanId(aInstance, aPanId); } +} - otError otPlatRadioEnable(otInstance *aInstance) +void otPlatRadioSetExtendedAddress(otInstance *aInstance, const otExtAddress *aExtAddr) +{ + if (g_testPlatRadioSetExtendedAddress) { - if (g_testPlatRadioEnable) - { - return g_testPlatRadioEnable(aInstance); - } - else - { - return OT_ERROR_NONE; - } + g_testPlatRadioSetExtendedAddress(aInstance, aExtAddr); } +} - otError otPlatRadioDisable(otInstance *aInstance) +void otPlatRadioSetShortAddress(otInstance *aInstance, uint16_t aShortAddr) +{ + if (g_testPlatRadioSetShortAddress) { - if (g_testPlatRadioEnable) - { - return g_testPlatRadioDisable(aInstance); - } - else - { - return OT_ERROR_NONE; - } + g_testPlatRadioSetShortAddress(aInstance, aShortAddr); } +} - otError otPlatRadioSleep(otInstance *) +void otPlatRadioSetPromiscuous(otInstance *, bool) +{ +} + +bool otPlatRadioIsEnabled(otInstance *aInstance) +{ + if (g_testPlatRadioIsEnabled) + { + return g_testPlatRadioIsEnabled(aInstance); + } + else + { + return true; + } +} + +otError otPlatRadioEnable(otInstance *aInstance) +{ + if (g_testPlatRadioEnable) + { + return g_testPlatRadioEnable(aInstance); + } + else { return OT_ERROR_NONE; } +} - otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) +otError otPlatRadioDisable(otInstance *aInstance) +{ + if (g_testPlatRadioEnable) { - if (g_testPlatRadioReceive) - { - return g_testPlatRadioReceive(aInstance, aChannel); - } - else - { - return OT_ERROR_NONE; - } + return g_testPlatRadioDisable(aInstance); } - - otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aFrame) + else { - (void)aFrame; - - if (g_testPlatRadioTransmit) - { - return g_testPlatRadioTransmit(aInstance); - } - else - { - return OT_ERROR_NONE; - } - } - - otRadioFrame *otPlatRadioGetTransmitBuffer(otInstance *aInstance) - { - if (g_testPlatRadioGetTransmitBuffer) - { - return g_testPlatRadioGetTransmitBuffer(aInstance); - } - else - { - return (otRadioFrame *)0; - } - } - - int8_t otPlatRadioGetRssi(otInstance *) - { - return 0; - } - - otRadioCaps otPlatRadioGetCaps(otInstance *) - { - return g_testPlatRadioCaps; - } - - bool otPlatRadioGetPromiscuous(otInstance *) - { - return false; - } - - void otPlatRadioEnableSrcMatch(otInstance *aInstance, bool aEnable) - { - (void)aInstance; - (void)aEnable; - } - - otError otPlatRadioAddSrcMatchShortEntry(otInstance *aInstance, const uint16_t aShortAddress) - { - (void)aInstance; - (void)aShortAddress; return OT_ERROR_NONE; } +} - otError otPlatRadioAddSrcMatchExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) +otError otPlatRadioSleep(otInstance *) +{ + return OT_ERROR_NONE; +} + +otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) +{ + if (g_testPlatRadioReceive) + { + return g_testPlatRadioReceive(aInstance, aChannel); + } + else { - (void)aInstance; - (void)aExtAddress; return OT_ERROR_NONE; } +} - otError otPlatRadioClearSrcMatchShortEntry(otInstance *aInstance, const uint16_t aShortAddress) +otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aFrame) +{ + (void)aFrame; + + if (g_testPlatRadioTransmit) + { + return g_testPlatRadioTransmit(aInstance); + } + else { - (void)aInstance; - (void)aShortAddress; return OT_ERROR_NONE; } +} - otError otPlatRadioClearSrcMatchExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) +otRadioFrame *otPlatRadioGetTransmitBuffer(otInstance *aInstance) +{ + if (g_testPlatRadioGetTransmitBuffer) { - (void)aInstance; - (void)aExtAddress; - return OT_ERROR_NONE; + return g_testPlatRadioGetTransmitBuffer(aInstance); } - - void otPlatRadioClearSrcMatchShortEntries(otInstance *aInstance) + else { - (void)aInstance; + return (otRadioFrame *)0; } +} - void otPlatRadioClearSrcMatchExtEntries(otInstance *aInstance) - { - (void)aInstance; - } +int8_t otPlatRadioGetRssi(otInstance *) +{ + return 0; +} - otError otPlatRadioEnergyScan(otInstance *, uint8_t, uint16_t) - { - return OT_ERROR_NOT_IMPLEMENTED; - } +otRadioCaps otPlatRadioGetCaps(otInstance *) +{ + return g_testPlatRadioCaps; +} - otError otPlatRadioSetTransmitPower(otInstance *aInstance, int8_t aPower) - { - (void)aInstance; - (void)aPower; - return OT_ERROR_NOT_IMPLEMENTED; - } +bool otPlatRadioGetPromiscuous(otInstance *) +{ + return false; +} - int8_t otPlatRadioGetReceiveSensitivity(otInstance *aInstance) - { - (void)aInstance; - return 0; - } - // - // Random - // +void otPlatRadioEnableSrcMatch(otInstance *aInstance, bool aEnable) +{ + (void)aInstance; + (void)aEnable; +} - uint32_t otPlatRandomGet(void) - { +otError otPlatRadioAddSrcMatchShortEntry(otInstance *aInstance, const uint16_t aShortAddress) +{ + (void)aInstance; + (void)aShortAddress; + return OT_ERROR_NONE; +} + +otError otPlatRadioAddSrcMatchExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) +{ + (void)aInstance; + (void)aExtAddress; + return OT_ERROR_NONE; +} + +otError otPlatRadioClearSrcMatchShortEntry(otInstance *aInstance, const uint16_t aShortAddress) +{ + (void)aInstance; + (void)aShortAddress; + return OT_ERROR_NONE; +} + +otError otPlatRadioClearSrcMatchExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) +{ + (void)aInstance; + (void)aExtAddress; + return OT_ERROR_NONE; +} + +void otPlatRadioClearSrcMatchShortEntries(otInstance *aInstance) +{ + (void)aInstance; +} + +void otPlatRadioClearSrcMatchExtEntries(otInstance *aInstance) +{ + (void)aInstance; +} + +otError otPlatRadioEnergyScan(otInstance *, uint8_t, uint16_t) +{ + return OT_ERROR_NOT_IMPLEMENTED; +} + +otError otPlatRadioSetTransmitPower(otInstance *aInstance, int8_t aPower) +{ + (void)aInstance; + (void)aPower; + return OT_ERROR_NOT_IMPLEMENTED; +} + +int8_t otPlatRadioGetReceiveSensitivity(otInstance *aInstance) +{ + (void)aInstance; + return 0; +} +// +// Random +// + +uint32_t otPlatRandomGet(void) +{ #if _WIN32 - return (uint32_t)rand(); + return (uint32_t)rand(); #else - return (uint32_t)random(); + return (uint32_t)random(); #endif - } +} - otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength) +otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength) +{ + otError error = OT_ERROR_NONE; + + VerifyOrExit(aOutput, error = OT_ERROR_INVALID_ARGS); + + for (uint16_t length = 0; length < aOutputLength; length++) { - otError error = OT_ERROR_NONE; - - VerifyOrExit(aOutput, error = OT_ERROR_INVALID_ARGS); - - for (uint16_t length = 0; length < aOutputLength; length++) - { - aOutput[length] = (uint8_t)otPlatRandomGet(); - } + aOutput[length] = (uint8_t)otPlatRandomGet(); + } exit: - return error; - } + return error; +} - // - // Diag - // +// +// Diag +// - void otPlatDiagProcess(int argc, char *argv[], char *aOutput) - { - // no more diagnostics features for Posix platform - sprintf(aOutput, "diag feature '%s' is not supported\r\n", argv[0]); - (void)argc; - } +void otPlatDiagProcess(int argc, char *argv[], char *aOutput) +{ + // no more diagnostics features for Posix platform + sprintf(aOutput, "diag feature '%s' is not supported\r\n", argv[0]); + (void)argc; +} - void otPlatDiagModeSet(bool aMode) - { - sDiagMode = aMode; - } +void otPlatDiagModeSet(bool aMode) +{ + sDiagMode = aMode; +} - bool otPlatDiagModeGet() - { - return sDiagMode; - } +bool otPlatDiagModeGet() +{ + return sDiagMode; +} - void otPlatDiagAlarmFired(otInstance *) - { - } +void otPlatDiagAlarmFired(otInstance *) +{ +} - void otPlatDiagRadioTransmitDone(otInstance *, otRadioFrame *, otError) - { - } +void otPlatDiagRadioTransmitDone(otInstance *, otRadioFrame *, otError) +{ +} - void otPlatDiagRadioReceiveDone(otInstance *, otRadioFrame *, otError) - { - } +void otPlatDiagRadioReceiveDone(otInstance *, otRadioFrame *, otError) +{ +} - // - // Uart - // +// +// Uart +// - void otPlatUartSendDone(void) - { - } +void otPlatUartSendDone(void) +{ +} - void otPlatUartReceived(const uint8_t *, uint16_t) - { - } +void otPlatUartReceived(const uint8_t *, uint16_t) +{ +} - // - // Misc - // +// +// Misc +// - void otPlatReset(otInstance *aInstance) - { - (void)aInstance; - } +void otPlatReset(otInstance *aInstance) +{ + (void)aInstance; +} - otPlatResetReason otPlatGetResetReason(otInstance *aInstance) - { - (void)aInstance; - return OT_PLAT_RESET_REASON_POWER_ON; - } +otPlatResetReason otPlatGetResetReason(otInstance *aInstance) +{ + (void)aInstance; + return OT_PLAT_RESET_REASON_POWER_ON; +} - void otPlatLog(otLogLevel, otLogRegion, const char *, ...) - { - } +void otPlatLog(otLogLevel, otLogRegion, const char *, ...) +{ +} - // - // Settings - // +// +// Settings +// - void otPlatSettingsInit(otInstance *aInstance) - { - (void)aInstance; - } +void otPlatSettingsInit(otInstance *aInstance) +{ + (void)aInstance; +} - otError otPlatSettingsBeginChange(otInstance *aInstance) - { - (void)aInstance; +otError otPlatSettingsBeginChange(otInstance *aInstance) +{ + (void)aInstance; - return OT_ERROR_NONE; - } + return OT_ERROR_NONE; +} - otError otPlatSettingsCommitChange(otInstance *aInstance) - { - (void)aInstance; +otError otPlatSettingsCommitChange(otInstance *aInstance) +{ + (void)aInstance; - return OT_ERROR_NONE; - } + return OT_ERROR_NONE; +} - otError otPlatSettingsAbandonChange(otInstance *aInstance) - { - (void)aInstance; +otError otPlatSettingsAbandonChange(otInstance *aInstance) +{ + (void)aInstance; - return OT_ERROR_NONE; - } + return OT_ERROR_NONE; +} - otError otPlatSettingsGet(otInstance *aInstance, uint16_t aKey, int aIndex, uint8_t *aValue, - uint16_t *aValueLength) - { - (void)aInstance; - (void)aKey; - (void)aIndex; - (void)aValue; - (void)aValueLength; +otError otPlatSettingsGet(otInstance *aInstance, uint16_t aKey, int aIndex, uint8_t *aValue, uint16_t *aValueLength) +{ + (void)aInstance; + (void)aKey; + (void)aIndex; + (void)aValue; + (void)aValueLength; - return OT_ERROR_NOT_FOUND; - } + return OT_ERROR_NOT_FOUND; +} - otError otPlatSettingsSet(otInstance *aInstance, uint16_t aKey, const uint8_t *aValue, uint16_t aValueLength) - { - (void)aInstance; - (void)aKey; - (void)aValue; - (void)aValueLength; +otError otPlatSettingsSet(otInstance *aInstance, uint16_t aKey, const uint8_t *aValue, uint16_t aValueLength) +{ + (void)aInstance; + (void)aKey; + (void)aValue; + (void)aValueLength; - return OT_ERROR_NONE; - } + return OT_ERROR_NONE; +} - otError otPlatSettingsAdd(otInstance *aInstance, uint16_t aKey, const uint8_t *aValue, uint16_t aValueLength) - { - (void)aInstance; - (void)aKey; - (void)aValue; - (void)aValueLength; +otError otPlatSettingsAdd(otInstance *aInstance, uint16_t aKey, const uint8_t *aValue, uint16_t aValueLength) +{ + (void)aInstance; + (void)aKey; + (void)aValue; + (void)aValueLength; - return OT_ERROR_NONE; - } + return OT_ERROR_NONE; +} - otError otPlatSettingsDelete(otInstance *aInstance, uint16_t aKey, int aIndex) - { - (void)aInstance; - (void)aKey; - (void)aIndex; +otError otPlatSettingsDelete(otInstance *aInstance, uint16_t aKey, int aIndex) +{ + (void)aInstance; + (void)aKey; + (void)aIndex; - return OT_ERROR_NONE; - } + return OT_ERROR_NONE; +} - void otPlatSettingsWipe(otInstance *aInstance) - { - (void)aInstance; - } +void otPlatSettingsWipe(otInstance *aInstance) +{ + (void)aInstance; +} } // extern "C" diff --git a/tests/unit/test_platform.h b/tests/unit/test_platform.h index 87b3e7c56..9290029cb 100644 --- a/tests/unit/test_platform.h +++ b/tests/unit/test_platform.h @@ -31,8 +31,8 @@ #if _WIN32 #define _CRT_SECURE_NO_WARNINGS -#include #include +#include #endif #include @@ -58,11 +58,11 @@ typedef void (*testPlatAlarmStop)(otInstance *); typedef void (*testPlatAlarmStartAt)(otInstance *, uint32_t, uint32_t); typedef uint32_t (*testPlatAlarmGetNow)(void); -extern bool g_testPlatAlarmSet; -extern uint32_t g_testPlatAlarmNext; -extern testPlatAlarmStop g_testPlatAlarmStop; -extern testPlatAlarmStartAt g_testPlatAlarmStartAt; -extern testPlatAlarmGetNow g_testPlatAlarmGetNow; +extern bool g_testPlatAlarmSet; +extern uint32_t g_testPlatAlarmNext; +extern testPlatAlarmStop g_testPlatAlarmStop; +extern testPlatAlarmStartAt g_testPlatAlarmStartAt; +extern testPlatAlarmGetNow g_testPlatAlarmGetNow; // // Radio Platform @@ -72,26 +72,26 @@ typedef void (*testPlatRadioSetPanId)(otInstance *, uint16_t); typedef void (*testPlatRadioSetExtendedAddress)(otInstance *, const otExtAddress *); typedef void (*testPlatRadioSetShortAddress)(otInstance *, uint16_t); -typedef bool(*testPlatRadioIsEnabled)(otInstance *); -typedef otError(*testPlatRadioEnable)(otInstance *); -typedef otError(*testPlatRadioDisable)(otInstance *); -typedef otError(*testPlatRadioReceive)(otInstance *, uint8_t); -typedef otError(*testPlatRadioTransmit)(otInstance *); +typedef bool (*testPlatRadioIsEnabled)(otInstance *); +typedef otError (*testPlatRadioEnable)(otInstance *); +typedef otError (*testPlatRadioDisable)(otInstance *); +typedef otError (*testPlatRadioReceive)(otInstance *, uint8_t); +typedef otError (*testPlatRadioTransmit)(otInstance *); typedef otRadioFrame *(*testPlatRadioGetTransmitBuffer)(otInstance *); -extern otRadioCaps g_testPlatRadioCaps; -extern testPlatRadioSetPanId g_testPlatRadioSetPanId; -extern testPlatRadioSetExtendedAddress g_testPlatRadioSetExtendedAddress; -extern testPlatRadioSetShortAddress g_testPlatRadioSetShortAddress; -extern testPlatRadioIsEnabled g_testPlatRadioIsEnabled; -extern testPlatRadioEnable g_testPlatRadioEnable; -extern testPlatRadioDisable g_testPlatRadioDisable; -extern testPlatRadioReceive g_testPlatRadioReceive; -extern testPlatRadioTransmit g_testPlatRadioTransmit; -extern testPlatRadioGetTransmitBuffer g_testPlatRadioGetTransmitBuffer; +extern otRadioCaps g_testPlatRadioCaps; +extern testPlatRadioSetPanId g_testPlatRadioSetPanId; +extern testPlatRadioSetExtendedAddress g_testPlatRadioSetExtendedAddress; +extern testPlatRadioSetShortAddress g_testPlatRadioSetShortAddress; +extern testPlatRadioIsEnabled g_testPlatRadioIsEnabled; +extern testPlatRadioEnable g_testPlatRadioEnable; +extern testPlatRadioDisable g_testPlatRadioDisable; +extern testPlatRadioReceive g_testPlatRadioReceive; +extern testPlatRadioTransmit g_testPlatRadioTransmit; +extern testPlatRadioGetTransmitBuffer g_testPlatRadioGetTransmitBuffer; ot::Instance *testInitInstance(void); -void testFreeInstance(otInstance *aInstance); +void testFreeInstance(otInstance *aInstance); // Resets platform functions to defaults void testPlatResetToDefaults(void); diff --git a/tests/unit/test_priority_queue.cpp b/tests/unit/test_priority_queue.cpp index 2338b9c66..cb97d3639 100644 --- a/tests/unit/test_priority_queue.cpp +++ b/tests/unit/test_priority_queue.cpp @@ -38,16 +38,16 @@ #include "test_platform.h" #include "test_util.h" -#define kNumTestMessages 3 +#define kNumTestMessages 3 // This function verifies the content of the priority queue to match the passed in messages void VerifyPriorityQueueContent(ot::PriorityQueue &aPriorityQueue, int aExpectedLength, ...) { - va_list args; + va_list args; ot::Message *message; ot::Message *msgArg; - uint8_t curPriority = 0xff; - uint16_t msgCount, bufCount; + uint8_t curPriority = 0xff; + uint16_t msgCount, bufCount; // Check the `GetInfo` aPriorityQueue.GetInfo(msgCount, bufCount); @@ -81,15 +81,12 @@ void VerifyPriorityQueueContent(ot::PriorityQueue &aPriorityQueue, int aExpected // Check the `GetHeadForPriority` is NULL if there are no expected message for this priority level. VerifyOrQuit( aPriorityQueue.GetHeadForPriority(curPriority) == NULL, - "PriorityQueue::GetHeadForPriority is non-NULL when no expected msg for this priority.\n" - ); + "PriorityQueue::GetHeadForPriority is non-NULL when no expected msg for this priority.\n"); } // Check the `GetHeadForPriority`. - VerifyOrQuit( - aPriorityQueue.GetHeadForPriority(curPriority) == msgArg, - "PriorityQueue::GetHeadForPriority failed.\n" - ); + VerifyOrQuit(aPriorityQueue.GetHeadForPriority(curPriority) == msgArg, + "PriorityQueue::GetHeadForPriority failed.\n"); } // Check the queued message to match the one from argument list @@ -103,10 +100,8 @@ void VerifyPriorityQueueContent(ot::PriorityQueue &aPriorityQueue, int aExpected // Check the `GetHeadForPriority` is NULL if there are no expected message for any remaining priority level. for (curPriority++; curPriority < 4; curPriority++) { - VerifyOrQuit( - aPriorityQueue.GetHeadForPriority(curPriority) == NULL, - "PriorityQueue::GetHeadForPriority is non-NULL when no expected msg for this priority.\n" - ); + VerifyOrQuit(aPriorityQueue.GetHeadForPriority(curPriority) == NULL, + "PriorityQueue::GetHeadForPriority is non-NULL when no expected msg for this priority.\n"); } } @@ -116,9 +111,9 @@ void VerifyPriorityQueueContent(ot::PriorityQueue &aPriorityQueue, int aExpected // This function verifies the content of the all message queue to match the passed in messages void VerifyAllMessagesContent(ot::MessagePool *aMessagePool, int aExpectedLength, ...) { - va_list args; + va_list args; ot::MessagePool::Iterator it; - ot::Message *msgArg; + ot::Message * msgArg; va_start(args, aExpectedLength); @@ -129,7 +124,7 @@ void VerifyAllMessagesContent(ot::MessagePool *aMessagePool, int aExpectedLength } else { - for (it = aMessagePool->GetAllMessagesHead(); !it.HasEnded() ; it.GoToNext()) + for (it = aMessagePool->GetAllMessagesHead(); !it.HasEnded(); it.GoToNext()) { VerifyOrQuit(aExpectedLength != 0, "AllMessagesQueue contains more entries than expected.\n"); msgArg = va_arg(args, ot::Message *); @@ -147,9 +142,9 @@ void VerifyAllMessagesContent(ot::MessagePool *aMessagePool, int aExpectedLength // through the AllMessages list in reverse. void VerifyAllMessagesContentInReverse(ot::MessagePool *aMessagePool, int aExpectedLength, ...) { - va_list args; + va_list args; ot::MessagePool::Iterator it; - ot::Message *msgArg; + ot::Message * msgArg; va_start(args, aExpectedLength); @@ -160,7 +155,7 @@ void VerifyAllMessagesContentInReverse(ot::MessagePool *aMessagePool, int aExpec } else { - for (it = aMessagePool->GetAllMessagesTail(); !it.HasEnded() ; it.GoToPrev()) + for (it = aMessagePool->GetAllMessagesTail(); !it.HasEnded(); it.GoToPrev()) { VerifyOrQuit(aExpectedLength != 0, "AllMessagesQueue contains more entries than expected.\n"); msgArg = va_arg(args, ot::Message *); @@ -177,7 +172,7 @@ void VerifyAllMessagesContentInReverse(ot::MessagePool *aMessagePool, int aExpec // This function verifies the content of the message queue to match the passed in messages void VerifyMsgQueueContent(ot::MessageQueue &aMessageQueue, int aExpectedLength, ...) { - va_list args; + va_list args; ot::Message *message; ot::Message *msgArg; @@ -208,14 +203,14 @@ void VerifyMsgQueueContent(ot::MessageQueue &aMessageQueue, int aExpectedLength, void TestPriorityQueue(void) { - ot::Instance *instance; - ot::MessagePool *messagePool; - ot::PriorityQueue queue; - ot::MessageQueue messageQueue; - ot::Message *msgHigh [kNumTestMessages]; - ot::Message *msgMed [kNumTestMessages]; - ot::Message *msgLow [kNumTestMessages]; - ot::Message *msgVeryLow [kNumTestMessages]; + ot::Instance * instance; + ot::MessagePool * messagePool; + ot::PriorityQueue queue; + ot::MessageQueue messageQueue; + ot::Message * msgHigh[kNumTestMessages]; + ot::Message * msgMed[kNumTestMessages]; + ot::Message * msgLow[kNumTestMessages]; + ot::Message * msgVeryLow[kNumTestMessages]; ot::MessagePool::Iterator it; instance = testInitInstance(); @@ -241,10 +236,8 @@ void TestPriorityQueue(void) } // Check the failure case for `SetPriority` for invalid argument. - VerifyOrQuit( - msgHigh[2]->SetPriority(ot::Message::kNumPriorities) == OT_ERROR_INVALID_ARGS, - "Message::SetPriority() with out of range value did not fail as expected.\n" - ); + VerifyOrQuit(msgHigh[2]->SetPriority(ot::Message::kNumPriorities) == OT_ERROR_INVALID_ARGS, + "Message::SetPriority() with out of range value did not fail as expected.\n"); // Check the `GetPriority()` for (int i = 0; i < kNumTestMessages; i++) @@ -324,14 +317,10 @@ void TestPriorityQueue(void) // Check the failure cases: Enqueuing an already queued message, or dequeuing a message not queued. SuccessOrQuit(queue.Enqueue(*msgHigh[0]), "PriorityQueue::Enqueue() failed.\n"); VerifyPriorityQueueContent(queue, 1, msgHigh[0]); - VerifyOrQuit( - queue.Enqueue(*msgHigh[0]) == OT_ERROR_ALREADY, - "Enqueuing an already queued message did not fail as expected.\n" - ); - VerifyOrQuit( - queue.Dequeue(*msgMed[0]) == OT_ERROR_NOT_FOUND, - "Dequeuing a message not queued, did not fail as expected.\n" - ); + VerifyOrQuit(queue.Enqueue(*msgHigh[0]) == OT_ERROR_ALREADY, + "Enqueuing an already queued message did not fail as expected.\n"); + VerifyOrQuit(queue.Dequeue(*msgMed[0]) == OT_ERROR_NOT_FOUND, + "Dequeuing a message not queued, did not fail as expected.\n"); SuccessOrQuit(queue.Dequeue(*msgHigh[0]), "PriorityQueue::Dequeue() failed.\n"); VerifyPriorityQueueContent(queue, 0); diff --git a/tests/unit/test_pskc.cpp b/tests/unit/test_pskc.cpp index bab836fac..0ee9d0229 100644 --- a/tests/unit/test_pskc.cpp +++ b/tests/unit/test_pskc.cpp @@ -28,28 +28,22 @@ #include #include +#include "common/logging.hpp" #include "meshcop/commissioner.hpp" #include "utils/wrap_string.h" -#include "common/logging.hpp" #include "test_platform.h" #include "test_util.h" -static const uint8_t sXPanId[] = -{ - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 -}; +static const uint8_t sXPanId[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; void TestMinimumPassphrase(void) { - uint8_t pskc[OT_PSKC_MAX_SIZE]; - const uint8_t expectedPskc[] = - { - 0x44, 0x98, 0x8e, 0x22, 0xcf, 0x65, 0x2e, 0xee, - 0xcc, 0xd1, 0xe4, 0xc0, 0x1d, 0x01, 0x54, 0xf8 - }; - const char passphrase[] = "123456"; - otInstance *instance = testInitInstance(); + uint8_t pskc[OT_PSKC_MAX_SIZE]; + const uint8_t expectedPskc[] = {0x44, 0x98, 0x8e, 0x22, 0xcf, 0x65, 0x2e, 0xee, + 0xcc, 0xd1, 0xe4, 0xc0, 0x1d, 0x01, 0x54, 0xf8}; + const char passphrase[] = "123456"; + otInstance * instance = testInitInstance(); SuccessOrQuit(ot::MeshCoP::Commissioner::GeneratePSKc(passphrase, "OpenThread", sXPanId, pskc), "TestMinimumPassphrase failed to generate PSKc"); VerifyOrQuit(memcmp(pskc, expectedPskc, sizeof(pskc)) == 0, "TestMinimumPassphrase got wrong pskc"); @@ -58,17 +52,25 @@ void TestMinimumPassphrase(void) void TestMaximumPassphrase(void) { - uint8_t pskc[OT_PSKC_MAX_SIZE]; - const uint8_t expectedPskc[] = - { - 0x9e, 0x81, 0xbd, 0x35, 0xa2, 0x53, 0x76, 0x2f, - 0x80, 0xee, 0x04, 0xff, 0x2f, 0xa2, 0x85, 0xe9 - }; - const char passphrase[] = - "1234567812345678" "1234567812345678" "1234567812345678" "1234567812345678" - "1234567812345678" "1234567812345678" "1234567812345678" "1234567812345678" - "1234567812345678" "1234567812345678" "1234567812345678" "1234567812345678" - "1234567812345678" "1234567812345678" "1234567812345678" "123456781234567"; + uint8_t pskc[OT_PSKC_MAX_SIZE]; + const uint8_t expectedPskc[] = {0x9e, 0x81, 0xbd, 0x35, 0xa2, 0x53, 0x76, 0x2f, + 0x80, 0xee, 0x04, 0xff, 0x2f, 0xa2, 0x85, 0xe9}; + const char passphrase[] = "1234567812345678" + "1234567812345678" + "1234567812345678" + "1234567812345678" + "1234567812345678" + "1234567812345678" + "1234567812345678" + "1234567812345678" + "1234567812345678" + "1234567812345678" + "1234567812345678" + "1234567812345678" + "1234567812345678" + "1234567812345678" + "1234567812345678" + "123456781234567"; otInstance *instance = testInitInstance(); SuccessOrQuit(ot::MeshCoP::Commissioner::GeneratePSKc(passphrase, "OpenThread", sXPanId, pskc), diff --git a/tests/unit/test_spinel_decoder.cpp b/tests/unit/test_spinel_decoder.cpp index 2a6f66698..c6680bd31 100644 --- a/tests/unit/test_spinel_decoder.cpp +++ b/tests/unit/test_spinel_decoder.cpp @@ -44,18 +44,17 @@ enum kTestBufferSize = 800, }; - // Dump the buffer content to screen. void DumpBuffer(const char *aTextMessage, uint8_t *aBuffer, uint16_t aBufferLength) { enum { - kBytesPerLine = 32, // Number of bytes per line. + kBytesPerLine = 32, // Number of bytes per line. }; - char charBuff[kBytesPerLine + 1]; + char charBuff[kBytesPerLine + 1]; uint16_t counter; - uint8_t byte; + uint8_t byte; printf("\n%s - len = %u\n ", aTextMessage, aBufferLength); @@ -88,67 +87,62 @@ void DumpBuffer(const char *aTextMessage, uint8_t *aBuffer, uint16_t aBufferLeng void TestSpinelDecoder(void) { - uint8_t buffer[kTestBufferSize]; + uint8_t buffer[kTestBufferSize]; SpinelDecoder decoder; spinel_ssize_t frameLen; - const bool kBool_1 = true; - const bool kBool_2 = false; - const uint8_t kUint8 = 0x42; - const int8_t kInt8 = -73; - const uint16_t kUint16 = 0xabcd; - const int16_t kInt16 = -567; - const uint32_t kUint32 = 0xdeadbeef; - const int32_t kInt32 = -123455678L; - const uint64_t kUint64 = 0xfe10dc32ba549876ULL; - const int64_t kInt64 = -9197712039090021561LL; + const bool kBool_1 = true; + const bool kBool_2 = false; + const uint8_t kUint8 = 0x42; + const int8_t kInt8 = -73; + const uint16_t kUint16 = 0xabcd; + const int16_t kInt16 = -567; + const uint32_t kUint32 = 0xdeadbeef; + const int32_t kInt32 = -123455678L; + const uint64_t kUint64 = 0xfe10dc32ba549876ULL; + const int64_t kInt64 = -9197712039090021561LL; - const unsigned int kUint_1 = 9; - const unsigned int kUint_2 = 0xa3; - const unsigned int kUint_3 = 0x8765; - const unsigned int kUint_4 = SPINEL_MAX_UINT_PACKED - 1; + const unsigned int kUint_1 = 9; + const unsigned int kUint_2 = 0xa3; + const unsigned int kUint_3 = 0x8765; + const unsigned int kUint_4 = SPINEL_MAX_UINT_PACKED - 1; + const spinel_ipv6addr_t kIp6Addr = { + {0x6B, 0x41, 0x65, 0x73, 0x42, 0x68, 0x61, 0x76, 0x54, 0x61, 0x72, 0x7A, 0x49, 0x69, 0x61, 0x4E}}; - const spinel_ipv6addr_t kIp6Addr = - { - { 0x6B, 0x41, 0x65, 0x73, 0x42, 0x68, 0x61, 0x76, 0x54, 0x61, 0x72, 0x7A, 0x49, 0x69, 0x61, 0x4E } + const spinel_eui48_t kEui48 = { + {4, 8, 15, 16, 23, 42} // "Lost" EUI48! }; - const spinel_eui48_t kEui48 = - { - { 4, 8, 15, 16, 23, 42 } // "Lost" EUI48! - }; - - const spinel_eui64_t kEui64 = - { - { 2, 3, 5, 7, 11, 13, 17, 19 }, // "Prime" EUI64! + const spinel_eui64_t kEui64 = { + {2, 3, 5, 7, 11, 13, 17, 19}, // "Prime" EUI64! }; const char kString_1[] = "OpenThread"; const char kString_2[] = ""; - const uint16_t kData[] = { 10, 20, 3, 15, 1000, 60, 16 }; // ... then comes 17,18,19,20 :) + const uint16_t kData[] = {10, 20, 3, 15, 1000, 60, 16}; // ... then comes 17,18,19,20 :) - bool b_1, b_2; - uint8_t u8; - int8_t i8; - uint16_t u16; - int16_t i16; - uint32_t u32; - int32_t i32; - uint64_t u64; - int64_t i64; - unsigned int u_1, u_2, u_3, u_4; + bool b_1, b_2; + uint8_t u8; + int8_t i8; + uint16_t u16; + int16_t i16; + uint32_t u32; + int32_t i32; + uint64_t u64; + int64_t i64; + unsigned int u_1, u_2, u_3, u_4; const spinel_ipv6addr_t *ip6Addr; - const spinel_eui48_t *eui48; - const spinel_eui64_t *eui64; - const char *utf_1; - const char *utf_2; - const uint8_t *dataPtr_1; - const uint8_t *dataPtr_2; - uint16_t dataLen_1; - uint16_t dataLen_2; + const spinel_eui48_t * eui48; + const spinel_eui64_t * eui64; + const char * utf_1; + const char * utf_2; + const uint8_t * dataPtr_1; + const uint8_t * dataPtr_2; + uint16_t dataLen_1; + uint16_t dataLen_2; memset(buffer, 0, sizeof(buffer)); @@ -156,122 +150,84 @@ void TestSpinelDecoder(void) printf("\nTest 1: Decoding simple types"); frameLen = spinel_datatype_pack( - buffer, - sizeof(buffer), - ( - SPINEL_DATATYPE_BOOL_S - SPINEL_DATATYPE_BOOL_S - SPINEL_DATATYPE_UINT8_S - SPINEL_DATATYPE_INT8_S - SPINEL_DATATYPE_UINT16_S - SPINEL_DATATYPE_INT16_S - SPINEL_DATATYPE_UINT32_S - SPINEL_DATATYPE_INT32_S - SPINEL_DATATYPE_UINT64_S - SPINEL_DATATYPE_INT64_S - SPINEL_DATATYPE_UINT_PACKED_S - SPINEL_DATATYPE_UINT_PACKED_S - SPINEL_DATATYPE_UINT_PACKED_S - SPINEL_DATATYPE_UINT_PACKED_S - SPINEL_DATATYPE_IPv6ADDR_S - SPINEL_DATATYPE_EUI48_S - SPINEL_DATATYPE_EUI64_S - SPINEL_DATATYPE_UTF8_S - SPINEL_DATATYPE_UTF8_S - SPINEL_DATATYPE_DATA_WLEN_S - SPINEL_DATATYPE_DATA_S - ), - kBool_1, - kBool_2, - kUint8, - kInt8, - kUint16, - kInt16, - kUint32, - kInt32, - kUint64, - kInt64, - kUint_1, - kUint_2, - kUint_3, - kUint_4, - &kIp6Addr, - &kEui48, - &kEui64, - kString_1, - kString_2, - kData, sizeof(kData), - kData, sizeof(kData) - ); + buffer, sizeof(buffer), + (SPINEL_DATATYPE_BOOL_S SPINEL_DATATYPE_BOOL_S SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_INT8_S + SPINEL_DATATYPE_UINT16_S SPINEL_DATATYPE_INT16_S SPINEL_DATATYPE_UINT32_S SPINEL_DATATYPE_INT32_S + SPINEL_DATATYPE_UINT64_S SPINEL_DATATYPE_INT64_S SPINEL_DATATYPE_UINT_PACKED_S + SPINEL_DATATYPE_UINT_PACKED_S SPINEL_DATATYPE_UINT_PACKED_S SPINEL_DATATYPE_UINT_PACKED_S + SPINEL_DATATYPE_IPv6ADDR_S SPINEL_DATATYPE_EUI48_S SPINEL_DATATYPE_EUI64_S + SPINEL_DATATYPE_UTF8_S SPINEL_DATATYPE_UTF8_S SPINEL_DATATYPE_DATA_WLEN_S + SPINEL_DATATYPE_DATA_S), + kBool_1, kBool_2, kUint8, kInt8, kUint16, kInt16, kUint32, kInt32, kUint64, kInt64, kUint_1, kUint_2, kUint_3, + kUint_4, &kIp6Addr, &kEui48, &kEui64, kString_1, kString_2, kData, sizeof(kData), kData, sizeof(kData)); DumpBuffer("Packed Spinel Frame", buffer, static_cast(frameLen)); decoder.Init(buffer, static_cast(frameLen)); - VerifyOrQuit(decoder.GetFrame() == &buffer[0], "GetFrame() failed."); - VerifyOrQuit(decoder.GetLength() == frameLen, "GetLength() failed."); + VerifyOrQuit(decoder.GetFrame() == &buffer[0], "GetFrame() failed."); + VerifyOrQuit(decoder.GetLength() == frameLen, "GetLength() failed."); - VerifyOrQuit(decoder.GetReadLength() == 0, "GetReadLength() failed."); - VerifyOrQuit(decoder.GetRemainingLength() == frameLen, "GetRemainingLength() failed."); - VerifyOrQuit(decoder.IsAllRead() == false, "IsAllRead() failed."); + VerifyOrQuit(decoder.GetReadLength() == 0, "GetReadLength() failed."); + VerifyOrQuit(decoder.GetRemainingLength() == frameLen, "GetRemainingLength() failed."); + VerifyOrQuit(decoder.IsAllRead() == false, "IsAllRead() failed."); - SuccessOrQuit(decoder.ReadBool(b_1), "ReadBool() failed."); - SuccessOrQuit(decoder.ReadBool(b_2), "ReadBool() failed."); - SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); - SuccessOrQuit(decoder.ReadInt8(i8), "ReadUint8() failed."); - SuccessOrQuit(decoder.ReadUint16(u16), "ReadUint16() failed."); - SuccessOrQuit(decoder.ReadInt16(i16), "ReadInt16() failed."); - SuccessOrQuit(decoder.ReadUint32(u32), "ReadUint32() failed."); - SuccessOrQuit(decoder.ReadInt32(i32), "ReadUint32() failed."); - SuccessOrQuit(decoder.ReadUint64(u64), "ReadUint64() failed."); - SuccessOrQuit(decoder.ReadInt64(i64), "ReadUint64() failed."); + SuccessOrQuit(decoder.ReadBool(b_1), "ReadBool() failed."); + SuccessOrQuit(decoder.ReadBool(b_2), "ReadBool() failed."); + SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); + SuccessOrQuit(decoder.ReadInt8(i8), "ReadUint8() failed."); + SuccessOrQuit(decoder.ReadUint16(u16), "ReadUint16() failed."); + SuccessOrQuit(decoder.ReadInt16(i16), "ReadInt16() failed."); + SuccessOrQuit(decoder.ReadUint32(u32), "ReadUint32() failed."); + SuccessOrQuit(decoder.ReadInt32(i32), "ReadUint32() failed."); + SuccessOrQuit(decoder.ReadUint64(u64), "ReadUint64() failed."); + SuccessOrQuit(decoder.ReadInt64(i64), "ReadUint64() failed."); // Check the state - VerifyOrQuit(decoder.GetReadLength() != 0, "GetReadLength() failed."); - VerifyOrQuit(decoder.GetRemainingLength() == frameLen - decoder.GetReadLength(), - "GetRemainingLength() failed."); - VerifyOrQuit(decoder.IsAllRead() == false, "IsAllRead() failed."); + VerifyOrQuit(decoder.GetReadLength() != 0, "GetReadLength() failed."); + VerifyOrQuit(decoder.GetRemainingLength() == frameLen - decoder.GetReadLength(), "GetRemainingLength() failed."); + VerifyOrQuit(decoder.IsAllRead() == false, "IsAllRead() failed."); - SuccessOrQuit(decoder.ReadUintPacked(u_1), "ReadUintPacked() failed."); + SuccessOrQuit(decoder.ReadUintPacked(u_1), "ReadUintPacked() failed."); - SuccessOrQuit(decoder.ReadUintPacked(u_2), "ReadUintPacked() failed."); - SuccessOrQuit(decoder.ReadUintPacked(u_3), "ReadUintPacked() failed."); - SuccessOrQuit(decoder.ReadUintPacked(u_4), "ReadUintPacked() failed."); - SuccessOrQuit(decoder.ReadIp6Address(ip6Addr), "ReadIp6Addr() failed."); - SuccessOrQuit(decoder.ReadEui48(eui48), "ReadEui48() failed."); - SuccessOrQuit(decoder.ReadEui64(eui64), "ReadEui64() failed."); - SuccessOrQuit(decoder.ReadUtf8(utf_1), "ReadUtf8() failed."); - SuccessOrQuit(decoder.ReadUtf8(utf_2), "ReadUtf8() failed."); - SuccessOrQuit(decoder.ReadDataWithLen(dataPtr_1, dataLen_1), "ReadDataWithLen() failed."); - SuccessOrQuit(decoder.ReadData(dataPtr_2, dataLen_2), "ReadData() failed."); + SuccessOrQuit(decoder.ReadUintPacked(u_2), "ReadUintPacked() failed."); + SuccessOrQuit(decoder.ReadUintPacked(u_3), "ReadUintPacked() failed."); + SuccessOrQuit(decoder.ReadUintPacked(u_4), "ReadUintPacked() failed."); + SuccessOrQuit(decoder.ReadIp6Address(ip6Addr), "ReadIp6Addr() failed."); + SuccessOrQuit(decoder.ReadEui48(eui48), "ReadEui48() failed."); + SuccessOrQuit(decoder.ReadEui64(eui64), "ReadEui64() failed."); + SuccessOrQuit(decoder.ReadUtf8(utf_1), "ReadUtf8() failed."); + SuccessOrQuit(decoder.ReadUtf8(utf_2), "ReadUtf8() failed."); + SuccessOrQuit(decoder.ReadDataWithLen(dataPtr_1, dataLen_1), "ReadDataWithLen() failed."); + SuccessOrQuit(decoder.ReadData(dataPtr_2, dataLen_2), "ReadData() failed."); - VerifyOrQuit(decoder.GetReadLength() == frameLen, "GetReadLength() failed."); - VerifyOrQuit(decoder.GetRemainingLength() == 0, "GetRemainingLength() failed."); - VerifyOrQuit(decoder.IsAllRead() == true, "IsAllRead() failed."); + VerifyOrQuit(decoder.GetReadLength() == frameLen, "GetReadLength() failed."); + VerifyOrQuit(decoder.GetRemainingLength() == 0, "GetRemainingLength() failed."); + VerifyOrQuit(decoder.IsAllRead() == true, "IsAllRead() failed."); - VerifyOrQuit(b_1 == kBool_1, "ReadBool() parse failed."); - VerifyOrQuit(b_2 == kBool_2, "ReadBool() parse failed."); - VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); - VerifyOrQuit(i8 == kInt8, "ReadUint8() parse failed."); - VerifyOrQuit(u16 == kUint16, "ReadUint16() parse failed."); - VerifyOrQuit(i16 == kInt16, "ReadInt16() parse failed."); - VerifyOrQuit(u32 == kUint32, "ReadUint32() parse failed."); - VerifyOrQuit(i32 == kInt32, "ReadInt32() parse failed."); - VerifyOrQuit(u64 == kUint64, "ReadUint64() parse failed."); - VerifyOrQuit(i64 == kInt64, "ReadInt64() parse failed."); - VerifyOrQuit(u_1 == kUint_1, "ReadUintPacked() parse failed."); - VerifyOrQuit(u_2 == kUint_2, "ReadUintPacked() parse failed."); - VerifyOrQuit(u_3 == kUint_3, "ReadUintPacked() parse failed."); - VerifyOrQuit(u_4 == kUint_4, "ReadUintPacked() parse failed."); - VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "ReadIp6Address() parse failed."); - VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "ReadEui48() parse failed."); - VerifyOrQuit(memcmp(eui64, &kEui64, sizeof(spinel_eui64_t)) == 0, "ReadEui64() parse failed."); - VerifyOrQuit(memcmp(utf_1, kString_1, sizeof(kString_1)) == 0, "ReadUtf8() parse failed."); - VerifyOrQuit(memcmp(utf_2, kString_2, sizeof(kString_2)) == 0, "ReadUtf8() parse failed."); - VerifyOrQuit(dataLen_1 == sizeof(kData), "ReadData() parse failed."); - VerifyOrQuit(memcmp(dataPtr_1, &kData, sizeof(kData)) == 0, "ReadData() parse failed."); - VerifyOrQuit(dataLen_2 == sizeof(kData), "ReadData() parse failed."); - VerifyOrQuit(memcmp(dataPtr_2, &kData, sizeof(kData)) == 0, "ReadData() parse failed."); + VerifyOrQuit(b_1 == kBool_1, "ReadBool() parse failed."); + VerifyOrQuit(b_2 == kBool_2, "ReadBool() parse failed."); + VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); + VerifyOrQuit(i8 == kInt8, "ReadUint8() parse failed."); + VerifyOrQuit(u16 == kUint16, "ReadUint16() parse failed."); + VerifyOrQuit(i16 == kInt16, "ReadInt16() parse failed."); + VerifyOrQuit(u32 == kUint32, "ReadUint32() parse failed."); + VerifyOrQuit(i32 == kInt32, "ReadInt32() parse failed."); + VerifyOrQuit(u64 == kUint64, "ReadUint64() parse failed."); + VerifyOrQuit(i64 == kInt64, "ReadInt64() parse failed."); + VerifyOrQuit(u_1 == kUint_1, "ReadUintPacked() parse failed."); + VerifyOrQuit(u_2 == kUint_2, "ReadUintPacked() parse failed."); + VerifyOrQuit(u_3 == kUint_3, "ReadUintPacked() parse failed."); + VerifyOrQuit(u_4 == kUint_4, "ReadUintPacked() parse failed."); + VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "ReadIp6Address() parse failed."); + VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "ReadEui48() parse failed."); + VerifyOrQuit(memcmp(eui64, &kEui64, sizeof(spinel_eui64_t)) == 0, "ReadEui64() parse failed."); + VerifyOrQuit(memcmp(utf_1, kString_1, sizeof(kString_1)) == 0, "ReadUtf8() parse failed."); + VerifyOrQuit(memcmp(utf_2, kString_2, sizeof(kString_2)) == 0, "ReadUtf8() parse failed."); + VerifyOrQuit(dataLen_1 == sizeof(kData), "ReadData() parse failed."); + VerifyOrQuit(memcmp(dataPtr_1, &kData, sizeof(kData)) == 0, "ReadData() parse failed."); + VerifyOrQuit(dataLen_2 == sizeof(kData), "ReadData() parse failed."); + VerifyOrQuit(memcmp(dataPtr_2, &kData, sizeof(kData)) == 0, "ReadData() parse failed."); printf(" -- PASS\n"); @@ -279,150 +235,138 @@ void TestSpinelDecoder(void) printf("\nTest 2: Test Reset(), SavePosition(), ResetToSaved()"); // `ResetToSaved()` should fail if there is no saved position - VerifyOrQuit(decoder.ResetToSaved() == OT_ERROR_INVALID_STATE, "ResetToSaved() did not fail"); + VerifyOrQuit(decoder.ResetToSaved() == OT_ERROR_INVALID_STATE, "ResetToSaved() did not fail"); decoder.Reset(); - VerifyOrQuit(decoder.GetFrame() == &buffer[0], "GetFrame() failed."); - VerifyOrQuit(decoder.GetLength() == frameLen, "GetLength() failed."); - VerifyOrQuit(decoder.GetReadLength() == 0, "GetReadLength() failed."); - VerifyOrQuit(decoder.GetRemainingLength() == frameLen, "GetRemainingLength() failed."); - VerifyOrQuit(decoder.IsAllRead() == false, "IsAllRead() failed."); + VerifyOrQuit(decoder.GetFrame() == &buffer[0], "GetFrame() failed."); + VerifyOrQuit(decoder.GetLength() == frameLen, "GetLength() failed."); + VerifyOrQuit(decoder.GetReadLength() == 0, "GetReadLength() failed."); + VerifyOrQuit(decoder.GetRemainingLength() == frameLen, "GetRemainingLength() failed."); + VerifyOrQuit(decoder.IsAllRead() == false, "IsAllRead() failed."); - SuccessOrQuit(decoder.ReadBool(b_1), "ReadBool() failed."); - SuccessOrQuit(decoder.ReadBool(b_2), "ReadBool() failed."); - SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); - SuccessOrQuit(decoder.ReadInt8(i8), "ReadUint8() failed."); - SuccessOrQuit(decoder.ReadUint16(u16), "ReadUint16() failed."); - SuccessOrQuit(decoder.ReadInt16(i16), "ReadInt16() failed."); - SuccessOrQuit(decoder.ReadUint32(u32), "ReadUint32() failed."); - SuccessOrQuit(decoder.ReadInt32(i32), "ReadUint32() failed."); + SuccessOrQuit(decoder.ReadBool(b_1), "ReadBool() failed."); + SuccessOrQuit(decoder.ReadBool(b_2), "ReadBool() failed."); + SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); + SuccessOrQuit(decoder.ReadInt8(i8), "ReadUint8() failed."); + SuccessOrQuit(decoder.ReadUint16(u16), "ReadUint16() failed."); + SuccessOrQuit(decoder.ReadInt16(i16), "ReadInt16() failed."); + SuccessOrQuit(decoder.ReadUint32(u32), "ReadUint32() failed."); + SuccessOrQuit(decoder.ReadInt32(i32), "ReadUint32() failed."); // `ResetToSaved()` should fail if there is no saved position - VerifyOrQuit(decoder.ResetToSaved() == OT_ERROR_INVALID_STATE, "ResetToSaved() did not fail"); + VerifyOrQuit(decoder.ResetToSaved() == OT_ERROR_INVALID_STATE, "ResetToSaved() did not fail"); // Save position decoder.SavePosition(); - SuccessOrQuit(decoder.ReadUint64(u64), "ReadUint64() failed."); - SuccessOrQuit(decoder.ReadInt64(i64), "ReadUint64() failed."); - SuccessOrQuit(decoder.ReadUintPacked(u_1), "ReadUintPacked() failed."); - SuccessOrQuit(decoder.ReadUintPacked(u_2), "ReadUintPacked() failed."); - SuccessOrQuit(decoder.ReadUintPacked(u_3), "ReadUintPacked() failed."); - SuccessOrQuit(decoder.ReadUintPacked(u_4), "ReadUintPacked() failed."); - SuccessOrQuit(decoder.ReadIp6Address(ip6Addr), "ReadIp6Addr() failed."); + SuccessOrQuit(decoder.ReadUint64(u64), "ReadUint64() failed."); + SuccessOrQuit(decoder.ReadInt64(i64), "ReadUint64() failed."); + SuccessOrQuit(decoder.ReadUintPacked(u_1), "ReadUintPacked() failed."); + SuccessOrQuit(decoder.ReadUintPacked(u_2), "ReadUintPacked() failed."); + SuccessOrQuit(decoder.ReadUintPacked(u_3), "ReadUintPacked() failed."); + SuccessOrQuit(decoder.ReadUintPacked(u_4), "ReadUintPacked() failed."); + SuccessOrQuit(decoder.ReadIp6Address(ip6Addr), "ReadIp6Addr() failed."); - VerifyOrQuit(b_1 == kBool_1, "ReadBool() parse failed."); - VerifyOrQuit(b_2 == kBool_2, "ReadBool() parse failed."); - VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); - VerifyOrQuit(i8 == kInt8, "ReadUint8() parse failed."); - VerifyOrQuit(u16 == kUint16, "ReadUint16() parse failed."); - VerifyOrQuit(i16 == kInt16, "ReadInt16() parse failed."); - VerifyOrQuit(u32 == kUint32, "ReadUint32() parse failed."); - VerifyOrQuit(i32 == kInt32, "ReadUint32() parse failed."); - VerifyOrQuit(u64 == kUint64, "ReadUint64() parse failed."); - VerifyOrQuit(i64 == kInt64, "ReadInt64() parse failed."); - VerifyOrQuit(u_1 == kUint_1, "ReadUintPacked() parse failed."); - VerifyOrQuit(u_2 == kUint_2, "ReadUintPacked() parse failed."); - VerifyOrQuit(u_3 == kUint_3, "ReadUintPacked() parse failed."); - VerifyOrQuit(u_4 == kUint_4, "ReadUintPacked() parse failed."); - VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "ReadIp6Address() parse failed."); + VerifyOrQuit(b_1 == kBool_1, "ReadBool() parse failed."); + VerifyOrQuit(b_2 == kBool_2, "ReadBool() parse failed."); + VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); + VerifyOrQuit(i8 == kInt8, "ReadUint8() parse failed."); + VerifyOrQuit(u16 == kUint16, "ReadUint16() parse failed."); + VerifyOrQuit(i16 == kInt16, "ReadInt16() parse failed."); + VerifyOrQuit(u32 == kUint32, "ReadUint32() parse failed."); + VerifyOrQuit(i32 == kInt32, "ReadUint32() parse failed."); + VerifyOrQuit(u64 == kUint64, "ReadUint64() parse failed."); + VerifyOrQuit(i64 == kInt64, "ReadInt64() parse failed."); + VerifyOrQuit(u_1 == kUint_1, "ReadUintPacked() parse failed."); + VerifyOrQuit(u_2 == kUint_2, "ReadUintPacked() parse failed."); + VerifyOrQuit(u_3 == kUint_3, "ReadUintPacked() parse failed."); + VerifyOrQuit(u_4 == kUint_4, "ReadUintPacked() parse failed."); + VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "ReadIp6Address() parse failed."); - SuccessOrQuit(decoder.ResetToSaved(), "ResetToSaved() failed"); + SuccessOrQuit(decoder.ResetToSaved(), "ResetToSaved() failed"); - SuccessOrQuit(decoder.ReadUint64(u64), "ReadUint64() failed."); - SuccessOrQuit(decoder.ReadInt64(i64), "ReadUint64() failed."); - SuccessOrQuit(decoder.ReadUintPacked(u_1), "ReadUintPacked() failed."); - SuccessOrQuit(decoder.ReadUintPacked(u_2), "ReadUintPacked() failed."); - SuccessOrQuit(decoder.ReadUintPacked(u_3), "ReadUintPacked() failed."); - SuccessOrQuit(decoder.ReadUintPacked(u_4), "ReadUintPacked() failed."); - SuccessOrQuit(decoder.ReadIp6Address(ip6Addr), "ReadIp6Addr() failed."); + SuccessOrQuit(decoder.ReadUint64(u64), "ReadUint64() failed."); + SuccessOrQuit(decoder.ReadInt64(i64), "ReadUint64() failed."); + SuccessOrQuit(decoder.ReadUintPacked(u_1), "ReadUintPacked() failed."); + SuccessOrQuit(decoder.ReadUintPacked(u_2), "ReadUintPacked() failed."); + SuccessOrQuit(decoder.ReadUintPacked(u_3), "ReadUintPacked() failed."); + SuccessOrQuit(decoder.ReadUintPacked(u_4), "ReadUintPacked() failed."); + SuccessOrQuit(decoder.ReadIp6Address(ip6Addr), "ReadIp6Addr() failed."); - VerifyOrQuit(u64 == kUint64, "ReadUint64() parse failed."); - VerifyOrQuit(i64 == kInt64, "ReadInt64() parse failed."); - VerifyOrQuit(u_1 == kUint_1, "ReadUintPacked() parse failed."); - VerifyOrQuit(u_2 == kUint_2, "ReadUintPacked() parse failed."); - VerifyOrQuit(u_3 == kUint_3, "ReadUintPacked() parse failed."); - VerifyOrQuit(u_4 == kUint_4, "ReadUintPacked() parse failed."); - VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "ReadIp6Address() parse failed."); + VerifyOrQuit(u64 == kUint64, "ReadUint64() parse failed."); + VerifyOrQuit(i64 == kInt64, "ReadInt64() parse failed."); + VerifyOrQuit(u_1 == kUint_1, "ReadUintPacked() parse failed."); + VerifyOrQuit(u_2 == kUint_2, "ReadUintPacked() parse failed."); + VerifyOrQuit(u_3 == kUint_3, "ReadUintPacked() parse failed."); + VerifyOrQuit(u_4 == kUint_4, "ReadUintPacked() parse failed."); + VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "ReadIp6Address() parse failed."); // Go back to save position again. - SuccessOrQuit(decoder.ResetToSaved(), "ResetToSaved() failed"); + SuccessOrQuit(decoder.ResetToSaved(), "ResetToSaved() failed"); - SuccessOrQuit(decoder.ReadUint64(u64), "ReadUint64() failed."); - SuccessOrQuit(decoder.ReadInt64(i64), "ReadUint64() failed."); - SuccessOrQuit(decoder.ReadUintPacked(u_1), "ReadUintPacked() failed."); - SuccessOrQuit(decoder.ReadUintPacked(u_2), "ReadUintPacked() failed."); - SuccessOrQuit(decoder.ReadUintPacked(u_3), "ReadUintPacked() failed."); - SuccessOrQuit(decoder.ReadUintPacked(u_4), "ReadUintPacked() failed."); - SuccessOrQuit(decoder.ReadIp6Address(ip6Addr), "ReadIp6Addr() failed."); + SuccessOrQuit(decoder.ReadUint64(u64), "ReadUint64() failed."); + SuccessOrQuit(decoder.ReadInt64(i64), "ReadUint64() failed."); + SuccessOrQuit(decoder.ReadUintPacked(u_1), "ReadUintPacked() failed."); + SuccessOrQuit(decoder.ReadUintPacked(u_2), "ReadUintPacked() failed."); + SuccessOrQuit(decoder.ReadUintPacked(u_3), "ReadUintPacked() failed."); + SuccessOrQuit(decoder.ReadUintPacked(u_4), "ReadUintPacked() failed."); + SuccessOrQuit(decoder.ReadIp6Address(ip6Addr), "ReadIp6Addr() failed."); - VerifyOrQuit(u64 == kUint64, "ReadUint64() parse failed."); - VerifyOrQuit(i64 == kInt64, "ReadInt64() parse failed."); - VerifyOrQuit(u_1 == kUint_1, "ReadUintPacked() parse failed."); - VerifyOrQuit(u_2 == kUint_2, "ReadUintPacked() parse failed."); - VerifyOrQuit(u_3 == kUint_3, "ReadUintPacked() parse failed."); - VerifyOrQuit(u_4 == kUint_4, "ReadUintPacked() parse failed."); - VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "ReadIp6Address() parse failed."); + VerifyOrQuit(u64 == kUint64, "ReadUint64() parse failed."); + VerifyOrQuit(i64 == kInt64, "ReadInt64() parse failed."); + VerifyOrQuit(u_1 == kUint_1, "ReadUintPacked() parse failed."); + VerifyOrQuit(u_2 == kUint_2, "ReadUintPacked() parse failed."); + VerifyOrQuit(u_3 == kUint_3, "ReadUintPacked() parse failed."); + VerifyOrQuit(u_4 == kUint_4, "ReadUintPacked() parse failed."); + VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "ReadIp6Address() parse failed."); // Ensure saved position is cleared when decoder is reset or re-initialized. decoder.Reset(); // `ResetToSaved()` should fail if there is no saved position - VerifyOrQuit(decoder.ResetToSaved() == OT_ERROR_INVALID_STATE, "ResetToSaved() did not fail"); + VerifyOrQuit(decoder.ResetToSaved() == OT_ERROR_INVALID_STATE, "ResetToSaved() did not fail"); decoder.SavePosition(); - SuccessOrQuit(decoder.ResetToSaved(), "ResetToSaved() failed"); + SuccessOrQuit(decoder.ResetToSaved(), "ResetToSaved() failed"); decoder.Init(buffer, static_cast(frameLen)); - VerifyOrQuit(decoder.ResetToSaved() == OT_ERROR_INVALID_STATE, "ResetToSaved() did not fail"); + VerifyOrQuit(decoder.ResetToSaved() == OT_ERROR_INVALID_STATE, "ResetToSaved() did not fail"); printf(" -- PASS\n"); printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"); printf("\nTest 3: Test decoding a single simple struct."); - frameLen = spinel_datatype_pack( - buffer, - sizeof(buffer), - ( - SPINEL_DATATYPE_UINT8_S - SPINEL_DATATYPE_STRUCT_S( - SPINEL_DATATYPE_UINT32_S - SPINEL_DATATYPE_EUI48_S - SPINEL_DATATYPE_UINT_PACKED_S - ) - SPINEL_DATATYPE_INT16_S + frameLen = spinel_datatype_pack(buffer, sizeof(buffer), + (SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_STRUCT_S( + SPINEL_DATATYPE_UINT32_S SPINEL_DATATYPE_EUI48_S SPINEL_DATATYPE_UINT_PACKED_S) + SPINEL_DATATYPE_INT16_S - ), - kUint8, - kUint32, - &kEui48, - kUint_3, - kInt16 - ); + ), + kUint8, kUint32, &kEui48, kUint_3, kInt16); DumpBuffer("Packed Spinel Frame (single struct)", buffer, static_cast(frameLen)); decoder.Init(buffer, static_cast(frameLen)); - SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); - SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); + SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(decoder.ReadUint32(u32), "ReadUint32() failed."); - SuccessOrQuit(decoder.ReadEui48(eui48), "ReadEui48() failed."); - SuccessOrQuit(decoder.ReadUintPacked(u_3), "ReadUintPacked() failed."); + SuccessOrQuit(decoder.ReadUint32(u32), "ReadUint32() failed."); + SuccessOrQuit(decoder.ReadEui48(eui48), "ReadEui48() failed."); + SuccessOrQuit(decoder.ReadUintPacked(u_3), "ReadUintPacked() failed."); } - SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); - SuccessOrQuit(decoder.ReadInt16(i16), "ReadInt16() failed."); - VerifyOrQuit(decoder.IsAllRead() == true, "IsAllRead() failed."); + SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); + SuccessOrQuit(decoder.ReadInt16(i16), "ReadInt16() failed."); + VerifyOrQuit(decoder.IsAllRead() == true, "IsAllRead() failed."); - VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); - VerifyOrQuit(i16 == kInt16, "ReadInt16() parse failed."); - VerifyOrQuit(u32 == kUint32, "ReadUint32() parse failed."); - VerifyOrQuit(u_3 == kUint_3, "ReadUintPacked() parse failed."); - VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "ReadEui48() parse failed."); + VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); + VerifyOrQuit(i16 == kInt16, "ReadInt16() parse failed."); + VerifyOrQuit(u32 == kUint32, "ReadUint32() parse failed."); + VerifyOrQuit(u_3 == kUint_3, "ReadUintPacked() parse failed."); + VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "ReadEui48() parse failed."); printf(" -- PASS\n"); @@ -433,21 +377,20 @@ void TestSpinelDecoder(void) decoder.Init(buffer, static_cast(frameLen)); - SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); - SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); + SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(decoder.ReadUint32(u32), "ReadUint32() failed."); + SuccessOrQuit(decoder.ReadUint32(u32), "ReadUint32() failed."); // Skip the remaining fields in the struct } - SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); - SuccessOrQuit(decoder.ReadInt16(i16), "ReadInt16() failed."); + SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); + SuccessOrQuit(decoder.ReadInt16(i16), "ReadInt16() failed."); - VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); - VerifyOrQuit(i16 == kInt16, "ReadInt16() parse failed."); + VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); + VerifyOrQuit(i16 == kInt16, "ReadInt16() parse failed."); printf(" -- PASS\n"); - printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"); printf("\nTest 5: Test `GetRemainingLengthInStruct()` and `IsAllReadInStruct`() in and out of an struct"); @@ -455,55 +398,54 @@ void TestSpinelDecoder(void) decoder.Init(buffer, static_cast(frameLen)); - VerifyOrQuit(decoder.GetFrame() == &buffer[0], "GetFrame() failed."); - VerifyOrQuit(decoder.GetLength() == frameLen, "GetLength() failed."); + VerifyOrQuit(decoder.GetFrame() == &buffer[0], "GetFrame() failed."); + VerifyOrQuit(decoder.GetLength() == frameLen, "GetLength() failed."); - VerifyOrQuit(decoder.GetReadLength() == 0, "GetReadLength() failed."); - VerifyOrQuit(decoder.GetRemainingLength() == frameLen, "GetRemainingLength() failed."); - VerifyOrQuit(decoder.IsAllRead() == false, "IsAllRead() failed."); + VerifyOrQuit(decoder.GetReadLength() == 0, "GetReadLength() failed."); + VerifyOrQuit(decoder.GetRemainingLength() == frameLen, "GetRemainingLength() failed."); + VerifyOrQuit(decoder.IsAllRead() == false, "IsAllRead() failed."); // When not in an struct, `etRemainingLengthInStruct()` should consider the whole frame. - VerifyOrQuit(decoder.GetRemainingLengthInStruct() == frameLen, "GetRemLengthInStruct() failed."); - VerifyOrQuit(decoder.IsAllReadInStruct() == false, "IsAllReadInStruct() failed."); + VerifyOrQuit(decoder.GetRemainingLengthInStruct() == frameLen, "GetRemLengthInStruct() failed."); + VerifyOrQuit(decoder.IsAllReadInStruct() == false, "IsAllReadInStruct() failed."); - SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); - SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); + SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); { - VerifyOrQuit(decoder.IsAllReadInStruct() == false, "IsAllReadInStruct() failed."); + VerifyOrQuit(decoder.IsAllReadInStruct() == false, "IsAllReadInStruct() failed."); - SuccessOrQuit(decoder.ReadUint32(u32), "ReadUint32() failed."); - SuccessOrQuit(decoder.ReadEui48(eui48), "ReadEui48() failed."); - SuccessOrQuit(decoder.ReadUintPacked(u_3), "ReadUintPacked() failed."); + SuccessOrQuit(decoder.ReadUint32(u32), "ReadUint32() failed."); + SuccessOrQuit(decoder.ReadEui48(eui48), "ReadEui48() failed."); + SuccessOrQuit(decoder.ReadUintPacked(u_3), "ReadUintPacked() failed."); - VerifyOrQuit(decoder.IsAllReadInStruct() == true, "IsAllReadInStruct() failed."); - VerifyOrQuit(decoder.GetRemainingLengthInStruct() == 0, "GetRemLengthInStruct() failed."); + VerifyOrQuit(decoder.IsAllReadInStruct() == true, "IsAllReadInStruct() failed."); + VerifyOrQuit(decoder.GetRemainingLengthInStruct() == 0, "GetRemLengthInStruct() failed."); // Try reading beyond end of the struct and ensure it fails. - VerifyOrQuit(decoder.ReadUint8(u8) == OT_ERROR_PARSE, "ReadUint8() did not fail."); + VerifyOrQuit(decoder.ReadUint8(u8) == OT_ERROR_PARSE, "ReadUint8() did not fail."); // `ReadData()` at end of struct should still succeed but return zero as the data length. - SuccessOrQuit(decoder.ReadData(dataPtr_1, dataLen_1), "ReadData() failed."); - VerifyOrQuit(dataLen_1 == 0, "ReadData() parse value failed."); - + SuccessOrQuit(decoder.ReadData(dataPtr_1, dataLen_1), "ReadData() failed."); + VerifyOrQuit(dataLen_1 == 0, "ReadData() parse value failed."); } - SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); + SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); - VerifyOrQuit(decoder.IsAllReadInStruct() == false, "IsAllReadInStruct() failed."); - SuccessOrQuit(decoder.ReadInt16(i16), "ReadInt16() failed."); - VerifyOrQuit(decoder.IsAllRead() == true, "IsAllRead() failed."); + VerifyOrQuit(decoder.IsAllReadInStruct() == false, "IsAllReadInStruct() failed."); + SuccessOrQuit(decoder.ReadInt16(i16), "ReadInt16() failed."); + VerifyOrQuit(decoder.IsAllRead() == true, "IsAllRead() failed."); - VerifyOrQuit(decoder.GetRemainingLengthInStruct() == 0, "GetRemLengthInStruct() failed."); - VerifyOrQuit(decoder.IsAllReadInStruct() == true, "IsAllReadInStruct() failed."); + VerifyOrQuit(decoder.GetRemainingLengthInStruct() == 0, "GetRemLengthInStruct() failed."); + VerifyOrQuit(decoder.IsAllReadInStruct() == true, "IsAllReadInStruct() failed."); // `ReadData()` at end of frame should still succeed but return zero as the data length. - SuccessOrQuit(decoder.ReadData(dataPtr_1, dataLen_1), "ReadData() failed."); - VerifyOrQuit(dataLen_1 == 0, "ReadData() parse value failed."); + SuccessOrQuit(decoder.ReadData(dataPtr_1, dataLen_1), "ReadData() failed."); + VerifyOrQuit(dataLen_1 == 0, "ReadData() parse value failed."); - VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); - VerifyOrQuit(i16 == kInt16, "ReadInt16() parse failed."); - VerifyOrQuit(u32 == kUint32, "ReadUint32() parse failed."); - VerifyOrQuit(u_3 == kUint_3, "ReadUintPacked() parse failed."); - VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "ReadEui48() parse failed."); + VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); + VerifyOrQuit(i16 == kInt16, "ReadInt16() parse failed."); + VerifyOrQuit(u32 == kUint32, "ReadUint32() parse failed."); + VerifyOrQuit(u_3 == kUint_3, "ReadUintPacked() parse failed."); + VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "ReadEui48() parse failed."); printf(" -- PASS\n"); @@ -511,72 +453,49 @@ void TestSpinelDecoder(void) printf("\nTest 6: Test multiple nested structs"); frameLen = spinel_datatype_pack( - buffer, - sizeof(buffer), - ( - SPINEL_DATATYPE_STRUCT_S( - SPINEL_DATATYPE_UINT8_S - SPINEL_DATATYPE_UTF8_S - SPINEL_DATATYPE_STRUCT_S( - SPINEL_DATATYPE_BOOL_S - SPINEL_DATATYPE_IPv6ADDR_S - ) - SPINEL_DATATYPE_UINT16_S - ) - SPINEL_DATATYPE_EUI48_S - SPINEL_DATATYPE_STRUCT_S( - SPINEL_DATATYPE_UINT32_S - ) - SPINEL_DATATYPE_INT32_S - ), - kUint8, - kString_1, - kBool_1, - &kIp6Addr, - kUint16, - &kEui48, - kUint32, - kInt32 - ); + buffer, sizeof(buffer), + (SPINEL_DATATYPE_STRUCT_S(SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_UTF8_S SPINEL_DATATYPE_STRUCT_S( + SPINEL_DATATYPE_BOOL_S SPINEL_DATATYPE_IPv6ADDR_S) SPINEL_DATATYPE_UINT16_S) + SPINEL_DATATYPE_EUI48_S SPINEL_DATATYPE_STRUCT_S(SPINEL_DATATYPE_UINT32_S) SPINEL_DATATYPE_INT32_S), + kUint8, kString_1, kBool_1, &kIp6Addr, kUint16, &kEui48, kUint32, kInt32); DumpBuffer("Packed Spinel Frame (multiple struct)", buffer, static_cast(frameLen)); decoder.Init(buffer, static_cast(frameLen)); - SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); - SuccessOrQuit(decoder.ReadUtf8(utf_1), "ReadUtf8() failed."); - SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); + SuccessOrQuit(decoder.ReadUtf8(utf_1), "ReadUtf8() failed."); + SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(decoder.ReadBool(b_1), "ReadBool() failed."); - SuccessOrQuit(decoder.ReadIp6Address(ip6Addr), "ReadIp6Addr() failed."); - + SuccessOrQuit(decoder.ReadBool(b_1), "ReadBool() failed."); + SuccessOrQuit(decoder.ReadIp6Address(ip6Addr), "ReadIp6Addr() failed."); } - SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); - SuccessOrQuit(decoder.ReadUint16(u16), "ReadUint16() failed."); + SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); + SuccessOrQuit(decoder.ReadUint16(u16), "ReadUint16() failed."); } - SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); - SuccessOrQuit(decoder.ReadEui48(eui48), "ReadEui48() failed."); - SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); + SuccessOrQuit(decoder.ReadEui48(eui48), "ReadEui48() failed."); + SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(decoder.ReadUint32(u32), "ReadUint32() failed."); + SuccessOrQuit(decoder.ReadUint32(u32), "ReadUint32() failed."); } - SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); - SuccessOrQuit(decoder.ReadInt32(i32), "WriteUint32() failed."); + SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); + SuccessOrQuit(decoder.ReadInt32(i32), "WriteUint32() failed."); - VerifyOrQuit(decoder.GetReadLength() == frameLen, "GetReadLength() failed."); - VerifyOrQuit(decoder.GetRemainingLength() == 0, "GetRemainingLength() failed."); - VerifyOrQuit(decoder.IsAllRead() == true, "IsAllRead() failed."); + VerifyOrQuit(decoder.GetReadLength() == frameLen, "GetReadLength() failed."); + VerifyOrQuit(decoder.GetRemainingLength() == 0, "GetRemainingLength() failed."); + VerifyOrQuit(decoder.IsAllRead() == true, "IsAllRead() failed."); - VerifyOrQuit(b_1 == kBool_1, "ReadBool() parse failed."); - VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); - VerifyOrQuit(u16 == kUint16, "ReadUint16() parse failed."); - VerifyOrQuit(u32 == kUint32, "ReadUint32() parse failed."); - VerifyOrQuit(i32 == kInt32, "ReadUint32() parse failed."); - VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "ReadIp6Address() parse failed."); - VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "ReadEui48() parse failed."); - VerifyOrQuit(memcmp(utf_1, kString_1, sizeof(kString_1)) == 0, "ReadUtf8() parse failed."); + VerifyOrQuit(b_1 == kBool_1, "ReadBool() parse failed."); + VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); + VerifyOrQuit(u16 == kUint16, "ReadUint16() parse failed."); + VerifyOrQuit(u32 == kUint32, "ReadUint32() parse failed."); + VerifyOrQuit(i32 == kInt32, "ReadUint32() parse failed."); + VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "ReadIp6Address() parse failed."); + VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "ReadEui48() parse failed."); + VerifyOrQuit(memcmp(utf_1, kString_1, sizeof(kString_1)) == 0, "ReadUtf8() parse failed."); printf(" -- PASS\n"); @@ -587,59 +506,58 @@ void TestSpinelDecoder(void) decoder.Init(buffer, static_cast(frameLen)); - SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); + SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); decoder.SavePosition(); - SuccessOrQuit(decoder.ReadUtf8(utf_1), "ReadUtf8() failed."); - SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(decoder.ReadUtf8(utf_1), "ReadUtf8() failed."); + SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(decoder.ReadBool(b_1), "ReadBool() failed."); + SuccessOrQuit(decoder.ReadBool(b_1), "ReadBool() failed."); } // Verify the read content so far. - VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); - VerifyOrQuit(b_1 == kBool_1, "ReadBool() parse failed."); - VerifyOrQuit(memcmp(utf_1, kString_1, sizeof(kString_1)) == 0, "ReadUtf8() parse failed."); + VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); + VerifyOrQuit(b_1 == kBool_1, "ReadBool() parse failed."); + VerifyOrQuit(memcmp(utf_1, kString_1, sizeof(kString_1)) == 0, "ReadUtf8() parse failed."); // Do not close the inner struct and jump to previously saved position and re-read the content. - SuccessOrQuit(decoder.ResetToSaved(), "ResetToSaved() failed."); + SuccessOrQuit(decoder.ResetToSaved(), "ResetToSaved() failed."); - SuccessOrQuit(decoder.ReadUtf8(utf_1), "ReadUtf8() failed."); - SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(decoder.ReadUtf8(utf_1), "ReadUtf8() failed."); + SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(decoder.ReadBool(b_1), "ReadBool() failed."); - SuccessOrQuit(decoder.ReadIp6Address(ip6Addr), "ReadIp6Addr() failed."); - + SuccessOrQuit(decoder.ReadBool(b_1), "ReadBool() failed."); + SuccessOrQuit(decoder.ReadIp6Address(ip6Addr), "ReadIp6Addr() failed."); } - SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); - SuccessOrQuit(decoder.ReadUint16(u16), "ReadUint16() failed."); + SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); + SuccessOrQuit(decoder.ReadUint16(u16), "ReadUint16() failed."); } - SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); - SuccessOrQuit(decoder.ReadEui48(eui48), "ReadEui48() failed."); - SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); + SuccessOrQuit(decoder.ReadEui48(eui48), "ReadEui48() failed."); + SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(decoder.ReadUint32(u32), "ReadUint32() failed."); + SuccessOrQuit(decoder.ReadUint32(u32), "ReadUint32() failed."); } - SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); - SuccessOrQuit(decoder.ReadInt32(i32), "WriteUint32() failed."); + SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); + SuccessOrQuit(decoder.ReadInt32(i32), "WriteUint32() failed."); - VerifyOrQuit(decoder.GetReadLength() == frameLen, "GetReadLength() failed."); - VerifyOrQuit(decoder.GetRemainingLength() == 0, "GetRemainingLength() failed."); - VerifyOrQuit(decoder.IsAllRead() == true, "IsAllRead() failed."); + VerifyOrQuit(decoder.GetReadLength() == frameLen, "GetReadLength() failed."); + VerifyOrQuit(decoder.GetRemainingLength() == 0, "GetRemainingLength() failed."); + VerifyOrQuit(decoder.IsAllRead() == true, "IsAllRead() failed."); - VerifyOrQuit(b_1 == kBool_1, "ReadBool() parse failed."); - VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); - VerifyOrQuit(u16 == kUint16, "ReadUint16() parse failed."); - VerifyOrQuit(u32 == kUint32, "ReadUint32() parse failed."); - VerifyOrQuit(i32 == kInt32, "ReadUint32() parse failed."); - VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "ReadIp6Address() parse failed."); - VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "ReadEui48() parse failed."); - VerifyOrQuit(memcmp(utf_1, kString_1, sizeof(kString_1)) == 0, "ReadUtf8() parse failed."); + VerifyOrQuit(b_1 == kBool_1, "ReadBool() parse failed."); + VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); + VerifyOrQuit(u16 == kUint16, "ReadUint16() parse failed."); + VerifyOrQuit(u32 == kUint32, "ReadUint32() parse failed."); + VerifyOrQuit(i32 == kInt32, "ReadUint32() parse failed."); + VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "ReadIp6Address() parse failed."); + VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "ReadEui48() parse failed."); + VerifyOrQuit(memcmp(utf_1, kString_1, sizeof(kString_1)) == 0, "ReadUtf8() parse failed."); printf(" -- PASS\n"); @@ -650,53 +568,52 @@ void TestSpinelDecoder(void) decoder.Init(buffer, static_cast(frameLen)); - SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); - SuccessOrQuit(decoder.ReadUtf8(utf_1), "ReadUtf8() failed."); - SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); + SuccessOrQuit(decoder.ReadUtf8(utf_1), "ReadUtf8() failed."); + SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); { // Save position at start of the struct decoder.SavePosition(); - SuccessOrQuit(decoder.ReadBool(b_1), "ReadBool() failed."); + SuccessOrQuit(decoder.ReadBool(b_1), "ReadBool() failed."); // Verify the read content so far. - VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); - VerifyOrQuit(memcmp(utf_1, kString_1, sizeof(kString_1)) == 0, "ReadUtf8() parse failed."); - VerifyOrQuit(b_1 == kBool_1, "ReadBool() parse failed."); + VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); + VerifyOrQuit(memcmp(utf_1, kString_1, sizeof(kString_1)) == 0, "ReadUtf8() parse failed."); + VerifyOrQuit(b_1 == kBool_1, "ReadBool() parse failed."); // Do not close the struct and jump to the previously saved position and re-read the content. - SuccessOrQuit(decoder.ResetToSaved(), "ResetToSaved() failed."); - SuccessOrQuit(decoder.ReadBool(b_1), "ReadBool() failed."); - SuccessOrQuit(decoder.ReadIp6Address(ip6Addr), "ReadIp6Addr() failed."); - + SuccessOrQuit(decoder.ResetToSaved(), "ResetToSaved() failed."); + SuccessOrQuit(decoder.ReadBool(b_1), "ReadBool() failed."); + SuccessOrQuit(decoder.ReadIp6Address(ip6Addr), "ReadIp6Addr() failed."); } - SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); - SuccessOrQuit(decoder.ReadUint16(u16), "ReadUint16() failed."); + SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); + SuccessOrQuit(decoder.ReadUint16(u16), "ReadUint16() failed."); } - SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); - SuccessOrQuit(decoder.ReadEui48(eui48), "ReadEui48() failed."); - SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); + SuccessOrQuit(decoder.ReadEui48(eui48), "ReadEui48() failed."); + SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(decoder.ReadUint32(u32), "ReadUint32() failed."); + SuccessOrQuit(decoder.ReadUint32(u32), "ReadUint32() failed."); } - SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); - SuccessOrQuit(decoder.ReadInt32(i32), "WriteUint32() failed."); + SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); + SuccessOrQuit(decoder.ReadInt32(i32), "WriteUint32() failed."); - VerifyOrQuit(decoder.GetReadLength() == frameLen, "GetReadLength() failed."); - VerifyOrQuit(decoder.GetRemainingLength() == 0, "GetRemainingLength() failed."); - VerifyOrQuit(decoder.IsAllRead() == true, "IsAllRead() failed."); + VerifyOrQuit(decoder.GetReadLength() == frameLen, "GetReadLength() failed."); + VerifyOrQuit(decoder.GetRemainingLength() == 0, "GetRemainingLength() failed."); + VerifyOrQuit(decoder.IsAllRead() == true, "IsAllRead() failed."); - VerifyOrQuit(b_1 == kBool_1, "ReadBool() parse failed."); - VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); - VerifyOrQuit(u16 == kUint16, "ReadUint16() parse failed."); - VerifyOrQuit(u32 == kUint32, "ReadUint32() parse failed."); - VerifyOrQuit(i32 == kInt32, "ReadUint32() parse failed."); - VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "ReadIp6Address() parse failed."); - VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "ReadEui48() parse failed."); - VerifyOrQuit(memcmp(utf_1, kString_1, sizeof(kString_1)) == 0, "ReadUtf8() parse failed."); + VerifyOrQuit(b_1 == kBool_1, "ReadBool() parse failed."); + VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); + VerifyOrQuit(u16 == kUint16, "ReadUint16() parse failed."); + VerifyOrQuit(u32 == kUint32, "ReadUint32() parse failed."); + VerifyOrQuit(i32 == kInt32, "ReadUint32() parse failed."); + VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "ReadIp6Address() parse failed."); + VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "ReadEui48() parse failed."); + VerifyOrQuit(memcmp(utf_1, kString_1, sizeof(kString_1)) == 0, "ReadUtf8() parse failed."); printf(" -- PASS\n"); @@ -707,24 +624,23 @@ void TestSpinelDecoder(void) decoder.Init(buffer, static_cast(frameLen)); - SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); - SuccessOrQuit(decoder.ReadUtf8(utf_1), "ReadUtf8() failed."); - SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); + SuccessOrQuit(decoder.ReadUtf8(utf_1), "ReadUtf8() failed."); + SuccessOrQuit(decoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(decoder.ReadBool(b_1), "ReadBool() failed."); + SuccessOrQuit(decoder.ReadBool(b_1), "ReadBool() failed."); decoder.SavePosition(); - SuccessOrQuit(decoder.ReadIp6Address(ip6Addr), "ReadIp6Addr() failed."); - + SuccessOrQuit(decoder.ReadIp6Address(ip6Addr), "ReadIp6Addr() failed."); } - SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); - SuccessOrQuit(decoder.ReadUint16(u16), "ReadUint16() failed."); + SuccessOrQuit(decoder.CloseStruct(), "CloseStruct() failed."); + SuccessOrQuit(decoder.ReadUint16(u16), "ReadUint16() failed."); // `ResetToSaved()` should fail sicne the enclosing struct for the saved position is closed. - VerifyOrQuit(decoder.ResetToSaved() == OT_ERROR_INVALID_STATE, "ResetToSaved() did not fail."); + VerifyOrQuit(decoder.ResetToSaved() == OT_ERROR_INVALID_STATE, "ResetToSaved() did not fail."); } printf(" -- PASS\n"); @@ -732,18 +648,10 @@ void TestSpinelDecoder(void) printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"); printf("\nTest 10: Testing error cases and failures. (e.g., wrong struct length)."); - frameLen = spinel_datatype_pack( - buffer, - sizeof(buffer), - ( - SPINEL_DATATYPE_UINT8_S - SPINEL_DATATYPE_UINT16_S // Treat this as struct length - SPINEL_DATATYPE_BOOL_S - ), - kUint8, - 10, - kBool_1 - ); + frameLen = spinel_datatype_pack(buffer, sizeof(buffer), + (SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_UINT16_S // Treat this as struct length + SPINEL_DATATYPE_BOOL_S), + kUint8, 10, kBool_1); DumpBuffer("Packed Spinel Frame (incorrect format)", buffer, static_cast(frameLen)); @@ -751,33 +659,32 @@ void TestSpinelDecoder(void) decoder.SavePosition(); - SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); - VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); + SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); + VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); // `OpenStruct()` should fail, since it expects a length 10 but there are not enough // bytes in the frame. - VerifyOrQuit(decoder.OpenStruct() == OT_ERROR_PARSE, "OpenStruct() did not fail."); + VerifyOrQuit(decoder.OpenStruct() == OT_ERROR_PARSE, "OpenStruct() did not fail."); decoder.ResetToSaved(); - SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); - VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); - VerifyOrQuit(decoder.ReadDataWithLen(dataPtr_1, dataLen_1) == OT_ERROR_PARSE, - "ReadDataWithLen() did not fail."); + SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); + VerifyOrQuit(u8 == kUint8, "ReadUint8() parse failed."); + VerifyOrQuit(decoder.ReadDataWithLen(dataPtr_1, dataLen_1) == OT_ERROR_PARSE, "ReadDataWithLen() did not fail."); decoder.ResetToSaved(); - SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); - SuccessOrQuit(decoder.ReadUint16(u16), "ReadUint16() failed."); - SuccessOrQuit(decoder.ReadBool(b_1), "ReadUint16() failed."); + SuccessOrQuit(decoder.ReadUint8(u8), "ReadUint8() failed."); + SuccessOrQuit(decoder.ReadUint16(u16), "ReadUint16() failed."); + SuccessOrQuit(decoder.ReadBool(b_1), "ReadUint16() failed."); // Try reading beyond end of frame. - VerifyOrQuit(decoder.ReadUint8(u8) == OT_ERROR_PARSE, "ReadUint8() did not fail"); + VerifyOrQuit(decoder.ReadUint8(u8) == OT_ERROR_PARSE, "ReadUint8() did not fail"); printf(" -- PASS\n"); } -} // namespace Ncp -} // namespace ot +} // namespace Ncp +} // namespace ot #ifdef ENABLE_TEST_MAIN int main(void) diff --git a/tests/unit/test_spinel_encoder.cpp b/tests/unit/test_spinel_encoder.cpp index 1bd50888b..e430d1e0c 100644 --- a/tests/unit/test_spinel_encoder.cpp +++ b/tests/unit/test_spinel_encoder.cpp @@ -49,12 +49,12 @@ void DumpBuffer(const char *aTextMessage, uint8_t *aBuffer, uint16_t aBufferLeng { enum { - kBytesPerLine = 32, // Number of bytes per line. + kBytesPerLine = 32, // Number of bytes per line. }; - char charBuff[kBytesPerLine + 1]; + char charBuff[kBytesPerLine + 1]; uint16_t counter; - uint8_t byte; + uint8_t byte; printf("\n%s - len = %u\n ", aTextMessage, aBufferLength); @@ -85,7 +85,6 @@ void DumpBuffer(const char *aTextMessage, uint8_t *aBuffer, uint16_t aBufferLeng printf(" %s\n", charBuff); } - otError ReadFrame(NcpFrameBuffer &aNcpBuffer, uint8_t *aFrame, uint16_t &aFrameLen) { otError error = OT_ERROR_NONE; @@ -101,421 +100,310 @@ exit: void TestSpinelEncoder(void) { - uint8_t buffer[kTestBufferSize]; + uint8_t buffer[kTestBufferSize]; NcpFrameBuffer ncpBuffer(buffer, kTestBufferSize); - SpinelEncoder encoder(ncpBuffer); + SpinelEncoder encoder(ncpBuffer); - uint8_t frame[kTestBufferSize]; - uint16_t frameLen; + uint8_t frame[kTestBufferSize]; + uint16_t frameLen; spinel_ssize_t parsedLen; - const bool kBool_1 = true; - const bool kBool_2 = false; - const uint8_t kUint8 = 0x42; - const int8_t kInt8 = -73; - const uint16_t kUint16 = 0xabcd; - const int16_t kInt16 = -567; - const uint32_t kUint32 = 0xdeadbeef; - const int32_t kInt32 = -123455678L; - const uint64_t kUint64 = 0xfe10dc32ba549876ULL; - const int64_t kInt64 = -9197712039090021561LL; - const unsigned int kUint_1 = 9; - const unsigned int kUint_2 = 0xa3; - const unsigned int kUint_3 = 0x8765; - const unsigned int kUint_4 = SPINEL_MAX_UINT_PACKED - 1; + const bool kBool_1 = true; + const bool kBool_2 = false; + const uint8_t kUint8 = 0x42; + const int8_t kInt8 = -73; + const uint16_t kUint16 = 0xabcd; + const int16_t kInt16 = -567; + const uint32_t kUint32 = 0xdeadbeef; + const int32_t kInt32 = -123455678L; + const uint64_t kUint64 = 0xfe10dc32ba549876ULL; + const int64_t kInt64 = -9197712039090021561LL; + const unsigned int kUint_1 = 9; + const unsigned int kUint_2 = 0xa3; + const unsigned int kUint_3 = 0x8765; + const unsigned int kUint_4 = SPINEL_MAX_UINT_PACKED - 1; - const spinel_ipv6addr_t kIp6Addr = - { - { 0x6B, 0x41, 0x65, 0x73, 0x42, 0x68, 0x61, 0x76, 0x54, 0x61, 0x72, 0x7A, 0x49, 0x69, 0x61, 0x4E } + const spinel_ipv6addr_t kIp6Addr = { + {0x6B, 0x41, 0x65, 0x73, 0x42, 0x68, 0x61, 0x76, 0x54, 0x61, 0x72, 0x7A, 0x49, 0x69, 0x61, 0x4E}}; + + const spinel_eui48_t kEui48 = { + {4, 8, 15, 16, 23, 42} // "Lost" EUI48! }; - const spinel_eui48_t kEui48 = - { - { 4, 8, 15, 16, 23, 42 } // "Lost" EUI48! - }; - - const spinel_eui64_t kEui64 = - { - { 2, 3, 5, 7, 11, 13, 17, 19 }, // "Prime" EUI64! + const spinel_eui64_t kEui64 = { + {2, 3, 5, 7, 11, 13, 17, 19}, // "Prime" EUI64! }; const char kString_1[] = "OpenThread"; const char kString_2[] = ""; - const uint16_t kData[] = { 10, 20, 3, 15, 1000, 60, 16 }; // ... then comes 17,18,19,20 :) + const uint16_t kData[] = {10, 20, 3, 15, 1000, 60, 16}; // ... then comes 17,18,19,20 :) - bool b_1, b_2; - uint8_t u8; - int8_t i8; - uint16_t u16; - int16_t i16; - uint32_t u32; - int32_t i32; - uint64_t u64; - int64_t i64; - unsigned int u_1, u_2, u_3, u_4; + bool b_1, b_2; + uint8_t u8; + int8_t i8; + uint16_t u16; + int16_t i16; + uint32_t u32; + int32_t i32; + uint64_t u64; + int64_t i64; + unsigned int u_1, u_2, u_3, u_4; spinel_ipv6addr_t *ip6Addr; - spinel_eui48_t *eui48; - spinel_eui64_t *eui64; - const char *utf_1; - const char *utf_2; - const uint8_t *dataPtr; - spinel_size_t dataLen; + spinel_eui48_t * eui48; + spinel_eui64_t * eui64; + const char * utf_1; + const char * utf_2; + const uint8_t * dataPtr; + spinel_size_t dataLen; memset(buffer, 0, sizeof(buffer)); printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"); printf("\nTest 1: Encoding of simple types"); - SuccessOrQuit(encoder.BeginFrame(NcpFrameBuffer::kPriorityLow), "BeginFrame() failed."); - SuccessOrQuit(encoder.WriteBool(kBool_1), "WriteBool() failed."); - SuccessOrQuit(encoder.WriteBool(kBool_2), "WriteBool() failed."); - SuccessOrQuit(encoder.WriteUint8(kUint8), "WriteUint8() failed."); - SuccessOrQuit(encoder.WriteInt8(kInt8), "WriteUint8() failed."); - SuccessOrQuit(encoder.WriteUint16(kUint16), "WriteUint16() failed."); - SuccessOrQuit(encoder.WriteInt16(kInt16), "WriteInt16() failed."); - SuccessOrQuit(encoder.WriteUint32(kUint32), "WriteUint32() failed."); - SuccessOrQuit(encoder.WriteInt32(kInt32), "WriteUint32() failed."); - SuccessOrQuit(encoder.WriteUint64(kUint64), "WriteUint64() failed."); - SuccessOrQuit(encoder.WriteInt64(kInt64), "WriteUint64() failed."); - SuccessOrQuit(encoder.WriteUintPacked(kUint_1), "WriteUintPacked() failed."); - SuccessOrQuit(encoder.WriteUintPacked(kUint_2), "WriteUintPacked() failed."); - SuccessOrQuit(encoder.WriteUintPacked(kUint_3), "WriteUintPacked() failed."); - SuccessOrQuit(encoder.WriteUintPacked(kUint_4), "WriteUintPacked() failed."); - SuccessOrQuit(encoder.WriteIp6Address(kIp6Addr), "WriteIp6Addr() failed."); - SuccessOrQuit(encoder.WriteEui48(kEui48), "WriteEui48() failed."); - SuccessOrQuit(encoder.WriteEui64(kEui64), "WriteEui64() failed."); - SuccessOrQuit(encoder.WriteUtf8(kString_1), "WriteUtf8() failed."); - SuccessOrQuit(encoder.WriteUtf8(kString_2), "WriteUtf8() failed."); - SuccessOrQuit(encoder.WriteData((const uint8_t *)kData, sizeof(kData)), "WriteData() failed."); - SuccessOrQuit(encoder.EndFrame(), "EndFrame() failed."); + SuccessOrQuit(encoder.BeginFrame(NcpFrameBuffer::kPriorityLow), "BeginFrame() failed."); + SuccessOrQuit(encoder.WriteBool(kBool_1), "WriteBool() failed."); + SuccessOrQuit(encoder.WriteBool(kBool_2), "WriteBool() failed."); + SuccessOrQuit(encoder.WriteUint8(kUint8), "WriteUint8() failed."); + SuccessOrQuit(encoder.WriteInt8(kInt8), "WriteUint8() failed."); + SuccessOrQuit(encoder.WriteUint16(kUint16), "WriteUint16() failed."); + SuccessOrQuit(encoder.WriteInt16(kInt16), "WriteInt16() failed."); + SuccessOrQuit(encoder.WriteUint32(kUint32), "WriteUint32() failed."); + SuccessOrQuit(encoder.WriteInt32(kInt32), "WriteUint32() failed."); + SuccessOrQuit(encoder.WriteUint64(kUint64), "WriteUint64() failed."); + SuccessOrQuit(encoder.WriteInt64(kInt64), "WriteUint64() failed."); + SuccessOrQuit(encoder.WriteUintPacked(kUint_1), "WriteUintPacked() failed."); + SuccessOrQuit(encoder.WriteUintPacked(kUint_2), "WriteUintPacked() failed."); + SuccessOrQuit(encoder.WriteUintPacked(kUint_3), "WriteUintPacked() failed."); + SuccessOrQuit(encoder.WriteUintPacked(kUint_4), "WriteUintPacked() failed."); + SuccessOrQuit(encoder.WriteIp6Address(kIp6Addr), "WriteIp6Addr() failed."); + SuccessOrQuit(encoder.WriteEui48(kEui48), "WriteEui48() failed."); + SuccessOrQuit(encoder.WriteEui64(kEui64), "WriteEui64() failed."); + SuccessOrQuit(encoder.WriteUtf8(kString_1), "WriteUtf8() failed."); + SuccessOrQuit(encoder.WriteUtf8(kString_2), "WriteUtf8() failed."); + SuccessOrQuit(encoder.WriteData((const uint8_t *)kData, sizeof(kData)), "WriteData() failed."); + SuccessOrQuit(encoder.EndFrame(), "EndFrame() failed."); DumpBuffer("Buffer", buffer, 256); - SuccessOrQuit(ReadFrame(ncpBuffer, frame, frameLen), "ReadFrame() failed."); + SuccessOrQuit(ReadFrame(ncpBuffer, frame, frameLen), "ReadFrame() failed."); DumpBuffer("Frame", frame, frameLen); parsedLen = spinel_datatype_unpack( - frame, - (spinel_size_t)frameLen, - ( - SPINEL_DATATYPE_BOOL_S - SPINEL_DATATYPE_BOOL_S - SPINEL_DATATYPE_UINT8_S - SPINEL_DATATYPE_INT8_S - SPINEL_DATATYPE_UINT16_S - SPINEL_DATATYPE_INT16_S - SPINEL_DATATYPE_UINT32_S - SPINEL_DATATYPE_INT32_S - SPINEL_DATATYPE_UINT64_S - SPINEL_DATATYPE_INT64_S - SPINEL_DATATYPE_UINT_PACKED_S - SPINEL_DATATYPE_UINT_PACKED_S - SPINEL_DATATYPE_UINT_PACKED_S - SPINEL_DATATYPE_UINT_PACKED_S - SPINEL_DATATYPE_IPv6ADDR_S - SPINEL_DATATYPE_EUI48_S - SPINEL_DATATYPE_EUI64_S - SPINEL_DATATYPE_UTF8_S - SPINEL_DATATYPE_UTF8_S - SPINEL_DATATYPE_DATA_S - ), - &b_1, - &b_2, - &u8, - &i8, - &u16, - &i16, - &u32, - &i32, - &u64, - &i64, - &u_1, - &u_2, - &u_3, - &u_4, - &ip6Addr, - &eui48, - &eui64, - &utf_1, - &utf_2, - &dataPtr, - &dataLen - ); + frame, (spinel_size_t)frameLen, + (SPINEL_DATATYPE_BOOL_S SPINEL_DATATYPE_BOOL_S SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_INT8_S + SPINEL_DATATYPE_UINT16_S SPINEL_DATATYPE_INT16_S SPINEL_DATATYPE_UINT32_S SPINEL_DATATYPE_INT32_S + SPINEL_DATATYPE_UINT64_S SPINEL_DATATYPE_INT64_S SPINEL_DATATYPE_UINT_PACKED_S + SPINEL_DATATYPE_UINT_PACKED_S SPINEL_DATATYPE_UINT_PACKED_S SPINEL_DATATYPE_UINT_PACKED_S + SPINEL_DATATYPE_IPv6ADDR_S SPINEL_DATATYPE_EUI48_S SPINEL_DATATYPE_EUI64_S + SPINEL_DATATYPE_UTF8_S SPINEL_DATATYPE_UTF8_S SPINEL_DATATYPE_DATA_S), + &b_1, &b_2, &u8, &i8, &u16, &i16, &u32, &i32, &u64, &i64, &u_1, &u_2, &u_3, &u_4, &ip6Addr, &eui48, &eui64, + &utf_1, &utf_2, &dataPtr, &dataLen); - VerifyOrQuit(parsedLen == frameLen, "spinel parse failed"); - VerifyOrQuit(b_1 == kBool_1, "WriteBool() parse failed."); - VerifyOrQuit(b_2 == kBool_2, "WriteBool() parse failed."); - VerifyOrQuit(u8 == kUint8, "WriteUint8() parse failed."); - VerifyOrQuit(i8 == kInt8, "WriteUint8() parse failed."); - VerifyOrQuit(u16 == kUint16, "WriteUint16() parse failed."); - VerifyOrQuit(i16 == kInt16, "WriteInt16() parse failed."); - VerifyOrQuit(u32 == kUint32, "WriteUint32() parse failed."); - VerifyOrQuit(i32 == kInt32, "WriteUint32() parse failed."); - VerifyOrQuit(u64 == kUint64, "WriteUint64() parse failed."); - VerifyOrQuit(i64 == kInt64, "WriteUint64() parse failed."); - VerifyOrQuit(u_1 == kUint_1, "WriteUintPacked() parse failed."); - VerifyOrQuit(u_2 == kUint_2, "WriteUintPacked() parse failed."); - VerifyOrQuit(u_3 == kUint_3, "WriteUintPacked() parse failed."); - VerifyOrQuit(u_4 == kUint_4, "WriteUintPacked() parse failed."); - VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "WriteIp6Address() parse failed."); - VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "WriteEui48() parse failed."); - VerifyOrQuit(memcmp(eui64, &kEui64, sizeof(spinel_eui64_t)) == 0, "WriteEui64() parse failed."); - VerifyOrQuit(memcmp(utf_1, kString_1, sizeof(kString_1)) == 0, "WriteUtf8() parse failed."); - VerifyOrQuit(memcmp(utf_2, kString_2, sizeof(kString_2)) == 0, "WriteUtf8() parse failed."); - VerifyOrQuit(dataLen == sizeof(kData), "WriteData() parse failed."); - VerifyOrQuit(memcmp(dataPtr, &kData, sizeof(kData)) == 0, "WriteData() parse failed."); + VerifyOrQuit(parsedLen == frameLen, "spinel parse failed"); + VerifyOrQuit(b_1 == kBool_1, "WriteBool() parse failed."); + VerifyOrQuit(b_2 == kBool_2, "WriteBool() parse failed."); + VerifyOrQuit(u8 == kUint8, "WriteUint8() parse failed."); + VerifyOrQuit(i8 == kInt8, "WriteUint8() parse failed."); + VerifyOrQuit(u16 == kUint16, "WriteUint16() parse failed."); + VerifyOrQuit(i16 == kInt16, "WriteInt16() parse failed."); + VerifyOrQuit(u32 == kUint32, "WriteUint32() parse failed."); + VerifyOrQuit(i32 == kInt32, "WriteUint32() parse failed."); + VerifyOrQuit(u64 == kUint64, "WriteUint64() parse failed."); + VerifyOrQuit(i64 == kInt64, "WriteUint64() parse failed."); + VerifyOrQuit(u_1 == kUint_1, "WriteUintPacked() parse failed."); + VerifyOrQuit(u_2 == kUint_2, "WriteUintPacked() parse failed."); + VerifyOrQuit(u_3 == kUint_3, "WriteUintPacked() parse failed."); + VerifyOrQuit(u_4 == kUint_4, "WriteUintPacked() parse failed."); + VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "WriteIp6Address() parse failed."); + VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "WriteEui48() parse failed."); + VerifyOrQuit(memcmp(eui64, &kEui64, sizeof(spinel_eui64_t)) == 0, "WriteEui64() parse failed."); + VerifyOrQuit(memcmp(utf_1, kString_1, sizeof(kString_1)) == 0, "WriteUtf8() parse failed."); + VerifyOrQuit(memcmp(utf_2, kString_2, sizeof(kString_2)) == 0, "WriteUtf8() parse failed."); + VerifyOrQuit(dataLen == sizeof(kData), "WriteData() parse failed."); + VerifyOrQuit(memcmp(dataPtr, &kData, sizeof(kData)) == 0, "WriteData() parse failed."); printf(" -- PASS\n"); printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"); printf("\nTest 2: Test a single simple struct."); - SuccessOrQuit(encoder.BeginFrame(NcpFrameBuffer::kPriorityLow), "BeginFrame() failed."); - SuccessOrQuit(encoder.WriteUint8(kUint8), "WriteUint8() failed."); - SuccessOrQuit(encoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(encoder.BeginFrame(NcpFrameBuffer::kPriorityLow), "BeginFrame() failed."); + SuccessOrQuit(encoder.WriteUint8(kUint8), "WriteUint8() failed."); + SuccessOrQuit(encoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(encoder.WriteUint32(kUint32), "WriteUint32() failed."); - SuccessOrQuit(encoder.WriteEui48(kEui48), "WriteEui48() failed."); - SuccessOrQuit(encoder.WriteUintPacked(kUint_3), "WriteUintPacked() failed."); + SuccessOrQuit(encoder.WriteUint32(kUint32), "WriteUint32() failed."); + SuccessOrQuit(encoder.WriteEui48(kEui48), "WriteEui48() failed."); + SuccessOrQuit(encoder.WriteUintPacked(kUint_3), "WriteUintPacked() failed."); } - SuccessOrQuit(encoder.CloseStruct(), "CloseStruct() failed."); - SuccessOrQuit(encoder.WriteInt16(kInt16), "WriteInt16() failed."); - SuccessOrQuit(encoder.EndFrame(), "EndFrame() failed."); + SuccessOrQuit(encoder.CloseStruct(), "CloseStruct() failed."); + SuccessOrQuit(encoder.WriteInt16(kInt16), "WriteInt16() failed."); + SuccessOrQuit(encoder.EndFrame(), "EndFrame() failed."); DumpBuffer("Buffer", buffer, 256); - SuccessOrQuit(ReadFrame(ncpBuffer, frame, frameLen), "ReadFrame() failed."); + SuccessOrQuit(ReadFrame(ncpBuffer, frame, frameLen), "ReadFrame() failed."); DumpBuffer("Frame", frame, frameLen); parsedLen = spinel_datatype_unpack( - frame, - (spinel_size_t)frameLen, - ( - SPINEL_DATATYPE_UINT8_S - SPINEL_DATATYPE_STRUCT_S( - SPINEL_DATATYPE_UINT32_S - SPINEL_DATATYPE_EUI48_S - SPINEL_DATATYPE_UINT_PACKED_S - ) - SPINEL_DATATYPE_INT16_S + frame, (spinel_size_t)frameLen, + (SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_STRUCT_S( + SPINEL_DATATYPE_UINT32_S SPINEL_DATATYPE_EUI48_S SPINEL_DATATYPE_UINT_PACKED_S) SPINEL_DATATYPE_INT16_S - ), - &u8, - &u32, - &eui48, - &u_3, - &i16 - ); + ), + &u8, &u32, &eui48, &u_3, &i16); - VerifyOrQuit(parsedLen == frameLen, "spinel parse failed"); - VerifyOrQuit(u8 == kUint8, "WriteUint8() parse failed."); - VerifyOrQuit(i16 == kInt16, "WriteInt16() parse failed."); - VerifyOrQuit(u32 == kUint32, "WriteUint32() parse failed."); - VerifyOrQuit(u_3 == kUint_3, "WriteUintPacked() parse failed."); - VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "WriteEui48() parse failed."); + VerifyOrQuit(parsedLen == frameLen, "spinel parse failed"); + VerifyOrQuit(u8 == kUint8, "WriteUint8() parse failed."); + VerifyOrQuit(i16 == kInt16, "WriteInt16() parse failed."); + VerifyOrQuit(u32 == kUint32, "WriteUint32() parse failed."); + VerifyOrQuit(u_3 == kUint_3, "WriteUintPacked() parse failed."); + VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "WriteEui48() parse failed."); // Parse the struct as a "data with len". - parsedLen = spinel_datatype_unpack( - frame, - (spinel_size_t)frameLen, - ( - SPINEL_DATATYPE_UINT8_S - SPINEL_DATATYPE_DATA_WLEN_S - SPINEL_DATATYPE_INT16_S + parsedLen = spinel_datatype_unpack(frame, (spinel_size_t)frameLen, + (SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_DATA_WLEN_S SPINEL_DATATYPE_INT16_S - ), - &u8, - &dataPtr, - &dataLen, - &i16 - ); + ), + &u8, &dataPtr, &dataLen, &i16); - VerifyOrQuit(parsedLen == frameLen, "spinel parse failed"); - VerifyOrQuit(u8 == kUint8, "WriteUint8() parse failed."); - VerifyOrQuit(i16 == kInt16, "WriteInt16() parse failed."); + VerifyOrQuit(parsedLen == frameLen, "spinel parse failed"); + VerifyOrQuit(u8 == kUint8, "WriteUint8() parse failed."); + VerifyOrQuit(i16 == kInt16, "WriteInt16() parse failed."); printf(" -- PASS\n"); printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"); printf("\nTest 3: Test multiple structs and struct within struct."); - SuccessOrQuit(encoder.BeginFrame(NcpFrameBuffer::kPriorityLow), "BeginFrame() failed."); - SuccessOrQuit(encoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(encoder.BeginFrame(NcpFrameBuffer::kPriorityLow), "BeginFrame() failed."); + SuccessOrQuit(encoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(encoder.WriteUint8(kUint8), "WriteUint8() failed."); - SuccessOrQuit(encoder.WriteUtf8(kString_1), "WriteUtf8() failed."); - SuccessOrQuit(encoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(encoder.WriteUint8(kUint8), "WriteUint8() failed."); + SuccessOrQuit(encoder.WriteUtf8(kString_1), "WriteUtf8() failed."); + SuccessOrQuit(encoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(encoder.WriteBool(kBool_1), "WriteBool() failed."); - SuccessOrQuit(encoder.WriteIp6Address(kIp6Addr), "WriteIp6Addr() failed."); - + SuccessOrQuit(encoder.WriteBool(kBool_1), "WriteBool() failed."); + SuccessOrQuit(encoder.WriteIp6Address(kIp6Addr), "WriteIp6Addr() failed."); } - SuccessOrQuit(encoder.CloseStruct(), "CloseStruct() failed."); - SuccessOrQuit(encoder.WriteUint16(kUint16), "WriteUint16() failed."); + SuccessOrQuit(encoder.CloseStruct(), "CloseStruct() failed."); + SuccessOrQuit(encoder.WriteUint16(kUint16), "WriteUint16() failed."); } - SuccessOrQuit(encoder.CloseStruct(), "CloseStruct() failed."); - SuccessOrQuit(encoder.WriteEui48(kEui48), "WriteEui48() failed."); - SuccessOrQuit(encoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(encoder.CloseStruct(), "CloseStruct() failed."); + SuccessOrQuit(encoder.WriteEui48(kEui48), "WriteEui48() failed."); + SuccessOrQuit(encoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(encoder.WriteUint32(kUint32), "WriteUint32() failed."); + SuccessOrQuit(encoder.WriteUint32(kUint32), "WriteUint32() failed."); } - SuccessOrQuit(encoder.CloseStruct(), "CloseStruct() failed."); - SuccessOrQuit(encoder.WriteInt32(kInt32), "WriteUint32() failed."); - SuccessOrQuit(encoder.EndFrame(), "EndFrame() failed."); + SuccessOrQuit(encoder.CloseStruct(), "CloseStruct() failed."); + SuccessOrQuit(encoder.WriteInt32(kInt32), "WriteUint32() failed."); + SuccessOrQuit(encoder.EndFrame(), "EndFrame() failed."); DumpBuffer("Buffer", buffer, 256 + 100); - SuccessOrQuit(ReadFrame(ncpBuffer, frame, frameLen), "ReadFrame() failed."); + SuccessOrQuit(ReadFrame(ncpBuffer, frame, frameLen), "ReadFrame() failed."); parsedLen = spinel_datatype_unpack( - frame, - (spinel_size_t)frameLen, - ( - SPINEL_DATATYPE_STRUCT_S( - SPINEL_DATATYPE_UINT8_S - SPINEL_DATATYPE_UTF8_S - SPINEL_DATATYPE_STRUCT_S( - SPINEL_DATATYPE_BOOL_S - SPINEL_DATATYPE_IPv6ADDR_S - ) - SPINEL_DATATYPE_UINT16_S - ) - SPINEL_DATATYPE_EUI48_S - SPINEL_DATATYPE_STRUCT_S( - SPINEL_DATATYPE_UINT32_S - ) - SPINEL_DATATYPE_INT32_S - ), - &u8, - &utf_1, - &b_1, - &ip6Addr, - &u16, - &eui48, - &u32, - &i32 - ); + frame, (spinel_size_t)frameLen, + (SPINEL_DATATYPE_STRUCT_S(SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_UTF8_S SPINEL_DATATYPE_STRUCT_S( + SPINEL_DATATYPE_BOOL_S SPINEL_DATATYPE_IPv6ADDR_S) SPINEL_DATATYPE_UINT16_S) + SPINEL_DATATYPE_EUI48_S SPINEL_DATATYPE_STRUCT_S(SPINEL_DATATYPE_UINT32_S) SPINEL_DATATYPE_INT32_S), + &u8, &utf_1, &b_1, &ip6Addr, &u16, &eui48, &u32, &i32); - VerifyOrQuit(parsedLen == frameLen, "spinel parse failed"); - VerifyOrQuit(b_1 == kBool_1, "WriteBool() parse failed."); - VerifyOrQuit(u8 == kUint8, "WriteUint8() parse failed."); - VerifyOrQuit(u16 == kUint16, "WriteUint16() parse failed."); - VerifyOrQuit(u32 == kUint32, "WriteUint32() parse failed."); - VerifyOrQuit(i32 == kInt32, "WriteUint32() parse failed."); - VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "WriteIp6Address() parse failed."); - VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "WriteEui48() parse failed."); - VerifyOrQuit(memcmp(utf_1, kString_1, sizeof(kString_1)) == 0, "WriteUtf8() parse failed."); + VerifyOrQuit(parsedLen == frameLen, "spinel parse failed"); + VerifyOrQuit(b_1 == kBool_1, "WriteBool() parse failed."); + VerifyOrQuit(u8 == kUint8, "WriteUint8() parse failed."); + VerifyOrQuit(u16 == kUint16, "WriteUint16() parse failed."); + VerifyOrQuit(u32 == kUint32, "WriteUint32() parse failed."); + VerifyOrQuit(i32 == kInt32, "WriteUint32() parse failed."); + VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "WriteIp6Address() parse failed."); + VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "WriteEui48() parse failed."); + VerifyOrQuit(memcmp(utf_1, kString_1, sizeof(kString_1)) == 0, "WriteUtf8() parse failed."); printf(" -- PASS\n"); printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"); printf("\nTest 4: Test unclosed struct."); - SuccessOrQuit(encoder.BeginFrame(NcpFrameBuffer::kPriorityLow), "BeginFrame() failed."); - SuccessOrQuit(encoder.WriteUint8(kUint8), "WriteUint8() failed."); - SuccessOrQuit(encoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(encoder.BeginFrame(NcpFrameBuffer::kPriorityLow), "BeginFrame() failed."); + SuccessOrQuit(encoder.WriteUint8(kUint8), "WriteUint8() failed."); + SuccessOrQuit(encoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(encoder.WriteUint32(kUint32), "WriteUint32() failed."); - SuccessOrQuit(encoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(encoder.WriteUint32(kUint32), "WriteUint32() failed."); + SuccessOrQuit(encoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(encoder.WriteEui48(kEui48), "WriteEui48() failed."); - SuccessOrQuit(encoder.WriteUintPacked(kUint_3), "WriteUintPacked() failed."); + SuccessOrQuit(encoder.WriteEui48(kEui48), "WriteEui48() failed."); + SuccessOrQuit(encoder.WriteUintPacked(kUint_3), "WriteUintPacked() failed."); // Do not close the structs expecting `EndFrame()` to close them. } } - SuccessOrQuit(encoder.EndFrame(), "EndFrame() failed."); + SuccessOrQuit(encoder.EndFrame(), "EndFrame() failed."); - SuccessOrQuit(ReadFrame(ncpBuffer, frame, frameLen), "ReadFrame() failed."); + SuccessOrQuit(ReadFrame(ncpBuffer, frame, frameLen), "ReadFrame() failed."); parsedLen = spinel_datatype_unpack( - frame, - (spinel_size_t)frameLen, - ( - SPINEL_DATATYPE_UINT8_S - SPINEL_DATATYPE_STRUCT_S( - SPINEL_DATATYPE_UINT32_S - SPINEL_DATATYPE_STRUCT_S( - SPINEL_DATATYPE_EUI48_S - SPINEL_DATATYPE_UINT_PACKED_S - ) - ) - ), - &u8, - &u32, - &eui48, - &u_3 - ); + frame, (spinel_size_t)frameLen, + (SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_STRUCT_S( + SPINEL_DATATYPE_UINT32_S SPINEL_DATATYPE_STRUCT_S(SPINEL_DATATYPE_EUI48_S SPINEL_DATATYPE_UINT_PACKED_S))), + &u8, &u32, &eui48, &u_3); - VerifyOrQuit(parsedLen == frameLen, "spinel parse failed"); - VerifyOrQuit(u8 == kUint8, "WriteUint8() parse failed."); - VerifyOrQuit(u32 == kUint32, "WriteUint32() parse failed."); - VerifyOrQuit(u_3 == kUint_3, "WriteUintPacked() parse failed."); - VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "WriteEui48() parse failed."); + VerifyOrQuit(parsedLen == frameLen, "spinel parse failed"); + VerifyOrQuit(u8 == kUint8, "WriteUint8() parse failed."); + VerifyOrQuit(u32 == kUint32, "WriteUint32() parse failed."); + VerifyOrQuit(u_3 == kUint_3, "WriteUintPacked() parse failed."); + VerifyOrQuit(memcmp(eui48, &kEui48, sizeof(spinel_eui48_t)) == 0, "WriteEui48() parse failed."); printf(" -- PASS\n"); printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"); printf("\nTest 5: Test saving position and reseting back to a saved position"); - SuccessOrQuit(encoder.BeginFrame(NcpFrameBuffer::kPriorityLow), "BeginFrame() failed."); - SuccessOrQuit(encoder.WriteUint8(kUint8), "WriteUint8() failed."); - SuccessOrQuit(encoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(encoder.BeginFrame(NcpFrameBuffer::kPriorityLow), "BeginFrame() failed."); + SuccessOrQuit(encoder.WriteUint8(kUint8), "WriteUint8() failed."); + SuccessOrQuit(encoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(encoder.WriteUint32(kUint32), "WriteUint32() failed."); + SuccessOrQuit(encoder.WriteUint32(kUint32), "WriteUint32() failed."); // Save position in middle a first open struct. - SuccessOrQuit(encoder.SavePosition(), "SavePosition failed."); - SuccessOrQuit(encoder.OpenStruct(), "OpenStruct() failed."); + SuccessOrQuit(encoder.SavePosition(), "SavePosition failed."); + SuccessOrQuit(encoder.OpenStruct(), "OpenStruct() failed."); { - SuccessOrQuit(encoder.WriteEui48(kEui48), "WriteEui48() failed."); - SuccessOrQuit(encoder.WriteUintPacked(kUint_3), "WriteUintPacked() failed."); + SuccessOrQuit(encoder.WriteEui48(kEui48), "WriteEui48() failed."); + SuccessOrQuit(encoder.WriteUintPacked(kUint_3), "WriteUintPacked() failed."); } // Reset to saved position in middle of the second open struct which should be discarded. - SuccessOrQuit(encoder.ResetToSaved(), "ResetToSaved() failed."); + SuccessOrQuit(encoder.ResetToSaved(), "ResetToSaved() failed."); - SuccessOrQuit(encoder.WriteIp6Address(kIp6Addr), "WriteIp6Addr() failed."); - SuccessOrQuit(encoder.WriteEui64(kEui64), "WriteEui64() failed."); + SuccessOrQuit(encoder.WriteIp6Address(kIp6Addr), "WriteIp6Addr() failed."); + SuccessOrQuit(encoder.WriteEui64(kEui64), "WriteEui64() failed."); } - SuccessOrQuit(encoder.CloseStruct(), "CloseStruct() failed."); - SuccessOrQuit(encoder.WriteUtf8(kString_1), "WriteUtf8() failed."); - SuccessOrQuit(encoder.EndFrame(), "EndFrame() failed."); + SuccessOrQuit(encoder.CloseStruct(), "CloseStruct() failed."); + SuccessOrQuit(encoder.WriteUtf8(kString_1), "WriteUtf8() failed."); + SuccessOrQuit(encoder.EndFrame(), "EndFrame() failed."); - SuccessOrQuit(ReadFrame(ncpBuffer, frame, frameLen), "ReadFrame() failed."); + SuccessOrQuit(ReadFrame(ncpBuffer, frame, frameLen), "ReadFrame() failed."); parsedLen = spinel_datatype_unpack( - frame, - (spinel_size_t)frameLen, - ( - SPINEL_DATATYPE_UINT8_S - SPINEL_DATATYPE_STRUCT_S( - SPINEL_DATATYPE_UINT32_S - SPINEL_DATATYPE_IPv6ADDR_S - SPINEL_DATATYPE_EUI64_S - ) - SPINEL_DATATYPE_UTF8_S - ), - &u8, - &u32, - &ip6Addr, - &eui64, - &utf_1 - ); + frame, (spinel_size_t)frameLen, + (SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_STRUCT_S( + SPINEL_DATATYPE_UINT32_S SPINEL_DATATYPE_IPv6ADDR_S SPINEL_DATATYPE_EUI64_S) SPINEL_DATATYPE_UTF8_S), + &u8, &u32, &ip6Addr, &eui64, &utf_1); - VerifyOrQuit(parsedLen == frameLen, "spinel parse failed"); + VerifyOrQuit(parsedLen == frameLen, "spinel parse failed"); - VerifyOrQuit(u8 == kUint8, "WriteUint8() parse failed."); - VerifyOrQuit(u32 == kUint32, "WriteUint32() parse failed."); - VerifyOrQuit(i32 == kInt32, "WriteUint32() parse failed."); - VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "WriteIp6Address() parse failed."); - VerifyOrQuit(memcmp(eui64, &kEui64, sizeof(spinel_eui64_t)) == 0, "WriteEui64() parse failed."); - VerifyOrQuit(memcmp(utf_1, kString_1, sizeof(kString_1)) == 0, "WriteUtf8() parse failed."); + VerifyOrQuit(u8 == kUint8, "WriteUint8() parse failed."); + VerifyOrQuit(u32 == kUint32, "WriteUint32() parse failed."); + VerifyOrQuit(i32 == kInt32, "WriteUint32() parse failed."); + VerifyOrQuit(memcmp(ip6Addr, &kIp6Addr, sizeof(spinel_ipv6addr_t)) == 0, "WriteIp6Address() parse failed."); + VerifyOrQuit(memcmp(eui64, &kEui64, sizeof(spinel_eui64_t)) == 0, "WriteEui64() parse failed."); + VerifyOrQuit(memcmp(utf_1, kString_1, sizeof(kString_1)) == 0, "WriteUtf8() parse failed."); printf(" -- PASS\n"); } -} // namespace Ncp -} // namespace ot +} // namespace Ncp +} // namespace ot #ifdef ENABLE_TEST_MAIN int main(void) diff --git a/tests/unit/test_strlcat.c b/tests/unit/test_strlcat.c index 3da5597e0..e6bf86331 100644 --- a/tests/unit/test_strlcat.c +++ b/tests/unit/test_strlcat.c @@ -33,10 +33,10 @@ int main(int argc, char **argv) { - char string_a[8] = "foo"; - char string_b[8] = "barbar"; - size_t ret = 0; - int errors = 0; + char string_a[8] = "foo"; + char string_b[8] = "barbar"; + size_t ret = 0; + int errors = 0; (void)argc; (void)argv; diff --git a/tests/unit/test_strlcpy.c b/tests/unit/test_strlcpy.c index 0513ba9e3..8c9ac4364 100644 --- a/tests/unit/test_strlcpy.c +++ b/tests/unit/test_strlcpy.c @@ -33,10 +33,10 @@ int main(int argc, char **argv) { - char string_a[8] = "foo"; - char string_b[] = "barbarbar"; - size_t ret = 0; - int errors = 0; + char string_a[8] = "foo"; + char string_b[] = "barbarbar"; + size_t ret = 0; + int errors = 0; (void)argc; (void)argv; diff --git a/tests/unit/test_timer.cpp b/tests/unit/test_timer.cpp index 70b027d25..908e5fed3 100644 --- a/tests/unit/test_timer.cpp +++ b/tests/unit/test_timer.cpp @@ -68,9 +68,9 @@ uint32_t testTimerAlarmGetNow(void) void InitTestTimer(void) { - g_testPlatAlarmStop = testTimerAlarmStop; + g_testPlatAlarmStop = testTimerAlarmStop; g_testPlatAlarmStartAt = testTimerAlarmStartAt; - g_testPlatAlarmGetNow = testTimerAlarmGetNow; + g_testPlatAlarmGetNow = testTimerAlarmGetNow; } void InitCounters(void) @@ -79,22 +79,22 @@ void InitCounters(void) } /** - * `TestTimer` sub-classes `ot::TimerMilli` and provides a handler and a counter to keep track of number of times timer gets - * fired. + * `TestTimer` sub-classes `ot::TimerMilli` and provides a handler and a counter to keep track of number of times timer + * gets fired. */ -class TestTimer: public ot::TimerMilli +class TestTimer : public ot::TimerMilli { public: - TestTimer(ot::Instance &aInstance): - ot::TimerMilli(aInstance, TestTimer::HandleTimerFired, NULL), - mFiredCounter(0) - { } - - static void HandleTimerFired(ot::Timer &aTimer) { - static_cast(aTimer).HandleTimerFired(); + TestTimer(ot::Instance &aInstance) + : ot::TimerMilli(aInstance, TestTimer::HandleTimerFired, NULL) + , mFiredCounter(0) + { } - void HandleTimerFired(void) { + static void HandleTimerFired(ot::Timer &aTimer) { static_cast(aTimer).HandleTimerFired(); } + + void HandleTimerFired(void) + { sCallCount[kCallCountIndexTimerHandler]++; mFiredCounter++; } @@ -104,7 +104,7 @@ public: void ResetFiredCounter(void) { mFiredCounter = 0; } private: - uint32_t mFiredCounter; //< Number of times timer has been fired so far + uint32_t mFiredCounter; //< Number of times timer has been fired so far }; /** @@ -112,10 +112,10 @@ private: */ int TestOneTimer(void) { - const uint32_t kTimeT0 = 1000; + const uint32_t kTimeT0 = 1000; const uint32_t kTimerInterval = 10; - ot::Instance *instance = testInitInstance(); - TestTimer timer(*instance); + ot::Instance * instance = testInitInstance(); + TestTimer timer(*instance); // Test one Timer basic operation. @@ -127,22 +127,22 @@ int TestOneTimer(void) sNow = kTimeT0; timer.Start(kTimerInterval); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestOneTimer: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestOneTimer: Handler CallCount Failed.\n"); - VerifyOrQuit(sPlatT0 == 1000 && sPlatDt == 10, "TestOneTimer: Start params Failed.\n"); - VerifyOrQuit(timer.IsRunning(), "TestOneTimer: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn, "TestOneTimer: Platform Timer State Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestOneTimer: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestOneTimer: Handler CallCount Failed.\n"); + VerifyOrQuit(sPlatT0 == 1000 && sPlatDt == 10, "TestOneTimer: Start params Failed.\n"); + VerifyOrQuit(timer.IsRunning(), "TestOneTimer: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn, "TestOneTimer: Platform Timer State Failed.\n"); sNow += kTimerInterval; otPlatAlarmMilliFired(instance); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestOneTimer: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestOneTimer: Handler CallCount Failed.\n"); - VerifyOrQuit(timer.IsRunning() == false, "TestOneTimer: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn == false, "TestOneTimer: Platform Timer State Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestOneTimer: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestOneTimer: Handler CallCount Failed.\n"); + VerifyOrQuit(timer.IsRunning() == false, "TestOneTimer: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn == false, "TestOneTimer: Platform Timer State Failed.\n"); // Test one Timer that spans the 32-bit wrap. @@ -151,22 +151,22 @@ int TestOneTimer(void) sNow = 0 - (kTimerInterval - 2); timer.Start(kTimerInterval); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestOneTimer: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestOneTimer: Handler CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestOneTimer: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestOneTimer: Handler CallCount Failed.\n"); VerifyOrQuit(sPlatT0 == 0 - (kTimerInterval - 2) && sPlatDt == 10, "TestOneTimer: Start params Failed.\n"); - VerifyOrQuit(timer.IsRunning(), "TestOneTimer: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn, "TestOneTimer: Platform Timer State Failed.\n"); + VerifyOrQuit(timer.IsRunning(), "TestOneTimer: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn, "TestOneTimer: Platform Timer State Failed.\n"); sNow += kTimerInterval; otPlatAlarmMilliFired(instance); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestOneTimer: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestOneTimer: Handler CallCount Failed.\n"); - VerifyOrQuit(timer.IsRunning() == false, "TestOneTimer: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn == false, "TestOneTimer: Platform Timer State Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestOneTimer: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestOneTimer: Handler CallCount Failed.\n"); + VerifyOrQuit(timer.IsRunning() == false, "TestOneTimer: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn == false, "TestOneTimer: Platform Timer State Failed.\n"); // Test one Timer that is late by several msec @@ -175,22 +175,22 @@ int TestOneTimer(void) sNow = kTimeT0; timer.Start(kTimerInterval); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestOneTimer: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestOneTimer: Handler CallCount Failed.\n"); - VerifyOrQuit(sPlatT0 == 1000 && sPlatDt == 10, "TestOneTimer: Start params Failed.\n"); - VerifyOrQuit(timer.IsRunning(), "TestOneTimer: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn, "TestOneTimer: Platform Timer State Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestOneTimer: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestOneTimer: Handler CallCount Failed.\n"); + VerifyOrQuit(sPlatT0 == 1000 && sPlatDt == 10, "TestOneTimer: Start params Failed.\n"); + VerifyOrQuit(timer.IsRunning(), "TestOneTimer: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn, "TestOneTimer: Platform Timer State Failed.\n"); sNow += kTimerInterval + 5; otPlatAlarmMilliFired(instance); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestOneTimer: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestOneTimer: Handler CallCount Failed.\n"); - VerifyOrQuit(timer.IsRunning() == false, "TestOneTimer: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn == false, "TestOneTimer: Platform Timer State Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestOneTimer: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestOneTimer: Handler CallCount Failed.\n"); + VerifyOrQuit(timer.IsRunning() == false, "TestOneTimer: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn == false, "TestOneTimer: Platform Timer State Failed.\n"); // Test one Timer that is early by several msec @@ -199,32 +199,32 @@ int TestOneTimer(void) sNow = kTimeT0; timer.Start(kTimerInterval); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestOneTimer: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestOneTimer: Handler CallCount Failed.\n"); - VerifyOrQuit(sPlatT0 == 1000 && sPlatDt == 10, "TestOneTimer: Start params Failed.\n"); - VerifyOrQuit(timer.IsRunning(), "TestOneTimer: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn, "TestOneTimer: Platform Timer State Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestOneTimer: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestOneTimer: Handler CallCount Failed.\n"); + VerifyOrQuit(sPlatT0 == 1000 && sPlatDt == 10, "TestOneTimer: Start params Failed.\n"); + VerifyOrQuit(timer.IsRunning(), "TestOneTimer: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn, "TestOneTimer: Platform Timer State Failed.\n"); sNow += kTimerInterval - 2; otPlatAlarmMilliFired(instance); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestOneTimer: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestOneTimer: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestOneTimer: Handler CallCount Failed.\n"); - VerifyOrQuit(timer.IsRunning() == true, "TestOneTimer: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn == true, "TestOneTimer: Platform Timer State Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestOneTimer: Start CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestOneTimer: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestOneTimer: Handler CallCount Failed.\n"); + VerifyOrQuit(timer.IsRunning() == true, "TestOneTimer: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn == true, "TestOneTimer: Platform Timer State Failed.\n"); sNow += kTimerInterval; otPlatAlarmMilliFired(instance); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestOneTimer: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestOneTimer: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestOneTimer: Handler CallCount Failed.\n"); - VerifyOrQuit(timer.IsRunning() == false, "TestOneTimer: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn == false, "TestOneTimer: Platform Timer State Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestOneTimer: Start CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestOneTimer: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestOneTimer: Handler CallCount Failed.\n"); + VerifyOrQuit(timer.IsRunning() == false, "TestOneTimer: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn == false, "TestOneTimer: Platform Timer State Failed.\n"); printf(" --> PASSED\n"); @@ -238,11 +238,11 @@ int TestOneTimer(void) */ int TestTwoTimers(void) { - const uint32_t kTimeT0 = 1000; + const uint32_t kTimeT0 = 1000; const uint32_t kTimerInterval = 10; - ot::Instance *instance = testInitInstance(); - TestTimer timer1(*instance); - TestTimer timer2(*instance); + ot::Instance * instance = testInitInstance(); + TestTimer timer1(*instance); + TestTimer timer2(*instance); InitTestTimer(); printf("TestTwoTimers() "); @@ -254,47 +254,47 @@ int TestTwoTimers(void) sNow = kTimeT0; timer1.Start(kTimerInterval); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestTwoTimers: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTwoTimers: Handler CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestTwoTimers: Start CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTwoTimers: Handler CallCount Failed.\n"); VerifyOrQuit(sPlatT0 == kTimeT0 && sPlatDt == kTimerInterval, "TestTwoTimers: Start params Failed.\n"); - VerifyOrQuit(timer1.IsRunning(), "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n"); + VerifyOrQuit(timer1.IsRunning(), "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n"); sNow += kTimerInterval; timer2.Start(kTimerInterval); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestTwoTimers: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTwoTimers: Handler CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestTwoTimers: Start CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTwoTimers: Handler CallCount Failed.\n"); VerifyOrQuit(sPlatT0 == kTimeT0 && sPlatDt == kTimerInterval, "TestTwoTimers: Start params Failed.\n"); - VerifyOrQuit(timer1.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(timer2.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n"); + VerifyOrQuit(timer1.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(timer2.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n"); otPlatAlarmMilliFired(instance); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestTwoTimers: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestTwoTimers: Handler CallCount Failed.\n"); - VerifyOrQuit(timer1.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n"); - VerifyOrQuit(sPlatT0 == sNow && sPlatDt == kTimerInterval, "TestTwoTimers: Start params Failed.\n"); - VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(timer2.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn == true, "TestTwoTimers: Platform Timer State Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestTwoTimers: Start CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestTwoTimers: Handler CallCount Failed.\n"); + VerifyOrQuit(timer1.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n"); + VerifyOrQuit(sPlatT0 == sNow && sPlatDt == kTimerInterval, "TestTwoTimers: Start params Failed.\n"); + VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(timer2.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn == true, "TestTwoTimers: Platform Timer State Failed.\n"); sNow += kTimerInterval; otPlatAlarmMilliFired(instance); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestTwoTimers: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestTwoTimers: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 2, "TestTwoTimers: Handler CallCount Failed.\n"); - VerifyOrQuit(timer2.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n"); - VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn == false, "TestTwoTimers: Platform Timer State Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestTwoTimers: Start CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestTwoTimers: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 2, "TestTwoTimers: Handler CallCount Failed.\n"); + VerifyOrQuit(timer2.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n"); + VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn == false, "TestTwoTimers: Platform Timer State Failed.\n"); // Test when second timer starts at the fire time of first timer (before otPlatAlarmMilliFired()) and its fire time // is before the first timer. Ensure that the second timer handler is invoked before the first one. @@ -306,45 +306,45 @@ int TestTwoTimers(void) sNow = kTimeT0; timer1.Start(kTimerInterval); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestTwoTimers: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTwoTimers: Handler CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestTwoTimers: Start CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTwoTimers: Handler CallCount Failed.\n"); VerifyOrQuit(sPlatT0 == kTimeT0 && sPlatDt == kTimerInterval, "TestTwoTimers: Start params Failed.\n"); - VerifyOrQuit(timer1.IsRunning(), "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n"); + VerifyOrQuit(timer1.IsRunning(), "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n"); sNow += kTimerInterval; - timer2.StartAt(kTimeT0, kTimerInterval - 2); // Timer 2 is even before timer 1 + timer2.StartAt(kTimeT0, kTimerInterval - 2); // Timer 2 is even before timer 1 - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTwoTimers: Handler CallCount Failed.\n"); - VerifyOrQuit(timer1.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(timer2.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTwoTimers: Handler CallCount Failed.\n"); + VerifyOrQuit(timer1.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(timer2.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n"); otPlatAlarmMilliFired(instance); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestTwoTimers: Handler CallCount Failed.\n"); - VerifyOrQuit(timer2.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n"); - VerifyOrQuit(sPlatT0 == sNow && sPlatDt == 0, "TestTwoTimers: Start params Failed.\n"); - VerifyOrQuit(timer1.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn == true, "TestTwoTimers: Platform Timer State Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestTwoTimers: Handler CallCount Failed.\n"); + VerifyOrQuit(timer2.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n"); + VerifyOrQuit(sPlatT0 == sNow && sPlatDt == 0, "TestTwoTimers: Start params Failed.\n"); + VerifyOrQuit(timer1.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn == true, "TestTwoTimers: Platform Timer State Failed.\n"); otPlatAlarmMilliFired(instance); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestTwoTimers: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 2, "TestTwoTimers: Handler CallCount Failed.\n"); - VerifyOrQuit(timer1.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n"); - VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn == false, "TestTwoTimers: Platform Timer State Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestTwoTimers: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 2, "TestTwoTimers: Handler CallCount Failed.\n"); + VerifyOrQuit(timer1.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n"); + VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn == false, "TestTwoTimers: Platform Timer State Failed.\n"); - // Timer 1 fire callback is late by some ticks/ms, and second timer is scheduled (before call to otPlatAlarmMilliFired) - // with a maximum interval. This is to test (corner-case) scenario where the fire time of two timers spanning over - // the maximum interval. + // Timer 1 fire callback is late by some ticks/ms, and second timer is scheduled (before call to + // otPlatAlarmMilliFired) with a maximum interval. This is to test (corner-case) scenario where the fire time of two + // timers spanning over the maximum interval. InitCounters(); timer1.ResetFiredCounter(); @@ -353,47 +353,47 @@ int TestTwoTimers(void) sNow = kTimeT0; timer1.Start(kTimerInterval); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestTwoTimers: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTwoTimers: Handler CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestTwoTimers: Start CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTwoTimers: Handler CallCount Failed.\n"); VerifyOrQuit(sPlatT0 == kTimeT0 && sPlatDt == kTimerInterval, "TestTwoTimers: Start params Failed.\n"); - VerifyOrQuit(timer1.IsRunning(), "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n"); + VerifyOrQuit(timer1.IsRunning(), "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n"); sNow += kTimerInterval + 5; timer2.Start(ot::Timer::kMaxDt); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestTwoTimers: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTwoTimers: Handler CallCount Failed.\n"); - VerifyOrQuit(timer1.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(timer2.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestTwoTimers: Start CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTwoTimers: Handler CallCount Failed.\n"); + VerifyOrQuit(timer1.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(timer2.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n"); otPlatAlarmMilliFired(instance); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestTwoTimers: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestTwoTimers: Handler CallCount Failed.\n"); - VerifyOrQuit(timer1.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n"); - VerifyOrQuit(sPlatT0 == sNow, "TestTwoTimers: Start params Failed.\n"); - VerifyOrQuit(sPlatDt == ot::Timer::kMaxDt, "TestTwoTimers: Start params Failed.\n"); - VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(timer2.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn == true, "TestTwoTimers: Platform Timer State Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestTwoTimers: Start CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestTwoTimers: Handler CallCount Failed.\n"); + VerifyOrQuit(timer1.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n"); + VerifyOrQuit(sPlatT0 == sNow, "TestTwoTimers: Start params Failed.\n"); + VerifyOrQuit(sPlatDt == ot::Timer::kMaxDt, "TestTwoTimers: Start params Failed.\n"); + VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(timer2.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn == true, "TestTwoTimers: Platform Timer State Failed.\n"); sNow += ot::Timer::kMaxDt; otPlatAlarmMilliFired(instance); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestTwoTimers: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestTwoTimers: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 2, "TestTwoTimers: Handler CallCount Failed.\n"); - VerifyOrQuit(timer2.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n"); - VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); - VerifyOrQuit(sTimerOn == false, "TestTwoTimers: Platform Timer State Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestTwoTimers: Start CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestTwoTimers: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 2, "TestTwoTimers: Handler CallCount Failed.\n"); + VerifyOrQuit(timer2.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n"); + VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); + VerifyOrQuit(sTimerOn == false, "TestTwoTimers: Platform Timer State Failed.\n"); printf(" --> PASSED\n"); @@ -410,34 +410,11 @@ int TestTwoTimers(void) */ static void TenTimers(uint32_t aTimeShift) { - const uint32_t kNumTimers = 10; - const uint32_t kNumTriggers = 7; - const uint32_t kTimeT0[kNumTimers] = - { - 1000, - 1000, - 1001, - 1002, - 1003, - 1004, - 1005, - 1006, - 1007, - 1008 - }; - const uint32_t kTimerInterval[kNumTimers] = - { - 20, - 100, - (ot::Timer::kMaxDt - kTimeT0[2]), - 100000, - 1000000, - 10, - ot::Timer::kMaxDt, - 200, - 200, - 200 - }; + const uint32_t kNumTimers = 10; + const uint32_t kNumTriggers = 7; + const uint32_t kTimeT0[kNumTimers] = {1000, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008}; + const uint32_t kTimerInterval[kNumTimers] = { + 20, 100, (ot::Timer::kMaxDt - kTimeT0[2]), 100000, 1000000, 10, ot::Timer::kMaxDt, 200, 200, 200}; // Expected timer fire order // timer # Trigger time // 5 1014 @@ -450,16 +427,8 @@ static void TenTimers(uint32_t aTimeShift) // 4 1001003 // 2 kMaxDt // 6 kMaxDt + 1005 - const uint32_t kTriggerTimes[kNumTriggers] = - { - 1014, - 1020, - 1100, - 1207, - 101004, - ot::Timer::kMaxDt, - ot::Timer::kMaxDt + kTimeT0[6] - }; + const uint32_t kTriggerTimes[kNumTriggers] = { + 1014, 1020, 1100, 1207, 101004, ot::Timer::kMaxDt, ot::Timer::kMaxDt + kTimeT0[6]}; // Expected timers fired by each kTriggerTimes[] value // Trigger # Timers Fired // 0 5 @@ -469,87 +438,39 @@ static void TenTimers(uint32_t aTimeShift) // 4 9, 3 // 5 4, 2 // 6 6 - const bool kTimerStateAfterTrigger [kNumTriggers][kNumTimers] = - { - { true, true, true, true, true, false, true, true, true, true}, // 5 - { false, true, true, true, true, false, true, true, true, true}, // 0 - { false, false, true, true, true, false, true, true, true, true}, // 1 - { false, false, true, true, true, false, true, false, false, true}, // 7, 8 - { false, false, true, false, true, false, true, false, false, false}, // 9, 3 - { false, false, false, false, false, false, true, false, false, false}, // 4, 2 - { false, false, false, false, false, false, false, false, false, false} // 6 + const bool kTimerStateAfterTrigger[kNumTriggers][kNumTimers] = { + {true, true, true, true, true, false, true, true, true, true}, // 5 + {false, true, true, true, true, false, true, true, true, true}, // 0 + {false, false, true, true, true, false, true, true, true, true}, // 1 + {false, false, true, true, true, false, true, false, false, true}, // 7, 8 + {false, false, true, false, true, false, true, false, false, false}, // 9, 3 + {false, false, false, false, false, false, true, false, false, false}, // 4, 2 + {false, false, false, false, false, false, false, false, false, false} // 6 }; - const bool kSchedulerStateAfterTrigger[kNumTriggers] = - { - true, - true, - true, - true, - true, - true, - false - }; + const bool kSchedulerStateAfterTrigger[kNumTriggers] = {true, true, true, true, true, true, false}; - const uint32_t kTimerHandlerCountAfterTrigger[kNumTriggers] = - { - 1, - 2, - 3, - 5, - 7, - 9, - 10 - }; + const uint32_t kTimerHandlerCountAfterTrigger[kNumTriggers] = {1, 2, 3, 5, 7, 9, 10}; - const uint32_t kTimerStopCountAfterTrigger[kNumTriggers] = - { - 0, - 0, - 0, - 0, - 0, - 0, - 1 - }; + const uint32_t kTimerStopCountAfterTrigger[kNumTriggers] = {0, 0, 0, 0, 0, 0, 1}; - const uint32_t kTimerStartCountAfterTrigger[kNumTriggers] = - { - 3, - 4, - 5, - 7, - 9, - 11, - 11 - }; + const uint32_t kTimerStartCountAfterTrigger[kNumTriggers] = {3, 4, 5, 7, 9, 11, 11}; ot::Instance *instance = testInitInstance(); - TestTimer timer0(*instance); - TestTimer timer1(*instance); - TestTimer timer2(*instance); - TestTimer timer3(*instance); - TestTimer timer4(*instance); - TestTimer timer5(*instance); - TestTimer timer6(*instance); - TestTimer timer7(*instance); - TestTimer timer8(*instance); - TestTimer timer9(*instance); - TestTimer *timers[kNumTimers] = - { - &timer0, - &timer1, - &timer2, - &timer3, - &timer4, - &timer5, - &timer6, - &timer7, - &timer8, - &timer9 - }; - size_t i; + TestTimer timer0(*instance); + TestTimer timer1(*instance); + TestTimer timer2(*instance); + TestTimer timer3(*instance); + TestTimer timer4(*instance); + TestTimer timer5(*instance); + TestTimer timer6(*instance); + TestTimer timer7(*instance); + TestTimer timer8(*instance); + TestTimer timer9(*instance); + TestTimer *timers[kNumTimers] = {&timer0, &timer1, &timer2, &timer3, &timer4, + &timer5, &timer6, &timer7, &timer8, &timer9}; + size_t i; printf("TestTenTimer() with aTimeShift=%-10u ", aTimeShift); @@ -558,7 +479,7 @@ static void TenTimers(uint32_t aTimeShift) InitTestTimer(); InitCounters(); - for (i = 0; i < kNumTimers ; i++) + for (i = 0; i < kNumTimers; i++) { sNow = kTimeT0[i] + aTimeShift; timers[i]->Start(kTimerInterval[i]); @@ -566,21 +487,21 @@ static void TenTimers(uint32_t aTimeShift) // given the order in which timers are started, the TimerScheduler should call otPlatAlarmMilliStartAt 2 times. // one for timer[0] and one for timer[5] which will supercede timer[0]. - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestTenTimer: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTenTimer: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTenTimer: Handler CallCount Failed.\n"); - VerifyOrQuit(sPlatT0 == kTimeT0[5] + aTimeShift, "TestTenTimer: Start params Failed.\n"); - VerifyOrQuit(sPlatDt == kTimerInterval[5], "TestTenTimer: Start params Failed.\n"); - VerifyOrQuit(sTimerOn, "TestTenTimer: Platform Timer State Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestTenTimer: Start CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTenTimer: Stop CallCount Failed.\n"); + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTenTimer: Handler CallCount Failed.\n"); + VerifyOrQuit(sPlatT0 == kTimeT0[5] + aTimeShift, "TestTenTimer: Start params Failed.\n"); + VerifyOrQuit(sPlatDt == kTimerInterval[5], "TestTenTimer: Start params Failed.\n"); + VerifyOrQuit(sTimerOn, "TestTenTimer: Platform Timer State Failed.\n"); - for (i = 0 ; i < kNumTimers ; i++) + for (i = 0; i < kNumTimers; i++) { VerifyOrQuit(timers[i]->IsRunning(), "TestTenTimer: Timer running Failed.\n"); } // Issue the triggers and test the State after each trigger. - for (size_t trigger = 0 ; trigger < kNumTriggers ; trigger++) + for (size_t trigger = 0; trigger < kNumTriggers; trigger++) { sNow = kTriggerTimes[trigger] + aTimeShift; @@ -590,31 +511,27 @@ static void TenTimers(uint32_t aTimeShift) // For some combinations of sNow and Timers queued, it is necessary to call otPlatAlarmMilliFired() // multiple times in order to handle all the expired timers. It can be determined that another // timer is ready to be triggered by examining the aDt arg passed into otPlatAlarmMilliStartAt(). If - // that value is 0, then otPlatAlarmMilliFired should be fired immediately. This loop calls otPlatAlarmMilliFired() - // the requisite number of times based on the aDt argument. + // that value is 0, then otPlatAlarmMilliFired should be fired immediately. This loop calls + // otPlatAlarmMilliFired() the requisite number of times based on the aDt argument. otPlatAlarmMilliFired(instance); - } - while (sPlatDt == 0); + } while (sPlatDt == 0); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == kTimerStartCountAfterTrigger[trigger], + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == kTimerStartCountAfterTrigger[trigger], "TestTenTimer: Start CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == kTimerStopCountAfterTrigger[trigger], + VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == kTimerStopCountAfterTrigger[trigger], "TestTenTimer: Stop CallCount Failed.\n"); - VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == kTimerHandlerCountAfterTrigger[trigger], + VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == kTimerHandlerCountAfterTrigger[trigger], "TestTenTimer: Handler CallCount Failed.\n"); - VerifyOrQuit(sTimerOn == kSchedulerStateAfterTrigger[trigger], - "TestTenTimer: Platform Timer State Failed.\n"); + VerifyOrQuit(sTimerOn == kSchedulerStateAfterTrigger[trigger], "TestTenTimer: Platform Timer State Failed.\n"); - for (i = 0 ; i < kNumTimers ; i++) + for (i = 0; i < kNumTimers; i++) { - VerifyOrQuit( - timers[i]->IsRunning() == kTimerStateAfterTrigger[trigger][i], - "TestTenTimer: Timer running Failed.\n" - ); + VerifyOrQuit(timers[i]->IsRunning() == kTimerStateAfterTrigger[trigger][i], + "TestTenTimer: Timer running Failed.\n"); } } - for (i = 0 ; i < kNumTimers ; i++) + for (i = 0; i < kNumTimers; i++) { VerifyOrQuit(timers[i]->GetFiredCounter() == 1, "TestTenTimer: Timer fired counter Failed.\n"); } @@ -627,14 +544,8 @@ static void TenTimers(uint32_t aTimeShift) int TestTenTimers(void) { // Time shift to change the start/fire time of ten timers. - const uint32_t kTimeShift[] = - { - 0, - 100000U, - 0U - 1U, - 0U - 1100U, - ot::Timer::kMaxDt, - ot::Timer::kMaxDt + 1020U, + const uint32_t kTimeShift[] = { + 0, 100000U, 0U - 1U, 0U - 1100U, ot::Timer::kMaxDt, ot::Timer::kMaxDt + 1020U, }; size_t i; diff --git a/tests/unit/test_toolchain.cpp b/tests/unit/test_toolchain.cpp index 4fbdf1352..7409604d4 100644 --- a/tests/unit/test_toolchain.cpp +++ b/tests/unit/test_toolchain.cpp @@ -30,14 +30,14 @@ #include -#include "thread/topology.hpp" #include "test_util.h" +#include "thread/topology.hpp" #include "utils/wrap_stdint.h" extern "C" { - uint32_t otNetifAddress_Size_c(); - uint32_t otNetifAddress_offset_mNext_c(); - otNetifAddress CreateNetif_c(); +uint32_t otNetifAddress_Size_c(); +uint32_t otNetifAddress_offset_mNext_c(); +otNetifAddress CreateNetif_c(); } void test_packed1() diff --git a/tests/unit/test_util.cpp b/tests/unit/test_util.cpp index 6f9d427ef..8caa4424e 100644 --- a/tests/unit/test_util.cpp +++ b/tests/unit/test_util.cpp @@ -36,7 +36,7 @@ void otTestHexToVector(std::string &aHex, std::vector &aOutBytes) { std::istringstream ss(aHex); - std::string word; + std::string word; while (ss >> word) { @@ -53,9 +53,15 @@ void otTestPrintHex(uint8_t *aBuffer, int aLength) { printf("%02x ", aBuffer[i]); - if (i % 16 == 7) { printf(" "); } + if (i % 16 == 7) + { + printf(" "); + } - if (i % 16 == 15 && aLength != i + 1) { printf("\n"); } + if (i % 16 == 15 && aLength != i + 1) + { + printf("\n"); + } } printf("\n"); diff --git a/tests/unit/test_util.h b/tests/unit/test_util.h index 36b17e621..14b7a30c0 100644 --- a/tests/unit/test_util.h +++ b/tests/unit/test_util.h @@ -43,23 +43,25 @@ extern "C" { // Enable main functions #define ENABLE_TEST_MAIN -#define SuccessOrQuit(ERR, MSG) \ - do { \ - if ((ERR) != OT_ERROR_NONE) \ - { \ - fprintf(stderr, "\nFAILED %s:%d - %s\n", __FUNCTION__, __LINE__, MSG); \ - exit(-1); \ - } \ - } while (false) +#define SuccessOrQuit(ERR, MSG) \ + do \ + { \ + if ((ERR) != OT_ERROR_NONE) \ + { \ + fprintf(stderr, "\nFAILED %s:%d - %s\n", __FUNCTION__, __LINE__, MSG); \ + exit(-1); \ + } \ + } while (false) -#define VerifyOrQuit(TST, MSG) \ - do { \ - if (!(TST)) \ - { \ - fprintf(stderr, "\nFAILED %s:%d - %s\n", __FUNCTION__, __LINE__, MSG); \ - exit(-1); \ - } \ - } while (false) +#define VerifyOrQuit(TST, MSG) \ + do \ + { \ + if (!(TST)) \ + { \ + fprintf(stderr, "\nFAILED %s:%d - %s\n", __FUNCTION__, __LINE__, MSG); \ + exit(-1); \ + } \ + } while (false) //#define CompileTimeAssert(COND, MSG) typedef char __C_ASSERT__[(COND)?1:-1] @@ -70,7 +72,7 @@ extern "C" { // #define CompileTimeAssert(COND, MSG) -#define Log(aFormat, ...) printf(aFormat "\n", ## __VA_ARGS__) +#define Log(aFormat, ...) printf(aFormat "\n", ##__VA_ARGS__) #ifdef __cplusplus } @@ -90,7 +92,7 @@ extern utLogMessage s_LogMessage; #define CompileTimeAssert(COND, MSG) static_assert(COND, MSG) -#define Log(aFormat, ...) s_LogMessage(aFormat, ## __VA_ARGS__) +#define Log(aFormat, ...) s_LogMessage(aFormat, ##__VA_ARGS__) #endif