diff --git a/.astyleignore b/.astyleignore new file mode 100644 index 00000000000..bac5af58f0c --- /dev/null +++ b/.astyleignore @@ -0,0 +1,17 @@ +BUILD +cmsis +features/mbedtls +features/FEATURE_LWIP/lwip +rtos/TARGET_CORTEX/rtx4 +features/filesystem/littlefs/littlefs +features/filesystem/fat/ChaN +features/frameworks +features/FEATURE_BLE/targets +features/FEATURE_LWIP/lwip-interface/lwip +features/unsupported/ +features/FEATURE_COMMON_PAL/ +FEATURE_NANOSTACK/coap-service +FEATURE_NANOSTACK/sal-stack-nanostack +rtos/TARGET_CORTEX/rtx5 +targets +tools diff --git a/.astylerc b/.astylerc new file mode 100644 index 00000000000..b208b767a79 --- /dev/null +++ b/.astylerc @@ -0,0 +1,34 @@ +# Mbed OS code style definition file for astyle + +# Don't create backup files, let git handle it +suffix=none + +# K&R style +style=kr + +# 1 TBS addition to k&r, add braces to one liners +# Use -j as it was changed in astyle from brackets to braces, this way it is compatible with older astyle versions +-j + +# 4 spaces, convert tabs to spaces +indent=spaces=4 +convert-tabs + +# Indent switches and cases +indent-switches +indent-cases + +# Remove spaces in and around parentheses +unpad-paren + +# Insert a space after if, while, for, and around operators +pad-header +pad-oper + +# Pointer/reference operators go next to the name (on the right) +align-pointer=name +align-reference=name + +# Attach { for classes and namespaces +attach-namespaces +attach-classes diff --git a/.travis.yml b/.travis.yml index 9de36780801..19e19e1be69 100644 --- a/.travis.yml +++ b/.travis.yml @@ -94,6 +94,41 @@ matrix: # Report success since we have overridden default behaviour - bash -c "$STATUS" success "Local $NAME testing has passed" + - env: + - NAME=astyle + install: + - wget https://downloads.sourceforge.net/project/astyle/astyle/astyle%203.1/astyle_3.1_linux.tar.gz; + mkdir -p BUILD && tar xf astyle_3.1_linux.tar.gz -C BUILD; + pushd BUILD/astyle/build/gcc; + make; + export PATH=$PWD/bin:$PATH; + popd; + - astyle --version + script: + - find -regex '.*\.\(h\|c\|hpp\|cpp\)' -type f | fgrep -v -f .astyleignore | xargs -n 100 -I {} bash -c "astyle -n --options=.astylerc \"{}\"" > astyle.out; + if [ $(cat astyle.out | grep Formatted | wc -l) -ne 0 ]; then + git --no-pager diff; + echo "Please fix style issues as shown above"; + else + echo "Coding style check OK"; + fi + after_success: + # update status if we succeeded, compare with master if possible + - | + CURR=$(cat astyle.out | grep Formatted | wc -l) + PREV=$(curl https://api.github.com/repos/$TRAVIS_REPO_SLUG/status/master \ + | jq -re "select(.sha != \"$TRAVIS_COMMIT\") + | .statuses[] | select(.context == \"travis-ci/$NAME\").description + | capture(\", (?[0-9]+) warnings\").warnings" \ + || echo 0) + + STATUSM="Passed, ${CURR} warnings" + if [ "$PREV" -ne 0 ] + then + STATUSM="$STATUSM ($(python -c "print '%+d' % ($CURR-$PREV)") warnings)" + fi + - bash -c "$STATUS" success "$STATUSM" + - env: - NAME=events - EVENTS=events diff --git a/TESTS/events/queue/main.cpp b/TESTS/events/queue/main.cpp index 738fdd0d8dc..0857bfb3397 100644 --- a/TESTS/events/queue/main.cpp +++ b/TESTS/events/queue/main.cpp @@ -31,32 +31,38 @@ using namespace utest::v1; volatile bool touched = false; // static functions -void func5(int a0, int a1, int a2, int a3, int a4) { +void func5(int a0, int a1, int a2, int a3, int a4) +{ touched = true; TEST_ASSERT_EQUAL(a0 | a1 | a2 | a3 | a4, 0x1f); } -void func4(int a0, int a1, int a2, int a3) { +void func4(int a0, int a1, int a2, int a3) +{ touched = true; - TEST_ASSERT_EQUAL(a0 | a1 | a2 | a3, 0xf); + TEST_ASSERT_EQUAL(a0 | a1 | a2 | a3, 0xf); } -void func3(int a0, int a1, int a2) { +void func3(int a0, int a1, int a2) +{ touched = true; TEST_ASSERT_EQUAL(a0 | a1 | a2, 0x7); } -void func2(int a0, int a1) { +void func2(int a0, int a1) +{ touched = true; TEST_ASSERT_EQUAL(a0 | a1, 0x3); } -void func1(int a0) { +void func1(int a0) +{ touched = true; TEST_ASSERT_EQUAL(a0, 0x1); } -void func0() { +void func0() +{ touched = true; } @@ -88,40 +94,44 @@ SIMPLE_POSTS_TEST(1, 0x01) SIMPLE_POSTS_TEST(0) -void time_func(Timer *t, int ms) { +void time_func(Timer *t, int ms) +{ TEST_ASSERT_INT_WITHIN(5, ms, t->read_ms()); t->reset(); } template -void call_in_test() { +void call_in_test() +{ Timer tickers[N]; EventQueue queue(TEST_EQUEUE_SIZE); for (int i = 0; i < N; i++) { tickers[i].start(); - queue.call_in((i+1)*100, time_func, &tickers[i], (i+1)*100); + queue.call_in((i + 1) * 100, time_func, &tickers[i], (i + 1) * 100); } - queue.dispatch(N*100); + queue.dispatch(N * 100); } template -void call_every_test() { +void call_every_test() +{ Timer tickers[N]; EventQueue queue(TEST_EQUEUE_SIZE); for (int i = 0; i < N; i++) { tickers[i].start(); - queue.call_every((i+1)*100, time_func, &tickers[i], (i+1)*100); + queue.call_every((i + 1) * 100, time_func, &tickers[i], (i + 1) * 100); } - queue.dispatch(N*100); + queue.dispatch(N * 100); } -void allocate_failure_test() { +void allocate_failure_test() +{ EventQueue queue(TEST_EQUEUE_SIZE); int id; @@ -132,12 +142,14 @@ void allocate_failure_test() { TEST_ASSERT(!id); } -void no() { +void no() +{ TEST_ASSERT(false); } template -void cancel_test1() { +void cancel_test1() +{ EventQueue queue(TEST_EQUEUE_SIZE); int ids[N]; @@ -146,7 +158,7 @@ void cancel_test1() { ids[i] = queue.call_in(1000, no); } - for (int i = N-1; i >= 0; i--) { + for (int i = N - 1; i >= 0; i--) { queue.cancel(ids[i]); } @@ -157,31 +169,38 @@ void cancel_test1() { // Testing the dynamic arguments to the event class unsigned counter = 0; -void count5(unsigned a0, unsigned a1, unsigned a2, unsigned a3, unsigned a5) { +void count5(unsigned a0, unsigned a1, unsigned a2, unsigned a3, unsigned a5) +{ counter += a0 + a1 + a2 + a3 + a5; } -void count4(unsigned a0, unsigned a1, unsigned a2, unsigned a3) { +void count4(unsigned a0, unsigned a1, unsigned a2, unsigned a3) +{ counter += a0 + a1 + a2 + a3; } -void count3(unsigned a0, unsigned a1, unsigned a2) { +void count3(unsigned a0, unsigned a1, unsigned a2) +{ counter += a0 + a1 + a2; } -void count2(unsigned a0, unsigned a1) { +void count2(unsigned a0, unsigned a1) +{ counter += a0 + a1; } -void count1(unsigned a0) { +void count1(unsigned a0) +{ counter += a0; } -void count0() { +void count0() +{ counter += 0; } -void event_class_test() { +void event_class_test() +{ counter = 0; EventQueue queue(TEST_EQUEUE_SIZE); @@ -204,7 +223,8 @@ void event_class_test() { TEST_ASSERT_EQUAL(counter, 30); } -void event_class_helper_test() { +void event_class_helper_test() +{ counter = 0; EventQueue queue(TEST_EQUEUE_SIZE); @@ -227,7 +247,8 @@ void event_class_helper_test() { TEST_ASSERT_EQUAL(counter, 15); } -void event_inference_test() { +void event_inference_test() +{ counter = 0; EventQueue queue(TEST_EQUEUE_SIZE); @@ -252,7 +273,8 @@ void event_inference_test() { // Test setup -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(20, "default_auto"); return verbose_test_setup_handler(number_of_cases); } @@ -278,7 +300,8 @@ const Case cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/TESTS/events/timing/main.cpp b/TESTS/events/timing/main.cpp index 74ec8f949f9..6f93518e8a1 100644 --- a/TESTS/events/timing/main.cpp +++ b/TESTS/events/timing/main.cpp @@ -39,16 +39,18 @@ using namespace utest::v1; #endif // Random number generation to skew timing values -float gauss(float mu, float sigma) { - float x = (float)rand() / ((float)RAND_MAX+1); - float y = (float)rand() / ((float)RAND_MAX+1); - float x2pi = x*2.0*M_PI; - float g2rad = sqrt(-2.0 * log(1.0-y)); +float gauss(float mu, float sigma) +{ + float x = (float)rand() / ((float)RAND_MAX + 1); + float y = (float)rand() / ((float)RAND_MAX + 1); + float x2pi = x * 2.0 * M_PI; + float g2rad = sqrt(-2.0 * log(1.0 - y)); float z = cos(x2pi) * g2rad; - return mu + z*sigma; + return mu + z * sigma; } -float chisq(float sigma) { +float chisq(float sigma) +{ return pow(gauss(0, sqrt(sigma)), 2); } @@ -59,16 +61,17 @@ DigitalOut led(LED1); equeue_sema_t sema; // Timer timing test -void timer_timing_test() { +void timer_timing_test() +{ timer.reset(); timer.start(); int prev = timer.read_us(); - while (prev < TEST_EVENTS_TIMING_TIME*1000) { + while (prev < TEST_EVENTS_TIMING_TIME * 1000) { int next = timer.read_us(); if (next < prev) { printf("backwards drift %d -> %d (%08x -> %08x)\r\n", - prev, next, prev, next); + prev, next, prev, next); } TEST_ASSERT(next >= prev); prev = next; @@ -76,7 +79,8 @@ void timer_timing_test() { } // equeue tick timing test -void tick_timing_test() { +void tick_timing_test() +{ unsigned start = equeue_tick(); int prev = 0; @@ -84,7 +88,7 @@ void tick_timing_test() { int next = equeue_tick() - start; if (next < prev) { printf("backwards drift %d -> %d (%08x -> %08x)\r\n", - prev, next, prev, next); + prev, next, prev, next); } TEST_ASSERT(next >= prev); prev = next; @@ -92,7 +96,8 @@ void tick_timing_test() { } // equeue semaphore timing test -void semaphore_timing_test() { +void semaphore_timing_test() +{ srand(0); timer.reset(); timer.start(); @@ -121,8 +126,9 @@ void semaphore_timing_test() { // Test setup -utest::v1::status_t test_setup(const size_t number_of_cases) { - GREENTEA_SETUP((number_of_cases+1)*TEST_EVENTS_TIMING_TIME/1000, "default_auto"); +utest::v1::status_t test_setup(const size_t number_of_cases) +{ + GREENTEA_SETUP((number_of_cases + 1)*TEST_EVENTS_TIMING_TIME / 1000, "default_auto"); return verbose_test_setup_handler(number_of_cases); } @@ -134,7 +140,8 @@ const Case cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/TESTS/integration/basic/main.cpp b/TESTS/integration/basic/main.cpp index ec202446879..3989aada9a4 100644 --- a/TESTS/integration/basic/main.cpp +++ b/TESTS/integration/basic/main.cpp @@ -15,7 +15,8 @@ */ #include "test_env.h" -int main() { +int main() +{ GREENTEA_SETUP(15, "default_auto"); GREENTEA_TESTSUITE_RESULT(true); } diff --git a/TESTS/mbed_drivers/c_strings/main.cpp b/TESTS/mbed_drivers/c_strings/main.cpp index 68a25e068dc..beb69e15c1f 100644 --- a/TESTS/mbed_drivers/c_strings/main.cpp +++ b/TESTS/mbed_drivers/c_strings/main.cpp @@ -33,68 +33,76 @@ static char buffer[256] = {0}; using namespace utest::v1; -void test_case_c_string_i_d() { +void test_case_c_string_i_d() +{ CLEAN_BUFFER; sprintf(buffer, "%i %d %i %d %i %d %i %d %i %d %i %i", NEGATIVE_INTEGERS); TEST_ASSERT_EQUAL_STRING("-32768 -3214 -999 -100 -1 0 -1 -4231 -999 -4123 -32760 -99999", buffer); } -void test_case_c_string_u_d() { +void test_case_c_string_u_d() +{ CLEAN_BUFFER; sprintf(buffer, "%u %d %u %d %u %d %u %d %u %d %u %d", POSITIVE_INTEGERS); TEST_ASSERT_EQUAL_STRING("32768 3214 999 100 1 0 1 4231 999 4123 32760 99999", buffer); } -void test_case_c_string_x_E() { +void test_case_c_string_x_E() +{ CLEAN_BUFFER; sprintf(buffer, "%x %X %x %X %x %X %x %X %x %X %x %X", POSITIVE_INTEGERS); TEST_ASSERT_EQUAL_STRING("8000 C8E 3e7 64 1 0 1 1087 3e7 101B 7ff8 1869F", buffer); } -void test_case_c_string_f_f() { +void test_case_c_string_f_f() +{ CLEAN_BUFFER; sprintf(buffer, "%f %f %f %f %f %f %f %f %f %f", FLOATS); TEST_ASSERT_EQUAL_STRING("0.002000 0.924300 15.913200 791.773680 6208.200000 25719.495200 426815.982588 6429271.046000 42468024.930000 212006462.910000", buffer); } -void test_case_c_string_g_g() { +void test_case_c_string_g_g() +{ CLEAN_BUFFER; sprintf(buffer, "%g %g %g %g %g %g %g %g %g %g", FLOATS); TEST_ASSERT_EQUAL_STRING("0.002 0.9243 15.9132 791.774 6208.2 25719.5 426816 6.42927e+06 4.2468e+07 2.12006e+08", buffer); } -void test_case_c_string_e_E() { +void test_case_c_string_e_E() +{ CLEAN_BUFFER; sprintf(buffer, "%e %E %e %E %e %E %e %E %e %E", FLOATS); TEST_ASSERT_EQUAL_STRING("2.000000e-03 9.243000E-01 1.591320e+01 7.917737E+02 6.208200e+03 2.571950E+04 4.268160e+05 6.429271E+06 4.246802e+07 2.120065E+08", buffer); } -void test_case_c_string_strtok() { +void test_case_c_string_strtok() +{ CLEAN_BUFFER; - char str[] ="- This, a sample string."; - char * pch = strtok (str," ,.-"); + char str[] = "- This, a sample string."; + char *pch = strtok(str, " ,.-"); while (pch != NULL) { strcat(buffer, pch); - pch = strtok (NULL, " ,.-"); + pch = strtok(NULL, " ,.-"); } TEST_ASSERT_EQUAL_STRING("Thisasamplestring", buffer); } -void test_case_c_string_strpbrk() { +void test_case_c_string_strpbrk() +{ CLEAN_BUFFER; char str[] = "This is a sample string"; char key[] = "aeiou"; char *pch = strpbrk(str, key); - while (pch != NULL) - { + while (pch != NULL) { char buf[2] = {*pch, '\0'}; strcat(buffer, buf); - pch = strpbrk(pch + 1,key); + pch = strpbrk(pch + 1, key); } TEST_ASSERT_EQUAL_STRING("iiaaei", buffer); } -utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) { +utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) +{ greentea_case_failure_abort_handler(source, reason); return STATUS_CONTINUE; } @@ -110,13 +118,15 @@ Case cases[] = { Case("C strings: %g %g float formatting", test_case_c_string_g_g, greentea_failure_handler), }; -utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { +utest::v1::status_t greentea_test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(5, "default_auto"); return greentea_test_setup_handler(number_of_cases); } Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); -int main() { +int main() +{ Harness::run(specification); } diff --git a/TESTS/mbed_drivers/dev_null/main.cpp b/TESTS/mbed_drivers/dev_null/main.cpp index 5513ca64fc4..880979282e3 100644 --- a/TESTS/mbed_drivers/dev_null/main.cpp +++ b/TESTS/mbed_drivers/dev_null/main.cpp @@ -22,17 +22,20 @@ class DevNull : public Stream { DevNull(const char *name = NULL) : Stream(name) {} protected: - virtual int _getc() { + virtual int _getc() + { return 0; } - virtual int _putc(int c) { + virtual int _putc(int c) + { return c; } }; DevNull null("null"); -int main() { +int main() +{ GREENTEA_SETUP(2, "dev_null_auto"); printf("MBED: before re-routing stdout to /null\n"); // This shouldn't appear @@ -45,7 +48,7 @@ int main() { printf("MBED: this printf is already redirected to /null\n"); } - while(1) { - // Success is determined by the host test at this point, so busy wait + while (1) { + // Success is determined by the host test at this point, so busy wait } } diff --git a/TESTS/mbed_drivers/echo/main.cpp b/TESTS/mbed_drivers/echo/main.cpp index 6388299c401..95c97ce07a7 100644 --- a/TESTS/mbed_drivers/echo/main.cpp +++ b/TESTS/mbed_drivers/echo/main.cpp @@ -25,7 +25,8 @@ using namespace utest::v1; // Echo server (echo payload to host) template -void test_case_echo_server_x() { +void test_case_echo_server_x() +{ char _key[11] = {}; char _value[128] = {}; const int echo_count = N; @@ -40,13 +41,14 @@ void test_case_echo_server_x() { } while (expected_key); TEST_ASSERT_EQUAL_INT(echo_count, atoi(_value)); - for (int i=0; i < echo_count; ++i) { + for (int i = 0; i < echo_count; ++i) { greentea_parse_kv(_key, _value, sizeof(_key), sizeof(_value)); greentea_send_kv(_key, _value); } } -utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) { +utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) +{ greentea_case_failure_abort_handler(source, reason); return STATUS_CONTINUE; } @@ -55,13 +57,15 @@ Case cases[] = { Case("Echo server: x16", test_case_echo_server_x<16>, greentea_failure_handler), }; -utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { +utest::v1::status_t greentea_test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(30, "echo"); return greentea_test_setup_handler(number_of_cases); } Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); -int main() { +int main() +{ Harness::run(specification); } diff --git a/TESTS/mbed_drivers/flashiap/main.cpp b/TESTS/mbed_drivers/flashiap/main.cpp index 48c207104ed..5f468db3c12 100644 --- a/TESTS/mbed_drivers/flashiap/main.cpp +++ b/TESTS/mbed_drivers/flashiap/main.cpp @@ -16,7 +16,7 @@ */ #if !DEVICE_FLASH - #error [NOT_SUPPORTED] Flash API not supported for this target +#error [NOT_SUPPORTED] Flash API not supported for this target #endif #include "utest/utest.h" @@ -174,13 +174,15 @@ Case cases[] = { Case("FlashIAP - program errors", flashiap_program_error_test), }; -utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { +utest::v1::status_t greentea_test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(20, "default_auto"); return greentea_test_setup_handler(number_of_cases); } Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); -int main() { +int main() +{ Harness::run(specification); } diff --git a/TESTS/mbed_drivers/generic_tests/main.cpp b/TESTS/mbed_drivers/generic_tests/main.cpp index dc177e3f4d5..6c30816dc85 100644 --- a/TESTS/mbed_drivers/generic_tests/main.cpp +++ b/TESTS/mbed_drivers/generic_tests/main.cpp @@ -28,48 +28,56 @@ using namespace utest::v1; class CppTestCaseHelperClass { private: - const char* name; + const char *name; const unsigned pattern; public: - CppTestCaseHelperClass(const char* _name) : name(_name), pattern(PATTERN_CHECK_VALUE) { + CppTestCaseHelperClass(const char *_name) : name(_name), pattern(PATTERN_CHECK_VALUE) + { print("init"); } - void print(const char *message) { + void print(const char *message) + { printf("%s::%s\n", name, message); } - bool check_init(void) { + bool check_init(void) + { bool result = (pattern == PATTERN_CHECK_VALUE); print(result ? "check_init: OK" : "check_init: ERROR"); return result; } - void stack_test(void) { + void stack_test(void) + { print("stack_test"); CppTestCaseHelperClass t("Stack"); t.hello(); } - void hello(void) { + void hello(void) + { print("hello"); } - ~CppTestCaseHelperClass() { + ~CppTestCaseHelperClass() + { print("destroy"); } }; -void test_case_basic() { +void test_case_basic() +{ TEST_ASSERT_TRUE(true); TEST_ASSERT_FALSE(false); TEST_ASSERT_EQUAL_STRING("The quick brown fox jumps over the lazy dog", - "The quick brown fox jumps over the lazy dog"); + "The quick brown fox jumps over the lazy dog"); } -void test_case_blinky() { +void test_case_blinky() +{ static DigitalOut myled(LED1); const int cnt_max = 1024; for (int cnt = 0; cnt < cnt_max; ++cnt) { @@ -77,7 +85,8 @@ void test_case_blinky() { } } -void test_case_cpp_stack() { +void test_case_cpp_stack() +{ // Check C++ start-up initialisation CppTestCaseHelperClass s("Static"); @@ -86,7 +95,8 @@ void test_case_cpp_stack() { TEST_ASSERT_TRUE_MESSAGE(s.check_init(), "s.check_init() failed"); } -void test_case_cpp_heap() { +void test_case_cpp_heap() +{ // Heap test object simple test CppTestCaseHelperClass *m = new CppTestCaseHelperClass("Heap"); m->hello(); @@ -94,7 +104,8 @@ void test_case_cpp_heap() { delete m; } -utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) { +utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) +{ greentea_case_failure_abort_handler(source, reason); return STATUS_CONTINUE; } @@ -107,13 +118,15 @@ Case cases[] = { Case("C++ heap", test_case_cpp_heap, greentea_failure_handler) }; -utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { +utest::v1::status_t greentea_test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(20, "default_auto"); return greentea_test_setup_handler(number_of_cases); } Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); -int main() { +int main() +{ Harness::run(specification); } diff --git a/TESTS/mbed_drivers/lp_ticker/main.cpp b/TESTS/mbed_drivers/lp_ticker/main.cpp index aeb36765f1a..72103aecce6 100644 --- a/TESTS/mbed_drivers/lp_ticker/main.cpp +++ b/TESTS/mbed_drivers/lp_ticker/main.cpp @@ -20,7 +20,7 @@ #if !DEVICE_LOWPOWERTIMER - #error [NOT_SUPPORTED] Low power ticker not supported for this target +#error [NOT_SUPPORTED] Low power ticker not supported for this target #endif using utest::v1::Case; @@ -52,12 +52,12 @@ void sem_release(Semaphore *sem) void stop_gtimer_set_flag(void) { gtimer.stop(); - core_util_atomic_incr_u32((uint32_t*)&ticker_callback_flag, 1); + core_util_atomic_incr_u32((uint32_t *)&ticker_callback_flag, 1); } void increment_multi_counter(void) { - core_util_atomic_incr_u32((uint32_t*)&multi_counter, 1);; + core_util_atomic_incr_u32((uint32_t *)&multi_counter, 1);; } /** Test many tickers run one after the other @@ -80,7 +80,7 @@ void test_multi_ticker(void) Thread::wait(MULTI_TICKER_TIME_MS + extra_wait); for (int i = 0; i < TICKER_COUNT; i++) { - ticker[i].detach(); + ticker[i].detach(); } TEST_ASSERT_EQUAL(TICKER_COUNT, multi_counter); @@ -114,7 +114,7 @@ void test_multi_call_time(void) gtimer.start(); ticker.attach_us(callback(stop_gtimer_set_flag), MULTI_TICKER_TIME_MS * 1000); - while(!ticker_callback_flag); + while (!ticker_callback_flag); time_diff = gtimer.read_us(); TEST_ASSERT_UINT32_WITHIN(TOLERANCE_US, MULTI_TICKER_TIME_MS * 1000, time_diff); @@ -163,7 +163,7 @@ void test_attach_time(void) gtimer.reset(); gtimer.start(); ticker.attach(callback(stop_gtimer_set_flag), ((float)DELAY_US) / 1000000.0f); - while(!ticker_callback_flag); + while (!ticker_callback_flag); ticker.detach(); const int time_diff = gtimer.read_us(); @@ -185,7 +185,7 @@ void test_attach_us_time(void) gtimer.reset(); gtimer.start(); ticker.attach_us(callback(stop_gtimer_set_flag), DELAY_US); - while(!ticker_callback_flag); + while (!ticker_callback_flag); ticker.detach(); const int time_diff = gtimer.read_us(); diff --git a/TESTS/mbed_drivers/lp_timeout/main.cpp b/TESTS/mbed_drivers/lp_timeout/main.cpp index 9a16d6bdfbd..2d7c251e538 100644 --- a/TESTS/mbed_drivers/lp_timeout/main.cpp +++ b/TESTS/mbed_drivers/lp_timeout/main.cpp @@ -15,7 +15,7 @@ */ #if !DEVICE_LOWPOWERTIMER - #error [NOT_SUPPORTED] Low power timer not supported for this target +#error [NOT_SUPPORTED] Low power timer not supported for this target #endif #include "utest/utest.h" @@ -33,7 +33,8 @@ static LowPowerTimeout lpt; #define LONG_TIMEOUT (100000) #define SHORT_TIMEOUT (600) -void cb_done() { +void cb_done() +{ complete = true; } @@ -124,7 +125,8 @@ void lp_timeout_500us(void) } -utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) { +utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) +{ greentea_case_failure_abort_handler(source, reason); return STATUS_CONTINUE; } @@ -140,13 +142,15 @@ Case cases[] = { #endif /* DEVICE_SLEEP */ }; -utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { +utest::v1::status_t greentea_test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(20, "default_auto"); return greentea_test_setup_handler(number_of_cases); } Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); -int main() { +int main() +{ Harness::run(specification); } diff --git a/TESTS/mbed_drivers/lp_timer/main.cpp b/TESTS/mbed_drivers/lp_timer/main.cpp index a7232149a30..4eed305142b 100644 --- a/TESTS/mbed_drivers/lp_timer/main.cpp +++ b/TESTS/mbed_drivers/lp_timer/main.cpp @@ -61,13 +61,13 @@ extern uint32_t SystemCoreClock; #define US_FACTOR 1000000.0f #define CLOCK_MAX 130000000 -static const int delta_sys_clk_us = (SystemCoreClock < CLOCK_MAX? ((int) (TOLERANCE_FACTOR / (float) SystemCoreClock * US_FACTOR)):((int) (TOLERANCE_FACTOR / (float) CLOCK_MAX * US_FACTOR))); +static const int delta_sys_clk_us = (SystemCoreClock < CLOCK_MAX ? ((int)(TOLERANCE_FACTOR / (float) SystemCoreClock *US_FACTOR)) : ((int)(TOLERANCE_FACTOR / (float) CLOCK_MAX *US_FACTOR))); /* When test performs time measurement using Timer in sequence, then measurement error accumulates * in the successive attempts. */ - #define DELTA_US(i) (delta_sys_clk_us * i) - #define DELTA_S(i) ((float)delta_sys_clk_us * i / US_PER_SEC) - #define DELTA_MS(i) (1 + ( (i * delta_sys_clk_us) / US_PER_MSEC)) +#define DELTA_US(i) (delta_sys_clk_us * i) +#define DELTA_S(i) ((float)delta_sys_clk_us * i / US_PER_SEC) +#define DELTA_MS(i) (1 + ( (i * delta_sys_clk_us) / US_PER_MSEC)) /* This test verifies if low power timer is stopped after * creation. @@ -294,7 +294,7 @@ void test_lptimer_float_operator() lp_timer.stop(); /* Check result - 10 ms elapsed. */ - TEST_ASSERT_FLOAT_WITHIN(DELTA_S(1), 0.010f, (float )(lp_timer)); + TEST_ASSERT_FLOAT_WITHIN(DELTA_S(1), 0.010f, (float)(lp_timer)); } /* This test verifies if time counted by the low power timer is @@ -320,7 +320,7 @@ void test_lptimer_time_measurement() lp_timer.stop(); /* Check results - wait_val_us us have elapsed. */ - TEST_ASSERT_FLOAT_WITHIN(DELTA_S(1), (float )wait_val_us / 1000000, lp_timer.read()); + TEST_ASSERT_FLOAT_WITHIN(DELTA_S(1), (float)wait_val_us / 1000000, lp_timer.read()); TEST_ASSERT_INT32_WITHIN(DELTA_MS(1), wait_val_us / 1000, lp_timer.read_ms()); TEST_ASSERT_INT32_WITHIN(DELTA_US(1), wait_val_us, lp_timer.read_us()); TEST_ASSERT_UINT64_WITHIN(DELTA_US(1), wait_val_us, lp_timer.read_high_resolution_us()); diff --git a/TESTS/mbed_drivers/mem_trace/main.cpp b/TESTS/mbed_drivers/mem_trace/main.cpp index 286be0377b0..77dd39716ca 100644 --- a/TESTS/mbed_drivers/mem_trace/main.cpp +++ b/TESTS/mbed_drivers/mem_trace/main.cpp @@ -25,7 +25,7 @@ #include #ifndef MBED_MEM_TRACING_ENABLED - #error [NOT_SUPPORTED] test not supported +#error [NOT_SUPPORTED] test not supported #endif using utest::v1::Case; @@ -99,7 +99,7 @@ extern "C" void test_trace_cb(uint8_t op, void *res, void *caller, ...) va_start(va, caller); pmem->op = op; pmem->res = res; - switch(op) { + switch (op) { case MBED_MEM_TRACE_MALLOC: pmem->malloc_info.arg_size = va_arg(va, size_t); break; @@ -180,7 +180,7 @@ void malloc_free(volatile bool *thread_continue) { const size_t block_size = 126; - while(*thread_continue) { + while (*thread_continue) { void *p = malloc(block_size); TEST_ASSERT_NOT_EQUAL(p, NULL); free(p); @@ -403,8 +403,7 @@ static void test_case_multithread_malloc_free() -static Case cases[] = -{ +static Case cases[] = { Case("Test single malloc/free trace", test_case_single_malloc_free), Case("Test all memory operations trace", test_case_all_memory_ops), Case("Test trace off", test_case_trace_off), diff --git a/TESTS/mbed_drivers/race_test/main.cpp b/TESTS/mbed_drivers/race_test/main.cpp index 48ce06a6f70..6d0da127ead 100644 --- a/TESTS/mbed_drivers/race_test/main.cpp +++ b/TESTS/mbed_drivers/race_test/main.cpp @@ -23,7 +23,7 @@ #include #ifdef MBED_RTOS_SINGLE_THREAD - #error [NOT_SUPPORTED] test not supported for single threaded enviroment +#error [NOT_SUPPORTED] test not supported for single threaded enviroment #endif using namespace utest::v1; @@ -33,21 +33,24 @@ static uint32_t instance_count = 0; class TestClass { public: - TestClass() { + TestClass() + { Thread::wait(500); instance_count++; } - void do_something() { + void do_something() + { Thread::wait(100); } - ~TestClass() { + ~TestClass() + { instance_count--; } }; -static TestClass* get_test_class() +static TestClass *get_test_class() { static TestClass tc; return &tc; diff --git a/TESTS/mbed_drivers/rtc/main.cpp b/TESTS/mbed_drivers/rtc/main.cpp index 141dee2659e..8cac2dda258 100644 --- a/TESTS/mbed_drivers/rtc/main.cpp +++ b/TESTS/mbed_drivers/rtc/main.cpp @@ -56,9 +56,9 @@ static time_t read_rtc_stub(void) /* Stub of RTC write function. */ static void write_rtc_stub(time_t t) { - rtc_write_called = true; + rtc_write_called = true; - rtc_time_val = t; + rtc_time_val = t; } /* Stub of RTC init function. */ @@ -294,7 +294,7 @@ void test_time_read_RTC_func_undefined() seconds = time(NULL); /* Check if expected value has been returned. */ - TEST_ASSERT_EQUAL((time_t)-1, seconds); + TEST_ASSERT_EQUAL((time_t) -1, seconds); } /* This test verifies if time() function stores @@ -490,6 +490,7 @@ Case cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/TESTS/mbed_drivers/sleep_lock/main.cpp b/TESTS/mbed_drivers/sleep_lock/main.cpp index 2e1bcbd80a2..234c70dc2d2 100644 --- a/TESTS/mbed_drivers/sleep_lock/main.cpp +++ b/TESTS/mbed_drivers/sleep_lock/main.cpp @@ -16,7 +16,7 @@ */ #if !DEVICE_SLEEP - #error [NOT_SUPPORTED] Sleep not supported for this target +#error [NOT_SUPPORTED] Sleep not supported for this target #endif #include "utest/utest.h" @@ -120,13 +120,15 @@ Case cases[] = { Case("timer lock test", timer_lock_test), }; -utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { +utest::v1::status_t greentea_test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(20, "default_auto"); return greentea_test_setup_handler(number_of_cases); } Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); -int main() { +int main() +{ Harness::run(specification); } diff --git a/TESTS/mbed_drivers/stats/main.cpp b/TESTS/mbed_drivers/stats/main.cpp index b99adead2f1..2d7d6b27e90 100644 --- a/TESTS/mbed_drivers/stats/main.cpp +++ b/TESTS/mbed_drivers/stats/main.cpp @@ -23,7 +23,7 @@ #include #if !defined(MBED_HEAP_STATS_ENABLED) - #error [NOT_SUPPORTED] test not supported +#error [NOT_SUPPORTED] test not supported #endif using namespace utest::v1; @@ -33,12 +33,12 @@ using namespace utest::v1; #define ALLOCATION_SIZE_LARGE 700 #define ALLOCATION_SIZE_FAIL (1024 * 1024 *1024) -typedef void* (*malloc_cb_t) (uint32_t size); +typedef void *(*malloc_cb_t)(uint32_t size); -static void* thunk_malloc(uint32_t size); -static void* thunk_calloc_1(uint32_t size); -static void* thunk_calloc_4(uint32_t size); -static void* thunk_realloc(uint32_t size); +static void *thunk_malloc(uint32_t size); +static void *thunk_calloc_1(uint32_t size); +static void *thunk_calloc_4(uint32_t size); +static void *thunk_realloc(uint32_t size); malloc_cb_t malloc_thunk_array[] = { thunk_malloc, @@ -124,23 +124,23 @@ void test_case_allocate_fail() } } -static void* thunk_malloc(uint32_t size) +static void *thunk_malloc(uint32_t size) { return malloc(size); } -static void* thunk_calloc_1(uint32_t size) +static void *thunk_calloc_1(uint32_t size) { return calloc(size / 1, 1); } -static void* thunk_calloc_4(uint32_t size) +static void *thunk_calloc_4(uint32_t size) { return calloc(size / 4, 4); } -static void* thunk_realloc(uint32_t size) +static void *thunk_realloc(uint32_t size) { return realloc(NULL, size); } diff --git a/TESTS/mbed_drivers/stl_features/main.cpp b/TESTS/mbed_drivers/stl_features/main.cpp index a8a8f904e24..7d0b289e331 100644 --- a/TESTS/mbed_drivers/stl_features/main.cpp +++ b/TESTS/mbed_drivers/stl_features/main.cpp @@ -39,16 +39,17 @@ using namespace utest::v1; namespace { template -void BubbleSort(T& _array, size_t array_size, F functor) { +void BubbleSort(T &_array, size_t array_size, F functor) +{ bool flag = true; size_t numLength = array_size; - for(size_t i = 1; (i <= numLength) && flag; i++) { + for (size_t i = 1; (i <= numLength) && flag; i++) { flag = false; for (size_t j = 0; j < (numLength - 1); j++) { - if (functor(_array[j+1], _array[j])) { + if (functor(_array[j + 1], _array[j])) { int temp = _array[j]; _array[j] = _array[j + 1]; - _array[j+1] = temp; + _array[j + 1] = temp; flag = true; } } @@ -56,27 +57,33 @@ void BubbleSort(T& _array, size_t array_size, F functor) { } struct greaterAbs { - bool operator()(int a, int b) { return abs(a) > abs(b); } + bool operator()(int a, int b) + { + return abs(a) > abs(b); + } }; } // namespace -void test_case_stl_equal() { +void test_case_stl_equal() +{ const int n_integers[] = {NEGATIVE_INTEGERS}; std::vector v_pints(n_integers, n_integers + TABLE_SIZE(n_integers)); TEST_ASSERT_TRUE(std::equal(v_pints.begin(), v_pints.end(), n_integers)); } -void test_case_stl_transform() { +void test_case_stl_transform() +{ const float floats[] = {FLOATS}; - const char* floats_str[] = {FLOATS_STR}; + const char *floats_str[] = {FLOATS_STR}; float floats_transform[TABLE_SIZE(floats_str)] = {0.0}; std::transform(floats_str, floats_str + TABLE_SIZE(floats_str), floats_transform, atof); TEST_ASSERT_TRUE(std::equal(floats_transform, floats_transform + TABLE_SIZE(floats_transform), floats)); } -void test_case_stl_sort_greater() { +void test_case_stl_sort_greater() +{ int n_integers[] = {NEGATIVE_INTEGERS}; int n_integers2[] = {NEGATIVE_INTEGERS}; @@ -87,7 +94,8 @@ void test_case_stl_sort_greater() { } -void test_case_stl_sort_abs() { +void test_case_stl_sort_abs() +{ int n_integers[] = {NEGATIVE_INTEGERS}; int n_integers2[] = {NEGATIVE_INTEGERS}; @@ -98,7 +106,8 @@ void test_case_stl_sort_abs() { } -utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) { +utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) +{ greentea_case_failure_abort_handler(source, reason); return STATUS_CONTINUE; } @@ -110,13 +119,15 @@ Case cases[] = { Case("STL std::sort abs", test_case_stl_sort_abs, greentea_failure_handler) }; -utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { +utest::v1::status_t greentea_test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(5, "default_auto"); return greentea_test_setup_handler(number_of_cases); } Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); -int main() { +int main() +{ Harness::run(specification); } diff --git a/TESTS/mbed_drivers/ticker/main.cpp b/TESTS/mbed_drivers/ticker/main.cpp index bab9c2bf549..4aaef8867d6 100644 --- a/TESTS/mbed_drivers/ticker/main.cpp +++ b/TESTS/mbed_drivers/ticker/main.cpp @@ -45,7 +45,7 @@ volatile int ticker_count = 0; void switch_led1_state(void) { // blink 3 times per second - if((callback_trigger_count % 333) == 0) { + if ((callback_trigger_count % 333) == 0) { led1 = !led1; } } @@ -54,7 +54,7 @@ void switch_led2_state(void) { // blink 3 times per second // make led2 blink at the same callback_trigger_count value as led1 - if(((callback_trigger_count - 1) % 333) == 0) { + if (((callback_trigger_count - 1) % 333) == 0) { led2 = !led2; } } @@ -81,12 +81,12 @@ void sem_release(Semaphore *sem) void stop_gtimer_set_flag(void) { gtimer.stop(); - core_util_atomic_incr_u32((uint32_t*)&ticker_callback_flag, 1); + core_util_atomic_incr_u32((uint32_t *)&ticker_callback_flag, 1); } void increment_multi_counter(void) { - core_util_atomic_incr_u32((uint32_t*)&multi_counter, 1); + core_util_atomic_incr_u32((uint32_t *)&multi_counter, 1); } @@ -127,7 +127,7 @@ void test_case_1x_ticker() //get the results from host greentea_parse_kv(_key, _value, sizeof(_key), sizeof(_value)); - TEST_ASSERT_EQUAL_STRING_MESSAGE("pass", _key,"Host side script reported a fail..."); + TEST_ASSERT_EQUAL_STRING_MESSAGE("pass", _key, "Host side script reported a fail..."); } /* Tests is to measure the accuracy of Ticker over a period of time @@ -171,7 +171,7 @@ void test_case_2x_ticker() //get the results from host greentea_parse_kv(_key, _value, sizeof(_key), sizeof(_value)); - TEST_ASSERT_EQUAL_STRING_MESSAGE("pass", _key,"Host side script reported a fail..."); + TEST_ASSERT_EQUAL_STRING_MESSAGE("pass", _key, "Host side script reported a fail..."); } /** Test many tickers run one after the other @@ -194,7 +194,7 @@ void test_multi_ticker(void) Thread::wait(MULTI_TICKER_TIME_MS + extra_wait); for (int i = 0; i < TICKER_COUNT; i++) { - ticker[i].detach(); + ticker[i].detach(); } TEST_ASSERT_EQUAL(TICKER_COUNT, multi_counter); @@ -228,7 +228,7 @@ void test_multi_call_time(void) gtimer.start(); ticker.attach_us(callback(stop_gtimer_set_flag), MULTI_TICKER_TIME_MS * 1000); - while(!ticker_callback_flag); + while (!ticker_callback_flag); time_diff = gtimer.read_us(); TEST_ASSERT_UINT32_WITHIN(TOLERANCE_US, MULTI_TICKER_TIME_MS * 1000, time_diff); @@ -277,7 +277,7 @@ void test_attach_time(void) gtimer.reset(); gtimer.start(); ticker.attach(callback(stop_gtimer_set_flag), ((float)DELAY_US) / 1000000.0f); - while(!ticker_callback_flag); + while (!ticker_callback_flag); ticker.detach(); const int time_diff = gtimer.read_us(); @@ -299,7 +299,7 @@ void test_attach_us_time(void) gtimer.reset(); gtimer.start(); ticker.attach_us(callback(stop_gtimer_set_flag), DELAY_US); - while(!ticker_callback_flag); + while (!ticker_callback_flag); ticker.detach(); const int time_diff = gtimer.read_us(); diff --git a/TESTS/mbed_drivers/timeout/main.cpp b/TESTS/mbed_drivers/timeout/main.cpp index 851b947020c..b7a2c8e7b85 100644 --- a/TESTS/mbed_drivers/timeout/main.cpp +++ b/TESTS/mbed_drivers/timeout/main.cpp @@ -43,12 +43,14 @@ volatile uint32_t callback_trigger_count = 0; static const int test_timeout = 240; Timeout timeout; -void set_incremeant_count() { +void set_incremeant_count() +{ timeout.attach_us(set_incremeant_count, PERIOD_US); ++callback_trigger_count; } -void test_case_timeout() { +void test_case_timeout() +{ char _key[11] = { }; char _value[128] = { }; @@ -73,19 +75,21 @@ void test_case_timeout() { //get the results from host greentea_parse_kv(_key, _value, sizeof(_key), sizeof(_value)); - TEST_ASSERT_EQUAL_STRING_MESSAGE("pass", _key,"Host side script reported a fail..."); + TEST_ASSERT_EQUAL_STRING_MESSAGE("pass", _key, "Host side script reported a fail..."); } // Test casess Case cases[] = { Case("Timers: toggle on/off", test_case_timeout), }; -utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { +utest::v1::status_t greentea_test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(test_timeout, "timing_drift_auto"); return greentea_test_setup_handler(number_of_cases); } Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); -int main() { +int main() +{ Harness::run(specification); } diff --git a/TESTS/mbed_drivers/timer/main.cpp b/TESTS/mbed_drivers/timer/main.cpp index dfc16fdf3f2..d0417e142f4 100644 --- a/TESTS/mbed_drivers/timer/main.cpp +++ b/TESTS/mbed_drivers/timer/main.cpp @@ -48,13 +48,13 @@ extern uint32_t SystemCoreClock; #define TOLERANCE_FACTOR 30000.0f #define US_FACTOR 1000000.0f -static const int delta_sys_clk_us = ((int) (TOLERANCE_FACTOR / (float)SystemCoreClock * US_FACTOR)); +static const int delta_sys_clk_us = ((int)(TOLERANCE_FACTOR / (float)SystemCoreClock *US_FACTOR)); /* When test performs time measurement using Timer in sequence, then measurement error accumulates * in the successive attempts. */ - #define DELTA_US(i) (delta_sys_clk_us * i) - #define DELTA_S(i) ((float)delta_sys_clk_us * i / US_PER_SEC) - #define DELTA_MS(i) (1 + ( (i * delta_sys_clk_us) / US_PER_MSEC)) +#define DELTA_US(i) (delta_sys_clk_us * i) +#define DELTA_S(i) ((float)delta_sys_clk_us * i / US_PER_SEC) +#define DELTA_MS(i) (1 + ( (i * delta_sys_clk_us) / US_PER_MSEC)) #define TICKER_FREQ_1MHZ 1000000 #define TICKER_BITS 32 @@ -107,7 +107,7 @@ static void stub_fire_interrupt(void) ticker_info_t info = { TICKER_FREQ_1MHZ, TICKER_BITS }; -const ticker_info_t * stub_get_info(void) +const ticker_info_t *stub_get_info(void) { return &info; } @@ -133,7 +133,7 @@ static const ticker_data_t us_data = { }; /* Function which returns user ticker data. */ -const ticker_data_t* get_user_ticker_data(void) +const ticker_data_t *get_user_ticker_data(void) { return &us_data; } @@ -734,7 +734,8 @@ void test_timer_time_measurement() TEST_ASSERT_UINT64_WITHIN(DELTA_US(1), wait_val_us, p_timer->read_high_resolution_us()); } -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(15, "default_auto"); return verbose_test_setup_handler(number_of_cases); } @@ -763,7 +764,8 @@ Case cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/TESTS/mbed_drivers/timerevent/main.cpp b/TESTS/mbed_drivers/timerevent/main.cpp index 5dee5786459..af8c222928a 100644 --- a/TESTS/mbed_drivers/timerevent/main.cpp +++ b/TESTS/mbed_drivers/timerevent/main.cpp @@ -28,20 +28,24 @@ using namespace utest::v1; class TestTimerEvent: public TimerEvent { private: Semaphore sem; - virtual void handler() { + virtual void handler() + { sem.release(); } public: TestTimerEvent() : - TimerEvent(), sem(0, 1) { + TimerEvent(), sem(0, 1) + { } TestTimerEvent(const ticker_data_t *data) : - TimerEvent(data), sem(0, 1) { + TimerEvent(data), sem(0, 1) + { } - virtual ~TestTimerEvent() { + virtual ~TestTimerEvent() + { } // Make these methods publicly accessible @@ -49,7 +53,8 @@ class TestTimerEvent: public TimerEvent { using TimerEvent::insert_absolute; using TimerEvent::remove; - int32_t sem_wait(uint32_t millisec) { + int32_t sem_wait(uint32_t millisec) + { return sem.wait(millisec); } }; @@ -58,19 +63,23 @@ class TestTimerEventRelative: public TestTimerEvent { public: static const int32_t SEM_SLOTS_AFTER_PAST_TS_INSERTED = 0; TestTimerEventRelative() : - TestTimerEvent() { + TestTimerEvent() + { } TestTimerEventRelative(const ticker_data_t *data) : - TestTimerEvent(data) { + TestTimerEvent(data) + { } // Set relative timestamp of internal event to present_time + ts - void set_future_timestamp(timestamp_t ts) { + void set_future_timestamp(timestamp_t ts) + { insert(::ticker_read(_ticker_data) + ts); } - void set_past_timestamp(void) { + void set_past_timestamp(void) + { insert(::ticker_read(_ticker_data) - 1UL); } }; @@ -79,19 +88,23 @@ class TestTimerEventAbsolute: public TestTimerEvent { public: static const int32_t SEM_SLOTS_AFTER_PAST_TS_INSERTED = 1; TestTimerEventAbsolute() : - TestTimerEvent() { + TestTimerEvent() + { } TestTimerEventAbsolute(const ticker_data_t *data) : - TestTimerEvent(data) { + TestTimerEvent(data) + { } // Set absolute timestamp of internal event to present_time + ts - void set_future_timestamp(us_timestamp_t ts) { + void set_future_timestamp(us_timestamp_t ts) + { insert_absolute(::ticker_read_us(_ticker_data) + ts); } - void set_past_timestamp(void) { + void set_past_timestamp(void) + { insert_absolute(::ticker_read_us(_ticker_data) - 1ULL); } }; @@ -111,7 +124,8 @@ class TestTimerEventAbsolute: public TestTimerEvent { * Then an event handler is called */ template -void test_insert(void) { +void test_insert(void) +{ T tte; tte.set_future_timestamp(TEST_DELAY_US); @@ -139,7 +153,8 @@ void test_insert(void) { * Then the event handler is never called */ template -void test_remove(void) { +void test_remove(void) +{ T tte; tte.set_future_timestamp(TEST_DELAY_US * 2); @@ -156,7 +171,8 @@ void test_remove(void) { * When a timestamp of 0 us is set with @a insert_absolute() * Then an event handler is called instantly */ -void test_insert_zero(void) { +void test_insert_zero(void) +{ TestTimerEvent tte; tte.insert_absolute(0ULL); @@ -182,7 +198,8 @@ void test_insert_zero(void) { * Then an event handler is called instantly */ template -void test_insert_past(void) { +void test_insert_past(void) +{ T tte; tte.set_past_timestamp(); @@ -193,7 +210,7 @@ void test_insert_past(void) { } utest::v1::status_t test_setup(const size_t number_of_cases) - { +{ GREENTEA_SETUP(5, "default_auto"); return verbose_test_setup_handler(number_of_cases); } diff --git a/TESTS/mbed_functional/callback/main.cpp b/TESTS/mbed_functional/callback/main.cpp index f14d7537937..ea941fd7719 100644 --- a/TESTS/mbed_functional/callback/main.cpp +++ b/TESTS/mbed_functional/callback/main.cpp @@ -24,22 +24,34 @@ using namespace utest::v1; // static functions template T static_func0() - { return 0; } +{ + return 0; +} template T static_func1(T a0) - { return 0 | a0; } +{ + return 0 | a0; +} template T static_func2(T a0, T a1) - { return 0 | a0 | a1; } +{ + return 0 | a0 | a1; +} template T static_func3(T a0, T a1, T a2) - { return 0 | a0 | a1 | a2; } +{ + return 0 | a0 | a1 | a2; +} template T static_func4(T a0, T a1, T a2, T a3) - { return 0 | a0 | a1 | a2 | a3; } +{ + return 0 | a0 | a1 | a2 | a3; +} template T static_func5(T a0, T a1, T a2, T a3, T a4) - { return 0 | a0 | a1 | a2 | a3 | a4; } +{ + return 0 | a0 | a1 | a2 | a3 | a4; +} // class functions template @@ -48,205 +60,349 @@ struct Thing { Thing() : t(0x80) {} T member_func0() - { return t; } + { + return t; + } T member_func1(T a0) - { return t | a0; } + { + return t | a0; + } T member_func2(T a0, T a1) - { return t | a0 | a1; } + { + return t | a0 | a1; + } T member_func3(T a0, T a1, T a2) - { return t | a0 | a1 | a2; } + { + return t | a0 | a1 | a2; + } T member_func4(T a0, T a1, T a2, T a3) - { return t | a0 | a1 | a2 | a3; } + { + return t | a0 | a1 | a2 | a3; + } T member_func5(T a0, T a1, T a2, T a3, T a4) - { return t | a0 | a1 | a2 | a3 | a4; } + { + return t | a0 | a1 | a2 | a3 | a4; + } T const_member_func0() const - { return t; } + { + return t; + } T const_member_func1(T a0) const - { return t | a0; } + { + return t | a0; + } T const_member_func2(T a0, T a1) const - { return t | a0 | a1; } + { + return t | a0 | a1; + } T const_member_func3(T a0, T a1, T a2) const - { return t | a0 | a1 | a2; } + { + return t | a0 | a1 | a2; + } T const_member_func4(T a0, T a1, T a2, T a3) const - { return t | a0 | a1 | a2 | a3; } + { + return t | a0 | a1 | a2 | a3; + } T const_member_func5(T a0, T a1, T a2, T a3, T a4) const - { return t | a0 | a1 | a2 | a3 | a4; } + { + return t | a0 | a1 | a2 | a3 | a4; + } T volatile_member_func0() volatile - { return t; } + { + return t; + } T volatile_member_func1(T a0) volatile - { return t | a0; } + { + return t | a0; + } T volatile_member_func2(T a0, T a1) volatile - { return t | a0 | a1; } + { + return t | a0 | a1; + } T volatile_member_func3(T a0, T a1, T a2) volatile - { return t | a0 | a1 | a2; } + { + return t | a0 | a1 | a2; + } T volatile_member_func4(T a0, T a1, T a2, T a3) volatile - { return t | a0 | a1 | a2 | a3; } + { + return t | a0 | a1 | a2 | a3; + } T volatile_member_func5(T a0, T a1, T a2, T a3, T a4) volatile - { return t | a0 | a1 | a2 | a3 | a4; } + { + return t | a0 | a1 | a2 | a3 | a4; + } T const_volatile_member_func0() const volatile - { return t; } + { + return t; + } T const_volatile_member_func1(T a0) const volatile - { return t | a0; } + { + return t | a0; + } T const_volatile_member_func2(T a0, T a1) const volatile - { return t | a0 | a1; } + { + return t | a0 | a1; + } T const_volatile_member_func3(T a0, T a1, T a2) const volatile - { return t | a0 | a1 | a2; } + { + return t | a0 | a1 | a2; + } T const_volatile_member_func4(T a0, T a1, T a2, T a3) const volatile - { return t | a0 | a1 | a2 | a3; } + { + return t | a0 | a1 | a2 | a3; + } T const_volatile_member_func5(T a0, T a1, T a2, T a3, T a4) const volatile - { return t | a0 | a1 | a2 | a3 | a4; } + { + return t | a0 | a1 | a2 | a3 | a4; + } }; // bound functions template T bound_func0(Thing *t) - { return t->t; } +{ + return t->t; +} template T bound_func1(Thing *t, T a0) - { return t->t | a0; } +{ + return t->t | a0; +} template T bound_func2(Thing *t, T a0, T a1) - { return t->t | a0 | a1; } +{ + return t->t | a0 | a1; +} template T bound_func3(Thing *t, T a0, T a1, T a2) - { return t->t | a0 | a1 | a2; } +{ + return t->t | a0 | a1 | a2; +} template T bound_func4(Thing *t, T a0, T a1, T a2, T a3) - { return t->t | a0 | a1 | a2 | a3; } +{ + return t->t | a0 | a1 | a2 | a3; +} template T bound_func5(Thing *t, T a0, T a1, T a2, T a3, T a4) - { return t->t | a0 | a1 | a2 | a3 | a4; } +{ + return t->t | a0 | a1 | a2 | a3 | a4; +} template T const_bound_func0(const Thing *t) - { return t->t; } +{ + return t->t; +} template T const_bound_func1(const Thing *t, T a0) - { return t->t | a0; } +{ + return t->t | a0; +} template T const_bound_func2(const Thing *t, T a0, T a1) - { return t->t | a0 | a1; } +{ + return t->t | a0 | a1; +} template T const_bound_func3(const Thing *t, T a0, T a1, T a2) - { return t->t | a0 | a1 | a2; } +{ + return t->t | a0 | a1 | a2; +} template T const_bound_func4(const Thing *t, T a0, T a1, T a2, T a3) - { return t->t | a0 | a1 | a2 | a3; } +{ + return t->t | a0 | a1 | a2 | a3; +} template T const_bound_func5(const Thing *t, T a0, T a1, T a2, T a3, T a4) - { return t->t | a0 | a1 | a2 | a3 | a4; } +{ + return t->t | a0 | a1 | a2 | a3 | a4; +} template T volatile_bound_func0(volatile Thing *t) - { return t->t; } +{ + return t->t; +} template T volatile_bound_func1(volatile Thing *t, T a0) - { return t->t | a0; } +{ + return t->t | a0; +} template T volatile_bound_func2(volatile Thing *t, T a0, T a1) - { return t->t | a0 | a1; } +{ + return t->t | a0 | a1; +} template T volatile_bound_func3(volatile Thing *t, T a0, T a1, T a2) - { return t->t | a0 | a1 | a2; } +{ + return t->t | a0 | a1 | a2; +} template T volatile_bound_func4(volatile Thing *t, T a0, T a1, T a2, T a3) - { return t->t | a0 | a1 | a2 | a3; } +{ + return t->t | a0 | a1 | a2 | a3; +} template T volatile_bound_func5(volatile Thing *t, T a0, T a1, T a2, T a3, T a4) - { return t->t | a0 | a1 | a2 | a3 | a4; } +{ + return t->t | a0 | a1 | a2 | a3 | a4; +} template T const_volatile_bound_func0(const volatile Thing *t) - { return t->t; } +{ + return t->t; +} template T const_volatile_bound_func1(const volatile Thing *t, T a0) - { return t->t | a0; } +{ + return t->t | a0; +} template T const_volatile_bound_func2(const volatile Thing *t, T a0, T a1) - { return t->t | a0 | a1; } +{ + return t->t | a0 | a1; +} template T const_volatile_bound_func3(const volatile Thing *t, T a0, T a1, T a2) - { return t->t | a0 | a1 | a2; } +{ + return t->t | a0 | a1 | a2; +} template T const_volatile_bound_func4(const volatile Thing *t, T a0, T a1, T a2, T a3) - { return t->t | a0 | a1 | a2 | a3; } +{ + return t->t | a0 | a1 | a2 | a3; +} template T const_volatile_bound_func5(const volatile Thing *t, T a0, T a1, T a2, T a3, T a4) - { return t->t | a0 | a1 | a2 | a3 | a4; } +{ + return t->t | a0 | a1 | a2 | a3 | a4; +} // void functions template T void_func0(void *t) - { return static_cast*>(t)->t; } +{ + return static_cast*>(t)->t; +} template T void_func1(void *t, T a0) - { return static_cast*>(t)->t | a0; } +{ + return static_cast*>(t)->t | a0; +} template T void_func2(void *t, T a0, T a1) - { return static_cast*>(t)->t | a0 | a1; } +{ + return static_cast*>(t)->t | a0 | a1; +} template T void_func3(void *t, T a0, T a1, T a2) - { return static_cast*>(t)->t | a0 | a1 | a2; } +{ + return static_cast*>(t)->t | a0 | a1 | a2; +} template T void_func4(void *t, T a0, T a1, T a2, T a3) - { return static_cast*>(t)->t | a0 | a1 | a2 | a3; } +{ + return static_cast*>(t)->t | a0 | a1 | a2 | a3; +} template T void_func5(void *t, T a0, T a1, T a2, T a3, T a4) - { return static_cast*>(t)->t | a0 | a1 | a2 | a3 | a4; } +{ + return static_cast*>(t)->t | a0 | a1 | a2 | a3 | a4; +} template T const_void_func0(const void *t) - { return static_cast*>(t)->t; } +{ + return static_cast*>(t)->t; +} template T const_void_func1(const void *t, T a0) - { return static_cast*>(t)->t | a0; } +{ + return static_cast*>(t)->t | a0; +} template T const_void_func2(const void *t, T a0, T a1) - { return static_cast*>(t)->t | a0 | a1; } +{ + return static_cast*>(t)->t | a0 | a1; +} template T const_void_func3(const void *t, T a0, T a1, T a2) - { return static_cast*>(t)->t | a0 | a1 | a2; } +{ + return static_cast*>(t)->t | a0 | a1 | a2; +} template T const_void_func4(const void *t, T a0, T a1, T a2, T a3) - { return static_cast*>(t)->t | a0 | a1 | a2 | a3; } +{ + return static_cast*>(t)->t | a0 | a1 | a2 | a3; +} template T const_void_func5(const void *t, T a0, T a1, T a2, T a3, T a4) - { return static_cast*>(t)->t | a0 | a1 | a2 | a3 | a4; } +{ + return static_cast*>(t)->t | a0 | a1 | a2 | a3 | a4; +} template T volatile_void_func0(volatile void *t) - { return static_cast*>(t)->t; } +{ + return static_cast*>(t)->t; +} template T volatile_void_func1(volatile void *t, T a0) - { return static_cast*>(t)->t | a0; } +{ + return static_cast*>(t)->t | a0; +} template T volatile_void_func2(volatile void *t, T a0, T a1) - { return static_cast*>(t)->t | a0 | a1; } +{ + return static_cast*>(t)->t | a0 | a1; +} template T volatile_void_func3(volatile void *t, T a0, T a1, T a2) - { return static_cast*>(t)->t | a0 | a1 | a2; } +{ + return static_cast*>(t)->t | a0 | a1 | a2; +} template T volatile_void_func4(volatile void *t, T a0, T a1, T a2, T a3) - { return static_cast*>(t)->t | a0 | a1 | a2 | a3; } +{ + return static_cast*>(t)->t | a0 | a1 | a2 | a3; +} template T volatile_void_func5(volatile void *t, T a0, T a1, T a2, T a3, T a4) - { return static_cast*>(t)->t | a0 | a1 | a2 | a3 | a4; } +{ + return static_cast*>(t)->t | a0 | a1 | a2 | a3 | a4; +} template T const_volatile_void_func0(const volatile void *t) - { return static_cast*>(t)->t; } +{ + return static_cast*>(t)->t; +} template T const_volatile_void_func1(const volatile void *t, T a0) - { return static_cast*>(t)->t | a0; } +{ + return static_cast*>(t)->t | a0; +} template T const_volatile_void_func2(const volatile void *t, T a0, T a1) - { return static_cast*>(t)->t | a0 | a1; } +{ + return static_cast*>(t)->t | a0 | a1; +} template T const_volatile_void_func3(const volatile void *t, T a0, T a1, T a2) - { return static_cast*>(t)->t | a0 | a1 | a2; } +{ + return static_cast*>(t)->t | a0 | a1 | a2; +} template T const_volatile_void_func4(const volatile void *t, T a0, T a1, T a2, T a3) - { return static_cast*>(t)->t | a0 | a1 | a2 | a3; } +{ + return static_cast*>(t)->t | a0 | a1 | a2 | a3; +} template T const_volatile_void_func5(const volatile void *t, T a0, T a1, T a2, T a3, T a4) - { return static_cast*>(t)->t | a0 | a1 | a2 | a3 | a4; } +{ + return static_cast*>(t)->t | a0 | a1 | a2 | a3 | a4; +} // Inheriting class template @@ -257,73 +413,85 @@ class Thing2 : public Thing { // function call and result verification template struct Verifier { - static void verify0(Callback func) { + static void verify0(Callback func) + { T result = func(); TEST_ASSERT_EQUAL(result, 0x00); } template - static void verify0(O *obj, M method) { + static void verify0(O *obj, M method) + { Callback func(obj, method); T result = func(); TEST_ASSERT_EQUAL(result, 0x80); } - static void verify1(Callback func) { + static void verify1(Callback func) + { T result = func((1 << 0)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0)); } template - static void verify1(O *obj, M method) { + static void verify1(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0)); } - static void verify2(Callback func) { + static void verify2(Callback func) + { T result = func((1 << 0), (1 << 1)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0) | (1 << 1)); } template - static void verify2(O *obj, M method) { + static void verify2(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0), (1 << 1)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0) | (1 << 1)); } - static void verify3(Callback func) { + static void verify3(Callback func) + { T result = func((1 << 0), (1 << 1), (1 << 2)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0) | (1 << 1) | (1 << 2)); } template - static void verify3(O *obj, M method) { + static void verify3(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0), (1 << 1), (1 << 2)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0) | (1 << 1) | (1 << 2)); } - static void verify4(Callback func) { + static void verify4(Callback func) + { T result = func((1 << 0), (1 << 1), (1 << 2), (1 << 3)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3)); } template - static void verify4(O *obj, M method) { + static void verify4(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0), (1 << 1), (1 << 2), (1 << 3)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3)); } - static void verify5(Callback func) { + static void verify5(Callback func) + { T result = func((1 << 0), (1 << 1), (1 << 2), (1 << 3), (1 << 4)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4)); } template - static void verify5(O *obj, M method) { + static void verify5(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0), (1 << 1), (1 << 2), (1 << 3), (1 << 4)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4)); @@ -333,24 +501,25 @@ struct Verifier { // test dispatch template -void test_dispatch0() { +void test_dispatch0() +{ Thing thing; Thing2 thing2; Verifier::verify0(static_func0); Verifier::verify0(&thing, &Thing::member_func0); - Verifier::verify0((const Thing*)&thing, &Thing::const_member_func0); - Verifier::verify0((volatile Thing*)&thing, &Thing::volatile_member_func0); - Verifier::verify0((const volatile Thing*)&thing, &Thing::const_volatile_member_func0); + Verifier::verify0((const Thing *)&thing, &Thing::const_member_func0); + Verifier::verify0((volatile Thing *)&thing, &Thing::volatile_member_func0); + Verifier::verify0((const volatile Thing *)&thing, &Thing::const_volatile_member_func0); Verifier::verify0(&thing2, &Thing2::member_func0); Verifier::verify0(&bound_func0, &thing); - Verifier::verify0(&const_bound_func0, (const Thing*)&thing); - Verifier::verify0(&volatile_bound_func0, (volatile Thing*)&thing); - Verifier::verify0(&const_volatile_bound_func0, (const volatile Thing*)&thing); + Verifier::verify0(&const_bound_func0, (const Thing *)&thing); + Verifier::verify0(&volatile_bound_func0, (volatile Thing *)&thing); + Verifier::verify0(&const_volatile_bound_func0, (const volatile Thing *)&thing); Verifier::verify0(&bound_func0, &thing2); Verifier::verify0(&void_func0, &thing); - Verifier::verify0(&const_void_func0, (const Thing*)&thing); - Verifier::verify0(&volatile_void_func0, (volatile Thing*)&thing); - Verifier::verify0(&const_volatile_void_func0, (const volatile Thing*)&thing); + Verifier::verify0(&const_void_func0, (const Thing *)&thing); + Verifier::verify0(&volatile_void_func0, (volatile Thing *)&thing); + Verifier::verify0(&const_volatile_void_func0, (const volatile Thing *)&thing); Verifier::verify0(callback(static_func0)); Callback cb(static_func0); @@ -359,28 +528,29 @@ void test_dispatch0() { Verifier::verify0(cb); cb.attach(&bound_func0, &thing); Verifier::verify0(&cb, &Callback::call); - Verifier::verify0(&Callback::thunk, (void*)&cb); + Verifier::verify0(&Callback::thunk, (void *)&cb); } template -void test_dispatch1() { +void test_dispatch1() +{ Thing thing; Thing2 thing2; Verifier::verify1(static_func1); Verifier::verify1(&thing, &Thing::member_func1); - Verifier::verify1((const Thing*)&thing, &Thing::const_member_func1); - Verifier::verify1((volatile Thing*)&thing, &Thing::volatile_member_func1); - Verifier::verify1((const volatile Thing*)&thing, &Thing::const_volatile_member_func1); + Verifier::verify1((const Thing *)&thing, &Thing::const_member_func1); + Verifier::verify1((volatile Thing *)&thing, &Thing::volatile_member_func1); + Verifier::verify1((const volatile Thing *)&thing, &Thing::const_volatile_member_func1); Verifier::verify1(&thing2, &Thing2::member_func1); Verifier::verify1(&bound_func1, &thing); - Verifier::verify1(&const_bound_func1, (const Thing*)&thing); - Verifier::verify1(&volatile_bound_func1, (volatile Thing*)&thing); - Verifier::verify1(&const_volatile_bound_func1, (const volatile Thing*)&thing); + Verifier::verify1(&const_bound_func1, (const Thing *)&thing); + Verifier::verify1(&volatile_bound_func1, (volatile Thing *)&thing); + Verifier::verify1(&const_volatile_bound_func1, (const volatile Thing *)&thing); Verifier::verify1(&bound_func1, &thing2); Verifier::verify1(&void_func1, &thing); - Verifier::verify1(&const_void_func1, (const Thing*)&thing); - Verifier::verify1(&volatile_void_func1, (volatile Thing*)&thing); - Verifier::verify1(&const_volatile_void_func1, (const volatile Thing*)&thing); + Verifier::verify1(&const_void_func1, (const Thing *)&thing); + Verifier::verify1(&volatile_void_func1, (volatile Thing *)&thing); + Verifier::verify1(&const_volatile_void_func1, (const volatile Thing *)&thing); Verifier::verify1(callback(static_func1)); Callback cb(static_func1); @@ -389,28 +559,29 @@ void test_dispatch1() { Verifier::verify1(cb); cb.attach(&bound_func1, &thing); Verifier::verify1(&cb, &Callback::call); - Verifier::verify1(&Callback::thunk, (void*)&cb); + Verifier::verify1(&Callback::thunk, (void *)&cb); } template -void test_dispatch2() { +void test_dispatch2() +{ Thing thing; Thing2 thing2; Verifier::verify2(static_func2); Verifier::verify2(&thing, &Thing::member_func2); - Verifier::verify2((const Thing*)&thing, &Thing::const_member_func2); - Verifier::verify2((volatile Thing*)&thing, &Thing::volatile_member_func2); - Verifier::verify2((const volatile Thing*)&thing, &Thing::const_volatile_member_func2); + Verifier::verify2((const Thing *)&thing, &Thing::const_member_func2); + Verifier::verify2((volatile Thing *)&thing, &Thing::volatile_member_func2); + Verifier::verify2((const volatile Thing *)&thing, &Thing::const_volatile_member_func2); Verifier::verify2(&thing2, &Thing2::member_func2); Verifier::verify2(&bound_func2, &thing); - Verifier::verify2(&const_bound_func2, (const Thing*)&thing); - Verifier::verify2(&volatile_bound_func2, (volatile Thing*)&thing); - Verifier::verify2(&const_volatile_bound_func2, (const volatile Thing*)&thing); + Verifier::verify2(&const_bound_func2, (const Thing *)&thing); + Verifier::verify2(&volatile_bound_func2, (volatile Thing *)&thing); + Verifier::verify2(&const_volatile_bound_func2, (const volatile Thing *)&thing); Verifier::verify2(&bound_func2, &thing2); Verifier::verify2(&void_func2, &thing); - Verifier::verify2(&const_void_func2, (const Thing*)&thing); - Verifier::verify2(&volatile_void_func2, (volatile Thing*)&thing); - Verifier::verify2(&const_volatile_void_func2, (const volatile Thing*)&thing); + Verifier::verify2(&const_void_func2, (const Thing *)&thing); + Verifier::verify2(&volatile_void_func2, (volatile Thing *)&thing); + Verifier::verify2(&const_volatile_void_func2, (const volatile Thing *)&thing); Verifier::verify2(callback(static_func2)); Callback cb(static_func2); @@ -419,28 +590,29 @@ void test_dispatch2() { Verifier::verify2(cb); cb.attach(&bound_func2, &thing); Verifier::verify2(&cb, &Callback::call); - Verifier::verify2(&Callback::thunk, (void*)&cb); + Verifier::verify2(&Callback::thunk, (void *)&cb); } template -void test_dispatch3() { +void test_dispatch3() +{ Thing thing; Thing2 thing2; Verifier::verify3(static_func3); Verifier::verify3(&thing, &Thing::member_func3); - Verifier::verify3((const Thing*)&thing, &Thing::const_member_func3); - Verifier::verify3((volatile Thing*)&thing, &Thing::volatile_member_func3); - Verifier::verify3((const volatile Thing*)&thing, &Thing::const_volatile_member_func3); + Verifier::verify3((const Thing *)&thing, &Thing::const_member_func3); + Verifier::verify3((volatile Thing *)&thing, &Thing::volatile_member_func3); + Verifier::verify3((const volatile Thing *)&thing, &Thing::const_volatile_member_func3); Verifier::verify3(&thing2, &Thing2::member_func3); Verifier::verify3(&bound_func3, &thing); - Verifier::verify3(&const_bound_func3, (const Thing*)&thing); - Verifier::verify3(&volatile_bound_func3, (volatile Thing*)&thing); - Verifier::verify3(&const_volatile_bound_func3, (const volatile Thing*)&thing); + Verifier::verify3(&const_bound_func3, (const Thing *)&thing); + Verifier::verify3(&volatile_bound_func3, (volatile Thing *)&thing); + Verifier::verify3(&const_volatile_bound_func3, (const volatile Thing *)&thing); Verifier::verify3(&bound_func3, &thing2); Verifier::verify3(&void_func3, &thing); - Verifier::verify3(&const_void_func3, (const Thing*)&thing); - Verifier::verify3(&volatile_void_func3, (volatile Thing*)&thing); - Verifier::verify3(&const_volatile_void_func3, (const volatile Thing*)&thing); + Verifier::verify3(&const_void_func3, (const Thing *)&thing); + Verifier::verify3(&volatile_void_func3, (volatile Thing *)&thing); + Verifier::verify3(&const_volatile_void_func3, (const volatile Thing *)&thing); Verifier::verify3(callback(static_func3)); Callback cb(static_func3); @@ -449,28 +621,29 @@ void test_dispatch3() { Verifier::verify3(cb); cb.attach(&bound_func3, &thing); Verifier::verify3(&cb, &Callback::call); - Verifier::verify3(&Callback::thunk, (void*)&cb); + Verifier::verify3(&Callback::thunk, (void *)&cb); } template -void test_dispatch4() { +void test_dispatch4() +{ Thing thing; Thing2 thing2; Verifier::verify4(static_func4); Verifier::verify4(&thing, &Thing::member_func4); - Verifier::verify4((const Thing*)&thing, &Thing::const_member_func4); - Verifier::verify4((volatile Thing*)&thing, &Thing::volatile_member_func4); - Verifier::verify4((const volatile Thing*)&thing, &Thing::const_volatile_member_func4); + Verifier::verify4((const Thing *)&thing, &Thing::const_member_func4); + Verifier::verify4((volatile Thing *)&thing, &Thing::volatile_member_func4); + Verifier::verify4((const volatile Thing *)&thing, &Thing::const_volatile_member_func4); Verifier::verify4(&thing2, &Thing2::member_func4); Verifier::verify4(&bound_func4, &thing); - Verifier::verify4(&const_bound_func4, (const Thing*)&thing); - Verifier::verify4(&volatile_bound_func4, (volatile Thing*)&thing); - Verifier::verify4(&const_volatile_bound_func4, (const volatile Thing*)&thing); + Verifier::verify4(&const_bound_func4, (const Thing *)&thing); + Verifier::verify4(&volatile_bound_func4, (volatile Thing *)&thing); + Verifier::verify4(&const_volatile_bound_func4, (const volatile Thing *)&thing); Verifier::verify4(&bound_func4, &thing2); Verifier::verify4(&void_func4, &thing); - Verifier::verify4(&const_void_func4, (const Thing*)&thing); - Verifier::verify4(&volatile_void_func4, (volatile Thing*)&thing); - Verifier::verify4(&const_volatile_void_func4, (const volatile Thing*)&thing); + Verifier::verify4(&const_void_func4, (const Thing *)&thing); + Verifier::verify4(&volatile_void_func4, (volatile Thing *)&thing); + Verifier::verify4(&const_volatile_void_func4, (const volatile Thing *)&thing); Verifier::verify4(callback(static_func4)); Callback cb(static_func4); @@ -479,28 +652,29 @@ void test_dispatch4() { Verifier::verify4(cb); cb.attach(&bound_func4, &thing); Verifier::verify4(&cb, &Callback::call); - Verifier::verify4(&Callback::thunk, (void*)&cb); + Verifier::verify4(&Callback::thunk, (void *)&cb); } template -void test_dispatch5() { +void test_dispatch5() +{ Thing thing; Thing2 thing2; Verifier::verify5(static_func5); Verifier::verify5(&thing, &Thing::member_func5); - Verifier::verify5((const Thing*)&thing, &Thing::const_member_func5); - Verifier::verify5((volatile Thing*)&thing, &Thing::volatile_member_func5); - Verifier::verify5((const volatile Thing*)&thing, &Thing::const_volatile_member_func5); + Verifier::verify5((const Thing *)&thing, &Thing::const_member_func5); + Verifier::verify5((volatile Thing *)&thing, &Thing::volatile_member_func5); + Verifier::verify5((const volatile Thing *)&thing, &Thing::const_volatile_member_func5); Verifier::verify5(&thing2, &Thing2::member_func5); Verifier::verify5(&bound_func5, &thing); - Verifier::verify5(&const_bound_func5, (const Thing*)&thing); - Verifier::verify5(&volatile_bound_func5, (volatile Thing*)&thing); - Verifier::verify5(&const_volatile_bound_func5, (const volatile Thing*)&thing); + Verifier::verify5(&const_bound_func5, (const Thing *)&thing); + Verifier::verify5(&volatile_bound_func5, (volatile Thing *)&thing); + Verifier::verify5(&const_volatile_bound_func5, (const volatile Thing *)&thing); Verifier::verify5(&bound_func5, &thing2); Verifier::verify5(&void_func5, &thing); - Verifier::verify5(&const_void_func5, (const Thing*)&thing); - Verifier::verify5(&volatile_void_func5, (volatile Thing*)&thing); - Verifier::verify5(&const_volatile_void_func5, (const volatile Thing*)&thing); + Verifier::verify5(&const_void_func5, (const Thing *)&thing); + Verifier::verify5(&volatile_void_func5, (volatile Thing *)&thing); + Verifier::verify5(&const_volatile_void_func5, (const volatile Thing *)&thing); Verifier::verify5(callback(static_func5)); Callback cb(static_func5); @@ -509,12 +683,13 @@ void test_dispatch5() { Verifier::verify5(cb); cb.attach(&bound_func5, &thing); Verifier::verify5(&cb, &Callback::call); - Verifier::verify5(&Callback::thunk, (void*)&cb); + Verifier::verify5(&Callback::thunk, (void *)&cb); } // Test setup -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(10, "default_auto"); return verbose_test_setup_handler(number_of_cases); } @@ -530,6 +705,7 @@ Case cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/TESTS/mbed_functional/callback_big/main.cpp b/TESTS/mbed_functional/callback_big/main.cpp index 1aec88470e7..cac6827171a 100644 --- a/TESTS/mbed_functional/callback_big/main.cpp +++ b/TESTS/mbed_functional/callback_big/main.cpp @@ -23,17 +23,35 @@ using namespace utest::v1; // static functions template -T static_func0() { return 0; } +T static_func0() +{ + return 0; +} template -T static_func1(T a0) { return 0 | a0; } +T static_func1(T a0) +{ + return 0 | a0; +} template -T static_func2(T a0, T a1) { return 0 | a0 | a1; } +T static_func2(T a0, T a1) +{ + return 0 | a0 | a1; +} template -T static_func3(T a0, T a1, T a2) { return 0 | a0 | a1 | a2; } +T static_func3(T a0, T a1, T a2) +{ + return 0 | a0 | a1 | a2; +} template -T static_func4(T a0, T a1, T a2, T a3) { return 0 | a0 | a1 | a2 | a3; } +T static_func4(T a0, T a1, T a2, T a3) +{ + return 0 | a0 | a1 | a2 | a3; +} template -T static_func5(T a0, T a1, T a2, T a3, T a4) { return 0 | a0 | a1 | a2 | a3 | a4; } +T static_func5(T a0, T a1, T a2, T a3, T a4) +{ + return 0 | a0 | a1 | a2 | a3 | a4; +} // class functions template @@ -41,162 +59,318 @@ struct Thing { T t; Thing() : t(0x80) {} - T member_func0() { return t; } - T member_func1(T a0) { return t | a0; } - T member_func2(T a0, T a1) { return t | a0 | a1; } - T member_func3(T a0, T a1, T a2) { return t | a0 | a1 | a2; } - T member_func4(T a0, T a1, T a2, T a3) { return t | a0 | a1 | a2 | a3; } - T member_func5(T a0, T a1, T a2, T a3, T a4) { return t | a0 | a1 | a2 | a3 | a4; } - - T const_member_func0() const { return t; } - T const_member_func1(T a0) const { return t | a0; } - T const_member_func2(T a0, T a1) const { return t | a0 | a1; } - T const_member_func3(T a0, T a1, T a2) const { return t | a0 | a1 | a2; } - T const_member_func4(T a0, T a1, T a2, T a3) const { return t | a0 | a1 | a2 | a3; } - T const_member_func5(T a0, T a1, T a2, T a3, T a4) const { return t | a0 | a1 | a2 | a3 | a4; } - - T volatile_member_func0() volatile { return t; } - T volatile_member_func1(T a0) volatile { return t | a0; } - T volatile_member_func2(T a0, T a1) volatile { return t | a0 | a1; } - T volatile_member_func3(T a0, T a1, T a2) volatile { return t | a0 | a1 | a2; } - T volatile_member_func4(T a0, T a1, T a2, T a3) volatile { return t | a0 | a1 | a2 | a3; } - T volatile_member_func5(T a0, T a1, T a2, T a3, T a4) volatile { return t | a0 | a1 | a2 | a3 | a4; } - - T const_volatile_member_func0() const volatile { return t; } - T const_volatile_member_func1(T a0) const volatile { return t | a0; } - T const_volatile_member_func2(T a0, T a1) const volatile { return t | a0 | a1; } - T const_volatile_member_func3(T a0, T a1, T a2) const volatile { return t | a0 | a1 | a2; } - T const_volatile_member_func4(T a0, T a1, T a2, T a3) const volatile { return t | a0 | a1 | a2 | a3; } - T const_volatile_member_func5(T a0, T a1, T a2, T a3, T a4) const volatile { return t | a0 | a1 | a2 | a3 | a4; } + T member_func0() + { + return t; + } + T member_func1(T a0) + { + return t | a0; + } + T member_func2(T a0, T a1) + { + return t | a0 | a1; + } + T member_func3(T a0, T a1, T a2) + { + return t | a0 | a1 | a2; + } + T member_func4(T a0, T a1, T a2, T a3) + { + return t | a0 | a1 | a2 | a3; + } + T member_func5(T a0, T a1, T a2, T a3, T a4) + { + return t | a0 | a1 | a2 | a3 | a4; + } + + T const_member_func0() const + { + return t; + } + T const_member_func1(T a0) const + { + return t | a0; + } + T const_member_func2(T a0, T a1) const + { + return t | a0 | a1; + } + T const_member_func3(T a0, T a1, T a2) const + { + return t | a0 | a1 | a2; + } + T const_member_func4(T a0, T a1, T a2, T a3) const + { + return t | a0 | a1 | a2 | a3; + } + T const_member_func5(T a0, T a1, T a2, T a3, T a4) const + { + return t | a0 | a1 | a2 | a3 | a4; + } + + T volatile_member_func0() volatile + { + return t; + } + T volatile_member_func1(T a0) volatile + { + return t | a0; + } + T volatile_member_func2(T a0, T a1) volatile + { + return t | a0 | a1; + } + T volatile_member_func3(T a0, T a1, T a2) volatile + { + return t | a0 | a1 | a2; + } + T volatile_member_func4(T a0, T a1, T a2, T a3) volatile + { + return t | a0 | a1 | a2 | a3; + } + T volatile_member_func5(T a0, T a1, T a2, T a3, T a4) volatile + { + return t | a0 | a1 | a2 | a3 | a4; + } + + T const_volatile_member_func0() const volatile + { + return t; + } + T const_volatile_member_func1(T a0) const volatile + { + return t | a0; + } + T const_volatile_member_func2(T a0, T a1) const volatile + { + return t | a0 | a1; + } + T const_volatile_member_func3(T a0, T a1, T a2) const volatile + { + return t | a0 | a1 | a2; + } + T const_volatile_member_func4(T a0, T a1, T a2, T a3) const volatile + { + return t | a0 | a1 | a2 | a3; + } + T const_volatile_member_func5(T a0, T a1, T a2, T a3, T a4) const volatile + { + return t | a0 | a1 | a2 | a3 | a4; + } }; // bound functions template -T bound_func0(Thing *t) { return t->t; } +T bound_func0(Thing *t) +{ + return t->t; +} template -T bound_func1(Thing *t, T a0) { return t->t | a0; } +T bound_func1(Thing *t, T a0) +{ + return t->t | a0; +} template -T bound_func2(Thing *t, T a0, T a1) { return t->t | a0 | a1; } +T bound_func2(Thing *t, T a0, T a1) +{ + return t->t | a0 | a1; +} template -T bound_func3(Thing *t, T a0, T a1, T a2) { return t->t | a0 | a1 | a2; } +T bound_func3(Thing *t, T a0, T a1, T a2) +{ + return t->t | a0 | a1 | a2; +} template -T bound_func4(Thing *t, T a0, T a1, T a2, T a3) { return t->t | a0 | a1 | a2 | a3; } +T bound_func4(Thing *t, T a0, T a1, T a2, T a3) +{ + return t->t | a0 | a1 | a2 | a3; +} template -T bound_func5(Thing *t, T a0, T a1, T a2, T a3, T a4) { return t->t | a0 | a1 | a2 | a3 | a4; } +T bound_func5(Thing *t, T a0, T a1, T a2, T a3, T a4) +{ + return t->t | a0 | a1 | a2 | a3 | a4; +} // const bound functions template -T const_func0(const Thing *t) { return t->t; } +T const_func0(const Thing *t) +{ + return t->t; +} template -T const_func1(const Thing *t, T a0) { return t->t | a0; } +T const_func1(const Thing *t, T a0) +{ + return t->t | a0; +} template -T const_func2(const Thing *t, T a0, T a1) { return t->t | a0 | a1; } +T const_func2(const Thing *t, T a0, T a1) +{ + return t->t | a0 | a1; +} template -T const_func3(const Thing *t, T a0, T a1, T a2) { return t->t | a0 | a1 | a2; } +T const_func3(const Thing *t, T a0, T a1, T a2) +{ + return t->t | a0 | a1 | a2; +} template -T const_func4(const Thing *t, T a0, T a1, T a2, T a3) { return t->t | a0 | a1 | a2 | a3; } +T const_func4(const Thing *t, T a0, T a1, T a2, T a3) +{ + return t->t | a0 | a1 | a2 | a3; +} template -T const_func5(const Thing *t, T a0, T a1, T a2, T a3, T a4) { return t->t | a0 | a1 | a2 | a3 | a4; } +T const_func5(const Thing *t, T a0, T a1, T a2, T a3, T a4) +{ + return t->t | a0 | a1 | a2 | a3 | a4; +} // volatile bound functions template -T volatile_func0(volatile Thing *t) { return t->t; } +T volatile_func0(volatile Thing *t) +{ + return t->t; +} template -T volatile_func1(volatile Thing *t, T a0) { return t->t | a0; } +T volatile_func1(volatile Thing *t, T a0) +{ + return t->t | a0; +} template -T volatile_func2(volatile Thing *t, T a0, T a1) { return t->t | a0 | a1; } +T volatile_func2(volatile Thing *t, T a0, T a1) +{ + return t->t | a0 | a1; +} template -T volatile_func3(volatile Thing *t, T a0, T a1, T a2) { return t->t | a0 | a1 | a2; } +T volatile_func3(volatile Thing *t, T a0, T a1, T a2) +{ + return t->t | a0 | a1 | a2; +} template -T volatile_func4(volatile Thing *t, T a0, T a1, T a2, T a3) { return t->t | a0 | a1 | a2 | a3; } +T volatile_func4(volatile Thing *t, T a0, T a1, T a2, T a3) +{ + return t->t | a0 | a1 | a2 | a3; +} template -T volatile_func5(volatile Thing *t, T a0, T a1, T a2, T a3, T a4) { return t->t | a0 | a1 | a2 | a3 | a4; } +T volatile_func5(volatile Thing *t, T a0, T a1, T a2, T a3, T a4) +{ + return t->t | a0 | a1 | a2 | a3 | a4; +} // const volatile bound functions template -T const_volatile_func0(const volatile Thing *t) { return t->t; } +T const_volatile_func0(const volatile Thing *t) +{ + return t->t; +} template -T const_volatile_func1(const volatile Thing *t, T a0) { return t->t | a0; } +T const_volatile_func1(const volatile Thing *t, T a0) +{ + return t->t | a0; +} template -T const_volatile_func2(const volatile Thing *t, T a0, T a1) { return t->t | a0 | a1; } +T const_volatile_func2(const volatile Thing *t, T a0, T a1) +{ + return t->t | a0 | a1; +} template -T const_volatile_func3(const volatile Thing *t, T a0, T a1, T a2) { return t->t | a0 | a1 | a2; } +T const_volatile_func3(const volatile Thing *t, T a0, T a1, T a2) +{ + return t->t | a0 | a1 | a2; +} template -T const_volatile_func4(const volatile Thing *t, T a0, T a1, T a2, T a3) { return t->t | a0 | a1 | a2 | a3; } +T const_volatile_func4(const volatile Thing *t, T a0, T a1, T a2, T a3) +{ + return t->t | a0 | a1 | a2 | a3; +} template -T const_volatile_func5(const volatile Thing *t, T a0, T a1, T a2, T a3, T a4) { return t->t | a0 | a1 | a2 | a3 | a4; } +T const_volatile_func5(const volatile Thing *t, T a0, T a1, T a2, T a3, T a4) +{ + return t->t | a0 | a1 | a2 | a3 | a4; +} // function call and result verification template struct Verifier { - static void verify0(Callback func) { + static void verify0(Callback func) + { T result = func(); TEST_ASSERT_EQUAL(result, 0x00); } template - static void verify0(O *obj, M method) { + static void verify0(O *obj, M method) + { Callback func(obj, method); T result = func(); TEST_ASSERT_EQUAL(result, 0x80); } - static void verify1(Callback func) { + static void verify1(Callback func) + { T result = func((1 << 0)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0)); } template - static void verify1(O *obj, M method) { + static void verify1(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0)); } - static void verify2(Callback func) { + static void verify2(Callback func) + { T result = func((1 << 0), (1 << 1)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0) | (1 << 1)); } template - static void verify2(O *obj, M method) { + static void verify2(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0), (1 << 1)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0) | (1 << 1)); } - static void verify3(Callback func) { + static void verify3(Callback func) + { T result = func((1 << 0), (1 << 1), (1 << 2)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0) | (1 << 1) | (1 << 2)); } template - static void verify3(O *obj, M method) { + static void verify3(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0), (1 << 1), (1 << 2)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0) | (1 << 1) | (1 << 2)); } - static void verify4(Callback func) { + static void verify4(Callback func) + { T result = func((1 << 0), (1 << 1), (1 << 2), (1 << 3)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3)); } template - static void verify4(O *obj, M method) { + static void verify4(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0), (1 << 1), (1 << 2), (1 << 3)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3)); } - static void verify5(Callback func) { + static void verify5(Callback func) + { T result = func((1 << 0), (1 << 1), (1 << 2), (1 << 3), (1 << 4)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4)); } template - static void verify5(O *obj, M method) { + static void verify5(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0), (1 << 1), (1 << 2), (1 << 3), (1 << 4)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4)); @@ -206,17 +380,18 @@ struct Verifier { // test dispatch template -void test_dispatch0() { +void test_dispatch0() +{ Thing thing; Verifier::verify0(static_func0); Verifier::verify0(&thing, &Thing::member_func0); - Verifier::verify0((const Thing*)&thing, &Thing::const_member_func0); - Verifier::verify0((volatile Thing*)&thing, &Thing::volatile_member_func0); - Verifier::verify0((const volatile Thing*)&thing, &Thing::const_volatile_member_func0); + Verifier::verify0((const Thing *)&thing, &Thing::const_member_func0); + Verifier::verify0((volatile Thing *)&thing, &Thing::volatile_member_func0); + Verifier::verify0((const volatile Thing *)&thing, &Thing::const_volatile_member_func0); Verifier::verify0(&bound_func0, &thing); - Verifier::verify0(&const_func0, (const Thing*)&thing); - Verifier::verify0(&volatile_func0, (volatile Thing*)&thing); - Verifier::verify0(&const_volatile_func0, (const volatile Thing*)&thing); + Verifier::verify0(&const_func0, (const Thing *)&thing); + Verifier::verify0(&volatile_func0, (volatile Thing *)&thing); + Verifier::verify0(&const_volatile_func0, (const volatile Thing *)&thing); Verifier::verify0(callback(static_func0)); Callback cb(static_func0); @@ -225,21 +400,22 @@ void test_dispatch0() { Verifier::verify0(cb); cb.attach(&bound_func0, &thing); Verifier::verify0(&cb, &Callback::call); - Verifier::verify0(&Callback::thunk, (void*)&cb); + Verifier::verify0(&Callback::thunk, (void *)&cb); } template -void test_dispatch1() { +void test_dispatch1() +{ Thing thing; Verifier::verify1(static_func1); Verifier::verify1(&thing, &Thing::member_func1); - Verifier::verify1((const Thing*)&thing, &Thing::const_member_func1); - Verifier::verify1((volatile Thing*)&thing, &Thing::volatile_member_func1); - Verifier::verify1((const volatile Thing*)&thing, &Thing::const_volatile_member_func1); + Verifier::verify1((const Thing *)&thing, &Thing::const_member_func1); + Verifier::verify1((volatile Thing *)&thing, &Thing::volatile_member_func1); + Verifier::verify1((const volatile Thing *)&thing, &Thing::const_volatile_member_func1); Verifier::verify1(&bound_func1, &thing); - Verifier::verify1(&const_func1, (const Thing*)&thing); - Verifier::verify1(&volatile_func1, (volatile Thing*)&thing); - Verifier::verify1(&const_volatile_func1, (const volatile Thing*)&thing); + Verifier::verify1(&const_func1, (const Thing *)&thing); + Verifier::verify1(&volatile_func1, (volatile Thing *)&thing); + Verifier::verify1(&const_volatile_func1, (const volatile Thing *)&thing); Verifier::verify1(callback(static_func1)); Callback cb(static_func1); @@ -248,21 +424,22 @@ void test_dispatch1() { Verifier::verify1(cb); cb.attach(&bound_func1, &thing); Verifier::verify1(&cb, &Callback::call); - Verifier::verify1(&Callback::thunk, (void*)&cb); + Verifier::verify1(&Callback::thunk, (void *)&cb); } template -void test_dispatch2() { +void test_dispatch2() +{ Thing thing; Verifier::verify2(static_func2); Verifier::verify2(&thing, &Thing::member_func2); - Verifier::verify2((const Thing*)&thing, &Thing::const_member_func2); - Verifier::verify2((volatile Thing*)&thing, &Thing::volatile_member_func2); - Verifier::verify2((const volatile Thing*)&thing, &Thing::const_volatile_member_func2); + Verifier::verify2((const Thing *)&thing, &Thing::const_member_func2); + Verifier::verify2((volatile Thing *)&thing, &Thing::volatile_member_func2); + Verifier::verify2((const volatile Thing *)&thing, &Thing::const_volatile_member_func2); Verifier::verify2(&bound_func2, &thing); - Verifier::verify2(&const_func2, (const Thing*)&thing); - Verifier::verify2(&volatile_func2, (volatile Thing*)&thing); - Verifier::verify2(&const_volatile_func2, (const volatile Thing*)&thing); + Verifier::verify2(&const_func2, (const Thing *)&thing); + Verifier::verify2(&volatile_func2, (volatile Thing *)&thing); + Verifier::verify2(&const_volatile_func2, (const volatile Thing *)&thing); Verifier::verify2(callback(static_func2)); Callback cb(static_func2); @@ -271,21 +448,22 @@ void test_dispatch2() { Verifier::verify2(cb); cb.attach(&bound_func2, &thing); Verifier::verify2(&cb, &Callback::call); - Verifier::verify2(&Callback::thunk, (void*)&cb); + Verifier::verify2(&Callback::thunk, (void *)&cb); } template -void test_dispatch3() { +void test_dispatch3() +{ Thing thing; Verifier::verify3(static_func3); Verifier::verify3(&thing, &Thing::member_func3); - Verifier::verify3((const Thing*)&thing, &Thing::const_member_func3); - Verifier::verify3((volatile Thing*)&thing, &Thing::volatile_member_func3); - Verifier::verify3((const volatile Thing*)&thing, &Thing::const_volatile_member_func3); + Verifier::verify3((const Thing *)&thing, &Thing::const_member_func3); + Verifier::verify3((volatile Thing *)&thing, &Thing::volatile_member_func3); + Verifier::verify3((const volatile Thing *)&thing, &Thing::const_volatile_member_func3); Verifier::verify3(&bound_func3, &thing); - Verifier::verify3(&const_func3, (const Thing*)&thing); - Verifier::verify3(&volatile_func3, (volatile Thing*)&thing); - Verifier::verify3(&const_volatile_func3, (const volatile Thing*)&thing); + Verifier::verify3(&const_func3, (const Thing *)&thing); + Verifier::verify3(&volatile_func3, (volatile Thing *)&thing); + Verifier::verify3(&const_volatile_func3, (const volatile Thing *)&thing); Verifier::verify3(callback(static_func3)); Callback cb(static_func3); @@ -294,21 +472,22 @@ void test_dispatch3() { Verifier::verify3(cb); cb.attach(&bound_func3, &thing); Verifier::verify3(&cb, &Callback::call); - Verifier::verify3(&Callback::thunk, (void*)&cb); + Verifier::verify3(&Callback::thunk, (void *)&cb); } template -void test_dispatch4() { +void test_dispatch4() +{ Thing thing; Verifier::verify4(static_func4); Verifier::verify4(&thing, &Thing::member_func4); - Verifier::verify4((const Thing*)&thing, &Thing::const_member_func4); - Verifier::verify4((volatile Thing*)&thing, &Thing::volatile_member_func4); - Verifier::verify4((const volatile Thing*)&thing, &Thing::const_volatile_member_func4); + Verifier::verify4((const Thing *)&thing, &Thing::const_member_func4); + Verifier::verify4((volatile Thing *)&thing, &Thing::volatile_member_func4); + Verifier::verify4((const volatile Thing *)&thing, &Thing::const_volatile_member_func4); Verifier::verify4(&bound_func4, &thing); - Verifier::verify4(&const_func4, (const Thing*)&thing); - Verifier::verify4(&volatile_func4, (volatile Thing*)&thing); - Verifier::verify4(&const_volatile_func4, (const volatile Thing*)&thing); + Verifier::verify4(&const_func4, (const Thing *)&thing); + Verifier::verify4(&volatile_func4, (volatile Thing *)&thing); + Verifier::verify4(&const_volatile_func4, (const volatile Thing *)&thing); Verifier::verify4(callback(static_func4)); Callback cb(static_func4); @@ -317,21 +496,22 @@ void test_dispatch4() { Verifier::verify4(cb); cb.attach(&bound_func4, &thing); Verifier::verify4(&cb, &Callback::call); - Verifier::verify4(&Callback::thunk, (void*)&cb); + Verifier::verify4(&Callback::thunk, (void *)&cb); } template -void test_dispatch5() { +void test_dispatch5() +{ Thing thing; Verifier::verify5(static_func5); Verifier::verify5(&thing, &Thing::member_func5); - Verifier::verify5((const Thing*)&thing, &Thing::const_member_func5); - Verifier::verify5((volatile Thing*)&thing, &Thing::volatile_member_func5); - Verifier::verify5((const volatile Thing*)&thing, &Thing::const_volatile_member_func5); + Verifier::verify5((const Thing *)&thing, &Thing::const_member_func5); + Verifier::verify5((volatile Thing *)&thing, &Thing::volatile_member_func5); + Verifier::verify5((const volatile Thing *)&thing, &Thing::const_volatile_member_func5); Verifier::verify5(&bound_func5, &thing); - Verifier::verify5(&const_func5, (const Thing*)&thing); - Verifier::verify5(&volatile_func5, (volatile Thing*)&thing); - Verifier::verify5(&const_volatile_func5, (const volatile Thing*)&thing); + Verifier::verify5(&const_func5, (const Thing *)&thing); + Verifier::verify5(&volatile_func5, (volatile Thing *)&thing); + Verifier::verify5(&const_volatile_func5, (const volatile Thing *)&thing); Verifier::verify5(callback(static_func5)); Callback cb(static_func5); @@ -340,12 +520,13 @@ void test_dispatch5() { Verifier::verify5(cb); cb.attach(&bound_func5, &thing); Verifier::verify5(&cb, &Callback::call); - Verifier::verify5(&Callback::thunk, (void*)&cb); + Verifier::verify5(&Callback::thunk, (void *)&cb); } // Test setup -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(10, "default_auto"); return verbose_test_setup_handler(number_of_cases); } @@ -361,6 +542,7 @@ Case cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/TESTS/mbed_functional/callback_small/main.cpp b/TESTS/mbed_functional/callback_small/main.cpp index 583b8d0f534..262f69948e9 100644 --- a/TESTS/mbed_functional/callback_small/main.cpp +++ b/TESTS/mbed_functional/callback_small/main.cpp @@ -23,17 +23,35 @@ using namespace utest::v1; // static functions template -T static_func0() { return 0; } +T static_func0() +{ + return 0; +} template -T static_func1(T a0) { return 0 | a0; } +T static_func1(T a0) +{ + return 0 | a0; +} template -T static_func2(T a0, T a1) { return 0 | a0 | a1; } +T static_func2(T a0, T a1) +{ + return 0 | a0 | a1; +} template -T static_func3(T a0, T a1, T a2) { return 0 | a0 | a1 | a2; } +T static_func3(T a0, T a1, T a2) +{ + return 0 | a0 | a1 | a2; +} template -T static_func4(T a0, T a1, T a2, T a3) { return 0 | a0 | a1 | a2 | a3; } +T static_func4(T a0, T a1, T a2, T a3) +{ + return 0 | a0 | a1 | a2 | a3; +} template -T static_func5(T a0, T a1, T a2, T a3, T a4) { return 0 | a0 | a1 | a2 | a3 | a4; } +T static_func5(T a0, T a1, T a2, T a3, T a4) +{ + return 0 | a0 | a1 | a2 | a3 | a4; +} // class functions template @@ -41,162 +59,318 @@ struct Thing { T t; Thing() : t(0x80) {} - T member_func0() { return t; } - T member_func1(T a0) { return t | a0; } - T member_func2(T a0, T a1) { return t | a0 | a1; } - T member_func3(T a0, T a1, T a2) { return t | a0 | a1 | a2; } - T member_func4(T a0, T a1, T a2, T a3) { return t | a0 | a1 | a2 | a3; } - T member_func5(T a0, T a1, T a2, T a3, T a4) { return t | a0 | a1 | a2 | a3 | a4; } - - T const_member_func0() const { return t; } - T const_member_func1(T a0) const { return t | a0; } - T const_member_func2(T a0, T a1) const { return t | a0 | a1; } - T const_member_func3(T a0, T a1, T a2) const { return t | a0 | a1 | a2; } - T const_member_func4(T a0, T a1, T a2, T a3) const { return t | a0 | a1 | a2 | a3; } - T const_member_func5(T a0, T a1, T a2, T a3, T a4) const { return t | a0 | a1 | a2 | a3 | a4; } - - T volatile_member_func0() volatile { return t; } - T volatile_member_func1(T a0) volatile { return t | a0; } - T volatile_member_func2(T a0, T a1) volatile { return t | a0 | a1; } - T volatile_member_func3(T a0, T a1, T a2) volatile { return t | a0 | a1 | a2; } - T volatile_member_func4(T a0, T a1, T a2, T a3) volatile { return t | a0 | a1 | a2 | a3; } - T volatile_member_func5(T a0, T a1, T a2, T a3, T a4) volatile { return t | a0 | a1 | a2 | a3 | a4; } - - T const_volatile_member_func0() const volatile { return t; } - T const_volatile_member_func1(T a0) const volatile { return t | a0; } - T const_volatile_member_func2(T a0, T a1) const volatile { return t | a0 | a1; } - T const_volatile_member_func3(T a0, T a1, T a2) const volatile { return t | a0 | a1 | a2; } - T const_volatile_member_func4(T a0, T a1, T a2, T a3) const volatile { return t | a0 | a1 | a2 | a3; } - T const_volatile_member_func5(T a0, T a1, T a2, T a3, T a4) const volatile { return t | a0 | a1 | a2 | a3 | a4; } + T member_func0() + { + return t; + } + T member_func1(T a0) + { + return t | a0; + } + T member_func2(T a0, T a1) + { + return t | a0 | a1; + } + T member_func3(T a0, T a1, T a2) + { + return t | a0 | a1 | a2; + } + T member_func4(T a0, T a1, T a2, T a3) + { + return t | a0 | a1 | a2 | a3; + } + T member_func5(T a0, T a1, T a2, T a3, T a4) + { + return t | a0 | a1 | a2 | a3 | a4; + } + + T const_member_func0() const + { + return t; + } + T const_member_func1(T a0) const + { + return t | a0; + } + T const_member_func2(T a0, T a1) const + { + return t | a0 | a1; + } + T const_member_func3(T a0, T a1, T a2) const + { + return t | a0 | a1 | a2; + } + T const_member_func4(T a0, T a1, T a2, T a3) const + { + return t | a0 | a1 | a2 | a3; + } + T const_member_func5(T a0, T a1, T a2, T a3, T a4) const + { + return t | a0 | a1 | a2 | a3 | a4; + } + + T volatile_member_func0() volatile + { + return t; + } + T volatile_member_func1(T a0) volatile + { + return t | a0; + } + T volatile_member_func2(T a0, T a1) volatile + { + return t | a0 | a1; + } + T volatile_member_func3(T a0, T a1, T a2) volatile + { + return t | a0 | a1 | a2; + } + T volatile_member_func4(T a0, T a1, T a2, T a3) volatile + { + return t | a0 | a1 | a2 | a3; + } + T volatile_member_func5(T a0, T a1, T a2, T a3, T a4) volatile + { + return t | a0 | a1 | a2 | a3 | a4; + } + + T const_volatile_member_func0() const volatile + { + return t; + } + T const_volatile_member_func1(T a0) const volatile + { + return t | a0; + } + T const_volatile_member_func2(T a0, T a1) const volatile + { + return t | a0 | a1; + } + T const_volatile_member_func3(T a0, T a1, T a2) const volatile + { + return t | a0 | a1 | a2; + } + T const_volatile_member_func4(T a0, T a1, T a2, T a3) const volatile + { + return t | a0 | a1 | a2 | a3; + } + T const_volatile_member_func5(T a0, T a1, T a2, T a3, T a4) const volatile + { + return t | a0 | a1 | a2 | a3 | a4; + } }; // bound functions template -T bound_func0(Thing *t) { return t->t; } +T bound_func0(Thing *t) +{ + return t->t; +} template -T bound_func1(Thing *t, T a0) { return t->t | a0; } +T bound_func1(Thing *t, T a0) +{ + return t->t | a0; +} template -T bound_func2(Thing *t, T a0, T a1) { return t->t | a0 | a1; } +T bound_func2(Thing *t, T a0, T a1) +{ + return t->t | a0 | a1; +} template -T bound_func3(Thing *t, T a0, T a1, T a2) { return t->t | a0 | a1 | a2; } +T bound_func3(Thing *t, T a0, T a1, T a2) +{ + return t->t | a0 | a1 | a2; +} template -T bound_func4(Thing *t, T a0, T a1, T a2, T a3) { return t->t | a0 | a1 | a2 | a3; } +T bound_func4(Thing *t, T a0, T a1, T a2, T a3) +{ + return t->t | a0 | a1 | a2 | a3; +} template -T bound_func5(Thing *t, T a0, T a1, T a2, T a3, T a4) { return t->t | a0 | a1 | a2 | a3 | a4; } +T bound_func5(Thing *t, T a0, T a1, T a2, T a3, T a4) +{ + return t->t | a0 | a1 | a2 | a3 | a4; +} // const bound functions template -T const_func0(const Thing *t) { return t->t; } +T const_func0(const Thing *t) +{ + return t->t; +} template -T const_func1(const Thing *t, T a0) { return t->t | a0; } +T const_func1(const Thing *t, T a0) +{ + return t->t | a0; +} template -T const_func2(const Thing *t, T a0, T a1) { return t->t | a0 | a1; } +T const_func2(const Thing *t, T a0, T a1) +{ + return t->t | a0 | a1; +} template -T const_func3(const Thing *t, T a0, T a1, T a2) { return t->t | a0 | a1 | a2; } +T const_func3(const Thing *t, T a0, T a1, T a2) +{ + return t->t | a0 | a1 | a2; +} template -T const_func4(const Thing *t, T a0, T a1, T a2, T a3) { return t->t | a0 | a1 | a2 | a3; } +T const_func4(const Thing *t, T a0, T a1, T a2, T a3) +{ + return t->t | a0 | a1 | a2 | a3; +} template -T const_func5(const Thing *t, T a0, T a1, T a2, T a3, T a4) { return t->t | a0 | a1 | a2 | a3 | a4; } +T const_func5(const Thing *t, T a0, T a1, T a2, T a3, T a4) +{ + return t->t | a0 | a1 | a2 | a3 | a4; +} // volatile bound functions template -T volatile_func0(volatile Thing *t) { return t->t; } +T volatile_func0(volatile Thing *t) +{ + return t->t; +} template -T volatile_func1(volatile Thing *t, T a0) { return t->t | a0; } +T volatile_func1(volatile Thing *t, T a0) +{ + return t->t | a0; +} template -T volatile_func2(volatile Thing *t, T a0, T a1) { return t->t | a0 | a1; } +T volatile_func2(volatile Thing *t, T a0, T a1) +{ + return t->t | a0 | a1; +} template -T volatile_func3(volatile Thing *t, T a0, T a1, T a2) { return t->t | a0 | a1 | a2; } +T volatile_func3(volatile Thing *t, T a0, T a1, T a2) +{ + return t->t | a0 | a1 | a2; +} template -T volatile_func4(volatile Thing *t, T a0, T a1, T a2, T a3) { return t->t | a0 | a1 | a2 | a3; } +T volatile_func4(volatile Thing *t, T a0, T a1, T a2, T a3) +{ + return t->t | a0 | a1 | a2 | a3; +} template -T volatile_func5(volatile Thing *t, T a0, T a1, T a2, T a3, T a4) { return t->t | a0 | a1 | a2 | a3 | a4; } +T volatile_func5(volatile Thing *t, T a0, T a1, T a2, T a3, T a4) +{ + return t->t | a0 | a1 | a2 | a3 | a4; +} // const volatile bound functions template -T const_volatile_func0(const volatile Thing *t) { return t->t; } +T const_volatile_func0(const volatile Thing *t) +{ + return t->t; +} template -T const_volatile_func1(const volatile Thing *t, T a0) { return t->t | a0; } +T const_volatile_func1(const volatile Thing *t, T a0) +{ + return t->t | a0; +} template -T const_volatile_func2(const volatile Thing *t, T a0, T a1) { return t->t | a0 | a1; } +T const_volatile_func2(const volatile Thing *t, T a0, T a1) +{ + return t->t | a0 | a1; +} template -T const_volatile_func3(const volatile Thing *t, T a0, T a1, T a2) { return t->t | a0 | a1 | a2; } +T const_volatile_func3(const volatile Thing *t, T a0, T a1, T a2) +{ + return t->t | a0 | a1 | a2; +} template -T const_volatile_func4(const volatile Thing *t, T a0, T a1, T a2, T a3) { return t->t | a0 | a1 | a2 | a3; } +T const_volatile_func4(const volatile Thing *t, T a0, T a1, T a2, T a3) +{ + return t->t | a0 | a1 | a2 | a3; +} template -T const_volatile_func5(const volatile Thing *t, T a0, T a1, T a2, T a3, T a4) { return t->t | a0 | a1 | a2 | a3 | a4; } +T const_volatile_func5(const volatile Thing *t, T a0, T a1, T a2, T a3, T a4) +{ + return t->t | a0 | a1 | a2 | a3 | a4; +} // function call and result verification template struct Verifier { - static void verify0(Callback func) { + static void verify0(Callback func) + { T result = func(); TEST_ASSERT_EQUAL(result, 0x00); } template - static void verify0(O *obj, M method) { + static void verify0(O *obj, M method) + { Callback func(obj, method); T result = func(); TEST_ASSERT_EQUAL(result, 0x80); } - static void verify1(Callback func) { + static void verify1(Callback func) + { T result = func((1 << 0)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0)); } template - static void verify1(O *obj, M method) { + static void verify1(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0)); } - static void verify2(Callback func) { + static void verify2(Callback func) + { T result = func((1 << 0), (1 << 1)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0) | (1 << 1)); } template - static void verify2(O *obj, M method) { + static void verify2(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0), (1 << 1)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0) | (1 << 1)); } - static void verify3(Callback func) { + static void verify3(Callback func) + { T result = func((1 << 0), (1 << 1), (1 << 2)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0) | (1 << 1) | (1 << 2)); } template - static void verify3(O *obj, M method) { + static void verify3(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0), (1 << 1), (1 << 2)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0) | (1 << 1) | (1 << 2)); } - static void verify4(Callback func) { + static void verify4(Callback func) + { T result = func((1 << 0), (1 << 1), (1 << 2), (1 << 3)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3)); } template - static void verify4(O *obj, M method) { + static void verify4(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0), (1 << 1), (1 << 2), (1 << 3)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3)); } - static void verify5(Callback func) { + static void verify5(Callback func) + { T result = func((1 << 0), (1 << 1), (1 << 2), (1 << 3), (1 << 4)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4)); } template - static void verify5(O *obj, M method) { + static void verify5(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0), (1 << 1), (1 << 2), (1 << 3), (1 << 4)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4)); @@ -206,17 +380,18 @@ struct Verifier { // test dispatch template -void test_dispatch0() { +void test_dispatch0() +{ Thing thing; Verifier::verify0(static_func0); Verifier::verify0(&thing, &Thing::member_func0); - Verifier::verify0((const Thing*)&thing, &Thing::const_member_func0); - Verifier::verify0((volatile Thing*)&thing, &Thing::volatile_member_func0); - Verifier::verify0((const volatile Thing*)&thing, &Thing::const_volatile_member_func0); + Verifier::verify0((const Thing *)&thing, &Thing::const_member_func0); + Verifier::verify0((volatile Thing *)&thing, &Thing::volatile_member_func0); + Verifier::verify0((const volatile Thing *)&thing, &Thing::const_volatile_member_func0); Verifier::verify0(&bound_func0, &thing); - Verifier::verify0(&const_func0, (const Thing*)&thing); - Verifier::verify0(&volatile_func0, (volatile Thing*)&thing); - Verifier::verify0(&const_volatile_func0, (const volatile Thing*)&thing); + Verifier::verify0(&const_func0, (const Thing *)&thing); + Verifier::verify0(&volatile_func0, (volatile Thing *)&thing); + Verifier::verify0(&const_volatile_func0, (const volatile Thing *)&thing); Verifier::verify0(callback(static_func0)); Callback cb(static_func0); @@ -225,21 +400,22 @@ void test_dispatch0() { Verifier::verify0(cb); cb.attach(&bound_func0, &thing); Verifier::verify0(&cb, &Callback::call); - Verifier::verify0(&Callback::thunk, (void*)&cb); + Verifier::verify0(&Callback::thunk, (void *)&cb); } template -void test_dispatch1() { +void test_dispatch1() +{ Thing thing; Verifier::verify1(static_func1); Verifier::verify1(&thing, &Thing::member_func1); - Verifier::verify1((const Thing*)&thing, &Thing::const_member_func1); - Verifier::verify1((volatile Thing*)&thing, &Thing::volatile_member_func1); - Verifier::verify1((const volatile Thing*)&thing, &Thing::const_volatile_member_func1); + Verifier::verify1((const Thing *)&thing, &Thing::const_member_func1); + Verifier::verify1((volatile Thing *)&thing, &Thing::volatile_member_func1); + Verifier::verify1((const volatile Thing *)&thing, &Thing::const_volatile_member_func1); Verifier::verify1(&bound_func1, &thing); - Verifier::verify1(&const_func1, (const Thing*)&thing); - Verifier::verify1(&volatile_func1, (volatile Thing*)&thing); - Verifier::verify1(&const_volatile_func1, (const volatile Thing*)&thing); + Verifier::verify1(&const_func1, (const Thing *)&thing); + Verifier::verify1(&volatile_func1, (volatile Thing *)&thing); + Verifier::verify1(&const_volatile_func1, (const volatile Thing *)&thing); Verifier::verify1(callback(static_func1)); Callback cb(static_func1); @@ -248,21 +424,22 @@ void test_dispatch1() { Verifier::verify1(cb); cb.attach(&bound_func1, &thing); Verifier::verify1(&cb, &Callback::call); - Verifier::verify1(&Callback::thunk, (void*)&cb); + Verifier::verify1(&Callback::thunk, (void *)&cb); } template -void test_dispatch2() { +void test_dispatch2() +{ Thing thing; Verifier::verify2(static_func2); Verifier::verify2(&thing, &Thing::member_func2); - Verifier::verify2((const Thing*)&thing, &Thing::const_member_func2); - Verifier::verify2((volatile Thing*)&thing, &Thing::volatile_member_func2); - Verifier::verify2((const volatile Thing*)&thing, &Thing::const_volatile_member_func2); + Verifier::verify2((const Thing *)&thing, &Thing::const_member_func2); + Verifier::verify2((volatile Thing *)&thing, &Thing::volatile_member_func2); + Verifier::verify2((const volatile Thing *)&thing, &Thing::const_volatile_member_func2); Verifier::verify2(&bound_func2, &thing); - Verifier::verify2(&const_func2, (const Thing*)&thing); - Verifier::verify2(&volatile_func2, (volatile Thing*)&thing); - Verifier::verify2(&const_volatile_func2, (const volatile Thing*)&thing); + Verifier::verify2(&const_func2, (const Thing *)&thing); + Verifier::verify2(&volatile_func2, (volatile Thing *)&thing); + Verifier::verify2(&const_volatile_func2, (const volatile Thing *)&thing); Verifier::verify2(callback(static_func2)); Callback cb(static_func2); @@ -271,21 +448,22 @@ void test_dispatch2() { Verifier::verify2(cb); cb.attach(&bound_func2, &thing); Verifier::verify2(&cb, &Callback::call); - Verifier::verify2(&Callback::thunk, (void*)&cb); + Verifier::verify2(&Callback::thunk, (void *)&cb); } template -void test_dispatch3() { +void test_dispatch3() +{ Thing thing; Verifier::verify3(static_func3); Verifier::verify3(&thing, &Thing::member_func3); - Verifier::verify3((const Thing*)&thing, &Thing::const_member_func3); - Verifier::verify3((volatile Thing*)&thing, &Thing::volatile_member_func3); - Verifier::verify3((const volatile Thing*)&thing, &Thing::const_volatile_member_func3); + Verifier::verify3((const Thing *)&thing, &Thing::const_member_func3); + Verifier::verify3((volatile Thing *)&thing, &Thing::volatile_member_func3); + Verifier::verify3((const volatile Thing *)&thing, &Thing::const_volatile_member_func3); Verifier::verify3(&bound_func3, &thing); - Verifier::verify3(&const_func3, (const Thing*)&thing); - Verifier::verify3(&volatile_func3, (volatile Thing*)&thing); - Verifier::verify3(&const_volatile_func3, (const volatile Thing*)&thing); + Verifier::verify3(&const_func3, (const Thing *)&thing); + Verifier::verify3(&volatile_func3, (volatile Thing *)&thing); + Verifier::verify3(&const_volatile_func3, (const volatile Thing *)&thing); Verifier::verify3(callback(static_func3)); Callback cb(static_func3); @@ -294,21 +472,22 @@ void test_dispatch3() { Verifier::verify3(cb); cb.attach(&bound_func3, &thing); Verifier::verify3(&cb, &Callback::call); - Verifier::verify3(&Callback::thunk, (void*)&cb); + Verifier::verify3(&Callback::thunk, (void *)&cb); } template -void test_dispatch4() { +void test_dispatch4() +{ Thing thing; Verifier::verify4(static_func4); Verifier::verify4(&thing, &Thing::member_func4); - Verifier::verify4((const Thing*)&thing, &Thing::const_member_func4); - Verifier::verify4((volatile Thing*)&thing, &Thing::volatile_member_func4); - Verifier::verify4((const volatile Thing*)&thing, &Thing::const_volatile_member_func4); + Verifier::verify4((const Thing *)&thing, &Thing::const_member_func4); + Verifier::verify4((volatile Thing *)&thing, &Thing::volatile_member_func4); + Verifier::verify4((const volatile Thing *)&thing, &Thing::const_volatile_member_func4); Verifier::verify4(&bound_func4, &thing); - Verifier::verify4(&const_func4, (const Thing*)&thing); - Verifier::verify4(&volatile_func4, (volatile Thing*)&thing); - Verifier::verify4(&const_volatile_func4, (const volatile Thing*)&thing); + Verifier::verify4(&const_func4, (const Thing *)&thing); + Verifier::verify4(&volatile_func4, (volatile Thing *)&thing); + Verifier::verify4(&const_volatile_func4, (const volatile Thing *)&thing); Verifier::verify4(callback(static_func4)); Callback cb(static_func4); @@ -317,21 +496,22 @@ void test_dispatch4() { Verifier::verify4(cb); cb.attach(&bound_func4, &thing); Verifier::verify4(&cb, &Callback::call); - Verifier::verify4(&Callback::thunk, (void*)&cb); + Verifier::verify4(&Callback::thunk, (void *)&cb); } template -void test_dispatch5() { +void test_dispatch5() +{ Thing thing; Verifier::verify5(static_func5); Verifier::verify5(&thing, &Thing::member_func5); - Verifier::verify5((const Thing*)&thing, &Thing::const_member_func5); - Verifier::verify5((volatile Thing*)&thing, &Thing::volatile_member_func5); - Verifier::verify5((const volatile Thing*)&thing, &Thing::const_volatile_member_func5); + Verifier::verify5((const Thing *)&thing, &Thing::const_member_func5); + Verifier::verify5((volatile Thing *)&thing, &Thing::volatile_member_func5); + Verifier::verify5((const volatile Thing *)&thing, &Thing::const_volatile_member_func5); Verifier::verify5(&bound_func5, &thing); - Verifier::verify5(&const_func5, (const Thing*)&thing); - Verifier::verify5(&volatile_func5, (volatile Thing*)&thing); - Verifier::verify5(&const_volatile_func5, (const volatile Thing*)&thing); + Verifier::verify5(&const_func5, (const Thing *)&thing); + Verifier::verify5(&volatile_func5, (volatile Thing *)&thing); + Verifier::verify5(&const_volatile_func5, (const volatile Thing *)&thing); Verifier::verify5(callback(static_func5)); Callback cb(static_func5); @@ -340,12 +520,13 @@ void test_dispatch5() { Verifier::verify5(cb); cb.attach(&bound_func5, &thing); Verifier::verify5(&cb, &Callback::call); - Verifier::verify5(&Callback::thunk, (void*)&cb); + Verifier::verify5(&Callback::thunk, (void *)&cb); } // Test setup -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(10, "default_auto"); return verbose_test_setup_handler(number_of_cases); } @@ -361,6 +542,7 @@ Case cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/TESTS/mbed_functional/functionpointer/main.cpp b/TESTS/mbed_functional/functionpointer/main.cpp index 0850cf0da0b..ff4f370b06a 100644 --- a/TESTS/mbed_functional/functionpointer/main.cpp +++ b/TESTS/mbed_functional/functionpointer/main.cpp @@ -24,22 +24,34 @@ using namespace utest::v1; // static functions template T static_func0() - { return 0; } +{ + return 0; +} template T static_func1(T a0) - { return 0 | a0; } +{ + return 0 | a0; +} template T static_func2(T a0, T a1) - { return 0 | a0 | a1; } +{ + return 0 | a0 | a1; +} template T static_func3(T a0, T a1, T a2) - { return 0 | a0 | a1 | a2; } +{ + return 0 | a0 | a1 | a2; +} template T static_func4(T a0, T a1, T a2, T a3) - { return 0 | a0 | a1 | a2 | a3; } +{ + return 0 | a0 | a1 | a2 | a3; +} template T static_func5(T a0, T a1, T a2, T a3, T a4) - { return 0 | a0 | a1 | a2 | a3 | a4; } +{ + return 0 | a0 | a1 | a2 | a3 | a4; +} // class functions template @@ -48,277 +60,433 @@ struct Thing { Thing() : t(0x80) {} T member_func0() - { return t; } + { + return t; + } T member_func1(T a0) - { return t | a0; } + { + return t | a0; + } T member_func2(T a0, T a1) - { return t | a0 | a1; } + { + return t | a0 | a1; + } T member_func3(T a0, T a1, T a2) - { return t | a0 | a1 | a2; } + { + return t | a0 | a1 | a2; + } T member_func4(T a0, T a1, T a2, T a3) - { return t | a0 | a1 | a2 | a3; } + { + return t | a0 | a1 | a2 | a3; + } T member_func5(T a0, T a1, T a2, T a3, T a4) - { return t | a0 | a1 | a2 | a3 | a4; } + { + return t | a0 | a1 | a2 | a3 | a4; + } T const_member_func0() const - { return t; } + { + return t; + } T const_member_func1(T a0) const - { return t | a0; } + { + return t | a0; + } T const_member_func2(T a0, T a1) const - { return t | a0 | a1; } + { + return t | a0 | a1; + } T const_member_func3(T a0, T a1, T a2) const - { return t | a0 | a1 | a2; } + { + return t | a0 | a1 | a2; + } T const_member_func4(T a0, T a1, T a2, T a3) const - { return t | a0 | a1 | a2 | a3; } + { + return t | a0 | a1 | a2 | a3; + } T const_member_func5(T a0, T a1, T a2, T a3, T a4) const - { return t | a0 | a1 | a2 | a3 | a4; } + { + return t | a0 | a1 | a2 | a3 | a4; + } T volatile_member_func0() volatile - { return t; } + { + return t; + } T volatile_member_func1(T a0) volatile - { return t | a0; } + { + return t | a0; + } T volatile_member_func2(T a0, T a1) volatile - { return t | a0 | a1; } + { + return t | a0 | a1; + } T volatile_member_func3(T a0, T a1, T a2) volatile - { return t | a0 | a1 | a2; } + { + return t | a0 | a1 | a2; + } T volatile_member_func4(T a0, T a1, T a2, T a3) volatile - { return t | a0 | a1 | a2 | a3; } + { + return t | a0 | a1 | a2 | a3; + } T volatile_member_func5(T a0, T a1, T a2, T a3, T a4) volatile - { return t | a0 | a1 | a2 | a3 | a4; } + { + return t | a0 | a1 | a2 | a3 | a4; + } T const_volatile_member_func0() const volatile - { return t; } + { + return t; + } T const_volatile_member_func1(T a0) const volatile - { return t | a0; } + { + return t | a0; + } T const_volatile_member_func2(T a0, T a1) const volatile - { return t | a0 | a1; } + { + return t | a0 | a1; + } T const_volatile_member_func3(T a0, T a1, T a2) const volatile - { return t | a0 | a1 | a2; } + { + return t | a0 | a1 | a2; + } T const_volatile_member_func4(T a0, T a1, T a2, T a3) const volatile - { return t | a0 | a1 | a2 | a3; } + { + return t | a0 | a1 | a2 | a3; + } T const_volatile_member_func5(T a0, T a1, T a2, T a3, T a4) const volatile - { return t | a0 | a1 | a2 | a3 | a4; } + { + return t | a0 | a1 | a2 | a3 | a4; + } }; // bound functions template T bound_func0(Thing *t) - { return t->t; } +{ + return t->t; +} template T bound_func1(Thing *t, T a0) - { return t->t | a0; } +{ + return t->t | a0; +} template T bound_func2(Thing *t, T a0, T a1) - { return t->t | a0 | a1; } +{ + return t->t | a0 | a1; +} template T bound_func3(Thing *t, T a0, T a1, T a2) - { return t->t | a0 | a1 | a2; } +{ + return t->t | a0 | a1 | a2; +} template T bound_func4(Thing *t, T a0, T a1, T a2, T a3) - { return t->t | a0 | a1 | a2 | a3; } +{ + return t->t | a0 | a1 | a2 | a3; +} template T bound_func5(Thing *t, T a0, T a1, T a2, T a3, T a4) - { return t->t | a0 | a1 | a2 | a3 | a4; } +{ + return t->t | a0 | a1 | a2 | a3 | a4; +} template T const_bound_func0(const Thing *t) - { return t->t; } +{ + return t->t; +} template T const_bound_func1(const Thing *t, T a0) - { return t->t | a0; } +{ + return t->t | a0; +} template T const_bound_func2(const Thing *t, T a0, T a1) - { return t->t | a0 | a1; } +{ + return t->t | a0 | a1; +} template T const_bound_func3(const Thing *t, T a0, T a1, T a2) - { return t->t | a0 | a1 | a2; } +{ + return t->t | a0 | a1 | a2; +} template T const_bound_func4(const Thing *t, T a0, T a1, T a2, T a3) - { return t->t | a0 | a1 | a2 | a3; } +{ + return t->t | a0 | a1 | a2 | a3; +} template T const_bound_func5(const Thing *t, T a0, T a1, T a2, T a3, T a4) - { return t->t | a0 | a1 | a2 | a3 | a4; } +{ + return t->t | a0 | a1 | a2 | a3 | a4; +} template T volatile_bound_func0(volatile Thing *t) - { return t->t; } +{ + return t->t; +} template T volatile_bound_func1(volatile Thing *t, T a0) - { return t->t | a0; } +{ + return t->t | a0; +} template T volatile_bound_func2(volatile Thing *t, T a0, T a1) - { return t->t | a0 | a1; } +{ + return t->t | a0 | a1; +} template T volatile_bound_func3(volatile Thing *t, T a0, T a1, T a2) - { return t->t | a0 | a1 | a2; } +{ + return t->t | a0 | a1 | a2; +} template T volatile_bound_func4(volatile Thing *t, T a0, T a1, T a2, T a3) - { return t->t | a0 | a1 | a2 | a3; } +{ + return t->t | a0 | a1 | a2 | a3; +} template T volatile_bound_func5(volatile Thing *t, T a0, T a1, T a2, T a3, T a4) - { return t->t | a0 | a1 | a2 | a3 | a4; } +{ + return t->t | a0 | a1 | a2 | a3 | a4; +} template T const_volatile_bound_func0(const volatile Thing *t) - { return t->t; } +{ + return t->t; +} template T const_volatile_bound_func1(const volatile Thing *t, T a0) - { return t->t | a0; } +{ + return t->t | a0; +} template T const_volatile_bound_func2(const volatile Thing *t, T a0, T a1) - { return t->t | a0 | a1; } +{ + return t->t | a0 | a1; +} template T const_volatile_bound_func3(const volatile Thing *t, T a0, T a1, T a2) - { return t->t | a0 | a1 | a2; } +{ + return t->t | a0 | a1 | a2; +} template T const_volatile_bound_func4(const volatile Thing *t, T a0, T a1, T a2, T a3) - { return t->t | a0 | a1 | a2 | a3; } +{ + return t->t | a0 | a1 | a2 | a3; +} template T const_volatile_bound_func5(const volatile Thing *t, T a0, T a1, T a2, T a3, T a4) - { return t->t | a0 | a1 | a2 | a3 | a4; } +{ + return t->t | a0 | a1 | a2 | a3 | a4; +} // void functions template T void_func0(void *t) - { return static_cast*>(t)->t; } +{ + return static_cast*>(t)->t; +} template T void_func1(void *t, T a0) - { return static_cast*>(t)->t | a0; } +{ + return static_cast*>(t)->t | a0; +} template T void_func2(void *t, T a0, T a1) - { return static_cast*>(t)->t | a0 | a1; } +{ + return static_cast*>(t)->t | a0 | a1; +} template T void_func3(void *t, T a0, T a1, T a2) - { return static_cast*>(t)->t | a0 | a1 | a2; } +{ + return static_cast*>(t)->t | a0 | a1 | a2; +} template T void_func4(void *t, T a0, T a1, T a2, T a3) - { return static_cast*>(t)->t | a0 | a1 | a2 | a3; } +{ + return static_cast*>(t)->t | a0 | a1 | a2 | a3; +} template T void_func5(void *t, T a0, T a1, T a2, T a3, T a4) - { return static_cast*>(t)->t | a0 | a1 | a2 | a3 | a4; } +{ + return static_cast*>(t)->t | a0 | a1 | a2 | a3 | a4; +} template T const_void_func0(const void *t) - { return static_cast*>(t)->t; } +{ + return static_cast*>(t)->t; +} template T const_void_func1(const void *t, T a0) - { return static_cast*>(t)->t | a0; } +{ + return static_cast*>(t)->t | a0; +} template T const_void_func2(const void *t, T a0, T a1) - { return static_cast*>(t)->t | a0 | a1; } +{ + return static_cast*>(t)->t | a0 | a1; +} template T const_void_func3(const void *t, T a0, T a1, T a2) - { return static_cast*>(t)->t | a0 | a1 | a2; } +{ + return static_cast*>(t)->t | a0 | a1 | a2; +} template T const_void_func4(const void *t, T a0, T a1, T a2, T a3) - { return static_cast*>(t)->t | a0 | a1 | a2 | a3; } +{ + return static_cast*>(t)->t | a0 | a1 | a2 | a3; +} template T const_void_func5(const void *t, T a0, T a1, T a2, T a3, T a4) - { return static_cast*>(t)->t | a0 | a1 | a2 | a3 | a4; } +{ + return static_cast*>(t)->t | a0 | a1 | a2 | a3 | a4; +} template T volatile_void_func0(volatile void *t) - { return static_cast*>(t)->t; } +{ + return static_cast*>(t)->t; +} template T volatile_void_func1(volatile void *t, T a0) - { return static_cast*>(t)->t | a0; } +{ + return static_cast*>(t)->t | a0; +} template T volatile_void_func2(volatile void *t, T a0, T a1) - { return static_cast*>(t)->t | a0 | a1; } +{ + return static_cast*>(t)->t | a0 | a1; +} template T volatile_void_func3(volatile void *t, T a0, T a1, T a2) - { return static_cast*>(t)->t | a0 | a1 | a2; } +{ + return static_cast*>(t)->t | a0 | a1 | a2; +} template T volatile_void_func4(volatile void *t, T a0, T a1, T a2, T a3) - { return static_cast*>(t)->t | a0 | a1 | a2 | a3; } +{ + return static_cast*>(t)->t | a0 | a1 | a2 | a3; +} template T volatile_void_func5(volatile void *t, T a0, T a1, T a2, T a3, T a4) - { return static_cast*>(t)->t | a0 | a1 | a2 | a3 | a4; } +{ + return static_cast*>(t)->t | a0 | a1 | a2 | a3 | a4; +} template T const_volatile_void_func0(const volatile void *t) - { return static_cast*>(t)->t; } +{ + return static_cast*>(t)->t; +} template T const_volatile_void_func1(const volatile void *t, T a0) - { return static_cast*>(t)->t | a0; } +{ + return static_cast*>(t)->t | a0; +} template T const_volatile_void_func2(const volatile void *t, T a0, T a1) - { return static_cast*>(t)->t | a0 | a1; } +{ + return static_cast*>(t)->t | a0 | a1; +} template T const_volatile_void_func3(const volatile void *t, T a0, T a1, T a2) - { return static_cast*>(t)->t | a0 | a1 | a2; } +{ + return static_cast*>(t)->t | a0 | a1 | a2; +} template T const_volatile_void_func4(const volatile void *t, T a0, T a1, T a2, T a3) - { return static_cast*>(t)->t | a0 | a1 | a2 | a3; } +{ + return static_cast*>(t)->t | a0 | a1 | a2 | a3; +} template T const_volatile_void_func5(const volatile void *t, T a0, T a1, T a2, T a3, T a4) - { return static_cast*>(t)->t | a0 | a1 | a2 | a3 | a4; } +{ + return static_cast*>(t)->t | a0 | a1 | a2 | a3 | a4; +} // function call and result verification template struct Verifier { - static void verify0(Callback func) { + static void verify0(Callback func) + { T result = func(); TEST_ASSERT_EQUAL(result, 0x00); } template - static void verify0(O *obj, M method) { + static void verify0(O *obj, M method) + { Callback func(obj, method); T result = func(); TEST_ASSERT_EQUAL(result, 0x80); } - static void verify1(Callback func) { + static void verify1(Callback func) + { T result = func((1 << 0)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0)); } template - static void verify1(O *obj, M method) { + static void verify1(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0)); } - static void verify2(Callback func) { + static void verify2(Callback func) + { T result = func((1 << 0), (1 << 1)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0) | (1 << 1)); } template - static void verify2(O *obj, M method) { + static void verify2(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0), (1 << 1)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0) | (1 << 1)); } - static void verify3(Callback func) { + static void verify3(Callback func) + { T result = func((1 << 0), (1 << 1), (1 << 2)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0) | (1 << 1) | (1 << 2)); } template - static void verify3(O *obj, M method) { + static void verify3(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0), (1 << 1), (1 << 2)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0) | (1 << 1) | (1 << 2)); } - static void verify4(Callback func) { + static void verify4(Callback func) + { T result = func((1 << 0), (1 << 1), (1 << 2), (1 << 3)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3)); } template - static void verify4(O *obj, M method) { + static void verify4(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0), (1 << 1), (1 << 2), (1 << 3)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3)); } - static void verify5(Callback func) { + static void verify5(Callback func) + { T result = func((1 << 0), (1 << 1), (1 << 2), (1 << 3), (1 << 4)); TEST_ASSERT_EQUAL(result, 0x00 | (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4)); } template - static void verify5(O *obj, M method) { + static void verify5(O *obj, M method) + { Callback func(obj, method); T result = func((1 << 0), (1 << 1), (1 << 2), (1 << 3), (1 << 4)); TEST_ASSERT_EQUAL(result, 0x80 | (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4)); @@ -328,24 +496,27 @@ struct Verifier { // test dispatch template -void test_fparg1() { +void test_fparg1() +{ Thing thing; - FunctionPointerArg1 fp(static_func1); + FunctionPointerArg1 fp(static_func1); Verifier::verify1(fp); Verifier::verify1(fp.get_function()); } template -void test_fparg0() { +void test_fparg0() +{ Thing thing; - FunctionPointerArg1 fp(static_func0); + FunctionPointerArg1 fp(static_func0); Verifier::verify0(fp); Verifier::verify0(fp.get_function()); } // Test setup -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(10, "default_auto"); return verbose_test_setup_handler(number_of_cases); } @@ -357,6 +528,7 @@ Case cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/TESTS/mbed_hal/critical_section/main.cpp b/TESTS/mbed_hal/critical_section/main.cpp index faa0039fc80..abe1f7083e1 100644 --- a/TESTS/mbed_hal/critical_section/main.cpp +++ b/TESTS/mbed_hal/critical_section/main.cpp @@ -31,11 +31,11 @@ bool test_are_interrupts_enabled(void) // NRF5x targets don't disable interrupts when in critical section, instead they mask application interrupts this is due to BLE stack // (BLE to be operational requires some interrupts to be always enabled) #ifdef TARGET_NRF52_DK - // check if APP interrupts are masked for NRF52_DK board - return (((NVIC->ISER[0] & __NRF_NVIC_APP_IRQS_0) != 0) || ((NVIC->ISER[1] & __NRF_NVIC_APP_IRQS_1) != 0)); + // check if APP interrupts are masked for NRF52_DK board + return (((NVIC->ISER[0] & __NRF_NVIC_APP_IRQS_0) != 0) || ((NVIC->ISER[1] & __NRF_NVIC_APP_IRQS_1) != 0)); #elif TARGET_NRF5 - // check if APP interrupts are masked for other NRF5 boards - return ((NVIC->ISER[0] & __NRF_NVIC_APP_IRQS_0) != 0); + // check if APP interrupts are masked for other NRF5 boards + return ((NVIC->ISER[0] & __NRF_NVIC_APP_IRQS_0) != 0); #else #if defined(__CORTEX_A9) return ((__get_CPSR() & 0x80) == 0); diff --git a/TESTS/mbed_hal/flash/functional_tests/main.cpp b/TESTS/mbed_hal/flash/functional_tests/main.cpp index af101b7232b..93f093e5618 100644 --- a/TESTS/mbed_hal/flash/functional_tests/main.cpp +++ b/TESTS/mbed_hal/flash/functional_tests/main.cpp @@ -15,7 +15,7 @@ */ #if !DEVICE_FLASH - #error [NOT_SUPPORTED] Flash API not supported for this target +#error [NOT_SUPPORTED] Flash API not supported for this target #endif #include "utest/utest.h" @@ -56,40 +56,42 @@ static void erase_range(flash_t *flash, uint32_t addr, uint32_t size) MBED_NOINLINE __asm static void delay_loop(uint32_t count) { +// *INDENT-OFF* 1 SUBS a1, a1, #1 BCS %BT1 BX lr +// *INDENT-ON* } #elif defined (__ICCARM__) MBED_NOINLINE static void delay_loop(uint32_t count) { - __asm volatile( - "loop: \n" - " SUBS %0, %0, #1 \n" - " BCS.n loop\n" - : "+r" (count) - : - : "cc" - ); + __asm volatile( + "loop: \n" + " SUBS %0, %0, #1 \n" + " BCS.n loop\n" + : "+r"(count) + : + : "cc" + ); } #elif defined ( __GNUC__ ) || (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)) MBED_NOINLINE static void delay_loop(uint32_t count) { - __asm__ volatile ( - "%=:\n\t" + __asm__ volatile( + "%=:\n\t" #if defined(__thumb__) && !defined(__thumb2__) && !defined(__ARMCC_VERSION) - "SUB %0, #1\n\t" + "SUB %0, #1\n\t" #else - "SUBS %0, %0, #1\n\t" + "SUBS %0, %0, #1\n\t" #endif - "BCS %=b\n\t" - : "+l" (count) - : - : "cc" - ); + "BCS %=b\n\t" + : "+l"(count) + : + : "cc" + ); } #endif @@ -190,7 +192,7 @@ void flash_program_page_test() } // the one before the last page in the system - uint32_t address = flash_get_start_address(&test_flash) + flash_get_size(&test_flash) - (2*test_size); + uint32_t address = flash_get_start_address(&test_flash) + flash_get_size(&test_flash) - (2 * test_size); // sector size might not be same as page size uint32_t erase_sector_boundary = ALIGN_DOWN(address, flash_get_sector_size(&test_flash, address)); @@ -282,13 +284,15 @@ Case cases[] = { Case("Flash - clock and cache test", flash_clock_and_cache_test), }; -utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { +utest::v1::status_t greentea_test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(20, "default_auto"); return greentea_test_setup_handler(number_of_cases); } Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); -int main() { +int main() +{ Harness::run(specification); } diff --git a/TESTS/mbed_hal/lp_ticker/main.cpp b/TESTS/mbed_hal/lp_ticker/main.cpp index 5802644c580..40b5c15a9a5 100644 --- a/TESTS/mbed_hal/lp_ticker/main.cpp +++ b/TESTS/mbed_hal/lp_ticker/main.cpp @@ -15,7 +15,7 @@ */ #if !DEVICE_LOWPOWERTIMER - #error [NOT_SUPPORTED] Low power timer not supported for this target +#error [NOT_SUPPORTED] Low power timer not supported for this target #endif #include "utest/utest.h" @@ -38,7 +38,8 @@ static LowPowerTimer lp_timer; #define LONG_TIMEOUT (100000) #define SHORT_TIMEOUT (600) -void cb_done(uint32_t id) { +void cb_done(uint32_t id) +{ if ((uint32_t)&delay_event == id) { complete_time = timer.read_us(); complete = true; @@ -48,7 +49,8 @@ void cb_done(uint32_t id) { } } -void cb_done_deepsleep(uint32_t id) { +void cb_done_deepsleep(uint32_t id) +{ if ((uint32_t)&delay_event == id) { complete_time = lp_timer.read_us(); complete = true; @@ -160,7 +162,8 @@ void lp_ticker_5s(void) lp_ticker_delay_us(5000000, LONG_TIMEOUT); } -utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) { +utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) +{ greentea_case_failure_abort_handler(source, reason); return STATUS_CONTINUE; } @@ -176,7 +179,8 @@ Case cases[] = { #endif /* DEVICE_SLEEP */ }; -utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { +utest::v1::status_t greentea_test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(20, "default_auto"); lp_ticker_data->interface->init(); return greentea_test_setup_handler(number_of_cases); @@ -184,6 +188,7 @@ utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); -int main() { +int main() +{ Harness::run(specification); } diff --git a/TESTS/mbed_hal/lp_us_tickers/main.cpp b/TESTS/mbed_hal/lp_us_tickers/main.cpp index ddeab5de491..36fafb10a58 100644 --- a/TESTS/mbed_hal/lp_us_tickers/main.cpp +++ b/TESTS/mbed_hal/lp_us_tickers/main.cpp @@ -24,11 +24,11 @@ using namespace utest::v1; namespace { - volatile bool complete; - const ticker_interface_t* intf; +volatile bool complete; +const ticker_interface_t *intf; } -/* Ticker init should be run just once, thus read should always return a value that +/* Ticker init should be run just once, thus read should always return a value that * increases (no reset). */ void test_ticker_init(void) @@ -96,7 +96,7 @@ Case cases[] = { #endif }; -utest::v1::status_t greentea_test_setup(const size_t number_of_cases) +utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { GREENTEA_SETUP(20, "default_auto"); return greentea_test_setup_handler(number_of_cases); @@ -104,7 +104,7 @@ utest::v1::status_t greentea_test_setup(const size_t number_of_cases) Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); -int main() +int main() { Harness::run(specification); } diff --git a/TESTS/mbed_hal/rtc_time/main.cpp b/TESTS/mbed_hal/rtc_time/main.cpp index c101e19b625..fe063296772 100644 --- a/TESTS/mbed_hal/rtc_time/main.cpp +++ b/TESTS/mbed_hal/rtc_time/main.cpp @@ -73,8 +73,7 @@ void test_is_leap_year() } /* Structure to test border values for _rtc_maketime(). */ -typedef struct -{ +typedef struct { struct tm timeinfo; time_t exp_seconds; // if result is false then exp_seconds is irrelevant bool result; @@ -85,7 +84,7 @@ typedef struct * Expected range: the 1st of January 1970 at 00:00:00 (seconds: 0) to the 7th of February 2106 at 06:28:15 (seconds: UINT_MAX). */ test_mk_time_struct test_mk_time_arr_full[] = { - {{ 0, 0, 0, 1, 0, 70, 0, 0, 0 }, (time_t) 0, true}, // valid lower bound - the 1st of January 1970 at 00:00:00 + {{ 0, 0, 0, 1, 0, 70, 0, 0, 0 }, (time_t) 0, true}, // valid lower bound - the 1st of January 1970 at 00:00:00 {{ 59, 59, 23, 31, 11, 59, 0, 0, 0 }, (time_t) 0, false }, // invalid lower bound - the 31st of December 1969 at 23:59:59 {{ 15, 28, 6, 7, 1, 206, 0, 0, 0 }, (time_t)(UINT_MAX), true }, // valid upper bound - the 7th of February 2106 at 06:28:15 @@ -98,7 +97,7 @@ test_mk_time_struct test_mk_time_arr_full[] = { * Expected range: the 1st of January 1970 at 00:00:00 (seconds: 0) to the 6th of February 2106 at 06:28:15 (seconds: UINT_MAX). */ test_mk_time_struct test_mk_time_arr_partial[] = { - {{ 0, 0, 0, 1, 0, 70, 0, 0, 0 }, (time_t) 0, true}, // valid lower bound - the 1st of January 1970 at 00:00:00 + {{ 0, 0, 0, 1, 0, 70, 0, 0, 0 }, (time_t) 0, true}, // valid lower bound - the 1st of January 1970 at 00:00:00 {{ 59, 59, 23, 31, 11, 59, 0, 0, 0 }, (time_t) 0, false }, // invalid lower bound - the 31st of December 1969 at 23:59:59 {{ 15, 28, 6, 6, 1, 206, 0, 0, 0 }, (time_t)(UINT_MAX), true }, // valid upper bound - the 6th of February 2106 at 06:28:15 @@ -152,10 +151,10 @@ void test_mk_time_invalid_param() time_t seconds; struct tm timeinfo; - TEST_ASSERT_EQUAL(false, _rtc_maketime(NULL, &seconds, RTC_FULL_LEAP_YEAR_SUPPORT )); - TEST_ASSERT_EQUAL(false, _rtc_maketime(NULL, &seconds, RTC_4_YEAR_LEAP_YEAR_SUPPORT )); - TEST_ASSERT_EQUAL(false, _rtc_maketime(&timeinfo, NULL, RTC_FULL_LEAP_YEAR_SUPPORT )); - TEST_ASSERT_EQUAL(false, _rtc_maketime(&timeinfo, NULL, RTC_4_YEAR_LEAP_YEAR_SUPPORT )); + TEST_ASSERT_EQUAL(false, _rtc_maketime(NULL, &seconds, RTC_FULL_LEAP_YEAR_SUPPORT)); + TEST_ASSERT_EQUAL(false, _rtc_maketime(NULL, &seconds, RTC_4_YEAR_LEAP_YEAR_SUPPORT)); + TEST_ASSERT_EQUAL(false, _rtc_maketime(&timeinfo, NULL, RTC_FULL_LEAP_YEAR_SUPPORT)); + TEST_ASSERT_EQUAL(false, _rtc_maketime(&timeinfo, NULL, RTC_4_YEAR_LEAP_YEAR_SUPPORT)); } /* Test _rtc_localtime() function - call with invalid parameters. @@ -166,24 +165,24 @@ void test_mk_time_invalid_param() */ void test_local_time_invalid_param() { - TEST_ASSERT_EQUAL(false, _rtc_localtime(1, NULL, RTC_FULL_LEAP_YEAR_SUPPORT )); - TEST_ASSERT_EQUAL(false, _rtc_localtime(1, NULL, RTC_4_YEAR_LEAP_YEAR_SUPPORT )); + TEST_ASSERT_EQUAL(false, _rtc_localtime(1, NULL, RTC_FULL_LEAP_YEAR_SUPPORT)); + TEST_ASSERT_EQUAL(false, _rtc_localtime(1, NULL, RTC_4_YEAR_LEAP_YEAR_SUPPORT)); } -utest::v1::status_t teardown_handler_t(const Case * const source, const size_t passed, const size_t failed, - const failure_t reason) +utest::v1::status_t teardown_handler_t(const Case *const source, const size_t passed, const size_t failed, + const failure_t reason) { return greentea_case_teardown_handler(source, passed, failed, reason); } -utest::v1::status_t full_leap_year_case_setup_handler_t(const Case * const source, const size_t index_of_case) +utest::v1::status_t full_leap_year_case_setup_handler_t(const Case *const source, const size_t index_of_case) { rtc_leap_year_support = RTC_FULL_LEAP_YEAR_SUPPORT; return greentea_case_setup_handler(source, index_of_case); } -utest::v1::status_t partial_leap_year_case_setup_handler_t(const Case * const source, const size_t index_of_case) +utest::v1::status_t partial_leap_year_case_setup_handler_t(const Case *const source, const size_t index_of_case) { rtc_leap_year_support = RTC_4_YEAR_LEAP_YEAR_SUPPORT; @@ -191,12 +190,12 @@ utest::v1::status_t partial_leap_year_case_setup_handler_t(const Case * const so } Case cases[] = { - Case("test is leap year - RTC leap years full support", full_leap_year_case_setup_handler_t, test_is_leap_year, teardown_handler_t), - Case("test is leap year - RTC leap years partial support", partial_leap_year_case_setup_handler_t, test_is_leap_year, teardown_handler_t), - Case("test make time boundary values - RTC leap years full support", full_leap_year_case_setup_handler_t, test_mk_time_boundary, teardown_handler_t), - Case("test make time boundary values - RTC leap years partial support", partial_leap_year_case_setup_handler_t, test_mk_time_boundary, teardown_handler_t), - Case("test make time - invalid param", test_mk_time_invalid_param, teardown_handler_t), - Case("test local time - invalid param", test_local_time_invalid_param, teardown_handler_t), + Case("test is leap year - RTC leap years full support", full_leap_year_case_setup_handler_t, test_is_leap_year, teardown_handler_t), + Case("test is leap year - RTC leap years partial support", partial_leap_year_case_setup_handler_t, test_is_leap_year, teardown_handler_t), + Case("test make time boundary values - RTC leap years full support", full_leap_year_case_setup_handler_t, test_mk_time_boundary, teardown_handler_t), + Case("test make time boundary values - RTC leap years partial support", partial_leap_year_case_setup_handler_t, test_mk_time_boundary, teardown_handler_t), + Case("test make time - invalid param", test_mk_time_invalid_param, teardown_handler_t), + Case("test local time - invalid param", test_local_time_invalid_param, teardown_handler_t), }; utest::v1::status_t greentea_test_setup(const size_t number_of_cases) diff --git a/TESTS/mbed_hal/rtc_time_conv/main.cpp b/TESTS/mbed_hal/rtc_time_conv/main.cpp index a33b363492d..0a716542403 100644 --- a/TESTS/mbed_hal/rtc_time_conv/main.cpp +++ b/TESTS/mbed_hal/rtc_time_conv/main.cpp @@ -51,8 +51,8 @@ bool is_leap_year(int year) struct tm make_time_info(int year, int month, int day, int hours, int minutes, int seconds) { - struct tm timeinfo = - { seconds, // tm_sec + struct tm timeinfo = { + seconds, // tm_sec minutes, // tm_min hours, // tm_hour day, // tm_mday @@ -61,7 +61,7 @@ struct tm make_time_info(int year, int month, int day, int hours, int minutes, i 0, // tm_wday 0, // tm_yday 0, // tm_isdst - }; + }; return timeinfo; } @@ -79,9 +79,9 @@ struct tm make_time_info(int year, int month, int day, int hours, int minutes, i void test_case_mktime_localtime() { char _key[11] = - { }; + { }; char _value[128] = - { }; + { }; size_t years[] = {70, 71, 100, 196, 200, 205}; @@ -89,7 +89,7 @@ void test_case_mktime_localtime() greentea_send_kv("leap_year_setup", rtc_leap_year_support); /* Check the first and last last day of each month. */ - for (size_t year_id = 0; year_id < (sizeof(years) /sizeof(size_t)) ; ++year_id) { + for (size_t year_id = 0; year_id < (sizeof(years) / sizeof(size_t)) ; ++year_id) { for (size_t month = 0; month < 12; ++month) { for (size_t dayid = 0; dayid < 2; ++dayid) { @@ -100,8 +100,7 @@ void test_case_mktime_localtime() * day 0 - first, * day 1 - last * */ - switch (dayid) - { + switch (dayid) { case 0: day = 1; break; @@ -122,7 +121,7 @@ void test_case_mktime_localtime() } /* Additional conditions for RTCs with partial leap year support. */ - if(month == 1 && year == 200 && rtc_leap_year_support == RTC_4_YEAR_LEAP_YEAR_SUPPORT) { + if (month == 1 && year == 200 && rtc_leap_year_support == RTC_4_YEAR_LEAP_YEAR_SUPPORT) { day = 29; } @@ -172,30 +171,30 @@ void test_case_mktime_localtime() } } -utest::v1::status_t full_leap_year_case_setup_handler_t(const Case * const source, const size_t index_of_case) +utest::v1::status_t full_leap_year_case_setup_handler_t(const Case *const source, const size_t index_of_case) { rtc_leap_year_support = RTC_FULL_LEAP_YEAR_SUPPORT; return greentea_case_setup_handler(source, index_of_case); } -utest::v1::status_t partial_leap_year_case_setup_handler_t(const Case * const source, const size_t index_of_case) +utest::v1::status_t partial_leap_year_case_setup_handler_t(const Case *const source, const size_t index_of_case) { rtc_leap_year_support = RTC_4_YEAR_LEAP_YEAR_SUPPORT; return greentea_case_setup_handler(source, index_of_case); } -utest::v1::status_t teardown_handler_t(const Case * const source, const size_t passed, const size_t failed, - const failure_t reason) +utest::v1::status_t teardown_handler_t(const Case *const source, const size_t passed, const size_t failed, + const failure_t reason) { return greentea_case_teardown_handler(source, passed, failed, reason); } // Test cases -Case cases[] ={ - Case("test make time and local time - RTC leap years full support", full_leap_year_case_setup_handler_t, test_case_mktime_localtime, teardown_handler_t), - Case("test make time and local time - RTC leap years partial support", partial_leap_year_case_setup_handler_t, test_case_mktime_localtime, teardown_handler_t), +Case cases[] = { + Case("test make time and local time - RTC leap years full support", full_leap_year_case_setup_handler_t, test_case_mktime_localtime, teardown_handler_t), + Case("test make time and local time - RTC leap years partial support", partial_leap_year_case_setup_handler_t, test_case_mktime_localtime, teardown_handler_t), }; utest::v1::status_t greentea_test_setup(const size_t number_of_cases) diff --git a/TESTS/mbed_hal/sleep_manager/main.cpp b/TESTS/mbed_hal/sleep_manager/main.cpp index 07353f17d78..c04daca78c1 100644 --- a/TESTS/mbed_hal/sleep_manager/main.cpp +++ b/TESTS/mbed_hal/sleep_manager/main.cpp @@ -27,7 +27,7 @@ void sleep_manager_deepsleep_counter_test() { bool deep_sleep_allowed = sleep_manager_can_deep_sleep(); TEST_ASSERT_TRUE(deep_sleep_allowed); - + sleep_manager_lock_deep_sleep(); deep_sleep_allowed = sleep_manager_can_deep_sleep(); TEST_ASSERT_FALSE(deep_sleep_allowed); @@ -37,13 +37,13 @@ void sleep_manager_deepsleep_counter_test() TEST_ASSERT_TRUE(deep_sleep_allowed); } -utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) +utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) { greentea_case_failure_abort_handler(source, reason); return STATUS_CONTINUE; } -utest::v1::status_t greentea_test_setup(const size_t number_of_cases) +utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { GREENTEA_SETUP(20, "default_auto"); return greentea_test_setup_handler(number_of_cases); @@ -55,6 +55,7 @@ Case cases[] = { Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); -int main() { +int main() +{ Harness::run(specification); } diff --git a/TESTS/mbed_hal/sleep_manager_racecondition/main.cpp b/TESTS/mbed_hal/sleep_manager_racecondition/main.cpp index ed2aa2f3458..fcad7f24de0 100644 --- a/TESTS/mbed_hal/sleep_manager_racecondition/main.cpp +++ b/TESTS/mbed_hal/sleep_manager_racecondition/main.cpp @@ -83,7 +83,7 @@ void sleep_manager_irq_test() TEST_ASSERT_TRUE_MESSAGE(deep_sleep_allowed, "Deep sleep should be allowed"); } -utest::v1::status_t greentea_test_setup(const size_t number_of_cases) +utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { GREENTEA_SETUP(30, "default_auto"); return greentea_test_setup_handler(number_of_cases); @@ -96,6 +96,7 @@ Case cases[] = { Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); -int main() { +int main() +{ Harness::run(specification); } diff --git a/TESTS/mbed_hal/ticker/main.cpp b/TESTS/mbed_hal/ticker/main.cpp index 93ab4f4a94c..3e712757631 100644 --- a/TESTS/mbed_hal/ticker/main.cpp +++ b/TESTS/mbed_hal/ticker/main.cpp @@ -32,12 +32,12 @@ using namespace utest::v1; #define TIMESTAMP_MAX_DELTA_BITS(bits) ((uint64_t)(0x7 << ((bits) - 4))) #define TIMESTAMP_MAX_DELTA TIMESTAMP_MAX_DELTA_BITS(32) -struct ticker_interface_stub_t { +struct ticker_interface_stub_t { ticker_interface_t interface; - bool initialized; + bool initialized; bool interrupt_flag; timestamp_t timestamp ; - timestamp_t interrupt_timestamp; + timestamp_t interrupt_timestamp; unsigned int init_call; unsigned int read_call; unsigned int disable_interrupt_call; @@ -60,10 +60,10 @@ static uint32_t ticker_interface_stub_read() { ++interface_stub.read_call; return interface_stub.timestamp; -} +} static void ticker_interface_stub_disable_interrupt() -{ +{ ++interface_stub.disable_interrupt_call; } @@ -76,7 +76,7 @@ static void ticker_interface_stub_clear_interrupt() static void ticker_interface_stub_set_interrupt(timestamp_t timestamp) { ++interface_stub.set_interrupt_call; - interface_stub.interrupt_timestamp = timestamp; + interface_stub.interrupt_timestamp = timestamp; } static void ticker_interface_stub_fire_interrupt() @@ -94,11 +94,11 @@ static void reset_ticker_interface_stub() { interface_stub.interface.init = ticker_interface_stub_init; interface_stub.interface.read = ticker_interface_stub_read; - interface_stub.interface.disable_interrupt = + interface_stub.interface.disable_interrupt = ticker_interface_stub_disable_interrupt; - interface_stub.interface.clear_interrupt = + interface_stub.interface.clear_interrupt = ticker_interface_stub_clear_interrupt; - interface_stub.interface.set_interrupt =ticker_interface_stub_set_interrupt; + interface_stub.interface.set_interrupt = ticker_interface_stub_set_interrupt; interface_stub.interface.fire_interrupt = ticker_interface_stub_fire_interrupt; interface_stub.interface.get_info = ticker_interface_stub_get_info; interface_stub.initialized = false; @@ -116,7 +116,7 @@ static void reset_ticker_interface_stub() interface_info_stub.bits = 32; } -// stub of the event queue +// stub of the event queue static ticker_event_queue_t queue_stub = { /* event handler */ NULL, /* head */ NULL, @@ -180,7 +180,8 @@ static void test_over_frequency_and_width(void) static utest::v1::status_t case_setup_handler( const Case *const source, const size_t index_of_case -) { +) +{ utest::v1::status_t status = greentea_case_setup_handler(source, index_of_case); reset_ticker_stub(); return status; @@ -188,20 +189,22 @@ static utest::v1::status_t case_setup_handler( static utest::v1::status_t case_teardown_handler( const Case *const source, const size_t passed, const size_t failed, const failure_t reason -) { +) +{ reset_ticker_stub(); utest::v1::status_t status = greentea_case_teardown_handler( - source, passed, failed, reason - ); + source, passed, failed, reason + ); return status; } static utest::v1::status_t greentea_failure_handler( const Case *const source, const failure_t reason -) { +) +{ utest::v1::status_t status = greentea_case_failure_abort_handler( - source, reason - ); + source, reason + ); return status; } @@ -217,13 +220,13 @@ static utest::v1::status_t greentea_failure_handler( } /** - * Given an unitialized ticker_data instance. - * When the ticker is initialized - * Then: - * - The ticker interface should be initialized + * Given an unitialized ticker_data instance. + * When the ticker is initialized + * Then: + * - The ticker interface should be initialized * - The queue handler should be set to the handler provided in parameter * - The internal ticker timestamp should be zero - * - interrupt should be scheduled in current timestamp + + * - interrupt should be scheduled in current timestamp + * TIMESTAMP_MAX_DELTA * - The queue should not contains any event */ @@ -231,7 +234,7 @@ static void test_ticker_initialization() { ticker_event_handler dummy_handler = (ticker_event_handler)0xDEADBEEF; - // setup of the stub + // setup of the stub interface_stub.timestamp = 0xFEEDBABE; ticker_set_handler(&ticker_stub, dummy_handler); @@ -249,9 +252,9 @@ static void test_ticker_initialization() } /** - * Given an initialized ticker_data instance. - * When the ticker handler is set to a new value - * Then: + * Given an initialized ticker_data instance. + * When the ticker handler is set to a new value + * Then: * - The ticker interface initialization function should not be called. * - The queue handler should be set to the new handler. * - The events in the queue should remains the same. @@ -260,10 +263,10 @@ static void test_ticker_re_initialization() { ticker_event_handler dummy_handler = (ticker_event_handler) 0xDEADBEEF; ticker_event_handler expected_handler = (ticker_event_handler) 0xFEEDDEAF; - - ticker_event_t first_event = { 0 }; - ticker_event_t second_event = { 0 }; - ticker_event_t third_event = { 0 }; + + ticker_event_t first_event = { 0 }; + ticker_event_t second_event = { 0 }; + ticker_event_t third_event = { 0 }; first_event.next = &second_event; second_event.next = &third_event; @@ -287,15 +290,15 @@ static void test_ticker_re_initialization() } /** - * Given an initialized ticker_data instance. - * When the ticker is read + * Given an initialized ticker_data instance. + * When the ticker is read * Then it should return the value present in the ticker interface */ static void test_ticker_read() { ticker_set_handler(&ticker_stub, NULL); - timestamp_t timestamps[] = { + timestamp_t timestamps[] = { 0xA, 0xAA, 0xAAA, @@ -316,19 +319,19 @@ static void test_ticker_read() } /** - * Given an initialized ticker_data instance. - * When the ticker is read and the value read is less than the previous + * Given an initialized ticker_data instance. + * When the ticker is read and the value read is less than the previous * value read. * Then: - * - ticker_read should return the value read in the ticker interface - * - ticker_read_us should return a value where: + * - ticker_read should return the value read in the ticker interface + * - ticker_read_us should return a value where: * + lower 8 bytes should be equal to the value in the ticker interface * + upper 8 bytes should be equal to the previous value of upper 8 bytes * plus one. */ static void test_ticker_read_overflow() { - const timestamp_t timestamps[] = { + const timestamp_t timestamps[] = { 0xAAAAAAAA, 0xAAAAAAA, 0xAAAAAA, @@ -356,15 +359,15 @@ static void test_ticker_read_overflow() } /** - * Given an initialized ticker without user registered events. - * When an event is inserted with ticker_insert_event and the timestamp passed - * in parameter is in range [ticker_timestamp : ticker_timestamp + + * Given an initialized ticker without user registered events. + * When an event is inserted with ticker_insert_event and the timestamp passed + * in parameter is in range [ticker_timestamp : ticker_timestamp + * TIMESTAMP_MAX_DELTA[. - * Then + * Then * - The event should be in the queue - * - The interrupt timestamp should be equal to the timestamp of the event - * - The timestamp of the event should reflect the timestamp requested. - * - The id of the event should be equal to the id passed in parameter. + * - The interrupt timestamp should be equal to the timestamp of the event + * - The timestamp of the event should reflect the timestamp requested. + * - The id of the event should be equal to the id passed in parameter. */ static void test_legacy_insert_event_outside_overflow_range() { @@ -373,17 +376,17 @@ static void test_legacy_insert_event_outside_overflow_range() // test the end of the range ticker_event_t last_event = { 0 }; - const timestamp_t timestamp_last_event = - interface_stub.timestamp + TIMESTAMP_MAX_DELTA; + const timestamp_t timestamp_last_event = + interface_stub.timestamp + TIMESTAMP_MAX_DELTA; const uint32_t id_last_event = 0xDEADDEAF; ticker_insert_event( - &ticker_stub, + &ticker_stub, &last_event, timestamp_last_event, id_last_event ); TEST_ASSERT_EQUAL_PTR(&last_event, queue_stub.head); - TEST_ASSERT_EQUAL(1, interface_stub.set_interrupt_call); + TEST_ASSERT_EQUAL(1, interface_stub.set_interrupt_call); TEST_ASSERT_EQUAL_UINT32( timestamp_last_event, interface_stub.interrupt_timestamp ); @@ -397,12 +400,12 @@ static void test_legacy_insert_event_outside_overflow_range() const uint32_t id_first_event = 0xAAAAAAAA; ticker_insert_event( - &ticker_stub, + &ticker_stub, &first_event, timestamp_first_event, id_first_event ); TEST_ASSERT_EQUAL_PTR(&first_event, queue_stub.head); - TEST_ASSERT_EQUAL(2, interface_stub.set_interrupt_call); + TEST_ASSERT_EQUAL(2, interface_stub.set_interrupt_call); TEST_ASSERT_EQUAL_UINT32( timestamp_first_event, interface_stub.interrupt_timestamp ); @@ -413,19 +416,19 @@ static void test_legacy_insert_event_outside_overflow_range() TEST_ASSERT_EQUAL_UINT32(id_first_event, first_event.id); TEST_ASSERT_EQUAL(0, interface_stub.disable_interrupt_call); -} +} /** - * Given an initialized ticker without user registered events. - * When an event is inserted with ticker_insert_event and a timestamp in the - * range [ticker_timestamp + TIMESTAMP_MAX_DELTA + 1 : + * Given an initialized ticker without user registered events. + * When an event is inserted with ticker_insert_event and a timestamp in the + * range [ticker_timestamp + TIMESTAMP_MAX_DELTA + 1 : * ticker_timestamp + UINT32MAX [ - * Then + * Then * - The event should be in the queue - * - The interrupt timestamp should be equal to - * TIMESTAMP_MAX_DELTA - * - The timestamp of the event should reflect the timestamp requested. - * - The id of the event should be equal to the id passed in parameter. + * - The interrupt timestamp should be equal to + * TIMESTAMP_MAX_DELTA + * - The timestamp of the event should reflect the timestamp requested. + * - The id of the event should be equal to the id passed in parameter. */ static void test_legacy_insert_event_in_overflow_range() { @@ -434,19 +437,19 @@ static void test_legacy_insert_event_in_overflow_range() // test the end of the range ticker_event_t last_event = { 0 }; - const timestamp_t timestamp_last_event = - interface_stub.timestamp + UINT32_MAX; + const timestamp_t timestamp_last_event = + interface_stub.timestamp + UINT32_MAX; const uint32_t id_last_event = 0xDEADDEAF; ticker_insert_event( - &ticker_stub, + &ticker_stub, &last_event, timestamp_last_event, id_last_event ); TEST_ASSERT_EQUAL_PTR(&last_event, queue_stub.head); - TEST_ASSERT_EQUAL(1, interface_stub.set_interrupt_call); + TEST_ASSERT_EQUAL(1, interface_stub.set_interrupt_call); TEST_ASSERT_EQUAL_UINT32( - interface_stub.timestamp + TIMESTAMP_MAX_DELTA, + interface_stub.timestamp + TIMESTAMP_MAX_DELTA, interface_stub.interrupt_timestamp ); TEST_ASSERT_EQUAL_PTR(NULL, queue_stub.head->next); @@ -457,19 +460,19 @@ static void test_legacy_insert_event_in_overflow_range() ++interface_stub.timestamp; ticker_event_t first_event = { 0 }; - const timestamp_t timestamp_first_event = - interface_stub.timestamp + TIMESTAMP_MAX_DELTA + 1; + const timestamp_t timestamp_first_event = + interface_stub.timestamp + TIMESTAMP_MAX_DELTA + 1; const uint32_t id_first_event = 0xAAAAAAAA; ticker_insert_event( - &ticker_stub, + &ticker_stub, &first_event, timestamp_first_event, id_first_event ); TEST_ASSERT_EQUAL_PTR(&first_event, queue_stub.head); - TEST_ASSERT_EQUAL(2, interface_stub.set_interrupt_call); + TEST_ASSERT_EQUAL(2, interface_stub.set_interrupt_call); TEST_ASSERT_EQUAL_UINT32( - interface_stub.timestamp + TIMESTAMP_MAX_DELTA, + interface_stub.timestamp + TIMESTAMP_MAX_DELTA, interface_stub.interrupt_timestamp ); TEST_ASSERT_EQUAL_PTR(&last_event, queue_stub.head->next); @@ -479,21 +482,22 @@ static void test_legacy_insert_event_in_overflow_range() TEST_ASSERT_EQUAL_UINT32(id_first_event, first_event.id); TEST_ASSERT_EQUAL(0, interface_stub.disable_interrupt_call); -} +} /** - * Given an initialized ticker without user registered events. - * When an event is inserted with ticker_insert_event and the timestamp in + * Given an initialized ticker without user registered events. + * When an event is inserted with ticker_insert_event and the timestamp in * parameter is less than the current timestamp value. - * Then + * Then * - The event should be in the queue * - The timestamp of the event should reflect the timestamp requested: - * + lower 8 bytes should be equal to the timestamp in input. + * + lower 8 bytes should be equal to the timestamp in input. * + upper 8 bytes should be equal to the upper of the upper 8 bytes of the * timestamp state stored in the queue plus one. - * - The id of the event should be equal to the id passed in parameter. + * - The id of the event should be equal to the id passed in parameter. */ -static void test_legacy_insert_event_overflow(){ +static void test_legacy_insert_event_overflow() +{ ticker_set_handler(&ticker_stub, NULL); interface_stub.set_interrupt_call = 0; @@ -501,23 +505,23 @@ static void test_legacy_insert_event_overflow(){ ticker_read(&ticker_stub); ticker_event_t event = { 0 }; - const timestamp_t expected_timestamp = - interface_stub.timestamp + - TIMESTAMP_MAX_DELTA + - 1; - const us_timestamp_t expected_us_timestamp = + const timestamp_t expected_timestamp = + interface_stub.timestamp + + TIMESTAMP_MAX_DELTA + + 1; + const us_timestamp_t expected_us_timestamp = (((queue_stub.present_time >> 32) + 1) << 32) | expected_timestamp; const uint32_t expected_id = 0xDEADDEAF; ticker_insert_event( - &ticker_stub, + &ticker_stub, &event, expected_timestamp, expected_id ); TEST_ASSERT_EQUAL_PTR(&event, queue_stub.head); - TEST_ASSERT_EQUAL(1, interface_stub.set_interrupt_call); + TEST_ASSERT_EQUAL(1, interface_stub.set_interrupt_call); TEST_ASSERT_EQUAL_UINT32( - interface_stub.timestamp + TIMESTAMP_MAX_DELTA, + interface_stub.timestamp + TIMESTAMP_MAX_DELTA, interface_stub.interrupt_timestamp ); TEST_ASSERT_EQUAL_PTR(NULL, queue_stub.head->next); @@ -525,18 +529,18 @@ static void test_legacy_insert_event_overflow(){ TEST_ASSERT_EQUAL_UINT32(expected_id, event.id); TEST_ASSERT_EQUAL(0, interface_stub.disable_interrupt_call); -} +} /** * Given an initialized ticker. - * When an event is inserted with ticker_insert_event and a timestamp less than + * When an event is inserted with ticker_insert_event and a timestamp less than * the one for the next scheduled timestamp. - * Then + * Then * - The event inserted should be the first in the queue - * - The interrupt timestamp should be equal to the timestamp of the event or + * - The interrupt timestamp should be equal to the timestamp of the event or * TIMESTAMP_MAX_DELTA if in the overflow range. * - The timestamp of the event should reflect the timestamp requested. - * - The id of the event should be equal to the id passed in parameter. + * - The id of the event should be equal to the id passed in parameter. * - Events in the queue should remained ordered by timestamp. */ static void test_legacy_insert_event_head() @@ -544,7 +548,7 @@ static void test_legacy_insert_event_head() ticker_set_handler(&ticker_stub, NULL); interface_stub.set_interrupt_call = 0; - const timestamp_t timestamps[] = { + const timestamp_t timestamps[] = { UINT32_MAX, TIMESTAMP_MAX_DELTA + 1, TIMESTAMP_MAX_DELTA, @@ -555,22 +559,22 @@ static void test_legacy_insert_event_head() }; ticker_event_t events[MBED_ARRAY_SIZE(timestamps)] = { 0 }; - for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { + for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { ticker_insert_event( - &ticker_stub, + &ticker_stub, &events[i], timestamps[i], i ); TEST_ASSERT_EQUAL_PTR(&events[i], queue_stub.head); - TEST_ASSERT_EQUAL(i + 1, interface_stub.set_interrupt_call); - if (timestamps[i] < TIMESTAMP_MAX_DELTA) { + TEST_ASSERT_EQUAL(i + 1, interface_stub.set_interrupt_call); + if (timestamps[i] < TIMESTAMP_MAX_DELTA) { TEST_ASSERT_EQUAL_UINT32( - timestamps[i], + timestamps[i], interface_stub.interrupt_timestamp ); - } else { + } else { TEST_ASSERT_EQUAL_UINT32( - TIMESTAMP_MAX_DELTA, + TIMESTAMP_MAX_DELTA, interface_stub.interrupt_timestamp ); } @@ -580,13 +584,13 @@ static void test_legacy_insert_event_head() ); TEST_ASSERT_EQUAL_UINT32(i, events[i].id); - ticker_event_t* e = &events[i]; - while (e) { + ticker_event_t *e = &events[i]; + while (e) { TEST_ASSERT_EQUAL_UINT32(timestamps[e->id], e->timestamp); - if (e->next) { + if (e->next) { TEST_ASSERT_TRUE(e->id > e->next->id); TEST_ASSERT_TRUE(e->timestamp < e->next->timestamp); - } else { + } else { TEST_ASSERT_EQUAL_UINT32(0, e->id); } e = e->next; @@ -594,18 +598,18 @@ static void test_legacy_insert_event_head() } TEST_ASSERT_EQUAL(0, interface_stub.disable_interrupt_call); -} +} -/** +/** * Given an initialized ticker. - * When an event is inserted with ticker_insert_event and its timestamp is bigger + * When an event is inserted with ticker_insert_event and its timestamp is bigger * than the one of the last event in the queue. - * Then + * Then * - The event inserted should be the last in the queue - * - The interrupt timestamp should remains equal to the interrupt timestamp + * - The interrupt timestamp should remains equal to the interrupt timestamp * of the head event . * - The timestamp of the event should reflect the timestamp requested. - * - The id of the event should be equal to the id passed in parameter. + * - The id of the event should be equal to the id passed in parameter. * - Events in the queue should remained ordered by timestamp. */ static void test_legacy_insert_event_tail() @@ -613,7 +617,7 @@ static void test_legacy_insert_event_tail() ticker_set_handler(&ticker_stub, NULL); interface_stub.set_interrupt_call = 0; - const timestamp_t timestamps[] = { + const timestamp_t timestamps[] = { 0xA, 0xAA, 0xAAA, @@ -625,9 +629,9 @@ static void test_legacy_insert_event_tail() }; ticker_event_t events[MBED_ARRAY_SIZE(timestamps)] = { 0 }; - for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { + for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { ticker_insert_event( - &ticker_stub, + &ticker_stub, &events[i], timestamps[i], i ); @@ -639,13 +643,13 @@ static void test_legacy_insert_event_tail() TEST_ASSERT_EQUAL_UINT32(timestamps[i], events[i].timestamp); TEST_ASSERT_EQUAL_UINT32(i, events[i].id); - ticker_event_t* e = queue_stub.head; - while (e) { + ticker_event_t *e = queue_stub.head; + while (e) { TEST_ASSERT_EQUAL_UINT32(timestamps[e->id], e->timestamp); - if (e->next) { + if (e->next) { TEST_ASSERT_TRUE(e->id < e->next->id); TEST_ASSERT_TRUE(e->timestamp < e->next->timestamp); - } else { + } else { TEST_ASSERT_EQUAL_UINT32(&events[i], e); } e = e->next; @@ -653,19 +657,19 @@ static void test_legacy_insert_event_tail() } TEST_ASSERT_EQUAL(0, interface_stub.disable_interrupt_call); -} +} /** * Given an initialized ticker. - * When an event is inserted with ticker_insert_event and a timestamp less - * than the current timestamp in the interface and less than the relative + * When an event is inserted with ticker_insert_event and a timestamp less + * than the current timestamp in the interface and less than the relative * timestamp of the next event to execute. - * Then + * Then * - The event inserted should be after the head - * - The interrupt timestamp should remains equal to the interrupt timestamp + * - The interrupt timestamp should remains equal to the interrupt timestamp * of the head event . * - The timestamp of the event should reflect the timestamp requested (overflow) - * - The id of the event should be equal to the id passed in parameter. + * - The id of the event should be equal to the id passed in parameter. * - Events in the queue should remained ordered by timestamp. */ static void test_legacy_insert_event_multiple_overflow() @@ -673,7 +677,7 @@ static void test_legacy_insert_event_multiple_overflow() ticker_set_handler(&ticker_stub, NULL); interface_stub.set_interrupt_call = 0; - const timestamp_t timestamps[] = { + const timestamp_t timestamps[] = { 0xA, 0xAA, 0xAAA, @@ -688,19 +692,19 @@ static void test_legacy_insert_event_multiple_overflow() ticker_event_t ref_event; timestamp_t ref_event_timestamp = 0xCCCCCCCC; ticker_insert_event( - &ticker_stub, + &ticker_stub, &ref_event, ref_event_timestamp, 0xDEADBEEF ); - timestamp_t last_timestamp_to_insert = + timestamp_t last_timestamp_to_insert = timestamps[MBED_ARRAY_SIZE(timestamps) - 1]; - interface_stub.timestamp = - last_timestamp_to_insert + + interface_stub.timestamp = + last_timestamp_to_insert + ((ref_event_timestamp - last_timestamp_to_insert) / 2); - for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { + for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { ticker_insert_event( - &ticker_stub, + &ticker_stub, &events[i], timestamps[i], i ); @@ -713,13 +717,13 @@ static void test_legacy_insert_event_multiple_overflow() TEST_ASSERT_EQUAL_UINT32(timestamps[i], events[i].timestamp); TEST_ASSERT_EQUAL_UINT32(i, events[i].id); - ticker_event_t* e = queue_stub.head->next; - while (e) { + ticker_event_t *e = queue_stub.head->next; + while (e) { TEST_ASSERT_EQUAL_UINT32(timestamps[e->id], e->timestamp); - if (e->next) { + if (e->next) { TEST_ASSERT_TRUE(e->id < e->next->id); TEST_ASSERT_TRUE(e->timestamp < e->next->timestamp); - } else { + } else { TEST_ASSERT_EQUAL_UINT32(&events[i], e); } e = e->next; @@ -732,14 +736,14 @@ static void test_legacy_insert_event_multiple_overflow() /** * Given an initialized ticker. * When an event is inserted with ticker_insert_event. - * Then + * Then * - The event inserted should be at the correct position in the queue * - The event queue should remain ordered by timestamp - * - The interrupt timestamp should be equal to the interrupt timestamp - * of the head event or TIMESTAMP_MAX_DELTA if the + * - The interrupt timestamp should be equal to the interrupt timestamp + * of the head event or TIMESTAMP_MAX_DELTA if the * timestamp is in the overflow range. * - The timestamp of the event should reflect the timestamp requested (overflow) - * - The id of the event should be equal to the id passed in parameter. + * - The id of the event should be equal to the id passed in parameter. * - Events in the queue should remained ordered by timestamp. */ static void test_legacy_insert_event_multiple_random() @@ -750,9 +754,9 @@ static void test_legacy_insert_event_multiple_random() const timestamp_t ref_timestamp = UINT32_MAX / 2; interface_stub.timestamp = ref_timestamp; - // insert first event at the head of the queue + // insert first event at the head of the queue ticker_event_t first_event; - const timestamp_t first_event_timestamp = + const timestamp_t first_event_timestamp = ref_timestamp + TIMESTAMP_MAX_DELTA + 100; ticker_insert_event( @@ -768,7 +772,7 @@ static void test_legacy_insert_event_multiple_random() TEST_ASSERT_EQUAL_UINT32(first_event_timestamp, first_event.timestamp); TEST_ASSERT_EQUAL_UINT64( first_event.timestamp, - first_event_timestamp + + first_event_timestamp + ((first_event_timestamp < ref_timestamp) ? (1ULL << 32) : 0) ); TEST_ASSERT_EQUAL_UINT32((uint32_t) &first_event, first_event.id); @@ -791,7 +795,7 @@ static void test_legacy_insert_event_multiple_random() TEST_ASSERT_EQUAL_UINT32(second_event_timestamp, second_event.timestamp); TEST_ASSERT_EQUAL_UINT64( second_event.timestamp, - second_event_timestamp + + second_event_timestamp + ((second_event_timestamp < ref_timestamp) ? (1ULL << 32) : 0) ); TEST_ASSERT_EQUAL_UINT32((uint32_t) &second_event, second_event.id); @@ -799,7 +803,7 @@ static void test_legacy_insert_event_multiple_random() // insert third event at the head of the queue out the overflow zone ticker_event_t third_event; - const timestamp_t third_event_timestamp = + const timestamp_t third_event_timestamp = ref_timestamp + TIMESTAMP_MAX_DELTA - 100; ticker_insert_event( @@ -817,7 +821,7 @@ static void test_legacy_insert_event_multiple_random() TEST_ASSERT_EQUAL_UINT32(third_event_timestamp, third_event.timestamp); TEST_ASSERT_EQUAL_UINT64( third_event.timestamp, - third_event_timestamp + + third_event_timestamp + ((third_event_timestamp < ref_timestamp) ? (1ULL << 32) : 0) ); TEST_ASSERT_EQUAL_UINT32((uint32_t) &third_event, third_event.id); @@ -842,7 +846,7 @@ static void test_legacy_insert_event_multiple_random() TEST_ASSERT_EQUAL_UINT32(fourth_event_timestamp, fourth_event.timestamp); TEST_ASSERT_EQUAL_UINT64( fourth_event.timestamp, - fourth_event_timestamp + + fourth_event_timestamp + ((fourth_event_timestamp < ref_timestamp) ? (1ULL << 32) : 0) ); TEST_ASSERT_EQUAL_UINT32((uint32_t) &fourth_event, fourth_event.id); @@ -851,15 +855,15 @@ static void test_legacy_insert_event_multiple_random() } /** - * Given an initialized ticker without user registered events. - * When an event is inserted with ticker_insert_event_us and the timestamp passed - * in parameter is in range [ticker_timestamp : ticker_timestamp + + * Given an initialized ticker without user registered events. + * When an event is inserted with ticker_insert_event_us and the timestamp passed + * in parameter is in range [ticker_timestamp : ticker_timestamp + * TIMESTAMP_MAX_DELTA[. - * Then + * Then * - The event should be in the queue - * - The interrupt timestamp should be equal to the lower 8 bytes of the event. - * - The timestamp of the event should be equal to the timestamp requested. - * - The id of the event should be equal to the id passed in parameter. + * - The interrupt timestamp should be equal to the lower 8 bytes of the event. + * - The timestamp of the event should be equal to the timestamp requested. + * - The id of the event should be equal to the id passed in parameter. */ static void test_insert_event_us_outside_overflow_range() { @@ -871,17 +875,17 @@ static void test_insert_event_us_outside_overflow_range() // test the end of the range ticker_event_t last_event = { 0 }; - const us_timestamp_t timestamp_last_event = + const us_timestamp_t timestamp_last_event = queue_stub.present_time + TIMESTAMP_MAX_DELTA; const uint32_t id_last_event = 0xDEADDEAF; ticker_insert_event_us( - &ticker_stub, + &ticker_stub, &last_event, timestamp_last_event, id_last_event ); TEST_ASSERT_EQUAL_PTR(&last_event, queue_stub.head); - TEST_ASSERT_EQUAL(1, interface_stub.set_interrupt_call); + TEST_ASSERT_EQUAL(1, interface_stub.set_interrupt_call); TEST_ASSERT_EQUAL_UINT32( timestamp_last_event, interface_stub.interrupt_timestamp ); @@ -895,12 +899,12 @@ static void test_insert_event_us_outside_overflow_range() const uint32_t id_first_event = 0xAAAAAAAA; ticker_insert_event_us( - &ticker_stub, + &ticker_stub, &first_event, timestamp_first_event, id_first_event ); TEST_ASSERT_EQUAL_PTR(&first_event, queue_stub.head); - TEST_ASSERT_EQUAL(2, interface_stub.set_interrupt_call); + TEST_ASSERT_EQUAL(2, interface_stub.set_interrupt_call); TEST_ASSERT_EQUAL_UINT32( timestamp_first_event, interface_stub.interrupt_timestamp ); @@ -911,17 +915,17 @@ static void test_insert_event_us_outside_overflow_range() TEST_ASSERT_EQUAL_UINT32(id_first_event, first_event.id); TEST_ASSERT_EQUAL(0, interface_stub.disable_interrupt_call); -} +} /** - * Given an initialized ticker without user registered events. - * When an event is inserted with ticker_insert_event_us and a timestamp in the - * range [ticker_timestamp + TIMESTAMP_MAX_DELTA + 1 : UINT64_MAX [ - * Then + * Given an initialized ticker without user registered events. + * When an event is inserted with ticker_insert_event_us and a timestamp in the + * range [ticker_timestamp + TIMESTAMP_MAX_DELTA + 1 : UINT64_MAX [ + * Then * - The event should be in the queue - * - The interrupt timestamp should be equal to TIMESTAMP_MAX_DELTA - * - The timestamp of the event should be equal to the timestamp in parameter. - * - The id of the event should be equal to the id passed in parameter. + * - The interrupt timestamp should be equal to TIMESTAMP_MAX_DELTA + * - The timestamp of the event should be equal to the timestamp in parameter. + * - The id of the event should be equal to the id passed in parameter. */ static void test_insert_event_us_in_overflow_range() { @@ -933,18 +937,18 @@ static void test_insert_event_us_in_overflow_range() // test the end of the range ticker_event_t last_event = { 0 }; - const us_timestamp_t timestamp_last_event = UINT64_MAX; + const us_timestamp_t timestamp_last_event = UINT64_MAX; const uint32_t id_last_event = 0xDEADDEAF; ticker_insert_event_us( - &ticker_stub, + &ticker_stub, &last_event, timestamp_last_event, id_last_event ); TEST_ASSERT_EQUAL_PTR(&last_event, queue_stub.head); - TEST_ASSERT_EQUAL(1, interface_stub.set_interrupt_call); + TEST_ASSERT_EQUAL(1, interface_stub.set_interrupt_call); TEST_ASSERT_EQUAL_UINT32( - interface_stub.timestamp + TIMESTAMP_MAX_DELTA, + interface_stub.timestamp + TIMESTAMP_MAX_DELTA, interface_stub.interrupt_timestamp ); TEST_ASSERT_EQUAL_PTR(NULL, queue_stub.head->next); @@ -956,18 +960,18 @@ static void test_insert_event_us_in_overflow_range() ++queue_stub.present_time; ticker_event_t first_event = { 0 }; - const us_timestamp_t timestamp_first_event = + const us_timestamp_t timestamp_first_event = queue_stub.present_time + TIMESTAMP_MAX_DELTA + 1; uint32_t id_first_event = 0xAAAAAAAA; - ticker_insert_event_us(&ticker_stub, - &first_event, timestamp_first_event, id_first_event - ); + ticker_insert_event_us(&ticker_stub, + &first_event, timestamp_first_event, id_first_event + ); TEST_ASSERT_EQUAL_PTR(&first_event, queue_stub.head); - TEST_ASSERT_EQUAL(2, interface_stub.set_interrupt_call); + TEST_ASSERT_EQUAL(2, interface_stub.set_interrupt_call); TEST_ASSERT_EQUAL_UINT32( - interface_stub.timestamp + TIMESTAMP_MAX_DELTA, + interface_stub.timestamp + TIMESTAMP_MAX_DELTA, interface_stub.interrupt_timestamp ); TEST_ASSERT_EQUAL_PTR(&last_event, queue_stub.head->next); @@ -975,13 +979,13 @@ static void test_insert_event_us_in_overflow_range() TEST_ASSERT_EQUAL_UINT32(id_first_event, first_event.id); TEST_ASSERT_EQUAL(0, interface_stub.disable_interrupt_call); -} +} /** - * Given an initialized ticker without user registered events. - * When an event is inserted with ticker_insert_event_us and a timestamp less + * Given an initialized ticker without user registered events. + * When an event is inserted with ticker_insert_event_us and a timestamp less * than timestamp value in the ticker interface. - * Then + * Then * - The event should be in the queue * - The interrupt timestamp should be set to interface_stub.timestamp so it * is scheduled immediately. @@ -1009,18 +1013,18 @@ static void test_insert_event_us_underflow() TEST_ASSERT_EQUAL(1, interface_stub.fire_interrupt_call); TEST_ASSERT_EQUAL(0, interface_stub.disable_interrupt_call); -} +} /** * Given an initialized ticker. - * When an event is inserted with ticker_insert_event_us and a timestamp less + * When an event is inserted with ticker_insert_event_us and a timestamp less * than the one for the next scheduled timestamp. - * Then + * Then * - The event inserted should be the first in the queue - * - The interrupt timestamp should be equal to the timestamp of the event or + * - The interrupt timestamp should be equal to the timestamp of the event or * TIMESTAMP_MAX_DELTA if in the overflow range. - * - The timestamp of the event should be equal to the timestamp in parameter. - * - The id of the event should be equal to the id passed in parameter. + * - The timestamp of the event should be equal to the timestamp in parameter. + * - The id of the event should be equal to the id passed in parameter. * - Events in the queue should remained ordered by timestamp. */ static void test_insert_event_us_head() @@ -1031,7 +1035,7 @@ static void test_insert_event_us_head() queue_stub.tick_last_read = interface_stub.timestamp; queue_stub.present_time = 10ULL << 32 | interface_stub.timestamp; - const us_timestamp_t timestamps[] = { + const us_timestamp_t timestamps[] = { UINT64_MAX, queue_stub.present_time + TIMESTAMP_MAX_DELTA + 1, queue_stub.present_time + TIMESTAMP_MAX_DELTA, @@ -1042,19 +1046,19 @@ static void test_insert_event_us_head() }; ticker_event_t events[MBED_ARRAY_SIZE(timestamps)] = { 0 }; - for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { + for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { ticker_insert_event_us( - &ticker_stub, + &ticker_stub, &events[i], timestamps[i], i ); TEST_ASSERT_EQUAL_PTR(&events[i], queue_stub.head); if ((timestamps[i] - queue_stub.present_time) < TIMESTAMP_MAX_DELTA) { TEST_ASSERT_EQUAL_UINT32( - timestamps[i], + timestamps[i], interface_stub.interrupt_timestamp ); - } else { + } else { TEST_ASSERT_EQUAL_UINT32( queue_stub.present_time + TIMESTAMP_MAX_DELTA, interface_stub.interrupt_timestamp @@ -1064,13 +1068,13 @@ static void test_insert_event_us_head() TEST_ASSERT_EQUAL_UINT64(timestamps[i], events[i].timestamp); TEST_ASSERT_EQUAL_UINT32(i, events[i].id); - ticker_event_t* e = &events[i]; - while (e) { + ticker_event_t *e = &events[i]; + while (e) { TEST_ASSERT_EQUAL_UINT32(timestamps[e->id], e->timestamp); - if (e->next) { + if (e->next) { TEST_ASSERT_TRUE(e->id > e->next->id); TEST_ASSERT_TRUE(e->timestamp < e->next->timestamp); - } else { + } else { TEST_ASSERT_EQUAL_UINT32(0, e->id); } e = e->next; @@ -1078,18 +1082,18 @@ static void test_insert_event_us_head() } TEST_ASSERT_EQUAL(0, interface_stub.disable_interrupt_call); -} +} -/** +/** * Given an initialized ticker. - * When an event is inserted with ticker_insert_event_us and its timestamp is + * When an event is inserted with ticker_insert_event_us and its timestamp is * bigger than the one of the last event in the queue. - * Then + * Then * - The event inserted should be the last in the queue - * - The interrupt timestamp should remains equal to the interrupt timestamp + * - The interrupt timestamp should remains equal to the interrupt timestamp * of the head event . * - The timestamp of the event should reflect the timestamp requested. - * - The id of the event should be equal to the id passed in parameter. + * - The id of the event should be equal to the id passed in parameter. * - Events in the queue should remained ordered by timestamp. */ static void test_insert_event_us_tail() @@ -1097,7 +1101,7 @@ static void test_insert_event_us_tail() ticker_set_handler(&ticker_stub, NULL); interface_stub.set_interrupt_call = 0; - const us_timestamp_t timestamps[] = { + const us_timestamp_t timestamps[] = { 0xA, (1ULL << 32), (2ULL << 32), @@ -1109,26 +1113,26 @@ static void test_insert_event_us_tail() }; ticker_event_t events[MBED_ARRAY_SIZE(timestamps)] = { 0 }; - for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { + for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { ticker_insert_event_us( - &ticker_stub, + &ticker_stub, &events[i], timestamps[i], i ); - TEST_ASSERT_EQUAL_PTR(&events[0], queue_stub.head); + TEST_ASSERT_EQUAL_PTR(&events[0], queue_stub.head); TEST_ASSERT_EQUAL_UINT32( timestamps[0], interface_stub.interrupt_timestamp ); TEST_ASSERT_EQUAL_UINT64(timestamps[i], events[i].timestamp); TEST_ASSERT_EQUAL_UINT32(i, events[i].id); - ticker_event_t* e = queue_stub.head; - while (e) { + ticker_event_t *e = queue_stub.head; + while (e) { TEST_ASSERT_EQUAL_UINT32(timestamps[e->id], e->timestamp); - if (e->next) { + if (e->next) { TEST_ASSERT_TRUE(e->id < e->next->id); TEST_ASSERT_TRUE(e->timestamp < e->next->timestamp); - } else { + } else { TEST_ASSERT_EQUAL_UINT32(&events[i], e); } e = e->next; @@ -1136,19 +1140,19 @@ static void test_insert_event_us_tail() } TEST_ASSERT_EQUAL(0, interface_stub.disable_interrupt_call); -} +} /** * Given an initialized ticker. * When an event is inserted with ticker_insert_event_us. - * Then + * Then * - The event inserted should be at the correct position in the queue * - The event queue should remain ordered by timestamp - * - The interrupt timestamp should be equal to the interrupt timestamp - * of the head event or TIMESTAMP_MAX_DELTA if the + * - The interrupt timestamp should be equal to the interrupt timestamp + * of the head event or TIMESTAMP_MAX_DELTA if the * timestamp is in the overflow range. * - The timestamp of the event should be equal to the timestamp parameter. - * - The id of the event should be equal to the id passed in parameter. + * - The id of the event should be equal to the id passed in parameter. * - Events in the queue should remained ordered by timestamp. */ static void test_insert_event_us_multiple_random() @@ -1159,9 +1163,9 @@ static void test_insert_event_us_multiple_random() const timestamp_t ref_timestamp = UINT32_MAX / 2; interface_stub.timestamp = ref_timestamp; - // insert first event at the head of the queue + // insert first event at the head of the queue ticker_event_t first_event; - const us_timestamp_t first_event_timestamp = + const us_timestamp_t first_event_timestamp = ref_timestamp + TIMESTAMP_MAX_DELTA + 100; ticker_insert_event_us( @@ -1198,7 +1202,7 @@ static void test_insert_event_us_multiple_random() // insert third event at the head of the queue out the overflow zone ticker_event_t third_event; - const us_timestamp_t third_event_timestamp = + const us_timestamp_t third_event_timestamp = ref_timestamp + TIMESTAMP_MAX_DELTA - 100; ticker_insert_event_us( @@ -1240,17 +1244,17 @@ static void test_insert_event_us_multiple_random() } /** - * Given an initialized ticker with multiple events registered. + * Given an initialized ticker with multiple events registered. * When the event at the tail of the queue is removed from the queue. - * Then: + * Then: * - The event should not be in the queue. * - The events in the queue should remain ordered - * - The interrupt timestamp should be unchanged. + * - The interrupt timestamp should be unchanged. */ static void test_remove_event_tail() { ticker_set_handler(&ticker_stub, NULL); - const us_timestamp_t timestamps[] = { + const us_timestamp_t timestamps[] = { 0xA, (1ULL << 32), (2ULL << 32), @@ -1262,21 +1266,21 @@ static void test_remove_event_tail() }; ticker_event_t events[MBED_ARRAY_SIZE(timestamps)] = { 0 }; - for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { + for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { ticker_insert_event_us( - &ticker_stub, + &ticker_stub, &events[i], timestamps[i], i ); } - for (ssize_t i = MBED_ARRAY_SIZE(events) - 1; i >= 0; --i) { + for (ssize_t i = MBED_ARRAY_SIZE(events) - 1; i >= 0; --i) { ticker_remove_event(&ticker_stub, &events[i]); - ticker_event_t* e = queue_stub.head; + ticker_event_t *e = queue_stub.head; size_t event_count = 0; - while (e) { + while (e) { TEST_ASSERT_NOT_EQUAL(e, &events[i]); - if (e->next) { + if (e->next) { TEST_ASSERT_TRUE(e->timestamp <= e->next->timestamp); } e = e->next; @@ -1285,12 +1289,12 @@ static void test_remove_event_tail() TEST_ASSERT_EQUAL(i, event_count); - if (i != 0 ) { + if (i != 0) { TEST_ASSERT_EQUAL( timestamps[0], interface_stub.interrupt_timestamp ); - } else { + } else { TEST_ASSERT_EQUAL( interface_stub.timestamp + TIMESTAMP_MAX_DELTA, interface_stub.interrupt_timestamp @@ -1302,20 +1306,20 @@ static void test_remove_event_tail() } /** - * Given an initialized ticker with multiple events registered. + * Given an initialized ticker with multiple events registered. * When the event at the head of the queue is removed from the queue. - * Then: + * Then: * - The event should not be in the queue. - * - The event at the head of the queue should be the equal to the one + * - The event at the head of the queue should be the equal to the one * after the event removed. - * - The interrupt timestamp should be equal to the interrupt timestamp - * of the head event or TIMESTAMP_MAX_DELTA if the + * - The interrupt timestamp should be equal to the interrupt timestamp + * of the head event or TIMESTAMP_MAX_DELTA if the * timestamp is in the overflow range. */ static void test_remove_event_head() { ticker_set_handler(&ticker_stub, NULL); - const us_timestamp_t timestamps[] = { + const us_timestamp_t timestamps[] = { TIMESTAMP_MAX_DELTA / 8, TIMESTAMP_MAX_DELTA / 4, TIMESTAMP_MAX_DELTA / 2, @@ -1327,20 +1331,20 @@ static void test_remove_event_head() }; ticker_event_t events[MBED_ARRAY_SIZE(timestamps)] = { 0 }; - for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { - ticker_insert_event_us(&ticker_stub, - &events[i], timestamps[i], i - ); + for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { + ticker_insert_event_us(&ticker_stub, + &events[i], timestamps[i], i + ); } - for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { + for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { ticker_remove_event(&ticker_stub, &events[i]); - ticker_event_t* e = queue_stub.head; + ticker_event_t *e = queue_stub.head; size_t event_count = 0; - while (e) { + while (e) { TEST_ASSERT_NOT_EQUAL(e, &events[i]); - if (e->next) { + if (e->next) { TEST_ASSERT_TRUE(e->timestamp <= e->next->timestamp); } e = e->next; @@ -1349,15 +1353,15 @@ static void test_remove_event_head() TEST_ASSERT_EQUAL(MBED_ARRAY_SIZE(events) - i - 1, event_count); - if (event_count) { + if (event_count) { TEST_ASSERT_EQUAL( std::min( - timestamps[i + 1], + timestamps[i + 1], interface_stub.timestamp + TIMESTAMP_MAX_DELTA ), interface_stub.interrupt_timestamp ); - } else { + } else { TEST_ASSERT_EQUAL( interface_stub.timestamp + TIMESTAMP_MAX_DELTA, interface_stub.interrupt_timestamp @@ -1370,14 +1374,14 @@ static void test_remove_event_head() } /** - * Given an initialized ticker with multiple events registered. + * Given an initialized ticker with multiple events registered. * When an event not in the queue is attempted to be removed. * Then the queue should remains identical as before. */ static void test_remove_event_invalid() { ticker_set_handler(&ticker_stub, NULL); - const us_timestamp_t timestamps[] = { + const us_timestamp_t timestamps[] = { TIMESTAMP_MAX_DELTA / 8, TIMESTAMP_MAX_DELTA / 4, TIMESTAMP_MAX_DELTA / 2, @@ -1389,9 +1393,9 @@ static void test_remove_event_invalid() }; ticker_event_t events[MBED_ARRAY_SIZE(timestamps)] = { 0 }; - for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { + for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { ticker_insert_event_us( - &ticker_stub, + &ticker_stub, &events[i], timestamps[i], i ); } @@ -1401,9 +1405,9 @@ static void test_remove_event_invalid() TEST_ASSERT_EQUAL(&events[0], queue_stub.head); - ticker_event_t* e = queue_stub.head; + ticker_event_t *e = queue_stub.head; size_t event_count = 0; - while (e) { + while (e) { TEST_ASSERT_EQUAL(e, &events[event_count]); e = e->next; ++event_count; @@ -1417,8 +1421,8 @@ static void test_remove_event_invalid() * Then: * - the event should not be in the queue * - the queue should remain ordered - * - the interrupt timestamp should be set to either head->timestamp or - * TIMESTAMP_MAX_DELTA depending on the distance between the current time + * - the interrupt timestamp should be set to either head->timestamp or + * TIMESTAMP_MAX_DELTA depending on the distance between the current time * ans the timestamp of the event at the head of the queue. */ static void test_remove_random() @@ -1429,9 +1433,9 @@ static void test_remove_random() const timestamp_t ref_timestamp = UINT32_MAX / 2; interface_stub.timestamp = ref_timestamp; - // insert all events + // insert all events ticker_event_t first_event; - const us_timestamp_t first_event_timestamp = + const us_timestamp_t first_event_timestamp = ref_timestamp + TIMESTAMP_MAX_DELTA + 100; ticker_insert_event_us( @@ -1449,7 +1453,7 @@ static void test_remove_random() ); ticker_event_t third_event; - const us_timestamp_t third_event_timestamp = + const us_timestamp_t third_event_timestamp = ref_timestamp + TIMESTAMP_MAX_DELTA - 100; ticker_insert_event_us( @@ -1465,7 +1469,7 @@ static void test_remove_random() &fourth_event, fourth_event_timestamp, (uint32_t) &fourth_event ); - // test that the queue is in the correct state + // test that the queue is in the correct state TEST_ASSERT_EQUAL_PTR(&third_event, queue_stub.head); TEST_ASSERT_EQUAL_PTR(&fourth_event, third_event.next); TEST_ASSERT_EQUAL_PTR(&first_event, fourth_event.next); @@ -1477,7 +1481,7 @@ static void test_remove_random() TEST_ASSERT_EQUAL_UINT64(fourth_event_timestamp, fourth_event.timestamp); TEST_ASSERT_EQUAL_UINT32((uint32_t) &fourth_event, fourth_event.id); - // remove fourth event + // remove fourth event ticker_remove_event(&ticker_stub, &fourth_event); TEST_ASSERT_EQUAL_PTR(&third_event, queue_stub.head); @@ -1490,7 +1494,7 @@ static void test_remove_random() TEST_ASSERT_EQUAL_UINT64(third_event_timestamp, third_event.timestamp); TEST_ASSERT_EQUAL_UINT32((uint32_t) &third_event, third_event.id); - // remove third event + // remove third event ticker_remove_event(&ticker_stub, &third_event); TEST_ASSERT_EQUAL_PTR(&first_event, queue_stub.head); @@ -1502,7 +1506,7 @@ static void test_remove_random() TEST_ASSERT_EQUAL_UINT64(second_event_timestamp, second_event.timestamp); TEST_ASSERT_EQUAL_UINT32((uint32_t) &second_event, second_event.id); - // remove second event + // remove second event ticker_remove_event(&ticker_stub, &second_event); TEST_ASSERT_EQUAL_PTR(&first_event, queue_stub.head); @@ -1513,7 +1517,7 @@ static void test_remove_random() TEST_ASSERT_EQUAL_UINT64(first_event.timestamp, first_event_timestamp); TEST_ASSERT_EQUAL_UINT32((uint32_t) &first_event, first_event.id); - // remove first event + // remove first event ticker_remove_event(&ticker_stub, &first_event); TEST_ASSERT_EQUAL_PTR(NULL, queue_stub.head); @@ -1525,21 +1529,22 @@ static void test_remove_random() TEST_ASSERT_EQUAL(0, interface_stub.disable_interrupt_call); } -/** - * Given an initialized ticker without user registered events and a ticker - * interface timestamp equal or bigger than the one registered by the overflow +/** + * Given an initialized ticker without user registered events and a ticker + * interface timestamp equal or bigger than the one registered by the overflow * event. * When the interrupt handler is called. * Then: - * - The interrupt timestamp should be updated to the timestamp of the ticker - * interface plus TIMESTAMP_MAX_DELTA. + * - The interrupt timestamp should be updated to the timestamp of the ticker + * interface plus TIMESTAMP_MAX_DELTA. * - The irq handler registered should not be called. */ static void test_overflow_event_update() { static uint32_t handler_call = 0; - struct irq_handler_stub_t { - static void event_handler(uint32_t id) { + struct irq_handler_stub_t { + static void event_handler(uint32_t id) + { ++handler_call; } }; @@ -1550,10 +1555,10 @@ static void test_overflow_event_update() for (size_t i = 0; i < 8; ++i) { us_timestamp_t previous_timestamp = queue_stub.present_time; - timestamp_t interface_timestamp = + timestamp_t interface_timestamp = previous_timestamp + (TIMESTAMP_MAX_DELTA + i * 100); interface_stub.timestamp = interface_timestamp; - + ticker_irq_handler(&ticker_stub); TEST_ASSERT_EQUAL(i + 1, interface_stub.clear_interrupt_call); @@ -1566,22 +1571,23 @@ static void test_overflow_event_update() } TEST_ASSERT_EQUAL(0, interface_stub.disable_interrupt_call); -} +} -/** - * Given an initialized ticker without user registered events and a ticker +/** + * Given an initialized ticker without user registered events and a ticker * interface timestamp less than the one registered to handle overflow. * When the interrupt handler is called. * Then: - * - The interrupt timestamp should be updated to the timestamp of the ticker - * interface plus TIMESTAMP_MAX_DELTA. + * - The interrupt timestamp should be updated to the timestamp of the ticker + * interface plus TIMESTAMP_MAX_DELTA. * - The irq handler registered should not be called. */ static void test_overflow_event_update_when_spurious_interrupt() { static uint32_t handler_call = 0; - struct irq_handler_stub_t { - static void event_handler(uint32_t id) { + struct irq_handler_stub_t { + static void event_handler(uint32_t id) + { ++handler_call; } }; @@ -1592,10 +1598,10 @@ static void test_overflow_event_update_when_spurious_interrupt() for (size_t i = 0; i < 8; ++i) { us_timestamp_t previous_timestamp = queue_stub.present_time; - timestamp_t interface_timestamp = + timestamp_t interface_timestamp = previous_timestamp + (TIMESTAMP_MAX_DELTA / (2 + i)); interface_stub.timestamp = interface_timestamp; - + ticker_irq_handler(&ticker_stub); TEST_ASSERT_EQUAL(i + 1, interface_stub.clear_interrupt_call); @@ -1608,18 +1614,18 @@ static void test_overflow_event_update_when_spurious_interrupt() } TEST_ASSERT_EQUAL(0, interface_stub.disable_interrupt_call); -} +} /** - * Given an initialized ticker with a single ticker event inserted and a ticker - * interface timestamp bigger than the one set for interrupt. + * Given an initialized ticker with a single ticker event inserted and a ticker + * interface timestamp bigger than the one set for interrupt. * When ticker_irq_handler is called. - * Then: - * - The IRQ handler should be called with the id of the event at the head of + * Then: + * - The IRQ handler should be called with the id of the event at the head of * the queue. * - The event at the head of the queue should be replaced by the next event. - * - The interrupt timestamp in the ticker interface should be set to the - * value of the interface timestamp + TIMESTAMP_MAX_DELTA + * - The interrupt timestamp in the ticker interface should be set to the + * value of the interface timestamp + TIMESTAMP_MAX_DELTA */ static void test_irq_handler_single_event() { @@ -1627,9 +1633,10 @@ static void test_irq_handler_single_event() static const timestamp_t interface_timestamp_after_irq = event_timestamp + 100; uint32_t handler_call = 0; - struct irq_handler_stub_t { - static void event_handler(uint32_t id) { - ++ (*((uint32_t*) id)); + struct irq_handler_stub_t { + static void event_handler(uint32_t id) + { + ++ (*((uint32_t *) id)); interface_stub.timestamp = interface_timestamp_after_irq; } }; @@ -1637,7 +1644,7 @@ static void test_irq_handler_single_event() ticker_set_handler(&ticker_stub, irq_handler_stub_t::event_handler); interface_stub.set_interrupt_call = 0; - ticker_event_t e; + ticker_event_t e; ticker_insert_event(&ticker_stub, &e, event_timestamp, (uint32_t) &handler_call); interface_stub.timestamp = event_timestamp; @@ -1659,19 +1666,20 @@ static void test_irq_handler_single_event() } /** - * Given an initialized ticker with at least a ticker event inserted and a ticker - * interface timestamp less than the one set for interrupt. + * Given an initialized ticker with at least a ticker event inserted and a ticker + * interface timestamp less than the one set for interrupt. * When ticker_irq_handler is called. - * Then: + * Then: * - The IRQ handler should not be called. * - The event at the head of the queue should remains the same. - * - The interrupt timestamp in the ticker interface should be set to the - * value of the event timestamp + * - The interrupt timestamp in the ticker interface should be set to the + * value of the event timestamp */ static void test_irq_handler_single_event_spurious() { - struct irq_handler_stub_t { - static void event_handler(uint32_t id) { + struct irq_handler_stub_t { + static void event_handler(uint32_t id) + { TEST_FAIL(); } }; @@ -1680,17 +1688,17 @@ static void test_irq_handler_single_event_spurious() interface_stub.set_interrupt_call = 0; const us_timestamp_t timestamps [] = { - UINT32_MAX, - TIMESTAMP_MAX_DELTA + 1, + UINT32_MAX, + TIMESTAMP_MAX_DELTA + 1, TIMESTAMP_MAX_DELTA, TIMESTAMP_MAX_DELTA - 1 }; ticker_event_t events[MBED_ARRAY_SIZE(timestamps)] = { 0 }; - for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { + for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { ticker_insert_event_us( - &ticker_stub, + &ticker_stub, &events[i], timestamps[i], timestamps[i] ); interface_stub.set_interrupt_call = 0; @@ -1710,11 +1718,11 @@ static void test_irq_handler_single_event_spurious() } /** - * Given an initialized ticker with multiple ticker event inserted, its - * interface timestamp at greater than the timestamp of the next schedule event + * Given an initialized ticker with multiple ticker event inserted, its + * interface timestamp at greater than the timestamp of the next schedule event * and all event execution time taking at least the time befor ethe next event. * When ticker_irq_handler is called. - * Then: + * Then: * - The IRQ handler should have been called for every event. * - The head of the queue should be set to NULL. * - The interrupt timestamp in the ticker interface should be scheduled in @@ -1723,19 +1731,20 @@ static void test_irq_handler_single_event_spurious() static void test_irq_handler_multiple_event_multiple_dequeue() { const us_timestamp_t timestamps [] = { - 10, + 10, 10 + TIMESTAMP_MAX_DELTA - 1, 10 + TIMESTAMP_MAX_DELTA, - 10 + TIMESTAMP_MAX_DELTA + 1, + 10 + TIMESTAMP_MAX_DELTA + 1, UINT32_MAX }; static size_t handler_called = 0; - struct irq_handler_stub_t { - static void event_handler(uint32_t id) { + struct irq_handler_stub_t { + static void event_handler(uint32_t id) + { ++handler_called; - ticker_event_t* e = (ticker_event_t*) id; - if (e->next) { + ticker_event_t *e = (ticker_event_t *) id; + if (e->next) { interface_stub.timestamp = e->next->timestamp; } } @@ -1747,9 +1756,9 @@ static void test_irq_handler_multiple_event_multiple_dequeue() ticker_event_t events[MBED_ARRAY_SIZE(timestamps)] = { 0 }; - for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { + for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { ticker_insert_event_us( - &ticker_stub, + &ticker_stub, &events[i], timestamps[i], (uint32_t) &events[i] ); } @@ -1757,7 +1766,7 @@ static void test_irq_handler_multiple_event_multiple_dequeue() interface_stub.set_interrupt_call = 0; interface_stub.clear_interrupt_call = 0; interface_stub.timestamp = timestamps[0]; - + ticker_irq_handler(&ticker_stub); TEST_ASSERT_EQUAL(1, interface_stub.clear_interrupt_call); @@ -1773,11 +1782,11 @@ static void test_irq_handler_multiple_event_multiple_dequeue() } /** - * Given an initialized ticker with two ticker event inserted scheduled from more - * than TIMESTAMP_MAX_DELTA from one another. The interface - * timestamp is equal to the timestamp of the first event. + * Given an initialized ticker with two ticker event inserted scheduled from more + * than TIMESTAMP_MAX_DELTA from one another. The interface + * timestamp is equal to the timestamp of the first event. * When ticker_irq_handler is called. - * Then: + * Then: * - The IRQ handler should have been called for the first event. * - The head of the queue should be set to the event after the first event. * - The interrupt timestamp in the ticker interface should be scheduled in @@ -1786,14 +1795,15 @@ static void test_irq_handler_multiple_event_multiple_dequeue() static void test_irq_handler_multiple_event_single_dequeue_overflow() { const us_timestamp_t timestamps [] = { - 10, + 10, 10 + TIMESTAMP_MAX_DELTA + 1 }; size_t handler_called = 0; - struct irq_handler_stub_t { - static void event_handler(uint32_t id) { - ++ (*((size_t*) id)); + struct irq_handler_stub_t { + static void event_handler(uint32_t id) + { + ++ (*((size_t *) id)); } }; @@ -1802,9 +1812,9 @@ static void test_irq_handler_multiple_event_single_dequeue_overflow() ticker_event_t events[MBED_ARRAY_SIZE(timestamps)] = { 0 }; - for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { + for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { ticker_insert_event_us( - &ticker_stub, + &ticker_stub, &events[i], timestamps[i], (uint32_t) &handler_called ); } @@ -1812,7 +1822,7 @@ static void test_irq_handler_multiple_event_single_dequeue_overflow() interface_stub.set_interrupt_call = 0; interface_stub.clear_interrupt_call = 0; interface_stub.timestamp = timestamps[0]; - + ticker_irq_handler(&ticker_stub); TEST_ASSERT_EQUAL(1, interface_stub.clear_interrupt_call); @@ -1828,27 +1838,28 @@ static void test_irq_handler_multiple_event_single_dequeue_overflow() } /** - * Given an initialized ticker with two ticker event inserted scheduled from less - * than TIMESTAMP_MAX_DELTA from one another. The interface - * timestamp is equal to the timestamp of the first event. + * Given an initialized ticker with two ticker event inserted scheduled from less + * than TIMESTAMP_MAX_DELTA from one another. The interface + * timestamp is equal to the timestamp of the first event. * When ticker_irq_handler is called. - * Then: + * Then: * - The IRQ handler should have been called for the first event. * - The head of the queue should be set to second event. - * - The interrupt timestamp in the ticker interface should be equal to the + * - The interrupt timestamp in the ticker interface should be equal to the * timestamp of the second event. */ static void test_irq_handler_multiple_event_single_dequeue() { const us_timestamp_t timestamps [] = { - 10, + 10, 10 + TIMESTAMP_MAX_DELTA - 1 }; size_t handler_called = 0; - struct irq_handler_stub_t { - static void event_handler(uint32_t id) { - ++ (*((size_t*) id)); + struct irq_handler_stub_t { + static void event_handler(uint32_t id) + { + ++ (*((size_t *) id)); } }; @@ -1857,9 +1868,9 @@ static void test_irq_handler_multiple_event_single_dequeue() ticker_event_t events[MBED_ARRAY_SIZE(timestamps)] = { 0 }; - for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { + for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { ticker_insert_event_us( - &ticker_stub, + &ticker_stub, &events[i], timestamps[i], (uint32_t) &handler_called ); } @@ -1867,7 +1878,7 @@ static void test_irq_handler_multiple_event_single_dequeue() interface_stub.set_interrupt_call = 0; interface_stub.clear_interrupt_call = 0; interface_stub.timestamp = timestamps[0]; - + ticker_irq_handler(&ticker_stub); TEST_ASSERT_EQUAL(1, interface_stub.clear_interrupt_call); @@ -1883,47 +1894,48 @@ static void test_irq_handler_multiple_event_single_dequeue() } /** - * Given an initialized ticker with multiple ticker event inserted and the + * Given an initialized ticker with multiple ticker event inserted and the * interface timestamp is equal to the timestamp of the first event. The first - * event to execute will insert an events in the ticker which have to be executed + * event to execute will insert an events in the ticker which have to be executed * immediately. * When ticker_irq_handler is called. - * Then: - * - The IRQ handler should have been called for the first event and the event + * Then: + * - The IRQ handler should have been called for the first event and the event * inserted during irq. * - The head of the queue should be set correctly. - * - The interrupt timestamp in the ticker interface should be equal to + * - The interrupt timestamp in the ticker interface should be equal to * timestamp of the head event. */ static void test_irq_handler_insert_immediate_in_irq() { static const us_timestamp_t timestamps [] = { - 10, + 10, 10 + TIMESTAMP_MAX_DELTA - 1 }; - static const us_timestamp_t expected_timestamp = + static const us_timestamp_t expected_timestamp = ((timestamps[1] - timestamps[0]) / 2) + timestamps[0]; - struct ctrl_block_t { + struct ctrl_block_t { bool irq_event_called; - ticker_event_t immediate_event; + ticker_event_t immediate_event; size_t handler_called; }; ctrl_block_t ctrl_block = { 0 }; - struct irq_handler_stub_t { - static void event_handler(uint32_t id) { - ctrl_block_t* ctrl_block = (ctrl_block_t*) id; + struct irq_handler_stub_t { + static void event_handler(uint32_t id) + { + ctrl_block_t *ctrl_block = (ctrl_block_t *) id; if (ctrl_block->handler_called == 0) { ticker_insert_event( - &ticker_stub, + &ticker_stub, &ctrl_block->immediate_event, expected_timestamp, id ); interface_stub.timestamp = expected_timestamp; - } else if (ctrl_block->handler_called > 1) { + } else if (ctrl_block->handler_called > 1) { TEST_FAIL(); } ++ctrl_block->handler_called; @@ -1935,9 +1947,9 @@ static void test_irq_handler_insert_immediate_in_irq() ticker_event_t events[MBED_ARRAY_SIZE(timestamps)] = { 0 }; - for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { + for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { ticker_insert_event_us( - &ticker_stub, + &ticker_stub, &events[i], timestamps[i], (uint32_t) &ctrl_block ); } @@ -1945,7 +1957,7 @@ static void test_irq_handler_insert_immediate_in_irq() interface_stub.set_interrupt_call = 0; interface_stub.clear_interrupt_call = 0; interface_stub.timestamp = timestamps[0]; - + ticker_irq_handler(&ticker_stub); TEST_ASSERT_EQUAL(1, interface_stub.clear_interrupt_call); @@ -1960,45 +1972,46 @@ static void test_irq_handler_insert_immediate_in_irq() } /** - * Given an initialized ticker with multiple ticker event inserted and the + * Given an initialized ticker with multiple ticker event inserted and the * interface timestamp is equal to the timestamp of the first event. The first - * event to execute will insert an events in the ticker which does not have to + * event to execute will insert an events in the ticker which does not have to * be executed immediately. * When ticker_irq_handler is called. - * Then: + * Then: * - The IRQ handler should have been called for the first event. * - The head of the queue should be set to the event inserted in IRQ. - * - The interrupt timestamp in the ticker interface should be equal to + * - The interrupt timestamp in the ticker interface should be equal to * timestamp of the head event. */ static void test_irq_handler_insert_non_immediate_in_irq() { static const us_timestamp_t timestamps [] = { - 10, + 10, 10 + TIMESTAMP_MAX_DELTA - 1 }; - static const us_timestamp_t expected_timestamp = + static const us_timestamp_t expected_timestamp = ((timestamps[1] - timestamps[0]) / 2) + timestamps[0]; - struct ctrl_block_t { + struct ctrl_block_t { bool irq_event_called; - ticker_event_t non_immediate_event; + ticker_event_t non_immediate_event; size_t handler_called; }; ctrl_block_t ctrl_block = { 0 }; - struct irq_handler_stub_t { - static void event_handler(uint32_t id) { - ctrl_block_t* ctrl_block = (ctrl_block_t*) id; + struct irq_handler_stub_t { + static void event_handler(uint32_t id) + { + ctrl_block_t *ctrl_block = (ctrl_block_t *) id; if (ctrl_block->handler_called == 0) { ticker_insert_event( - &ticker_stub, + &ticker_stub, &ctrl_block->non_immediate_event, expected_timestamp, id ); - } else { + } else { TEST_FAIL(); } ++ctrl_block->handler_called; @@ -2011,9 +2024,9 @@ static void test_irq_handler_insert_non_immediate_in_irq() ticker_event_t events[MBED_ARRAY_SIZE(timestamps)] = { 0 }; - for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { + for (size_t i = 0; i < MBED_ARRAY_SIZE(events); ++i) { ticker_insert_event_us( - &ticker_stub, + &ticker_stub, &events[i], timestamps[i], (uint32_t) &ctrl_block ); } @@ -2021,7 +2034,7 @@ static void test_irq_handler_insert_non_immediate_in_irq() interface_stub.set_interrupt_call = 0; interface_stub.clear_interrupt_call = 0; interface_stub.timestamp = timestamps[0]; - + ticker_irq_handler(&ticker_stub); TEST_ASSERT_EQUAL(1, interface_stub.clear_interrupt_call); @@ -2045,7 +2058,7 @@ static uint32_t ticker_interface_stub_read_interrupt_time() } else { return interface_stub.timestamp; } -} +} /** * Test to insert an event that is already in the past, the fire_interrupt should @@ -2222,28 +2235,28 @@ typedef struct { static void test_match_interval_passed_table() { static const match_interval_entry_t test_values[] = { - /* prev, cur, match, result */ - {0x00000000, 0x00000000, 0x00000000, false}, - {0x00000000, 0x00000000, 0xffffffff, false}, - {0x00000000, 0x00000000, 0x00000001, false}, - {0x00000000, 0xffffffff, 0x00000000, false}, - {0x00000000, 0x00000001, 0x00000000, false}, - {0xffffffff, 0x00000000, 0x00000000, true}, - {0x00000001, 0x00000000, 0x00000000, true}, - {0x00005555, 0x00005555, 0x00005555, false}, - {0x00005555, 0x00005555, 0x00005554, false}, - {0x00005555, 0x00005555, 0x00005556, false}, - {0x00005555, 0x00005554, 0x00005555, false}, - {0x00005555, 0x00005556, 0x00005555, false}, - {0x00005554, 0x00005555, 0x00005555, true}, - {0x00005556, 0x00005555, 0x00005555, true}, - {0xffffffff, 0xffffffff, 0xffffffff, false}, - {0xffffffff, 0xffffffff, 0xfffffffe, false}, - {0xffffffff, 0xffffffff, 0x00000000, false}, - {0xffffffff, 0xfffffffe, 0xffffffff, false}, - {0xffffffff, 0x00000000, 0xffffffff, false}, - {0xfffffffe, 0xffffffff, 0xffffffff, true}, - {0x00000000, 0xffffffff, 0xffffffff, true}, + /* prev, cur, match, result */ + {0x00000000, 0x00000000, 0x00000000, false}, + {0x00000000, 0x00000000, 0xffffffff, false}, + {0x00000000, 0x00000000, 0x00000001, false}, + {0x00000000, 0xffffffff, 0x00000000, false}, + {0x00000000, 0x00000001, 0x00000000, false}, + {0xffffffff, 0x00000000, 0x00000000, true}, + {0x00000001, 0x00000000, 0x00000000, true}, + {0x00005555, 0x00005555, 0x00005555, false}, + {0x00005555, 0x00005555, 0x00005554, false}, + {0x00005555, 0x00005555, 0x00005556, false}, + {0x00005555, 0x00005554, 0x00005555, false}, + {0x00005555, 0x00005556, 0x00005555, false}, + {0x00005554, 0x00005555, 0x00005555, true}, + {0x00005556, 0x00005555, 0x00005555, true}, + {0xffffffff, 0xffffffff, 0xffffffff, false}, + {0xffffffff, 0xffffffff, 0xfffffffe, false}, + {0xffffffff, 0xffffffff, 0x00000000, false}, + {0xffffffff, 0xfffffffe, 0xffffffff, false}, + {0xffffffff, 0x00000000, 0xffffffff, false}, + {0xfffffffe, 0xffffffff, 0xffffffff, true}, + {0x00000000, 0xffffffff, 0xffffffff, true}, }; for (int i = 0; i < MBED_ARRAY_SIZE(test_values); i++) { const uint32_t prev = test_values[i].prev; @@ -2262,11 +2275,11 @@ static const case_t cases[] = { MAKE_TEST_CASE("ticker read", test_ticker_read), MAKE_TEST_CASE("ticker read overflow", test_ticker_read_overflow), MAKE_TEST_CASE( - "legacy insert event outside overflow range", + "legacy insert event outside overflow range", test_legacy_insert_event_outside_overflow_range ), MAKE_TEST_CASE( - "legacy insert event in overflow range", + "legacy insert event in overflow range", test_legacy_insert_event_in_overflow_range ), MAKE_TEST_CASE( @@ -2279,19 +2292,19 @@ static const case_t cases[] = { "legacy insert event tail", test_legacy_insert_event_tail ), MAKE_TEST_CASE( - "legacy insert event multiple overflow", + "legacy insert event multiple overflow", test_legacy_insert_event_multiple_overflow ), MAKE_TEST_CASE( - "test_legacy_insert_event_multiple_random", + "test_legacy_insert_event_multiple_random", test_legacy_insert_event_multiple_random ), MAKE_TEST_CASE( - "test_insert_event_us_outside_overflow_range", + "test_insert_event_us_outside_overflow_range", test_insert_event_us_outside_overflow_range ), MAKE_TEST_CASE( - "test_insert_event_us_in_overflow_range", + "test_insert_event_us_in_overflow_range", test_insert_event_us_in_overflow_range ), MAKE_TEST_CASE( @@ -2300,7 +2313,7 @@ static const case_t cases[] = { MAKE_TEST_CASE("test_insert_event_us_head", test_insert_event_us_head), MAKE_TEST_CASE("test_insert_event_us_tail", test_insert_event_us_tail), MAKE_TEST_CASE( - "test_insert_event_us_multiple_random", + "test_insert_event_us_multiple_random", test_insert_event_us_multiple_random ), MAKE_TEST_CASE("test_remove_event_tail", test_remove_event_tail), @@ -2309,42 +2322,42 @@ static const case_t cases[] = { MAKE_TEST_CASE("test_remove_random", test_remove_random), MAKE_TEST_CASE("update overflow guard", test_overflow_event_update), MAKE_TEST_CASE( - "update overflow guard in case of spurious interrupt", + "update overflow guard in case of spurious interrupt", test_overflow_event_update_when_spurious_interrupt ), MAKE_TEST_CASE( "test_irq_handler_single_event", test_irq_handler_single_event ), MAKE_TEST_CASE( - "test_irq_handler_single_event_spurious", + "test_irq_handler_single_event_spurious", test_irq_handler_single_event_spurious ), MAKE_TEST_CASE( - "test_irq_handler_multiple_event_multiple_dequeue", + "test_irq_handler_multiple_event_multiple_dequeue", test_irq_handler_multiple_event_multiple_dequeue ), MAKE_TEST_CASE( - "test_irq_handler_multiple_event_single_dequeue_overflow", + "test_irq_handler_multiple_event_single_dequeue_overflow", test_irq_handler_multiple_event_single_dequeue_overflow ), MAKE_TEST_CASE( - "test_irq_handler_multiple_event_single_dequeue", + "test_irq_handler_multiple_event_single_dequeue", test_irq_handler_multiple_event_single_dequeue ), MAKE_TEST_CASE( - "test_irq_handler_insert_immediate_in_irq", + "test_irq_handler_insert_immediate_in_irq", test_irq_handler_insert_immediate_in_irq ), MAKE_TEST_CASE( - "test_irq_handler_insert_non_immediate_in_irq", + "test_irq_handler_insert_non_immediate_in_irq", test_irq_handler_insert_non_immediate_in_irq ), MAKE_TEST_CASE( - "test_set_interrupt_past_time", + "test_set_interrupt_past_time", test_set_interrupt_past_time ), MAKE_TEST_CASE( - "test_set_interrupt_past_time_with_delay", + "test_set_interrupt_past_time_with_delay", test_set_interrupt_past_time_with_delay ), MAKE_TEST_CASE( diff --git a/TESTS/mbed_platform/FileHandle/TestFile.h b/TESTS/mbed_platform/FileHandle/TestFile.h index 1ec0315c49b..38e001ad009 100644 --- a/TESTS/mbed_platform/FileHandle/TestFile.h +++ b/TESTS/mbed_platform/FileHandle/TestFile.h @@ -39,10 +39,9 @@ class TestFile : public FileHandle { ssize_t read; _fnCalled = fnRead; - for(read = 0; (size_t)read < size; read++) - { - if(POS_IS_VALID(_pos)) { - ((uint8_t*)buffer)[read] = _data[_pos++]; + for (read = 0; (size_t)read < size; read++) { + if (POS_IS_VALID(_pos)) { + ((uint8_t *)buffer)[read] = _data[_pos++]; } else { break; } @@ -55,17 +54,16 @@ class TestFile : public FileHandle { ssize_t written; _fnCalled = fnWrite; - for(written = 0; (size_t)written < size; written++) - { - if(NEW_POS_IS_VALID(_pos)) { - _data[_pos++] = ((uint8_t*)buffer)[written]; + for (written = 0; (size_t)written < size; written++) { + if (NEW_POS_IS_VALID(_pos)) { + _data[_pos++] = ((uint8_t *)buffer)[written]; } else { - if(0 == written) { + if (0 == written) { return -ENOSPC; } break; } - if(_end < _pos) { + if (_end < _pos) { _end++; } } // for @@ -77,8 +75,7 @@ class TestFile : public FileHandle { _fnCalled = fnSeek; int32_t new_pos = INVALID_POS; - switch(whence) - { + switch (whence) { case SEEK_SET: new_pos = offset; break; @@ -96,7 +93,7 @@ class TestFile : public FileHandle { break; } - if(SEEK_POS_IS_VALID(new_pos)) { + if (SEEK_POS_IS_VALID(new_pos)) { _pos = new_pos; } else { return -EINVAL; diff --git a/TESTS/mbed_platform/Transaction/main.cpp b/TESTS/mbed_platform/Transaction/main.cpp index 0b2029be73d..46eb5768bef 100644 --- a/TESTS/mbed_platform/Transaction/main.cpp +++ b/TESTS/mbed_platform/Transaction/main.cpp @@ -23,7 +23,7 @@ using utest::v1::Case; static void dummy_callback(int) { - /* do nothing. */ + /* do nothing. */ } /** Test Transaction class - creation with initialisation @@ -43,7 +43,7 @@ void test_Transaction_init() const uint8_t word_width = 8; unsigned char tx_buffer[tx_buffer_size]; unsigned char rx_buffer[rx_buffer_size]; - const event_callback_t& callback = dummy_callback; + const event_callback_t &callback = dummy_callback; transaction_t transaction_data = { tx_buffer, tx_buffer_size, rx_buffer, rx_buffer_size, event_id, callback, word_width }; @@ -51,8 +51,8 @@ void test_Transaction_init() TEST_ASSERT_EQUAL(&object, test_transaction.get_object()); - TEST_ASSERT_EQUAL((void*)tx_buffer, test_transaction.get_transaction()->tx_buffer); - TEST_ASSERT_EQUAL((void*)rx_buffer, test_transaction.get_transaction()->rx_buffer); + TEST_ASSERT_EQUAL((void *)tx_buffer, test_transaction.get_transaction()->tx_buffer); + TEST_ASSERT_EQUAL((void *)rx_buffer, test_transaction.get_transaction()->rx_buffer); TEST_ASSERT_EQUAL(tx_buffer_size, test_transaction.get_transaction()->tx_length); TEST_ASSERT_EQUAL(rx_buffer_size, test_transaction.get_transaction()->rx_length); TEST_ASSERT_EQUAL(event_id, test_transaction.get_transaction()->event); diff --git a/TESTS/mbed_platform/critical_section/main.cpp b/TESTS/mbed_platform/critical_section/main.cpp index 16054310b65..43ce94c4fcf 100644 --- a/TESTS/mbed_platform/critical_section/main.cpp +++ b/TESTS/mbed_platform/critical_section/main.cpp @@ -38,7 +38,7 @@ void critical_section_raii_recursive(Timeout &timeout) depth++; TEST_ASSERT_TRUE(core_util_in_critical_section()); - if(depth < N) { + if (depth < N) { critical_section_raii_recursive(timeout); } else { // max depth reached - do the test @@ -87,7 +87,7 @@ void test_C_API(void) wait_us(wait_time_us); TEST_ASSERT_TRUE(callback_called); - for(int i = 0; i < N; i++) { + for (int i = 0; i < N; i++) { core_util_critical_section_enter(); TEST_ASSERT_TRUE(core_util_in_critical_section()); } @@ -98,7 +98,7 @@ void test_C_API(void) TEST_ASSERT_FALSE(callback_called); TEST_ASSERT_TRUE(core_util_in_critical_section()); - for(int i = 0; i < N - 1; i++) { + for (int i = 0; i < N - 1; i++) { core_util_critical_section_exit(); TEST_ASSERT_TRUE(core_util_in_critical_section()); TEST_ASSERT_FALSE(callback_called); @@ -184,7 +184,7 @@ void test_CPP_API_enable_disable(void) wait_us(wait_time_us); TEST_ASSERT_TRUE(callback_called); - for(int i = 0; i < N; i++) { + for (int i = 0; i < N; i++) { CriticalSectionLock::enable(); TEST_ASSERT_TRUE(core_util_in_critical_section()); } @@ -195,7 +195,7 @@ void test_CPP_API_enable_disable(void) TEST_ASSERT_FALSE(callback_called); TEST_ASSERT_TRUE(core_util_in_critical_section()); - for(int i = 0; i < N - 1; i++) { + for (int i = 0; i < N - 1; i++) { CriticalSectionLock::disable(); TEST_ASSERT_TRUE(core_util_in_critical_section()); TEST_ASSERT_FALSE(callback_called); diff --git a/TESTS/mbedmicro-mbed/attributes/attributes.c b/TESTS/mbedmicro-mbed/attributes/attributes.c index e08f124f0c8..5329b8a3c5e 100644 --- a/TESTS/mbedmicro-mbed/attributes/attributes.c +++ b/TESTS/mbedmicro-mbed/attributes/attributes.c @@ -9,12 +9,15 @@ MBED_PACKED(struct) TestAttrPackedStruct1 { int x; }; -typedef MBED_PACKED(struct) { +typedef MBED_PACKED(struct) +{ char a; int x; -} TestAttrPackedStruct2; +} +TestAttrPackedStruct2; -int testPacked() { +int testPacked() +{ int failed = 0; if (sizeof(struct TestAttrPackedStruct1) != sizeof(int) + sizeof(char)) { @@ -35,22 +38,23 @@ MBED_ALIGN(16) char c; MBED_ALIGN(8) char d; MBED_ALIGN(16) char e; -int testAlign() { +int testAlign() +{ int failed = 0; - if(((uintptr_t)&a) & 0x7){ + if (((uintptr_t)&a) & 0x7) { failed++; } - if(((uintptr_t)&b) & 0x7){ + if (((uintptr_t)&b) & 0x7) { failed++; } - if(((uintptr_t)&c) & 0xf){ + if (((uintptr_t)&c) & 0xf) { failed++; } - if(((uintptr_t)&d) & 0x7){ + if (((uintptr_t)&d) & 0x7) { failed++; } - if(((uintptr_t)&e) & 0xf){ + if (((uintptr_t)&e) & 0xf) { failed++; } @@ -58,11 +62,13 @@ int testAlign() { } -int testUnused1(MBED_UNUSED int arg) { +int testUnused1(MBED_UNUSED int arg) +{ return 0; } -int testUnused() { +int testUnused() +{ return testUnused1(0); } @@ -70,42 +76,51 @@ int testUnused() { int testWeak1(); int testWeak2(); -MBED_WEAK int testWeak1() { +MBED_WEAK int testWeak1() +{ return 1; } -int testWeak2() { +int testWeak2() +{ return 0; } -int testWeak() { +int testWeak() +{ return testWeak1() | testWeak2(); } -MBED_PURE int testPure1() { +MBED_PURE int testPure1() +{ return 0; } -int testPure() { +int testPure() +{ return testPure1(); } -MBED_FORCEINLINE int testForceInline1() { +MBED_FORCEINLINE int testForceInline1() +{ return 0; } -int testForceInline() { +int testForceInline() +{ return testForceInline1(); } -MBED_NORETURN int testNoReturn1() { +MBED_NORETURN int testNoReturn1() +{ while (1) {} } -int testNoReturn() { +int testNoReturn() +{ if (0) { testNoReturn1(); } @@ -113,7 +128,8 @@ int testNoReturn() { } -int testUnreachable1(int i) { +int testUnreachable1(int i) +{ switch (i) { case 0: return 0; @@ -122,18 +138,20 @@ int testUnreachable1(int i) { MBED_UNREACHABLE; } -int testUnreachable() { +int testUnreachable() +{ return testUnreachable1(0); } MBED_DEPRECATED("this message should not be displayed") -void testDeprecatedUnused(); +void testDeprecatedUnused(); void testDeprecatedUnused() { } MBED_DEPRECATED("this message should be displayed") int testDeprecatedUsed(); -int testDeprecatedUsed() { +int testDeprecatedUsed() +{ return 0; } @@ -143,11 +161,13 @@ void testDeprecatedSinceUnused() { } MBED_DEPRECATED_SINCE("mbed-os-3.14", "this message should be displayed") int testDeprecatedSinceUsed(); -int testDeprecatedSinceUsed() { +int testDeprecatedSinceUsed() +{ return 0; } -int testDeprecated() { +int testDeprecated() +{ return testDeprecatedUsed() + testDeprecatedSinceUsed(); } diff --git a/TESTS/mbedmicro-mbed/attributes/main.cpp b/TESTS/mbedmicro-mbed/attributes/main.cpp index c64c29cba79..31d014e4ba3 100644 --- a/TESTS/mbedmicro-mbed/attributes/main.cpp +++ b/TESTS/mbedmicro-mbed/attributes/main.cpp @@ -40,11 +40,13 @@ extern "C" { // Test wrapper and test cases for utest template -void test_wrapper() { +void test_wrapper() +{ TEST_ASSERT_UNLESS(F()); } -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(5, "default_auto"); return verbose_test_setup_handler(number_of_cases); } @@ -63,6 +65,7 @@ Case cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/TESTS/mbedmicro-mbed/attributes/weak.c b/TESTS/mbedmicro-mbed/attributes/weak.c index 4bf279614b4..7b2f862177a 100644 --- a/TESTS/mbedmicro-mbed/attributes/weak.c +++ b/TESTS/mbedmicro-mbed/attributes/weak.c @@ -1,10 +1,12 @@ #include "mbed_toolchain.h" -int testWeak1() { +int testWeak1() +{ return 0; } -MBED_WEAK int testWeak2() { +MBED_WEAK int testWeak2() +{ return 1; } diff --git a/TESTS/mbedmicro-mbed/call_before_main/main.cpp b/TESTS/mbedmicro-mbed/call_before_main/main.cpp index 1d6266b7b6f..c185c5959bd 100644 --- a/TESTS/mbedmicro-mbed/call_before_main/main.cpp +++ b/TESTS/mbedmicro-mbed/call_before_main/main.cpp @@ -16,15 +16,17 @@ #include "greentea-client/test_env.h" namespace { - bool mbed_main_called = false; +bool mbed_main_called = false; } -extern "C" void mbed_main() { +extern "C" void mbed_main() +{ printf("MBED: mbed_main() call before main()\r\n"); mbed_main_called = true; } -int main() { +int main() +{ GREENTEA_SETUP(5, "default_auto"); printf("MBED: main() starts now!\r\n"); GREENTEA_TESTSUITE_RESULT(mbed_main_called); diff --git a/TESTS/mbedmicro-mbed/cpp/main.cpp b/TESTS/mbedmicro-mbed/cpp/main.cpp index 931748e316b..5597831f26e 100644 --- a/TESTS/mbedmicro-mbed/cpp/main.cpp +++ b/TESTS/mbedmicro-mbed/cpp/main.cpp @@ -20,37 +20,43 @@ class Test { private: - const char* name; + const char *name; const int pattern; public: - Test(const char* _name, bool print_message=true) : name(_name), pattern(PATTERN_CHECK_VALUE) { + Test(const char *_name, bool print_message = true) : name(_name), pattern(PATTERN_CHECK_VALUE) + { if (print_message) { print("init"); } } - void print(const char *message) { + void print(const char *message) + { printf("%s::%s\n", name, message); } - bool check_init(void) { + bool check_init(void) + { bool result = (pattern == PATTERN_CHECK_VALUE); print(result ? "check_init: OK" : "check_init: ERROR"); return result; } - void stack_test(void) { + void stack_test(void) + { print("stack_test"); Test t("Stack"); t.hello(); } - void hello(void) { + void hello(void) + { print("hello"); } - ~Test() { + ~Test() + { print("destroy"); } }; @@ -70,17 +76,16 @@ Heap::init Heap::hello Heap::destroy *******************/ -int main (void) { +int main(void) +{ GREENTEA_SETUP(10, "default_auto"); bool result = true; - for (;;) - { + for (;;) { s.print("init"); // Global stack object simple test s.stack_test(); - if (s.check_init() == false) - { + if (s.check_init() == false) { result = false; break; } @@ -89,8 +94,7 @@ int main (void) { Test *m = new Test("Heap"); m->hello(); - if (m->check_init() == false) - { + if (m->check_init() == false) { result = false; } delete m; diff --git a/TESTS/mbedmicro-mbed/div/main.cpp b/TESTS/mbedmicro-mbed/div/main.cpp index 1e9fc4cd589..05a018b59ae 100644 --- a/TESTS/mbedmicro-mbed/div/main.cpp +++ b/TESTS/mbedmicro-mbed/div/main.cpp @@ -17,7 +17,8 @@ #include "mbed.h" #include "greentea-client/test_env.h" -uint32_t test_64(uint64_t ticks) { +uint32_t test_64(uint64_t ticks) +{ ticks >>= 3; // divide by 8 if (ticks > 0xFFFFFFFF) { ticks /= 3; @@ -27,16 +28,19 @@ uint32_t test_64(uint64_t ticks) { return (uint32_t)(0xFFFFFFFF & ticks); } -const char *result_str(bool result) { +const char *result_str(bool result) +{ return result ? "[OK]" : "[FAIL]"; } -int main() { +int main() +{ GREENTEA_SETUP(5, "default_auto"); bool result = true; - { // 0xFFFFFFFF * 8 = 0x7fffffff8 + { + // 0xFFFFFFFF * 8 = 0x7fffffff8 std::pair values = std::make_pair(0x55555555, 0x7FFFFFFF8); uint32_t test_ret = test_64(values.second); bool test_res = values.first == test_ret; @@ -44,7 +48,8 @@ int main() { printf("64bit: 0x7FFFFFFF8: expected 0x%lX got 0x%lX ... %s\r\n", values.first, test_ret, result_str(test_res)); } - { // 0xFFFFFFFF * 24 = 0x17ffffffe8 + { + // 0xFFFFFFFF * 24 = 0x17ffffffe8 std::pair values = std::make_pair(0xFFFFFFFF, 0x17FFFFFFE8); uint32_t test_ret = test_64(values.second); bool test_res = values.first == test_ret; diff --git a/TESTS/mbedmicro-mbed/static_assert/main.cpp b/TESTS/mbedmicro-mbed/static_assert/main.cpp index 844a60aff44..dd963e0c25b 100644 --- a/TESTS/mbedmicro-mbed/static_assert/main.cpp +++ b/TESTS/mbedmicro-mbed/static_assert/main.cpp @@ -25,7 +25,8 @@ using namespace utest::v1; void no_test() {} -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(5, "default_auto"); return verbose_test_setup_handler(number_of_cases); } @@ -36,6 +37,7 @@ Case cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/TESTS/mbedmicro-mbed/static_assert/test_c.c b/TESTS/mbedmicro-mbed/static_assert/test_c.c index 476c3b044fa..0cda4d44f55 100644 --- a/TESTS/mbedmicro-mbed/static_assert/test_c.c +++ b/TESTS/mbedmicro-mbed/static_assert/test_c.c @@ -6,34 +6,35 @@ // Test for static asserts in global context MBED_STATIC_ASSERT(sizeof(int) >= sizeof(char), - "An int must be larger than char"); + "An int must be larger than char"); MBED_STATIC_ASSERT(2 + 2 == 4, - "Hopefully the universe is mathematically consistent"); + "Hopefully the universe is mathematically consistent"); MBED_STATIC_ASSERT(THE_ANSWER == 42, - "Said Deep Thought, with infinite majesty and calm"); + "Said Deep Thought, with infinite majesty and calm"); struct test { int dummy; // Test for static asserts in struct context MBED_STRUCT_STATIC_ASSERT(sizeof(int) >= sizeof(char), - "An int must be larger than char"); + "An int must be larger than char"); MBED_STRUCT_STATIC_ASSERT(2 + 2 == 4, - "Hopefully the universe is mathematically consistent"); + "Hopefully the universe is mathematically consistent"); MBED_STRUCT_STATIC_ASSERT(THE_ANSWER == 42, - "Said Deep Thought, with infinite majesty and calm"); + "Said Deep Thought, with infinite majesty and calm"); }; MBED_STATIC_ASSERT(sizeof(struct test) == sizeof(int), - "Static assertions should not change the size of a struct"); + "Static assertions should not change the size of a struct"); -void doit_c(void) { +void doit_c(void) +{ // Test for static asserts in function context MBED_STATIC_ASSERT(sizeof(int) >= sizeof(char), - "An int must be larger than char"); + "An int must be larger than char"); MBED_STATIC_ASSERT(2 + 2 == 4, - "Hopefully the universe is mathematically consistent"); + "Hopefully the universe is mathematically consistent"); MBED_STATIC_ASSERT(THE_ANSWER == 42, - "Said Deep Thought, with infinite majesty and calm"); + "Said Deep Thought, with infinite majesty and calm"); } diff --git a/TESTS/mbedmicro-mbed/static_assert/test_cpp.cpp b/TESTS/mbedmicro-mbed/static_assert/test_cpp.cpp index 987c01ab9aa..2cd337e432a 100644 --- a/TESTS/mbedmicro-mbed/static_assert/test_cpp.cpp +++ b/TESTS/mbedmicro-mbed/static_assert/test_cpp.cpp @@ -6,41 +6,42 @@ // Test for static asserts in global context MBED_STATIC_ASSERT(sizeof(int) >= sizeof(char), - "An int must be larger than char"); + "An int must be larger than char"); MBED_STATIC_ASSERT(2 + 2 == 4, - "Hopefully the universe is mathematically consistent"); + "Hopefully the universe is mathematically consistent"); MBED_STATIC_ASSERT(THE_ANSWER == 42, - "Said Deep Thought, with infinite majesty and calm"); + "Said Deep Thought, with infinite majesty and calm"); struct test { int dummy; // Test for static asserts in struct context MBED_STRUCT_STATIC_ASSERT(sizeof(int) >= sizeof(char), - "An int must be larger than char"); + "An int must be larger than char"); MBED_STRUCT_STATIC_ASSERT(2 + 2 == 4, - "Hopefully the universe is mathematically consistent"); + "Hopefully the universe is mathematically consistent"); MBED_STRUCT_STATIC_ASSERT(THE_ANSWER == 42, - "Said Deep Thought, with infinite majesty and calm"); + "Said Deep Thought, with infinite majesty and calm"); MBED_STATIC_ASSERT(sizeof(int) >= sizeof(char), - "An int must be larger than char"); + "An int must be larger than char"); MBED_STATIC_ASSERT(2 + 2 == 4, - "Hopefully the universe is mathematically consistent"); + "Hopefully the universe is mathematically consistent"); MBED_STATIC_ASSERT(THE_ANSWER == 42, - "Said Deep Thought, with infinite majesty and calm"); + "Said Deep Thought, with infinite majesty and calm"); }; MBED_STATIC_ASSERT(sizeof(struct test) == sizeof(int), - "Static assertions should not change the size of a struct"); + "Static assertions should not change the size of a struct"); -void doit_c(void) { +void doit_c(void) +{ // Test for static asserts in function context MBED_STATIC_ASSERT(sizeof(int) >= sizeof(char), - "An int must be larger than char"); + "An int must be larger than char"); MBED_STATIC_ASSERT(2 + 2 == 4, - "Hopefully the universe is mathematically consistent"); + "Hopefully the universe is mathematically consistent"); MBED_STATIC_ASSERT(THE_ANSWER == 42, - "Said Deep Thought, with infinite majesty and calm"); + "Said Deep Thought, with infinite majesty and calm"); } diff --git a/TESTS/mbedmicro-rtos-mbed/CircularBuffer/main.cpp b/TESTS/mbedmicro-rtos-mbed/CircularBuffer/main.cpp index 2191ee91b75..0fbf7c0170d 100644 --- a/TESTS/mbedmicro-rtos-mbed/CircularBuffer/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/CircularBuffer/main.cpp @@ -23,8 +23,7 @@ using namespace utest::v1; /* Structure for complex type. */ -typedef struct -{ +typedef struct { int a; char b; int c; diff --git a/TESTS/mbedmicro-rtos-mbed/MemoryPool/main.cpp b/TESTS/mbedmicro-rtos-mbed/MemoryPool/main.cpp index 1428d48e948..30e335873a1 100644 --- a/TESTS/mbedmicro-rtos-mbed/MemoryPool/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/MemoryPool/main.cpp @@ -21,14 +21,12 @@ using namespace utest::v1; /* Enum used to select block allocation method. */ -typedef enum -{ +typedef enum { ALLOC, CALLOC } AllocType; /* Structure for complex block type. */ -typedef struct -{ +typedef struct { int a; char b; int c; @@ -75,7 +73,7 @@ template void test_mem_pool_alloc_success(AllocType atype) { MemoryPool mem_pool; - T * p_blocks[numOfEntries]; + T *p_blocks[numOfEntries]; uint32_t i; /* Test alloc()/calloc() methods - try to allocate max number of @@ -121,7 +119,7 @@ template void test_mem_pool_alloc_success_complex(AllocType atype) { MemoryPool mem_pool; - T * p_blocks[numOfEntries]; + T *p_blocks[numOfEntries]; uint32_t i; /* Test alloc()/calloc() methods - try to allocate max number of @@ -164,8 +162,8 @@ template void test_mem_pool_alloc_fail(AllocType atype) { MemoryPool mem_pool; - T * p_blocks[numOfEntries]; - T * p_extra_block; + T *p_blocks[numOfEntries]; + T *p_extra_block; uint32_t i; /* Allocate all available blocks. */ @@ -203,7 +201,7 @@ template void test_mem_pool_free_success(AllocType atype) { MemoryPool mem_pool; - T * p_blocks[numOfEntries]; + T *p_blocks[numOfEntries]; uint32_t i; osStatus status; @@ -243,7 +241,7 @@ template void test_mem_pool_free_realloc_last(AllocType atype) { MemoryPool mem_pool; - T * p_blocks[numOfEntries]; + T *p_blocks[numOfEntries]; uint32_t i; osStatus status; @@ -299,7 +297,7 @@ template void test_mem_pool_free_realloc_last_complex(AllocType atype) { MemoryPool mem_pool; - T * p_blocks[numOfEntries]; + T *p_blocks[numOfEntries]; uint32_t i; osStatus status; @@ -355,7 +353,7 @@ template void test_mem_pool_free_realloc_first(AllocType atype) { MemoryPool mem_pool; - T * p_blocks[numOfEntries]; + T *p_blocks[numOfEntries]; uint32_t i; osStatus status; @@ -411,7 +409,7 @@ template void test_mem_pool_free_realloc_first_complex(AllocType atype) { MemoryPool mem_pool; - T * p_blocks[numOfEntries]; + T *p_blocks[numOfEntries]; uint32_t i; osStatus status; @@ -462,7 +460,7 @@ void test_mem_pool_free_realloc_first_complex(AllocType atype) void test_mem_pool_free_on_freed_block() { MemoryPool mem_pool; - int * p_block; + int *p_block; osStatus status; /* Allocate memory block. */ @@ -518,7 +516,7 @@ void free_block_invalid_parameter() osStatus status; /* Try to free block passing invalid parameter (variable address). */ - status = mem_pool.free(reinterpret_cast(&status)); + status = mem_pool.free(reinterpret_cast(&status)); /* Check operation status. */ TEST_ASSERT_EQUAL(osErrorParameter, status); diff --git a/TESTS/mbedmicro-rtos-mbed/basic/main.cpp b/TESTS/mbedmicro-rtos-mbed/basic/main.cpp index 87b1e6712f9..25ec8642d56 100644 --- a/TESTS/mbedmicro-rtos-mbed/basic/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/basic/main.cpp @@ -92,7 +92,7 @@ void test(void) //get the results from host greentea_parse_kv(_key, _value, sizeof(_key), sizeof(_value)); - TEST_ASSERT_EQUAL_STRING_MESSAGE("pass", _key,"Host side script reported a fail..."); + TEST_ASSERT_EQUAL_STRING_MESSAGE("pass", _key, "Host side script reported a fail..."); } Case cases[] = { diff --git a/TESTS/mbedmicro-rtos-mbed/condition_variable/main.cpp b/TESTS/mbedmicro-rtos-mbed/condition_variable/main.cpp index d33c9c7bac0..6ed1eb2e461 100644 --- a/TESTS/mbedmicro-rtos-mbed/condition_variable/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/condition_variable/main.cpp @@ -20,7 +20,7 @@ #include "rtos.h" #if defined(MBED_RTOS_SINGLE_THREAD) - #error [NOT_SUPPORTED] test not supported +#error [NOT_SUPPORTED] test not supported #endif using namespace utest::v1; diff --git a/TESTS/mbedmicro-rtos-mbed/event_flags/main.cpp b/TESTS/mbedmicro-rtos-mbed/event_flags/main.cpp index 7753a4521d9..c7f1363e993 100644 --- a/TESTS/mbedmicro-rtos-mbed/event_flags/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/event_flags/main.cpp @@ -23,7 +23,7 @@ using utest::v1::Case; #if defined(MBED_RTOS_SINGLE_THREAD) - #error [NOT_SUPPORTED] test not supported +#error [NOT_SUPPORTED] test not supported #endif #define THREAD_STACK_SIZE 320 /* 512B stack on GCC_ARM compiler cause out of memory on some 16kB RAM boards e.g. NUCLEO_F070RB */ @@ -48,7 +48,8 @@ Semaphore sync_sem(0, 1); * which aborts test program. */ #if defined(MBED_TRAP_ERRORS_ENABLED) && MBED_TRAP_ERRORS_ENABLED -void error(const char* format, ...) { +void error(const char *format, ...) +{ (void) format; } #endif @@ -264,7 +265,7 @@ void test_multi_thread_any_timeout(void) EventFlags ef; uint32_t ret; Thread thread(osPriorityNormal, THREAD_STACK_SIZE); - thread.start(callback(send_thread_sync, &ef)); + thread.start(callback(send_thread_sync < FLAG01 | FLAG02 | FLAG03, 1 >, &ef)); for (int i = 0; i <= MAX_FLAG_POS; i++) { uint32_t flag = 1 << i; diff --git a/TESTS/mbedmicro-rtos-mbed/heap_and_stack/main.cpp b/TESTS/mbedmicro-rtos-mbed/heap_and_stack/main.cpp index b5b6b4cbf90..69875b4c6ed 100644 --- a/TESTS/mbedmicro-rtos-mbed/heap_and_stack/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/heap_and_stack/main.cpp @@ -16,7 +16,7 @@ */ #if defined(TARGET_CORTEX_A) - #error [NOT_SUPPORTED] This function not supported for this target +#error [NOT_SUPPORTED] This function not supported for this target #endif #include @@ -46,7 +46,7 @@ extern uint32_t mbed_stack_isr_size; struct linked_list { - linked_list * next; + linked_list *next; uint8_t data[MALLOC_TEST_SIZE]; }; @@ -86,7 +86,7 @@ static bool rangeinrange(uint32_t addr, uint32_t size, uint32_t start, uint32_t /* * Return true if the region is filled only with the specified value */ -static bool valid_fill(uint8_t * data, uint32_t size, uint8_t fill) +static bool valid_fill(uint8_t *data, uint32_t size, uint8_t fill) { for (uint32_t i = 0; i < size; i++) { if (data[i] != fill) { @@ -100,18 +100,18 @@ static void allocate_and_fill_heap(linked_list *&head) { linked_list *current; - current = (linked_list*) malloc(sizeof(linked_list)); + current = (linked_list *) malloc(sizeof(linked_list)); TEST_ASSERT_NOT_NULL(current); current->next = NULL; - memset((void*) current->data, MALLOC_FILL, sizeof(current->data)); + memset((void *) current->data, MALLOC_FILL, sizeof(current->data)); // Allocate until malloc returns NULL head = current; while (true) { // Allocate - linked_list *temp = (linked_list*) malloc(sizeof(linked_list)); + linked_list *temp = (linked_list *) malloc(sizeof(linked_list)); if (NULL == temp) { break; @@ -122,7 +122,7 @@ static void allocate_and_fill_heap(linked_list *&head) // Init temp->next = NULL; - memset((void*) temp->data, MALLOC_FILL, sizeof(current->data)); + memset((void *) temp->data, MALLOC_FILL, sizeof(current->data)); // Add to list current->next = temp; @@ -133,7 +133,7 @@ static void allocate_and_fill_heap(linked_list *&head) static void check_and_free_heap(linked_list *head, uint32_t &max_allocation_size) { uint32_t total_size = 0; - linked_list * current = head; + linked_list *current = head; while (current != NULL) { total_size += sizeof(linked_list); @@ -141,7 +141,7 @@ static void check_and_free_heap(linked_list *head, uint32_t &max_allocation_size TEST_ASSERT_TRUE_MESSAGE(result, "Memory fill check failed"); - linked_list * next = current->next; + linked_list *next = current->next; free(current); current = next; } @@ -161,7 +161,7 @@ void test_heap_in_range(void) char *initial_heap; // Sanity check malloc - initial_heap = (char*) malloc(1); + initial_heap = (char *) malloc(1); TEST_ASSERT_NOT_NULL(initial_heap); bool result = inrange((uint32_t) initial_heap, mbed_heap_start, mbed_heap_size); @@ -178,10 +178,10 @@ void test_heap_in_range(void) */ void test_main_stack_in_range(void) { - os_thread_t *thread = (os_thread_t*) osThreadGetId(); + os_thread_t *thread = (os_thread_t *) osThreadGetId(); uint32_t psp = __get_PSP(); - uint8_t *stack_mem = (uint8_t*) thread->stack_mem; + uint8_t *stack_mem = (uint8_t *) thread->stack_mem; uint32_t stack_size = thread->stack_size; // PSP stack should be somewhere in the middle diff --git a/TESTS/mbedmicro-rtos-mbed/mail/main.cpp b/TESTS/mbedmicro-rtos-mbed/mail/main.cpp index 6c9aa96d1fb..39e7bf6dc10 100644 --- a/TESTS/mbedmicro-rtos-mbed/mail/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/mail/main.cpp @@ -20,7 +20,7 @@ #include "rtos.h" #if defined(MBED_RTOS_SINGLE_THREAD) - #error [NOT_SUPPORTED] test not supported +#error [NOT_SUPPORTED] test not supported #endif using namespace utest::v1; @@ -66,7 +66,7 @@ void receive_thread(Mail *m) for (uint32_t i = 0; i < queue_size; i++) { osEvent evt = m->get(); if (evt.status == osEventMail) { - mail_t *mail = (mail_t*)evt.value.p; + mail_t *mail = (mail_t *)evt.value.p; const uint8_t id = mail->thread_id; // verify thread id @@ -104,7 +104,7 @@ void test_single_thread_order(void) // mail receive (main thread) osEvent evt = mail_box.get(); if (evt.status == osEventMail) { - mail_t *mail = (mail_t*)evt.value.p; + mail_t *mail = (mail_t *)evt.value.p; const uint8_t id = mail->thread_id; // verify thread id @@ -146,7 +146,7 @@ void test_multi_thread_order(void) // mail receive (main thread) osEvent evt = mail_box.get(); if (evt.status == osEventMail) { - mail_t *mail = (mail_t*)evt.value.p; + mail_t *mail = (mail_t *)evt.value.p; const uint8_t id = mail->thread_id; // verify thread id @@ -343,13 +343,13 @@ void test_order(void) evt = mail_box.get(); TEST_ASSERT_EQUAL(evt.status, osEventMail); - mail1 = (int32_t*)evt.value.p; + mail1 = (int32_t *)evt.value.p; TEST_ASSERT_EQUAL(TEST_VAL1, *mail1); evt = mail_box.get(); TEST_ASSERT_EQUAL(evt.status, osEventMail); - mail2 = (int32_t*)evt.value.p; + mail2 = (int32_t *)evt.value.p; TEST_ASSERT_EQUAL(TEST_VAL2, *mail2); @@ -431,7 +431,7 @@ void test_data_type(void) osEvent evt = mail_box.get(); TEST_ASSERT_EQUAL(evt.status, osEventMail); - mail = (T*)evt.value.p; + mail = (T *)evt.value.p; TEST_ASSERT_EQUAL(TEST_VAL, *mail); diff --git a/TESTS/mbedmicro-rtos-mbed/malloc/main.cpp b/TESTS/mbedmicro-rtos-mbed/malloc/main.cpp index 6655bc33b73..f361c6f0feb 100644 --- a/TESTS/mbedmicro-rtos-mbed/malloc/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/malloc/main.cpp @@ -20,7 +20,7 @@ #if defined(MBED_RTOS_SINGLE_THREAD) - #error [NOT_SUPPORTED] test not supported +#error [NOT_SUPPORTED] test not supported #endif using utest::v1::Case; @@ -132,7 +132,7 @@ void test_zero_allocation(void) void *data = NULL; data = malloc(0); - if(data != NULL) { + if (data != NULL) { free(data); } TEST_ASSERT_MESSAGE(true, "malloc(0) succeed - no undefined behaviour happens"); diff --git a/TESTS/mbedmicro-rtos-mbed/mutex/main.cpp b/TESTS/mbedmicro-rtos-mbed/mutex/main.cpp index 0506a66dbd9..875ba09f8ed 100644 --- a/TESTS/mbedmicro-rtos-mbed/mutex/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/mutex/main.cpp @@ -20,7 +20,7 @@ #include "rtos.h" #if defined(MBED_RTOS_SINGLE_THREAD) - #error [NOT_SUPPORTED] test not supported +#error [NOT_SUPPORTED] test not supported #endif using namespace utest::v1; @@ -196,7 +196,7 @@ void test_dual_thread_lock_lock_thread(Mutex *mutex) osStatus stat = mutex->lock(TEST_DELAY); TEST_ASSERT_EQUAL(osErrorTimeout, stat); - TEST_ASSERT_UINT32_WITHIN(5000, TEST_DELAY*1000, timer.read_us()); + TEST_ASSERT_UINT32_WITHIN(5000, TEST_DELAY * 1000, timer.read_us()); } /** Test dual thread lock diff --git a/TESTS/mbedmicro-rtos-mbed/queue/main.cpp b/TESTS/mbedmicro-rtos-mbed/queue/main.cpp index 81fe8177bdf..fb62db83469 100644 --- a/TESTS/mbedmicro-rtos-mbed/queue/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/queue/main.cpp @@ -20,7 +20,7 @@ #include "rtos.h" #if defined(MBED_RTOS_SINGLE_THREAD) - #error [NOT_SUPPORTED] test not supported +#error [NOT_SUPPORTED] test not supported #endif using namespace utest::v1; @@ -34,7 +34,7 @@ template void thread_put_uint_msg(Queue *q) { Thread::wait(ms); - osStatus stat = q->put((uint32_t*) TEST_UINT_MSG); + osStatus stat = q->put((uint32_t *) TEST_UINT_MSG); TEST_ASSERT_EQUAL(osOK, stat); } @@ -57,7 +57,7 @@ void thread_get_uint_msg(Queue *q) void test_pass_uint() { Queue q; - osStatus stat = q.put((uint32_t*)TEST_UINT_MSG); + osStatus stat = q.put((uint32_t *)TEST_UINT_MSG); TEST_ASSERT_EQUAL(osOK, stat); osEvent evt = q.get(); @@ -77,14 +77,14 @@ void test_pass_uint() void test_pass_uint_twice() { Queue q; - osStatus stat = q.put((uint32_t*)TEST_UINT_MSG); + osStatus stat = q.put((uint32_t *)TEST_UINT_MSG); TEST_ASSERT_EQUAL(osOK, stat); osEvent evt = q.get(); TEST_ASSERT_EQUAL(osEventMessage, evt.status); TEST_ASSERT_EQUAL(TEST_UINT_MSG, evt.value.v); - stat = q.put((uint32_t*)TEST_UINT_MSG2); + stat = q.put((uint32_t *)TEST_UINT_MSG2); TEST_ASSERT_EQUAL(osOK, stat); evt = q.get(); @@ -177,10 +177,10 @@ void test_put_full_no_timeout() { Queue q; - osStatus stat = q.put((uint32_t*) TEST_UINT_MSG); + osStatus stat = q.put((uint32_t *) TEST_UINT_MSG); TEST_ASSERT_EQUAL(osOK, stat); - stat = q.put((uint32_t*) TEST_UINT_MSG); + stat = q.put((uint32_t *) TEST_UINT_MSG); TEST_ASSERT_EQUAL(osErrorResource, stat); } @@ -194,13 +194,13 @@ void test_put_full_timeout() { Queue q; - osStatus stat = q.put((uint32_t*) TEST_UINT_MSG, TEST_TIMEOUT); + osStatus stat = q.put((uint32_t *) TEST_UINT_MSG, TEST_TIMEOUT); TEST_ASSERT_EQUAL(osOK, stat); Timer timer; timer.start(); - stat = q.put((uint32_t*) TEST_UINT_MSG, TEST_TIMEOUT); + stat = q.put((uint32_t *) TEST_UINT_MSG, TEST_TIMEOUT); TEST_ASSERT_EQUAL(osErrorTimeout, stat); TEST_ASSERT_UINT32_WITHIN(TEST_TIMEOUT * 100, TEST_TIMEOUT * 1000, timer.read_us()); } @@ -220,12 +220,12 @@ void test_put_full_waitforever() t.start(callback(thread_get_uint_msg, &q)); - osStatus stat = q.put((uint32_t*) TEST_UINT_MSG); + osStatus stat = q.put((uint32_t *) TEST_UINT_MSG); TEST_ASSERT_EQUAL(osOK, stat); Timer timer; timer.start(); - stat = q.put((uint32_t*) TEST_UINT_MSG, osWaitForever); + stat = q.put((uint32_t *) TEST_UINT_MSG, osWaitForever); TEST_ASSERT_EQUAL(osOK, stat); TEST_ASSERT_UINT32_WITHIN(TEST_TIMEOUT * 100, TEST_TIMEOUT * 1000, timer.read_us()); @@ -242,10 +242,10 @@ void test_msg_order() { Queue q; - osStatus stat = q.put((uint32_t*) TEST_UINT_MSG, TEST_TIMEOUT); + osStatus stat = q.put((uint32_t *) TEST_UINT_MSG, TEST_TIMEOUT); TEST_ASSERT_EQUAL(osOK, stat); - stat = q.put((uint32_t*) TEST_UINT_MSG2, TEST_TIMEOUT); + stat = q.put((uint32_t *) TEST_UINT_MSG2, TEST_TIMEOUT); TEST_ASSERT_EQUAL(osOK, stat); osEvent evt = q.get(); @@ -267,10 +267,10 @@ void test_msg_prio() { Queue q; - osStatus stat = q.put((uint32_t*) TEST_UINT_MSG, TEST_TIMEOUT, 0); + osStatus stat = q.put((uint32_t *) TEST_UINT_MSG, TEST_TIMEOUT, 0); TEST_ASSERT_EQUAL(osOK, stat); - stat = q.put((uint32_t*) TEST_UINT_MSG2, TEST_TIMEOUT, 1); + stat = q.put((uint32_t *) TEST_UINT_MSG2, TEST_TIMEOUT, 1); TEST_ASSERT_EQUAL(osOK, stat); osEvent evt = q.get(); @@ -294,7 +294,7 @@ void test_queue_empty() TEST_ASSERT_EQUAL(true, q.empty()); - q.put((uint32_t*) TEST_UINT_MSG, TEST_TIMEOUT, 1); + q.put((uint32_t *) TEST_UINT_MSG, TEST_TIMEOUT, 1); TEST_ASSERT_EQUAL(false, q.empty()); } @@ -311,7 +311,7 @@ void test_queue_full() TEST_ASSERT_EQUAL(false, q.full()); - q.put((uint32_t*) TEST_UINT_MSG, TEST_TIMEOUT, 1); + q.put((uint32_t *) TEST_UINT_MSG, TEST_TIMEOUT, 1); TEST_ASSERT_EQUAL(true, q.full()); } diff --git a/TESTS/mbedmicro-rtos-mbed/rtostimer/main.cpp b/TESTS/mbedmicro-rtos-mbed/rtostimer/main.cpp index 694ea04bf3a..01b709312c3 100644 --- a/TESTS/mbedmicro-rtos-mbed/rtostimer/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/rtostimer/main.cpp @@ -36,7 +36,7 @@ class Stopwatch: public Timer { public: Stopwatch() : - Timer(), _sem(1) + Timer(), _sem(1) { } @@ -81,7 +81,7 @@ void sem_callback(Semaphore *sem) * which aborts test program. */ #if defined(MBED_TRAP_ERRORS_ENABLED) && MBED_TRAP_ERRORS_ENABLED -void error(const char* format, ...) +void error(const char *format, ...) { (void) format; } diff --git a/TESTS/mbedmicro-rtos-mbed/semaphore/main.cpp b/TESTS/mbedmicro-rtos-mbed/semaphore/main.cpp index ce211752080..14e2ecde32d 100644 --- a/TESTS/mbedmicro-rtos-mbed/semaphore/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/semaphore/main.cpp @@ -22,7 +22,7 @@ using namespace utest::v1; #if defined(MBED_RTOS_SINGLE_THREAD) - #error [NOT_SUPPORTED] test not supported +#error [NOT_SUPPORTED] test not supported #endif #define THREAD_DELAY 30 @@ -200,7 +200,7 @@ void test_multiple_tokens_wait() { Semaphore sem(5); - for(int i = 5; i >= 0; i--) { + for (int i = 5; i >= 0; i--) { int32_t cnt = sem.wait(0); TEST_ASSERT_EQUAL(i, cnt); } @@ -216,7 +216,7 @@ void test_multiple_tokens_release() { Semaphore sem(0, 5); - for(int i = 5; i > 0; i--) { + for (int i = 5; i > 0; i--) { osStatus stat = sem.release(); TEST_ASSERT_EQUAL(osOK, stat); } diff --git a/TESTS/mbedmicro-rtos-mbed/signals/main.cpp b/TESTS/mbedmicro-rtos-mbed/signals/main.cpp index 0809b14f175..f8c68a4dbf5 100644 --- a/TESTS/mbedmicro-rtos-mbed/signals/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/signals/main.cpp @@ -22,7 +22,7 @@ using utest::v1::Case; #if defined(MBED_RTOS_SINGLE_THREAD) - #error [NOT_SUPPORTED] test not supported +#error [NOT_SUPPORTED] test not supported #endif #define TEST_STACK_SIZE 512 @@ -52,7 +52,8 @@ struct Sync { * which aborts test program. */ #if defined(MBED_TRAP_ERRORS_ENABLED) && MBED_TRAP_ERRORS_ENABLED -void error(const char* format, ...) { +void error(const char *format, ...) +{ (void) format; } #endif @@ -356,7 +357,7 @@ void test_set_double(void) Semaphore sem(0, 1); Thread t(osPriorityNormal, TEST_STACK_SIZE); - t.start(callback(run_release_signal_wait, &sem)); + t.start(callback(run_release_signal_wait < SIGNAL1 | SIGNAL2 | SIGNAL3, osWaitForever, osEventSignal >, &sem)); sem.wait(); TEST_ASSERT_EQUAL(Thread::WaitingThreadFlag, t.get_state()); diff --git a/TESTS/mbedmicro-rtos-mbed/systimer/main.cpp b/TESTS/mbedmicro-rtos-mbed/systimer/main.cpp index 51a85cea963..c11989f6d29 100644 --- a/TESTS/mbedmicro-rtos-mbed/systimer/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/systimer/main.cpp @@ -50,7 +50,7 @@ class SysTimerTest: public rtos::internal::SysTimer { public: SysTimerTest() : - SysTimer(), _sem(0, 1) + SysTimer(), _sem(0, 1) { } diff --git a/TESTS/mbedmicro-rtos-mbed/threads/LockGuard.h b/TESTS/mbedmicro-rtos-mbed/threads/LockGuard.h index 1db70631091..fd5fd657197 100644 --- a/TESTS/mbedmicro-rtos-mbed/threads/LockGuard.h +++ b/TESTS/mbedmicro-rtos-mbed/threads/LockGuard.h @@ -31,21 +31,23 @@ class LockGuard { * Construct a LockGuard instance and ackire ownership of mutex in input. * @param mutex The mutex to ackire ownership of. */ - LockGuard(rtos::Mutex& mutex) : _mutex(mutex) { + LockGuard(rtos::Mutex &mutex) : _mutex(mutex) + { _mutex.lock(); } /** * Destruct the lock and release the inner mutex. */ - ~LockGuard() { + ~LockGuard() + { _mutex.unlock(); } private: - LockGuard(const LockGuard&); - LockGuard& operator=(const LockGuard&); - rtos::Mutex& _mutex; + LockGuard(const LockGuard &); + LockGuard &operator=(const LockGuard &); + rtos::Mutex &_mutex; }; #endif /* MBEDMICRO_RTOS_MBED_THREADS_LOCK_GUARD */ diff --git a/TESTS/mbedmicro-rtos-mbed/threads/SynchronizedIntegral.h b/TESTS/mbedmicro-rtos-mbed/threads/SynchronizedIntegral.h index a7b66255301..afb3ce0ef42 100644 --- a/TESTS/mbedmicro-rtos-mbed/threads/SynchronizedIntegral.h +++ b/TESTS/mbedmicro-rtos-mbed/threads/SynchronizedIntegral.h @@ -31,37 +31,43 @@ class SynchronizedIntegral { SynchronizedIntegral(T value) : _mutex(), _value(value) { } // preincrement operator - T operator++() { + T operator++() + { LockGuard lock(_mutex); return ++_value; } // predecrement operator - T operator--() { + T operator--() + { LockGuard lock(_mutex); return --_value; } // post increment operator - T operator++(int) { + T operator++(int) + { LockGuard lock(_mutex); return _value++; } // post decrement operator - T operator--(int) { + T operator--(int) + { LockGuard lock(_mutex); return _value--; } // conversion operator, used also for <,>,<=,>=,== and != - operator T() const { + operator T() const + { LockGuard lock(_mutex); return _value; } // access to the internal mutex - rtos::Mutex& internal_mutex() { + rtos::Mutex &internal_mutex() + { return _mutex; } diff --git a/TESTS/mbedmicro-rtos-mbed/threads/main.cpp b/TESTS/mbedmicro-rtos-mbed/threads/main.cpp index 7ebf09e795e..8489b8ad100 100644 --- a/TESTS/mbedmicro-rtos-mbed/threads/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/threads/main.cpp @@ -22,7 +22,7 @@ #include "LockGuard.h" #if defined(MBED_RTOS_SINGLE_THREAD) - #error [NOT_SUPPORTED] test not supported +#error [NOT_SUPPORTED] test not supported #endif #define THREAD_STACK_SIZE 512 @@ -46,28 +46,33 @@ class ParallelThread : public Thread { }; // Tasks with different functions to test on threads -void increment(counter_t* counter) { +void increment(counter_t *counter) +{ (*counter)++; } -void increment_with_yield(counter_t* counter) { +void increment_with_yield(counter_t *counter) +{ Thread::yield(); (*counter)++; } -void increment_with_wait(counter_t* counter) { +void increment_with_wait(counter_t *counter) +{ Thread::wait(100); (*counter)++; } -void increment_with_child(counter_t* counter) { +void increment_with_child(counter_t *counter) +{ Thread *child = new Thread(osPriorityNormal, CHILD_THREAD_STACK_SIZE); child->start(callback(increment, counter)); child->join(); delete child; } -void increment_with_murder(counter_t* counter) { +void increment_with_murder(counter_t *counter) +{ { // take ownership of the counter mutex so it prevent the child to // modify counter. @@ -81,7 +86,8 @@ void increment_with_murder(counter_t* counter) { (*counter)++; } -void self_terminate(Thread *self) { +void self_terminate(Thread *self) +{ self->terminate(); // Code should not get here TEST_ASSERT(0); @@ -120,7 +126,8 @@ void self_terminate(Thread *self) { then the final value of the counter is equal to 1 */ template -void test_single_thread() { +void test_single_thread() +{ counter_t counter(0); Thread thread(osPriorityNormal, THREAD_STACK_SIZE); thread.start(callback(F, &counter)); @@ -159,7 +166,8 @@ void test_single_thread() { then the final value of the counter is equal to number of parallel threads */ template -void test_parallel_threads() { +void test_parallel_threads() +{ counter_t counter(0); ParallelThread threads[N]; @@ -205,7 +213,8 @@ void test_parallel_threads() { then the final value of the counter is equal to number of serial threads */ template -void test_serial_threads() { +void test_serial_threads() +{ counter_t counter(0); for (int i = 0; i < N; i++) { @@ -223,7 +232,8 @@ void test_serial_threads() { when the thread calls @a terminate on its self then the thread terminates execution cleanly */ -void test_self_terminate() { +void test_self_terminate() +{ Thread *thread = new Thread(osPriorityNormal, THREAD_STACK_SIZE); thread->start(callback(self_terminate, thread)); thread->join(); @@ -330,11 +340,13 @@ void test_thread_signal_clr() t_wait.join(); } -void thread_wait_signal() { +void thread_wait_signal() +{ Thread::signal_wait(0x1); } -void stack_info() { +void stack_info() +{ Thread::signal_wait(0x1); thread_wait_signal(); @@ -354,7 +366,8 @@ void stack_info() { and the reported stack size is as requested in the constructor and the sum of free and used stack sizes is equal to the total stack size */ -void test_thread_stack_info() { +void test_thread_stack_info() +{ Thread t(osPriorityNormal, THREAD_STACK_SIZE); t.start(callback(stack_info)); @@ -388,7 +401,8 @@ void test_thread_stack_info() { when the @a wait function is called then the thread sleeps for given amount of time */ -void test_thread_wait() { +void test_thread_wait() +{ Timer timer; timer.start(); @@ -403,7 +417,8 @@ void test_thread_wait() { when the name is queried using @a get_name then the returned name is as set */ -void test_thread_name() { +void test_thread_name() +{ const char tname[] = "Amazing thread"; Thread t(osPriorityNormal, THREAD_STACK_SIZE, NULL, tname); t.start(callback(thread_wait_signal)); @@ -621,7 +636,8 @@ void test_msg_put() } /** Utility function that places some date on the stack */ -void use_some_stack () { +void use_some_stack() +{ volatile uint32_t stack_filler[10] = {0xDEADBEEF}; } @@ -631,18 +647,20 @@ void use_some_stack () { when the thread executes then the supplies buffer is used as a stack */ -void test_thread_ext_stack() { +void test_thread_ext_stack() +{ char stack[512]; - Thread t(osPriorityNormal, sizeof(stack), (unsigned char*)stack); + Thread t(osPriorityNormal, sizeof(stack), (unsigned char *)stack); memset(&stack, 0, sizeof(stack)); t.start(callback(use_some_stack)); t.join(); /* If buffer was used as a stack it was cleared with pattern and some data were placed in it */ - for(unsigned i = 0; i < sizeof(stack); i++) { - if (stack[i] != 0) + for (unsigned i = 0; i < sizeof(stack); i++) { + if (stack[i] != 0) { return; + } } TEST_FAIL_MESSAGE("External stack was not used."); @@ -654,7 +672,8 @@ void test_thread_ext_stack() { when new priority is set using @a set_priority then priority is changed and can be retrieved using @a get_priority */ -void test_thread_prio() { +void test_thread_prio() +{ Thread t(osPriorityNormal, THREAD_STACK_SIZE); t.start(callback(thread_wait_signal)); @@ -668,7 +687,8 @@ void test_thread_prio() { t.join(); } -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(20, "default_auto"); return verbose_test_setup_handler(number_of_cases); } @@ -679,8 +699,8 @@ utest::v1::status_t test_setup(const size_t number_of_cases) { // macros don't play nicely with the templates (extra comma). static const case_t cases[] = { {"Testing single thread", test_single_thread, DEFAULT_HANDLERS}, - {"Testing parallel threads", test_parallel_threads<3, increment> , DEFAULT_HANDLERS}, - {"Testing serial threads", test_serial_threads<10, increment> , DEFAULT_HANDLERS}, + {"Testing parallel threads", test_parallel_threads<3, increment>, DEFAULT_HANDLERS}, + {"Testing serial threads", test_serial_threads<10, increment>, DEFAULT_HANDLERS}, {"Testing single thread with yield", test_single_thread, DEFAULT_HANDLERS}, {"Testing parallel threads with yield", test_parallel_threads<3, increment_with_yield>, DEFAULT_HANDLERS}, @@ -727,6 +747,7 @@ static const case_t cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/TESTS/mbedtls/multi/main.cpp b/TESTS/mbedtls/multi/main.cpp index ce823cadcd4..4fe74da734f 100644 --- a/TESTS/mbedtls/multi/main.cpp +++ b/TESTS/mbedtls/multi/main.cpp @@ -28,65 +28,73 @@ using namespace utest::v1; #if defined(MBEDTLS_SHA256_C) /* Tests several call to mbedtls_sha256_update function that are not modulo 64 bytes */ -void test_case_sha256_split() { - const unsigned char test_buf[] = {"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopqabcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopqabcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"}; - // sha256_output_values for 3*abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq - const unsigned char test_sum[] = - { 0x50, 0xEA, 0x82, 0x5D, 0x96, 0x84, 0xF4, 0x22, - 0x9C, 0xA2, 0x9F, 0x1F, 0xEC, 0x51, 0x15, 0x93, - 0xE2, 0x81, 0xE4, 0x6A, 0x14, 0x0D, 0x81, 0xE0, - 0x00, 0x5F, 0x8F, 0x68, 0x86, 0x69, 0xA0, 0x6C}; - unsigned char outsum[32]; - int i; - - mbedtls_sha256_context ctx; - printf("test sha256\n"); - mbedtls_sha256_init( &ctx ); - mbedtls_sha256_starts( &ctx, 0); - #if 0 +void test_case_sha256_split() +{ + const unsigned char test_buf[] = {"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopqabcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopqabcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"}; + // sha256_output_values for 3*abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq + const unsigned char test_sum[] = { + 0x50, 0xEA, 0x82, 0x5D, 0x96, 0x84, 0xF4, 0x22, + 0x9C, 0xA2, 0x9F, 0x1F, 0xEC, 0x51, 0x15, 0x93, + 0xE2, 0x81, 0xE4, 0x6A, 0x14, 0x0D, 0x81, 0xE0, + 0x00, 0x5F, 0x8F, 0x68, 0x86, 0x69, 0xA0, 0x6C + }; + unsigned char outsum[32]; + int i; + + mbedtls_sha256_context ctx; + printf("test sha256\n"); + mbedtls_sha256_init(&ctx); + mbedtls_sha256_starts(&ctx, 0); +#if 0 printf("test not splitted\n"); - mbedtls_sha256_update( &ctx, test_buf, 168 ); - #else + mbedtls_sha256_update(&ctx, test_buf, 168); +#else printf("test splitted into 3 pieces\n"); - mbedtls_sha256_update( &ctx, test_buf, 2 ); - mbedtls_sha256_update( &ctx, test_buf+2, 66 ); - mbedtls_sha256_update( &ctx, test_buf+68, 100 ); - #endif - - mbedtls_sha256_finish( &ctx, outsum ); - mbedtls_sha256_free( &ctx ); - + mbedtls_sha256_update(&ctx, test_buf, 2); + mbedtls_sha256_update(&ctx, test_buf + 2, 66); + mbedtls_sha256_update(&ctx, test_buf + 68, 100); +#endif + + mbedtls_sha256_finish(&ctx, outsum); + mbedtls_sha256_free(&ctx); + printf("\nreceived result : "); - for (i=0;i<32;i++) { printf("%02X",outsum[i]);} + for (i = 0; i < 32; i++) { + printf("%02X", outsum[i]); + } printf("\nawaited result : 50EA825D9684F4229CA29F1FEC511593E281E46A140D81E0005F8F688669A06C\n"); // for abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq - + printf("\nend of test sha256\n"); - TEST_ASSERT_EQUAL_UINT8_ARRAY(outsum, test_sum,32); + TEST_ASSERT_EQUAL_UINT8_ARRAY(outsum, test_sum, 32); } /* Tests that treating 2 sha256 objects in // does not impact the result */ -void test_case_sha256_multi() { +void test_case_sha256_multi() +{ const unsigned char test_buf[] = {"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopqabcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopqabcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"}; const unsigned char test_buf2[] = {"abcdefghijklmnopqrstuvwxyz012345678901234567890123456789"}; // sha256_output_values for abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq - const unsigned char test_sum1[] = - { 0x24, 0x8D, 0x6A, 0x61, 0xD2, 0x06, 0x38, 0xB8, - 0xE5, 0xC0, 0x26, 0x93, 0x0C, 0x3E, 0x60, 0x39, - 0xA3, 0x3C, 0xE4, 0x59, 0x64, 0xFF, 0x21, 0x67, - 0xF6, 0xEC, 0xED, 0xD4, 0x19, 0xDB, 0x06, 0xC1 }; + const unsigned char test_sum1[] = { + 0x24, 0x8D, 0x6A, 0x61, 0xD2, 0x06, 0x38, 0xB8, + 0xE5, 0xC0, 0x26, 0x93, 0x0C, 0x3E, 0x60, 0x39, + 0xA3, 0x3C, 0xE4, 0x59, 0x64, 0xFF, 0x21, 0x67, + 0xF6, 0xEC, 0xED, 0xD4, 0x19, 0xDB, 0x06, 0xC1 + }; // sha256_output_values for 3*abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq - const unsigned char test_sum2[] = - { 0x50, 0xEA, 0x82, 0x5D, 0x96, 0x84, 0xF4, 0x22, - 0x9C, 0xA2, 0x9F, 0x1F, 0xEC, 0x51, 0x15, 0x93, - 0xE2, 0x81, 0xE4, 0x6A, 0x14, 0x0D, 0x81, 0xE0, - 0x00, 0x5F, 0x8F, 0x68, 0x86, 0x69, 0xA0, 0x6C}; + const unsigned char test_sum2[] = { + 0x50, 0xEA, 0x82, 0x5D, 0x96, 0x84, 0xF4, 0x22, + 0x9C, 0xA2, 0x9F, 0x1F, 0xEC, 0x51, 0x15, 0x93, + 0xE2, 0x81, 0xE4, 0x6A, 0x14, 0x0D, 0x81, 0xE0, + 0x00, 0x5F, 0x8F, 0x68, 0x86, 0x69, 0xA0, 0x6C + }; // sha256_output_values for abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopqabcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopqabcdefghijklmnopqrstuvwxyz012345678901234567890123456789 - const unsigned char test_sum3[] = - { 0x6D, 0x5D, 0xDB, 0x5F, 0x4A, 0x94, 0xAB, 0x7E, - 0x5C, 0xF7, 0x9A, 0xD8, 0x3F, 0x58, 0xD3, 0x97, - 0xFE, 0x79, 0xFB, 0x0D, 0x79, 0xB2, 0x0D, 0x22, - 0xFF, 0x95, 0x9F, 0x04, 0xA2, 0xE4, 0x6C, 0x68}; + const unsigned char test_sum3[] = { + 0x6D, 0x5D, 0xDB, 0x5F, 0x4A, 0x94, 0xAB, 0x7E, + 0x5C, 0xF7, 0x9A, 0xD8, 0x3F, 0x58, 0xD3, 0x97, + 0xFE, 0x79, 0xFB, 0x0D, 0x79, 0xB2, 0x0D, 0x22, + 0xFF, 0x95, 0x9F, 0x04, 0xA2, 0xE4, 0x6C, 0x68 + }; unsigned char outsum1[32], outsum2[32], outsum3[32]; int i; @@ -95,55 +103,62 @@ void test_case_sha256_multi() { mbedtls_sha256_context ctx3; printf("test sha256_multi\n"); //Init both contexts - mbedtls_sha256_init( &ctx1); - mbedtls_sha256_init( &ctx2); - mbedtls_sha256_init( &ctx3); + mbedtls_sha256_init(&ctx1); + mbedtls_sha256_init(&ctx2); + mbedtls_sha256_init(&ctx3); //Start both contexts - mbedtls_sha256_starts( &ctx1, 0); - mbedtls_sha256_starts( &ctx2, 0); + mbedtls_sha256_starts(&ctx1, 0); + mbedtls_sha256_starts(&ctx2, 0); printf("upd ctx1\n"); - mbedtls_sha256_update( &ctx1, test_buf, 56 ); + mbedtls_sha256_update(&ctx1, test_buf, 56); printf("upd ctx2\n"); - mbedtls_sha256_update( &ctx2, test_buf, 66 ); + mbedtls_sha256_update(&ctx2, test_buf, 66); printf("finish ctx1\n"); - mbedtls_sha256_finish( &ctx1, outsum1 ); + mbedtls_sha256_finish(&ctx1, outsum1); printf("upd ctx2\n"); - mbedtls_sha256_update( &ctx2, test_buf+66, 46 ); + mbedtls_sha256_update(&ctx2, test_buf + 66, 46); printf("clone ctx2 in ctx3\n"); mbedtls_sha256_clone(&ctx3, (const mbedtls_sha256_context *)&ctx2); printf("free ctx1\n"); - mbedtls_sha256_free( &ctx1 ); + mbedtls_sha256_free(&ctx1); printf("upd ctx2\n"); - mbedtls_sha256_update( &ctx2, test_buf+112, 56 ); + mbedtls_sha256_update(&ctx2, test_buf + 112, 56); printf("upd ctx3 with different values than ctx2\n"); - mbedtls_sha256_update( &ctx3, test_buf2, 56 ); + mbedtls_sha256_update(&ctx3, test_buf2, 56); printf("finish ctx2\n"); - mbedtls_sha256_finish( &ctx2, outsum2 ); + mbedtls_sha256_finish(&ctx2, outsum2); printf("finish ctx3\n"); - mbedtls_sha256_finish( &ctx3, outsum3 ); + mbedtls_sha256_finish(&ctx3, outsum3); printf("free ctx2\n"); - mbedtls_sha256_free( &ctx2 ); + mbedtls_sha256_free(&ctx2); printf("free ctx3\n"); - mbedtls_sha256_free( &ctx3 ); + mbedtls_sha256_free(&ctx3); printf("\nreceived result ctx1 : "); - for (i=0;i<32;i++) { printf("%02X",outsum1[i]);} + for (i = 0; i < 32; i++) { + printf("%02X", outsum1[i]); + } printf("\nawaited result : 248D6A61D20638B8E5C026930C3E6039A33CE45964FF216F6ECEDD19DB06C1\n"); // for abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq printf("\nreceived result ctx2 : "); - for (i=0;i<32;i++) { printf("%02X",outsum2[i]);} + for (i = 0; i < 32; i++) { + printf("%02X", outsum2[i]); + } printf("\nawaited result : 50EA825D9684F4229CA29F1FEC511593E281E46A140D81E0005F8F688669A06C\n"); // for 3*abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq printf("\nreceived result ctx3 : "); - for (i=0;i<32;i++) { printf("%02X",outsum3[i]);} + for (i = 0; i < 32; i++) { + printf("%02X", outsum3[i]); + } printf("\nawaited result : 6D5DDB5F4A94AB7E5CF79AD83F58D397FE79FB0D79B20D22FF959F04A2E46C68\n"); // for 2*abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq+3*0123456789 printf("\nend of test sha256\n"); - TEST_ASSERT_EQUAL_UINT8_ARRAY(outsum1, test_sum1,32); - TEST_ASSERT_EQUAL_UINT8_ARRAY(outsum2, test_sum2,32); - TEST_ASSERT_EQUAL_UINT8_ARRAY(outsum3, test_sum3,32); + TEST_ASSERT_EQUAL_UINT8_ARRAY(outsum1, test_sum1, 32); + TEST_ASSERT_EQUAL_UINT8_ARRAY(outsum2, test_sum2, 32); + TEST_ASSERT_EQUAL_UINT8_ARRAY(outsum3, test_sum3, 32); } #endif //MBEDTLS_SHA256_C -utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) { +utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) +{ greentea_case_failure_abort_handler(source, reason); return STATUS_CONTINUE; } @@ -155,13 +170,15 @@ Case cases[] = { #endif }; -utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { +utest::v1::status_t greentea_test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(10, "default_auto"); return greentea_test_setup_handler(number_of_cases); } Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); -int main() { +int main() +{ Harness::run(specification); } diff --git a/TESTS/mbedtls/selftest/main.cpp b/TESTS/mbedtls/selftest/main.cpp index d011d1911e1..2d9d37ba83c 100644 --- a/TESTS/mbedtls/selftest/main.cpp +++ b/TESTS/mbedtls/selftest/main.cpp @@ -89,14 +89,16 @@ Case cases[] = { #endif /* MBEDTLS_SELF_TEST */ }; -utest::v1::status_t test_setup(const size_t num_cases) { +utest::v1::status_t test_setup(const size_t num_cases) +{ GREENTEA_SETUP(120, "default_auto"); return verbose_test_setup_handler(num_cases); } Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/TESTS/netsocket/connectivity/main.cpp b/TESTS/netsocket/connectivity/main.cpp index 3330d2bbc37..2495aa2ab57 100644 --- a/TESTS/netsocket/connectivity/main.cpp +++ b/TESTS/netsocket/connectivity/main.cpp @@ -15,9 +15,9 @@ * limitations under the License. */ - #ifndef MBED_CONF_APP_CONNECT_STATEMENT - #error [NOT_SUPPORTED] No network configuration found for this target. - #endif +#ifndef MBED_CONF_APP_CONNECT_STATEMENT +#error [NOT_SUPPORTED] No network configuration found for this target. +#endif #include "mbed.h" #include "greentea-client/test_env.h" @@ -29,8 +29,9 @@ using namespace utest::v1; // Bringing the network up and down template -void test_bring_up_down() { - NetworkInterface* net = MBED_CONF_APP_OBJECT_CONSTRUCTION; +void test_bring_up_down() +{ + NetworkInterface *net = MBED_CONF_APP_OBJECT_CONSTRUCTION; for (int i = 0; i < COUNT; i++) { int err = MBED_CONF_APP_CONNECT_STATEMENT; @@ -58,7 +59,8 @@ void test_bring_up_down() { // Test setup -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(120, "default_auto"); return verbose_test_setup_handler(number_of_cases); } @@ -70,6 +72,7 @@ Case cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/TESTS/netsocket/gethostbyname/main.cpp b/TESTS/netsocket/gethostbyname/main.cpp index 58a4e47470c..24aef793e69 100644 --- a/TESTS/netsocket/gethostbyname/main.cpp +++ b/TESTS/netsocket/gethostbyname/main.cpp @@ -15,9 +15,9 @@ * limitations under the License. */ - #ifndef MBED_CONF_APP_CONNECT_STATEMENT - #error [NOT_SUPPORTED] No network configuration found for this target. - #endif +#ifndef MBED_CONF_APP_CONNECT_STATEMENT +#error [NOT_SUPPORTED] No network configuration found for this target. +#endif #include "mbed.h" #include "greentea-client/test_env.h" @@ -42,7 +42,8 @@ const char *ip_pref_repr; // Network setup NetworkInterface *net; -void net_bringup() { +void net_bringup() +{ net = MBED_CONF_APP_OBJECT_CONSTRUCTION; int err = MBED_CONF_APP_CONNECT_STATEMENT; TEST_ASSERT_EQUAL(0, err); @@ -57,22 +58,24 @@ void net_bringup() { // DNS tests -void test_dns_query() { +void test_dns_query() +{ SocketAddress addr; int err = net->gethostbyname(MBED_CONF_APP_DNS_TEST_HOST, &addr); printf("DNS: query \"%s\" => \"%s\"\n", - MBED_CONF_APP_DNS_TEST_HOST, addr.get_ip_address()); + MBED_CONF_APP_DNS_TEST_HOST, addr.get_ip_address()); TEST_ASSERT_EQUAL(0, err); TEST_ASSERT((bool)addr); TEST_ASSERT(strlen(addr.get_ip_address()) > 1); } -void test_dns_query_pref() { +void test_dns_query_pref() +{ SocketAddress addr; int err = net->gethostbyname(MBED_CONF_APP_DNS_TEST_HOST, &addr, ip_pref); printf("DNS: query %s \"%s\" => \"%s\"\n", - ip_pref_repr, MBED_CONF_APP_DNS_TEST_HOST, addr.get_ip_address()); + ip_pref_repr, MBED_CONF_APP_DNS_TEST_HOST, addr.get_ip_address()); TEST_ASSERT_EQUAL(0, err); TEST_ASSERT((bool)addr); @@ -80,11 +83,12 @@ void test_dns_query_pref() { TEST_ASSERT_EQUAL(ip_pref, addr.get_ip_version()); } -void test_dns_literal() { +void test_dns_literal() +{ SocketAddress addr; int err = net->gethostbyname(ip_literal, &addr); printf("DNS: literal \"%s\" => \"%s\"\n", - ip_literal, addr.get_ip_address()); + ip_literal, addr.get_ip_address()); TEST_ASSERT_EQUAL(0, err); TEST_ASSERT((bool)addr); @@ -92,11 +96,12 @@ void test_dns_literal() { TEST_ASSERT(strcmp(ip_literal, addr.get_ip_address()) == 0); } -void test_dns_literal_pref() { +void test_dns_literal_pref() +{ SocketAddress addr; int err = net->gethostbyname(ip_literal, &addr, ip_pref); printf("DNS: literal %s \"%s\" => \"%s\"\n", - ip_pref_repr, ip_literal, addr.get_ip_address()); + ip_pref_repr, ip_literal, addr.get_ip_address()); TEST_ASSERT_EQUAL(0, err); TEST_ASSERT((bool)addr); @@ -107,7 +112,8 @@ void test_dns_literal_pref() { // Test setup -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(120, "default_auto"); net_bringup(); return verbose_test_setup_handler(number_of_cases); @@ -122,6 +128,7 @@ Case cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/TESTS/netsocket/ip_parsing/main.cpp b/TESTS/netsocket/ip_parsing/main.cpp index 1ffe8058987..781f9558410 100644 --- a/TESTS/netsocket/ip_parsing/main.cpp +++ b/TESTS/netsocket/ip_parsing/main.cpp @@ -15,9 +15,9 @@ * limitations under the License. */ - #ifndef MBED_CONF_APP_CONNECT_STATEMENT - #error [NOT_SUPPORTED] No network configuration found for this target. - #endif +#ifndef MBED_CONF_APP_CONNECT_STATEMENT +#error [NOT_SUPPORTED] No network configuration found for this target. +#endif #include "mbed.h" #include "greentea-client/test_env.h" @@ -28,14 +28,16 @@ using namespace utest::v1; // IP parsing verification -void test_ip_accept(const char *string, nsapi_addr_t addr) { +void test_ip_accept(const char *string, nsapi_addr_t addr) +{ SocketAddress address; TEST_ASSERT(address.set_ip_address(string)); TEST_ASSERT(address == SocketAddress(addr)); } template -void test_ip_reject() { +void test_ip_reject() +{ SocketAddress address; TEST_ASSERT(!address.set_ip_address(string)); TEST_ASSERT(!address); @@ -55,42 +57,58 @@ void name() { \ // Test cases TEST_IP_ACCEPT(test_simple_ipv4_address, - "12.34.56.78", - {NSAPI_IPv4,{12,34,56,78}}) + "12.34.56.78", +{NSAPI_IPv4, {12, 34, 56, 78}}) TEST_IP_ACCEPT(test_left_weighted_ipv4_address, - "255.0.0.0", - {NSAPI_IPv4,{255,0,0,0}}) + "255.0.0.0", +{NSAPI_IPv4, {255, 0, 0, 0}}) TEST_IP_ACCEPT(test_right_weighted_ipv4_address, - "0.0.0.255", - {NSAPI_IPv4,{0,0,0,255}}) + "0.0.0.255", +{NSAPI_IPv4, {0, 0, 0, 255}}) TEST_IP_ACCEPT(test_null_ipv4_address, - "0.0.0.0", - {NSAPI_IPv4,{0,0,0,0}}) + "0.0.0.0", +{NSAPI_IPv4, {0, 0, 0, 0}}) TEST_IP_ACCEPT(test_simple_ipv6_address, - "1234:5678:9abc:def0:1234:5678:9abc:def0", - {NSAPI_IPv6,{0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0, - 0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0}}) +"1234:5678:9abc:def0:1234:5678:9abc:def0", { + NSAPI_IPv6, { + 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, + 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 + } +}) TEST_IP_ACCEPT(test_left_weighted_ipv6_address, - "1234:5678::", - {NSAPI_IPv6,{0x12,0x34,0x56,0x78,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}) +"1234:5678::", { + NSAPI_IPv6, { + 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + } +}) TEST_IP_ACCEPT(test_right_weighted_ipv6_address, - "::1234:5678", - {NSAPI_IPv6,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x12,0x34,0x56,0x78}}) +"::1234:5678", { + NSAPI_IPv6, { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x12, 0x34, 0x56, 0x78 + } +}) TEST_IP_ACCEPT(test_hollowed_ipv6_address, - "1234:5678::9abc:def8", - {NSAPI_IPv6,{0x12,0x34,0x56,0x78,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x9a,0xbc,0xde,0xf8}}) +"1234:5678::9abc:def8", { + NSAPI_IPv6, { + 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x9a, 0xbc, 0xde, 0xf8 + } +}) TEST_IP_ACCEPT(test_null_ipv6_address, - "::", - {NSAPI_IPv6,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}) +"::", { + NSAPI_IPv6, { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + } +}) // Test setup -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(10, "default_auto"); return verbose_test_setup_handler(number_of_cases); } @@ -110,6 +128,7 @@ Case cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/TESTS/netsocket/socket_sigio/main.cpp b/TESTS/netsocket/socket_sigio/main.cpp index a9e75a13edb..604e1e6872e 100644 --- a/TESTS/netsocket/socket_sigio/main.cpp +++ b/TESTS/netsocket/socket_sigio/main.cpp @@ -15,9 +15,9 @@ * limitations under the License. */ - #ifndef MBED_CONF_APP_CONNECT_STATEMENT - #error [NOT_SUPPORTED] No network configuration found for this target. - #endif +#ifndef MBED_CONF_APP_CONNECT_STATEMENT +#error [NOT_SUPPORTED] No network configuration found for this target. +#endif #include #include "mbed.h" @@ -35,42 +35,45 @@ using namespace utest::v1; #endif namespace { - // Test connection information - const int HTTP_SERVER_PORT = 80; +// Test connection information +const int HTTP_SERVER_PORT = 80; #if defined(TARGET_VK_RZ_A1H) - const int RECV_BUFFER_SIZE = 300; +const int RECV_BUFFER_SIZE = 300; #else - const int RECV_BUFFER_SIZE = 512; +const int RECV_BUFFER_SIZE = 512; #endif - // Test related data - const char *HTTP_OK_STR = "200 OK"; - const char *HTTP_HELLO_STR = "Hello world!"; +// Test related data +const char *HTTP_OK_STR = "200 OK"; +const char *HTTP_HELLO_STR = "Hello world!"; - // Test buffers - char buffer[RECV_BUFFER_SIZE] = {0}; +// Test buffers +char buffer[RECV_BUFFER_SIZE] = {0}; - Semaphore recvd; - NetworkInterface *net; +Semaphore recvd; +NetworkInterface *net; } -void net_bringup() { +void net_bringup() +{ net = MBED_CONF_APP_OBJECT_CONSTRUCTION; int err = MBED_CONF_APP_CONNECT_STATEMENT; TEST_ASSERT_EQUAL(0, err); } -bool find_substring(const char *first, const char *last, const char *s_first, const char *s_last) { +bool find_substring(const char *first, const char *last, const char *s_first, const char *s_last) +{ const char *f = std::search(first, last, s_first, s_last); return (f != last); } -void get_data(TCPSocket* sock){ +void get_data(TCPSocket *sock) +{ bool result = false; // Server will respond with HTTP GET's success code int len = 0; int ret; - while((ret = sock->recv(buffer+len, sizeof(buffer) - 1 - len)) > 0) { - len += ret; + while ((ret = sock->recv(buffer + len, sizeof(buffer) - 1 - len)) > 0) { + len += ret; } buffer[len] = '\0'; @@ -82,7 +85,9 @@ void get_data(TCPSocket* sock){ TEST_ASSERT_TRUE(found_200_ok); TEST_ASSERT_TRUE(found_hello); - if (found_200_ok && found_hello) result = true; + if (found_200_ok && found_hello) { + result = true; + } TEST_ASSERT_EQUAL(result, true); @@ -95,7 +100,8 @@ void get_data(TCPSocket* sock){ recvd.release(); } -void prep_buffer() { +void prep_buffer() +{ memset(buffer, 0, sizeof(buffer)); // We are constructing GET command like this: // GET http://developer.mbed.org/media/uploads/mbed_official/hello.txt HTTP/1.0\n\n @@ -105,12 +111,13 @@ void prep_buffer() { strcat(buffer, " HTTP/1.0\n\n"); } -void test_socket_attach() { +void test_socket_attach() +{ bool result = false; // Dispatch event queue Thread eventThread; - EventQueue queue(10*EVENTS_EVENT_SIZE); + EventQueue queue(10 * EVENTS_EVENT_SIZE); eventThread.start(callback(&queue, &EventQueue::dispatch_forever)); printf("TCP client IP Address is %s\r\n", net->get_ip_address()); @@ -136,18 +143,21 @@ void test_socket_attach() { TEST_ASSERT_EQUAL(true, result); } -void cb_fail() { +void cb_fail() +{ TEST_ASSERT(false); } -void cb_pass() { +void cb_pass() +{ recvd.release(); } -void test_socket_detach() { +void test_socket_detach() +{ // Dispatch event queue Thread eventThread; - EventQueue queue(4*EVENTS_EVENT_SIZE); + EventQueue queue(4 * EVENTS_EVENT_SIZE); eventThread.start(callback(&queue, &EventQueue::dispatch_forever)); printf("TCP client IP Address is %s\r\n", net->get_ip_address()); @@ -171,10 +181,11 @@ void test_socket_detach() { sock.close(); } -void test_socket_reattach() { +void test_socket_reattach() +{ // Dispatch event queue Thread eventThread; - EventQueue queue(4*EVENTS_EVENT_SIZE); + EventQueue queue(4 * EVENTS_EVENT_SIZE); eventThread.start(callback(&queue, &EventQueue::dispatch_forever)); printf("TCP client IP Address is %s\r\n", net->get_ip_address()); @@ -201,7 +212,8 @@ void test_socket_reattach() { // Test setup -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(120, "default_auto"); net_bringup(); return verbose_test_setup_handler(number_of_cases); @@ -215,6 +227,7 @@ Case cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/TESTS/netsocket/tcp_echo/main.cpp b/TESTS/netsocket/tcp_echo/main.cpp index 19af7763b57..ed3de79f120 100644 --- a/TESTS/netsocket/tcp_echo/main.cpp +++ b/TESTS/netsocket/tcp_echo/main.cpp @@ -32,8 +32,7 @@ using namespace utest::v1; #define MBED_CONF_APP_TCP_CLIENT_ECHO_BUFFER_SIZE 256 #endif -namespace -{ +namespace { char tx_buffer[MBED_CONF_APP_TCP_CLIENT_ECHO_BUFFER_SIZE] = {0}; char rx_buffer[MBED_CONF_APP_TCP_CLIENT_ECHO_BUFFER_SIZE] = {0}; } @@ -48,7 +47,7 @@ void prep_buffer(char *tx_buffer, size_t tx_size) void test_tcp_echo() { int n = 0; - NetworkInterface* net = MBED_CONF_APP_OBJECT_CONSTRUCTION; + NetworkInterface *net = MBED_CONF_APP_OBJECT_CONSTRUCTION; int err = MBED_CONF_APP_CONNECT_STATEMENT; if (err) { diff --git a/TESTS/netsocket/tcp_echo_parallel/main.cpp b/TESTS/netsocket/tcp_echo_parallel/main.cpp index e73d53fc64e..03b8488ddf2 100644 --- a/TESTS/netsocket/tcp_echo_parallel/main.cpp +++ b/TESTS/netsocket/tcp_echo_parallel/main.cpp @@ -45,7 +45,7 @@ using namespace utest::v1; #define STRINGIZE2(x) #x -NetworkInterface* net; +NetworkInterface *net; SocketAddress tcp_addr; Mutex iomutex; @@ -58,8 +58,7 @@ void prep_buffer(char *tx_buffer, size_t tx_size) // Each echo class is in charge of one parallel transaction -class Echo -{ +class Echo { private: char tx_buffer[MBED_CONF_APP_TCP_CLIENT_ECHO_BUFFER_SIZE]; char rx_buffer[MBED_CONF_APP_TCP_CLIENT_ECHO_BUFFER_SIZE]; diff --git a/TESTS/netsocket/tcp_hello_world/main.cpp b/TESTS/netsocket/tcp_hello_world/main.cpp index b6e36dd5385..6d4d7495842 100644 --- a/TESTS/netsocket/tcp_hello_world/main.cpp +++ b/TESTS/netsocket/tcp_hello_world/main.cpp @@ -15,9 +15,9 @@ * limitations under the License. */ - #ifndef MBED_CONF_APP_CONNECT_STATEMENT - #error [NOT_SUPPORTED] No network configuration found for this target. - #endif +#ifndef MBED_CONF_APP_CONNECT_STATEMENT +#error [NOT_SUPPORTED] No network configuration found for this target. +#endif #include #include "mbed.h" @@ -35,29 +35,31 @@ using namespace utest::v1; #endif namespace { - // Test connection information - const int HTTP_SERVER_PORT = 80; +// Test connection information +const int HTTP_SERVER_PORT = 80; #if defined(TARGET_VK_RZ_A1H) - const int RECV_BUFFER_SIZE = 300; +const int RECV_BUFFER_SIZE = 300; #else - const int RECV_BUFFER_SIZE = 512; +const int RECV_BUFFER_SIZE = 512; #endif - // Test related data - const char *HTTP_OK_STR = "200 OK"; - const char *HTTP_HELLO_STR = "Hello world!"; +// Test related data +const char *HTTP_OK_STR = "200 OK"; +const char *HTTP_HELLO_STR = "Hello world!"; - // Test buffers - char buffer[RECV_BUFFER_SIZE] = {0}; +// Test buffers +char buffer[RECV_BUFFER_SIZE] = {0}; } -bool find_substring(const char *first, const char *last, const char *s_first, const char *s_last) { +bool find_substring(const char *first, const char *last, const char *s_first, const char *s_last) +{ const char *f = std::search(first, last, s_first, s_last); return (f != last); } -void test_tcp_hello_world() { +void test_tcp_hello_world() +{ bool result = false; - NetworkInterface* net = MBED_CONF_APP_OBJECT_CONSTRUCTION; + NetworkInterface *net = MBED_CONF_APP_OBJECT_CONSTRUCTION; MBED_CONF_APP_CONNECT_STATEMENT; printf("TCP client IP Address is %s\r\n", net->get_ip_address()); @@ -81,10 +83,10 @@ void test_tcp_hello_world() { do { ret += bytes_recvd; - bytes_recvd = sock.recv(buffer+ret, sizeof(buffer) - 1 - ret); - }while(bytes_recvd > 0); + bytes_recvd = sock.recv(buffer + ret, sizeof(buffer) - 1 - ret); + } while (bytes_recvd > 0); buffer[ret] = '\0'; - + // Find 200 OK HTTP status in reply bool found_200_ok = find_substring(buffer, buffer + ret, HTTP_OK_STR, HTTP_OK_STR + strlen(HTTP_OK_STR)); // Find "Hello World!" string in reply @@ -93,7 +95,9 @@ void test_tcp_hello_world() { TEST_ASSERT_TRUE(found_200_ok); TEST_ASSERT_TRUE(found_hello); - if (found_200_ok && found_hello) result = true; + if (found_200_ok && found_hello) { + result = true; + } printf("HTTP: Received %d chars from server\r\n", ret); printf("HTTP: Received 200 OK status ... %s\r\n", found_200_ok ? "[OK]" : "[FAIL]"); @@ -111,7 +115,8 @@ void test_tcp_hello_world() { // Test setup -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(120, "default_auto"); return verbose_test_setup_handler(number_of_cases); } @@ -122,6 +127,7 @@ Case cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/TESTS/netsocket/tcp_packet_pressure/main.cpp b/TESTS/netsocket/tcp_packet_pressure/main.cpp index e4fe0df9379..2ef132ea250 100644 --- a/TESTS/netsocket/tcp_packet_pressure/main.cpp +++ b/TESTS/netsocket/tcp_packet_pressure/main.cpp @@ -54,8 +54,7 @@ using namespace utest::v1; // Simple xorshift pseudorandom number generator -class RandSeq -{ +class RandSeq { private: uint32_t x; uint32_t y; @@ -141,7 +140,7 @@ void test_tcp_packet_pressure() MBED_CONF_APP_TCP_CLIENT_PACKET_PRESSURE_MAX); printf("MBED: Generated buffer %d\r\n", buffer_size); - NetworkInterface* net = MBED_CONF_APP_OBJECT_CONSTRUCTION; + NetworkInterface *net = MBED_CONF_APP_OBJECT_CONSTRUCTION; int err = MBED_CONF_APP_CONNECT_STATEMENT; TEST_ASSERT_EQUAL(0, err); diff --git a/TESTS/netsocket/tcp_packet_pressure_parallel/main.cpp b/TESTS/netsocket/tcp_packet_pressure_parallel/main.cpp index bfd6ed0524e..78e551642fd 100644 --- a/TESTS/netsocket/tcp_packet_pressure_parallel/main.cpp +++ b/TESTS/netsocket/tcp_packet_pressure_parallel/main.cpp @@ -58,8 +58,7 @@ using namespace utest::v1; // Simple xorshift pseudorandom number generator -class RandSeq -{ +class RandSeq { private: uint32_t x; uint32_t y; @@ -136,14 +135,13 @@ void generate_buffer(uint8_t **buffer, size_t *size, size_t min, size_t max) // Global variables shared between pressure tests -NetworkInterface* net; +NetworkInterface *net; SocketAddress tcp_addr; Timer timer; Mutex iomutex; // Single instance of a pressure test -class PressureTest -{ +class PressureTest { private: uint8_t *buffer; size_t buffer_size; diff --git a/TESTS/netsocket/udp_dtls_handshake/main.cpp b/TESTS/netsocket/udp_dtls_handshake/main.cpp index b36191fa3fd..59e2300b091 100644 --- a/TESTS/netsocket/udp_dtls_handshake/main.cpp +++ b/TESTS/netsocket/udp_dtls_handshake/main.cpp @@ -15,9 +15,9 @@ * limitations under the License. */ - #ifndef MBED_CONF_APP_CONNECT_STATEMENT - #error [NOT_SUPPORTED] No network configuration found for this target. - #endif +#ifndef MBED_CONF_APP_CONNECT_STATEMENT +#error [NOT_SUPPORTED] No network configuration found for this target. +#endif #include "mbed.h" #include MBED_CONF_APP_HEADER_FILE @@ -50,8 +50,9 @@ uint8_t buffer[MBED_CFG_UDP_DTLS_HANDSHAKE_BUFFER_SIZE] = {0}; int udp_dtls_handshake_pattern[] = {MBED_CFG_UDP_DTLS_HANDSHAKE_PATTERN}; const int udp_dtls_handshake_count = sizeof(udp_dtls_handshake_pattern) / sizeof(int); -void test_udp_dtls_handshake() { - NetworkInterface* net = MBED_CONF_APP_OBJECT_CONSTRUCTION; +void test_udp_dtls_handshake() +{ + NetworkInterface *net = MBED_CONF_APP_OBJECT_CONSTRUCTION; int err = MBED_CONF_APP_CONNECT_STATEMENT; TEST_ASSERT_EQUAL(0, err); @@ -84,7 +85,7 @@ void test_udp_dtls_handshake() { printf("MBED: DTLS pattern ["); for (int i = 0; i < udp_dtls_handshake_count; i++) { printf("%d", udp_dtls_handshake_pattern[i]); - if (i != udp_dtls_handshake_count-1) { + if (i != udp_dtls_handshake_count - 1) { printf(", "); } } @@ -149,7 +150,8 @@ void test_udp_dtls_handshake() { // Test setup -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(120, "udp_shotgun"); return verbose_test_setup_handler(number_of_cases); } @@ -160,6 +162,7 @@ Case cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/TESTS/netsocket/udp_echo/main.cpp b/TESTS/netsocket/udp_echo/main.cpp index 3989bb74d6f..ef55501b8c5 100644 --- a/TESTS/netsocket/udp_echo/main.cpp +++ b/TESTS/netsocket/udp_echo/main.cpp @@ -16,7 +16,7 @@ */ #ifndef MBED_CONF_APP_CONNECT_STATEMENT - #error [NOT_SUPPORTED] No network configuration found for this target. +#error [NOT_SUPPORTED] No network configuration found for this target. #endif #include "mbed.h" @@ -38,22 +38,24 @@ using namespace utest::v1; #endif namespace { - char tx_buffer[MBED_CFG_UDP_CLIENT_ECHO_BUFFER_SIZE] = {0}; - char rx_buffer[MBED_CFG_UDP_CLIENT_ECHO_BUFFER_SIZE] = {0}; - const int ECHO_LOOPS = 16; +char tx_buffer[MBED_CFG_UDP_CLIENT_ECHO_BUFFER_SIZE] = {0}; +char rx_buffer[MBED_CFG_UDP_CLIENT_ECHO_BUFFER_SIZE] = {0}; +const int ECHO_LOOPS = 16; } -void prep_buffer(char *tx_buffer, size_t tx_size) { +void prep_buffer(char *tx_buffer, size_t tx_size) +{ size_t i = 0; - for (; iscan(ap, 30); - for (int i=0; iops.get_hwaddr(emac_if, eth_mac_addr); - printf("emac hwaddr %x:%x:%x:%x:%x:%x\r\n\r\n", eth_mac_addr[0],eth_mac_addr[1],eth_mac_addr[2],eth_mac_addr[3],eth_mac_addr[4],eth_mac_addr[5]); + printf("emac hwaddr %x:%x:%x:%x:%x:%x\r\n\r\n", eth_mac_addr[0], eth_mac_addr[1], eth_mac_addr[2], eth_mac_addr[3], eth_mac_addr[4], eth_mac_addr[5]); } int mtu = emac_if->ops.get_mtu_size(emac_if); diff --git a/TESTS/network/emac/emac_util.cpp b/TESTS/network/emac/emac_util.cpp index 920bd6407a6..73b3e9b0136 100644 --- a/TESTS/network/emac/emac_util.cpp +++ b/TESTS/network/emac/emac_util.cpp @@ -56,7 +56,7 @@ typedef struct { extern struct netif *netif_list; // Broadcast address -const unsigned char eth_mac_broadcast_addr[ETH_MAC_ADDR_LEN] = {0xff,0xff,0xff,0xff,0xff,0xff}; +const unsigned char eth_mac_broadcast_addr[ETH_MAC_ADDR_LEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; // Event queue static EventQueue worker_loop_event_queue; @@ -169,9 +169,9 @@ void emac_if_validate_outgoing_msg(void) if (!(outgoing_msgs[i].flags & PRINTED)) { if ((trace_level & TRACE_SUCCESS) || ((trace_level & TRACE_FAILURE) && failure)) { printf("response: receipt number %i %s %s %s\r\n\r\n", outgoing_msgs[i].receipt_number, - outgoing_msgs[i].flags & INVALID_LENGHT ? "LENGTH INVALID" : "LENGTH OK", - outgoing_msgs[i].flags & INVALID_DATA ? "DATA INVALID" : "DATA OK", - outgoing_msgs[i].flags & BROADCAST ? "BROADCAST" : "UNICAST"); + outgoing_msgs[i].flags & INVALID_LENGHT ? "LENGTH INVALID" : "LENGTH OK", + outgoing_msgs[i].flags & INVALID_DATA ? "DATA INVALID" : "DATA OK", + outgoing_msgs[i].flags & BROADCAST ? "BROADCAST" : "UNICAST"); outgoing_msgs[i].flags |= PRINTED; } } @@ -284,22 +284,22 @@ void emac_if_reset_error_flags(void) void emac_if_print_error_flags(void) { - int error_flags_value = emac_if_get_error_flags(); - - char no_resp_message[50]; - if (error_flags_value & NO_RESPONSE) { - snprintf(no_resp_message, 50, "no response from echo server, counter: %i", no_response_cnt); - } else if (no_response_cnt > 0) { - printf("no response from echo server, counter: %i\r\n\r\n", no_response_cnt); - } - - printf("test result: %s%s%s%s%s%s\r\n\r\n", - error_flags_value ? "Test FAILED, reason: ": "PASS", - error_flags_value & TEST_FAILED ? "test failed ": "", - error_flags_value & MSG_VALID_ERROR ? "message content validation error ": "", - error_flags_value & OUT_OF_MSG_DATA ? "out of message validation data storage ": "", - error_flags_value & NO_FREE_MEM_BUF ? "no free memory buffers ": "", - error_flags_value & NO_RESPONSE ? no_resp_message: ""); + int error_flags_value = emac_if_get_error_flags(); + + char no_resp_message[50]; + if (error_flags_value & NO_RESPONSE) { + snprintf(no_resp_message, 50, "no response from echo server, counter: %i", no_response_cnt); + } else if (no_response_cnt > 0) { + printf("no response from echo server, counter: %i\r\n\r\n", no_response_cnt); + } + + printf("test result: %s%s%s%s%s%s\r\n\r\n", + error_flags_value ? "Test FAILED, reason: " : "PASS", + error_flags_value & TEST_FAILED ? "test failed " : "", + error_flags_value & MSG_VALID_ERROR ? "message content validation error " : "", + error_flags_value & OUT_OF_MSG_DATA ? "out of message validation data storage " : "", + error_flags_value & NO_FREE_MEM_BUF ? "no free memory buffers " : "", + error_flags_value & NO_RESPONSE ? no_resp_message : ""); } void emac_if_set_trace_level(char trace_level_value) @@ -312,14 +312,14 @@ void emac_if_trace_to_ascii_hex_dump(const char *prefix, int len, unsigned char int line_len = 0; for (int i = 0; i < len; i++) { - if ((line_len % 14) == 0) { - if (line_len != 0) { - printf("\r\n"); - } - printf("%s %06x", prefix, line_len); - } - line_len++; - printf(" %02x", data[i]); + if ((line_len % 14) == 0) { + if (line_len != 0) { + printf("\r\n"); + } + printf("%s %06x", prefix, line_len); + } + line_len++; + printf(" %02x", data[i]); } printf("\r\n\r\n"); } @@ -358,7 +358,7 @@ static void link_input_event_cb(emac_stack_mem_chain_t *mem_chain_p) if (function == CTP_REPLY) { emac_if_update_reply_to_outgoing_msg(receipt_number, lenght, invalid_data_index); #if MBED_CONF_APP_ECHO_SERVER - // Echoes only if configured as echo server + // Echoes only if configured as echo server } else if (function == CTP_FORWARD) { emac_if_memory_buffer_write(mem_chain_p, eth_output_frame_data, false); emac_if_get()->ops.link_out(emac_if_get(), mem_chain_p); @@ -370,9 +370,9 @@ static void link_input_event_cb(emac_stack_mem_chain_t *mem_chain_p) emac_stack_mem_free(0, mem_chain_p); if (trace_level & TRACE_ETH_FRAMES) { - printf("LEN %i\r\n\r\n", lenght); - const char trace_type[] = "INP>"; - emac_if_trace_to_ascii_hex_dump(trace_type, ETH_FRAME_HEADER_LEN, eth_input_frame_data); + printf("LEN %i\r\n\r\n", lenght); + const char trace_type[] = "INP>"; + emac_if_trace_to_ascii_hex_dump(trace_type, ETH_FRAME_HEADER_LEN, eth_input_frame_data); } return; } diff --git a/TESTS/network/emac/main.cpp b/TESTS/network/emac/main.cpp index 454bb693530..b9149de3420 100644 --- a/TESTS/network/emac/main.cpp +++ b/TESTS/network/emac/main.cpp @@ -47,7 +47,8 @@ using namespace utest::v1; // Test setup -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ #if !MBED_CONF_APP_ECHO_SERVER GREENTEA_SETUP(600, "default_auto"); #endif diff --git a/TESTS/network/wifi/main.cpp b/TESTS/network/wifi/main.cpp index 38d311d6b9e..3ccfe9bb258 100644 --- a/TESTS/network/wifi/main.cpp +++ b/TESTS/network/wifi/main.cpp @@ -51,7 +51,8 @@ using namespace utest::v1; -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(240, "default_auto"); return verbose_test_setup_handler(number_of_cases); } @@ -93,6 +94,7 @@ Case cases[] = { Specification specification(test_setup, cases); // Entry point into the tests -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/TESTS/network/wifi/wifi-constructor.cpp b/TESTS/network/wifi/wifi-constructor.cpp index 3fa80ff5cbb..d97d3a3fde2 100644 --- a/TESTS/network/wifi/wifi-constructor.cpp +++ b/TESTS/network/wifi/wifi-constructor.cpp @@ -23,7 +23,8 @@ using namespace utest::v1; -void wifi_constructor() { +void wifi_constructor() +{ WiFiInterface *wifi = get_interface(); TEST_ASSERT(wifi); } diff --git a/TESTS/network/wifi/wifi_connect_disconnect_repeat.cpp b/TESTS/network/wifi/wifi_connect_disconnect_repeat.cpp index 90f4c5994bd..e23980e18af 100644 --- a/TESTS/network/wifi/wifi_connect_disconnect_repeat.cpp +++ b/TESTS/network/wifi/wifi_connect_disconnect_repeat.cpp @@ -33,7 +33,7 @@ void wifi_connect_disconnect_repeat(void) error = wifi->set_credentials(MBED_CONF_APP_WIFI_UNSECURE_SSID, NULL); TEST_ASSERT(error == NSAPI_ERROR_OK); - for(int i=0; i<10; i++) { + for (int i = 0; i < 10; i++) { error = wifi->connect(); TEST_ASSERT(error == NSAPI_ERROR_OK); error = wifi->disconnect(); diff --git a/TESTS/network/wifi/wifi_connect_params_channel_fail.cpp b/TESTS/network/wifi/wifi_connect_params_channel_fail.cpp index a3c531fd103..d365ed77d84 100644 --- a/TESTS/network/wifi/wifi_connect_params_channel_fail.cpp +++ b/TESTS/network/wifi/wifi_connect_params_channel_fail.cpp @@ -35,7 +35,7 @@ void wifi_connect_params_channel_fail(void) } nsapi_error_t error = wifi->connect(MBED_CONF_APP_WIFI_SECURE_SSID, MBED_CONF_APP_WIFI_PASSWORD, get_security(), MBED_CONF_APP_WIFI_CH_UNSECURE); - TEST_ASSERT(error==NSAPI_ERROR_CONNECTION_TIMEOUT || error==NSAPI_ERROR_NO_CONNECTION); + TEST_ASSERT(error == NSAPI_ERROR_CONNECTION_TIMEOUT || error == NSAPI_ERROR_NO_CONNECTION); } #endif // defined(MBED_CONF_APP_WIFI_SECURE_SSID) diff --git a/TESTS/network/wifi/wifi_connect_params_valid_secure.cpp b/TESTS/network/wifi/wifi_connect_params_valid_secure.cpp index 112a4af389c..eca57ef2023 100644 --- a/TESTS/network/wifi/wifi_connect_params_valid_secure.cpp +++ b/TESTS/network/wifi/wifi_connect_params_valid_secure.cpp @@ -29,7 +29,7 @@ void wifi_connect_params_valid_secure(void) { WiFiInterface *wifi = get_interface(); - if(wifi->connect(MBED_CONF_APP_WIFI_SECURE_SSID, MBED_CONF_APP_WIFI_PASSWORD, get_security()) == NSAPI_ERROR_OK) { + if (wifi->connect(MBED_CONF_APP_WIFI_SECURE_SSID, MBED_CONF_APP_WIFI_PASSWORD, get_security()) == NSAPI_ERROR_OK) { return; } diff --git a/TESTS/network/wifi/wifi_scan.cpp b/TESTS/network/wifi/wifi_scan.cpp index 6986d64d1ef..ab74e5deb99 100644 --- a/TESTS/network/wifi/wifi_scan.cpp +++ b/TESTS/network/wifi/wifi_scan.cpp @@ -44,7 +44,7 @@ void wifi_scan(void) TEST_ASSERT_EQUAL_INT_MESSAGE(6, sscanf(MBED_CONF_APP_AP_MAC_SECURE, coversion_string, &secure_bssid[0], &secure_bssid[1], &secure_bssid[2], &secure_bssid[3], &secure_bssid[4], &secure_bssid[5]), "Failed to convert ap-mac-secure from mbed_app.json"); TEST_ASSERT_EQUAL_INT_MESSAGE(6, sscanf(MBED_CONF_APP_AP_MAC_UNSECURE, coversion_string, &unsecure_bssid[0], &unsecure_bssid[1], &unsecure_bssid[2], &unsecure_bssid[3], &unsecure_bssid[4], &unsecure_bssid[5]), "Failed to convert ap-mac-unsecure from mbed_app.json"); - for (int i=0; iGetVersion(); TEST_ASSERT_EQUAL(version.api, ARM_STORAGE_API_VERSION); - TEST_ASSERT_EQUAL(version.drv, ARM_DRIVER_VERSION_MAJOR_MINOR(1,00)); + TEST_ASSERT_EQUAL(version.drv, ARM_DRIVER_VERSION_MAJOR_MINOR(1, 00)); } void test_getCapabilities() @@ -214,7 +214,7 @@ control_t test_powerControl(const size_t call_count) int32_t rc = drv->PowerControl(ARM_POWER_FULL); if (rc == ARM_DRIVER_OK) { TEST_ASSERT_EQUAL(1, capabilities.asynchronous_ops); - return (call_count < REPEAT_INSTANCES) ? CaseTimeout(200) + CaseRepeatAll: CaseTimeout(200); + return (call_count < REPEAT_INSTANCES) ? CaseTimeout(200) + CaseRepeatAll : CaseTimeout(200); } else { TEST_ASSERT(rc == 1); return (call_count < REPEAT_INSTANCES) ? CaseRepeatAll : CaseNext; @@ -270,7 +270,7 @@ control_t test_readData(const size_t call_count) rc = drv->ReadData(addr, buffer, sizeofData); if (rc == ARM_DRIVER_OK) { TEST_ASSERT_EQUAL(1, capabilities.asynchronous_ops); - return (call_count < REPEAT_INSTANCES) ? CaseTimeout(200) + CaseRepeatAll: CaseTimeout(200); + return (call_count < REPEAT_INSTANCES) ? CaseTimeout(200) + CaseRepeatAll : CaseTimeout(200); } else { TEST_ASSERT(rc > 0); return (call_count < REPEAT_INSTANCES) ? CaseRepeatAll : CaseNext; @@ -371,7 +371,7 @@ control_t test_programDataUsingProgramUnit(const size_t call_count) TEST_ASSERT(rc >= 0); if (rc == ARM_DRIVER_OK) { TEST_ASSERT_EQUAL(1, capabilities.asynchronous_ops); - return (call_count < REPEAT_INSTANCES) ? CaseTimeout(200) + CaseRepeatAll: CaseTimeout(200); + return (call_count < REPEAT_INSTANCES) ? CaseTimeout(200) + CaseRepeatAll : CaseTimeout(200); } else { TEST_ASSERT_EQUAL(firstBlock.attributes.erase_unit, rc); verifyBytePattern(addr, firstBlock.attributes.erase_unit, info.erased_value ? (uint8_t)0xFF : (uint8_t)0); @@ -389,7 +389,7 @@ control_t test_programDataUsingProgramUnit(const size_t call_count) rc = drv->ProgramData((uint32_t)addr, buffer, sizeofData); if (rc == ARM_DRIVER_OK) { TEST_ASSERT_EQUAL(1, capabilities.asynchronous_ops); - return (call_count < REPEAT_INSTANCES) ? CaseTimeout(200) + CaseRepeatAll: CaseTimeout(200); + return (call_count < REPEAT_INSTANCES) ? CaseTimeout(200) + CaseRepeatAll : CaseTimeout(200); } else { TEST_ASSERT(rc > 0); @@ -493,7 +493,7 @@ control_t test_programDataUsingOptimalProgramUnit(const size_t call_count) TEST_ASSERT(rc >= 0); if (rc == ARM_DRIVER_OK) { TEST_ASSERT_EQUAL(1, capabilities.asynchronous_ops); - return (call_count < REPEAT_INSTANCES) ? CaseTimeout(200) + CaseRepeatAll: CaseTimeout(200); + return (call_count < REPEAT_INSTANCES) ? CaseTimeout(200) + CaseRepeatAll : CaseTimeout(200); } else { TEST_ASSERT_EQUAL(firstBlock.attributes.erase_unit, rc); verifyBytePattern(addr, firstBlock.attributes.erase_unit, info.erased_value ? (uint8_t)0xFF : (uint8_t)0); @@ -508,7 +508,7 @@ control_t test_programDataUsingOptimalProgramUnit(const size_t call_count) rc = drv->ProgramData((uint32_t)addr, buffer, sizeofData); if (rc == ARM_DRIVER_OK) { TEST_ASSERT_EQUAL(1, capabilities.asynchronous_ops); - return (call_count < REPEAT_INSTANCES) ? CaseTimeout(200) + CaseRepeatAll: CaseTimeout(200); + return (call_count < REPEAT_INSTANCES) ? CaseTimeout(200) + CaseRepeatAll : CaseTimeout(200); } else { TEST_ASSERT_EQUAL(sizeofData, rc); @@ -627,7 +627,7 @@ control_t test_erase(const size_t call_count) int32_t rc = drv->Erase(addr, ERASE_UNITS_PER_ITERATION * firstBlock.attributes.erase_unit); if (rc == ARM_DRIVER_OK) { TEST_ASSERT_EQUAL(1, capabilities.asynchronous_ops); - return (call_count < REPEAT_INSTANCES) ? CaseTimeout(200) + CaseRepeatAll: CaseTimeout(200); + return (call_count < REPEAT_INSTANCES) ? CaseTimeout(200) + CaseRepeatAll : CaseTimeout(200); } else { TEST_ASSERT_EQUAL(ERASE_UNITS_PER_ITERATION * firstBlock.attributes.erase_unit, rc); @@ -707,7 +707,7 @@ control_t test_eraseAll(const size_t call_count) int32_t rc = drv->EraseAll(); if (rc == ARM_DRIVER_OK) { TEST_ASSERT_EQUAL(1, capabilities.asynchronous_ops); - return (call_count < REPEAT_INSTANCES) ? CaseTimeout(200) + CaseRepeatAll: CaseTimeout(200); + return (call_count < REPEAT_INSTANCES) ? CaseTimeout(200) + CaseRepeatAll : CaseTimeout(200); } else { TEST_ASSERT(rc == 1); @@ -811,9 +811,9 @@ void programDataWithMultipleProgramUnitsCallback(int32_t status, ARM_STORAGE_OPE ((uint32_t *)buffer)[index] = BYTE_PATTERN; } } else { - for (size_t index = 0; index < ((N_UNITS * info.program_unit)); index++) { - buffer[index] = ((const uint8_t *)&BYTE_PATTERN)[0]; - } + for (size_t index = 0; index < ((N_UNITS * info.program_unit)); index++) { + buffer[index] = ((const uint8_t *)&BYTE_PATTERN)[0]; + } } #ifndef __CC_ARM @@ -901,9 +901,9 @@ control_t test_programDataWithMultipleProgramUnits(const size_t call_count) ((uint32_t *)buffer)[index] = BYTE_PATTERN; } } else { - for (size_t index = 0; index < ((N_UNITS * info.program_unit)); index++) { - buffer[index] = ((const uint8_t *)&BYTE_PATTERN)[0]; - } + for (size_t index = 0; index < ((N_UNITS * info.program_unit)); index++) { + buffer[index] = ((const uint8_t *)&BYTE_PATTERN)[0]; + } } printf("programming %lu bytes at address %lu with pattern 0x%lx\n", (N_UNITS * info.program_unit), (uint32_t)firstBlock.addr, BYTE_PATTERN); @@ -986,7 +986,7 @@ Specification specification(greentea_setup, cases); Specification specification(default_setup, cases); #endif -int main(int argc, char** argv) +int main(int argc, char **argv) { // Run the test specification Harness::run(specification); diff --git a/drivers/AnalogIn.h b/drivers/AnalogIn.h index e81428fc21f..c9ccfa25a16 100644 --- a/drivers/AnalogIn.h +++ b/drivers/AnalogIn.h @@ -57,7 +57,8 @@ class AnalogIn { * * @param pin AnalogIn pin to connect to */ - AnalogIn(PinName pin) { + AnalogIn(PinName pin) + { lock(); analogin_init(&_adc, pin); unlock(); @@ -67,7 +68,8 @@ class AnalogIn { * * @returns A floating-point value representing the current input voltage, measured as a percentage */ - float read() { + float read() + { lock(); float ret = analogin_read(&_adc); unlock(); @@ -79,7 +81,8 @@ class AnalogIn { * @returns * 16-bit unsigned short representing the current input voltage, normalised to a 16-bit value */ - unsigned short read_u16() { + unsigned short read_u16() + { lock(); unsigned short ret = analogin_read_u16(&_adc); unlock(); @@ -99,22 +102,26 @@ class AnalogIn { * if(volume > 0.25) { ... } * @endcode */ - operator float() { + operator float() + { // Underlying call is thread safe return read(); } - virtual ~AnalogIn() { + virtual ~AnalogIn() + { // Do nothing } protected: - virtual void lock() { + virtual void lock() + { _mutex->lock(); } - virtual void unlock() { + virtual void unlock() + { _mutex->unlock(); } diff --git a/drivers/AnalogOut.h b/drivers/AnalogOut.h index 5038f0f7a43..3945c580c44 100644 --- a/drivers/AnalogOut.h +++ b/drivers/AnalogOut.h @@ -57,7 +57,8 @@ class AnalogOut { * * @param pin AnalogOut pin to connect to */ - AnalogOut(PinName pin) { + AnalogOut(PinName pin) + { analogout_init(&_dac, pin); } @@ -68,7 +69,8 @@ class AnalogOut { * 0.0f (representing 0v / 0%) and 1.0f (representing 3.3v / 100%). * Values outside this range will be saturated to 0.0f or 1.0f. */ - void write(float value) { + void write(float value) + { lock(); analogout_write(&_dac, value); unlock(); @@ -79,7 +81,8 @@ class AnalogOut { * @param value 16-bit unsigned short representing the output voltage, * normalised to a 16-bit value (0x0000 = 0v, 0xFFFF = 3.3v) */ - void write_u16(unsigned short value) { + void write_u16(unsigned short value) + { lock(); analogout_write_u16(&_dac, value); unlock(); @@ -95,7 +98,8 @@ class AnalogOut { * @note * This value may not match exactly the value set by a previous write(). */ - float read() { + float read() + { lock(); float ret = analogout_read(&_dac); unlock(); @@ -105,7 +109,8 @@ class AnalogOut { /** An operator shorthand for write() * \sa AnalogOut::write() */ - AnalogOut& operator= (float percent) { + AnalogOut &operator= (float percent) + { // Underlying write call is thread safe write(percent); return *this; @@ -114,7 +119,8 @@ class AnalogOut { /** An operator shorthand for write() * \sa AnalogOut::write() */ - AnalogOut& operator= (AnalogOut& rhs) { + AnalogOut &operator= (AnalogOut &rhs) + { // Underlying write call is thread safe write(rhs.read()); return *this; @@ -123,22 +129,26 @@ class AnalogOut { /** An operator shorthand for read() * \sa AnalogOut::read() */ - operator float() { + operator float() + { // Underlying read call is thread safe return read(); } - virtual ~AnalogOut() { + virtual ~AnalogOut() + { // Do nothing } protected: - virtual void lock() { + virtual void lock() + { _mutex.lock(); } - virtual void unlock() { + virtual void unlock() + { _mutex.unlock(); } diff --git a/drivers/BusIn.cpp b/drivers/BusIn.cpp index 1fd05282148..f6cc933e7ea 100644 --- a/drivers/BusIn.cpp +++ b/drivers/BusIn.cpp @@ -18,12 +18,13 @@ namespace mbed { -BusIn::BusIn(PinName p0, PinName p1, PinName p2, PinName p3, PinName p4, PinName p5, PinName p6, PinName p7, PinName p8, PinName p9, PinName p10, PinName p11, PinName p12, PinName p13, PinName p14, PinName p15) { +BusIn::BusIn(PinName p0, PinName p1, PinName p2, PinName p3, PinName p4, PinName p5, PinName p6, PinName p7, PinName p8, PinName p9, PinName p10, PinName p11, PinName p12, PinName p13, PinName p14, PinName p15) +{ PinName pins[16] = {p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15}; // No lock needed in the constructor _nc_mask = 0; - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { _pin[i] = (pins[i] != NC) ? new DigitalIn(pins[i]) : 0; if (pins[i] != NC) { _nc_mask |= (1 << i); @@ -31,10 +32,11 @@ BusIn::BusIn(PinName p0, PinName p1, PinName p2, PinName p3, PinName p4, PinName } } -BusIn::BusIn(PinName pins[16]) { +BusIn::BusIn(PinName pins[16]) +{ // No lock needed in the constructor _nc_mask = 0; - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { _pin[i] = (pins[i] != NC) ? new DigitalIn(pins[i]) : 0; if (pins[i] != NC) { _nc_mask |= (1 << i); @@ -42,19 +44,21 @@ BusIn::BusIn(PinName pins[16]) { } } -BusIn::~BusIn() { +BusIn::~BusIn() +{ // No lock needed in the destructor - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { if (_pin[i] != 0) { delete _pin[i]; } } } -int BusIn::read() { +int BusIn::read() +{ int v = 0; lock(); - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { if (_pin[i] != 0) { v |= _pin[i]->read() << i; } @@ -63,9 +67,10 @@ int BusIn::read() { return v; } -void BusIn::mode(PinMode pull) { +void BusIn::mode(PinMode pull) +{ lock(); - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { if (_pin[i] != 0) { _pin[i]->mode(pull); } @@ -73,20 +78,24 @@ void BusIn::mode(PinMode pull) { unlock(); } -void BusIn::lock() { +void BusIn::lock() +{ _mutex.lock(); } -void BusIn::unlock() { +void BusIn::unlock() +{ _mutex.unlock(); } -BusIn::operator int() { +BusIn::operator int() +{ // Underlying read is thread safe return read(); } -DigitalIn& BusIn::operator[] (int index) { +DigitalIn &BusIn::operator[](int index) +{ // No lock needed since _pin is not modified outside the constructor MBED_ASSERT(index >= 0 && index <= 16); MBED_ASSERT(_pin[index]); diff --git a/drivers/BusIn.h b/drivers/BusIn.h index d015529435f..80b20d72a1f 100644 --- a/drivers/BusIn.h +++ b/drivers/BusIn.h @@ -62,12 +62,12 @@ class BusIn : private NonCopyable { PinName p8 = NC, PinName p9 = NC, PinName p10 = NC, PinName p11 = NC, PinName p12 = NC, PinName p13 = NC, PinName p14 = NC, PinName p15 = NC); - + /** Create an BusIn, connected to the specified pins * * @param pins An array of pins to connect to bus bit */ - BusIn(PinName pins[16]); + BusIn(PinName pins[16]); virtual ~BusIn(); @@ -90,7 +90,8 @@ class BusIn : private NonCopyable { * @returns * Binary mask of connected pins */ - int mask() { + int mask() + { // No lock needed since _nc_mask is not modified outside the constructor return _nc_mask; } @@ -103,10 +104,10 @@ class BusIn : private NonCopyable { /** Access to particular bit in random-iterator fashion * @param index Position of bit */ - DigitalIn & operator[] (int index); + DigitalIn &operator[](int index); protected: - DigitalIn* _pin[16]; + DigitalIn *_pin[16]; /* Mask of bus's NC pins * If bit[n] is set to 1 - pin is connected diff --git a/drivers/BusInOut.cpp b/drivers/BusInOut.cpp index ff244fa464e..950cbb5d58f 100644 --- a/drivers/BusInOut.cpp +++ b/drivers/BusInOut.cpp @@ -18,12 +18,13 @@ namespace mbed { -BusInOut::BusInOut(PinName p0, PinName p1, PinName p2, PinName p3, PinName p4, PinName p5, PinName p6, PinName p7, PinName p8, PinName p9, PinName p10, PinName p11, PinName p12, PinName p13, PinName p14, PinName p15) { +BusInOut::BusInOut(PinName p0, PinName p1, PinName p2, PinName p3, PinName p4, PinName p5, PinName p6, PinName p7, PinName p8, PinName p9, PinName p10, PinName p11, PinName p12, PinName p13, PinName p14, PinName p15) +{ PinName pins[16] = {p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15}; // No lock needed in the constructor _nc_mask = 0; - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { _pin[i] = (pins[i] != NC) ? new DigitalInOut(pins[i]) : 0; if (pins[i] != NC) { _nc_mask |= (1 << i); @@ -31,10 +32,11 @@ BusInOut::BusInOut(PinName p0, PinName p1, PinName p2, PinName p3, PinName p4, P } } -BusInOut::BusInOut(PinName pins[16]) { +BusInOut::BusInOut(PinName pins[16]) +{ // No lock needed in the constructor _nc_mask = 0; - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { _pin[i] = (pins[i] != NC) ? new DigitalInOut(pins[i]) : 0; if (pins[i] != NC) { _nc_mask |= (1 << i); @@ -42,18 +44,20 @@ BusInOut::BusInOut(PinName pins[16]) { } } -BusInOut::~BusInOut() { +BusInOut::~BusInOut() +{ // No lock needed in the destructor - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { if (_pin[i] != 0) { delete _pin[i]; } } } -void BusInOut::write(int value) { +void BusInOut::write(int value) +{ lock(); - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { if (_pin[i] != 0) { _pin[i]->write((value >> i) & 1); } @@ -61,10 +65,11 @@ void BusInOut::write(int value) { unlock(); } -int BusInOut::read() { +int BusInOut::read() +{ lock(); int v = 0; - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { if (_pin[i] != 0) { v |= _pin[i]->read() << i; } @@ -73,9 +78,10 @@ int BusInOut::read() { return v; } -void BusInOut::output() { +void BusInOut::output() +{ lock(); - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { if (_pin[i] != 0) { _pin[i]->output(); } @@ -83,9 +89,10 @@ void BusInOut::output() { unlock(); } -void BusInOut::input() { +void BusInOut::input() +{ lock(); - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { if (_pin[i] != 0) { _pin[i]->input(); } @@ -93,9 +100,10 @@ void BusInOut::input() { unlock(); } -void BusInOut::mode(PinMode pull) { +void BusInOut::mode(PinMode pull) +{ lock(); - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { if (_pin[i] != 0) { _pin[i]->mode(pull); } @@ -103,35 +111,41 @@ void BusInOut::mode(PinMode pull) { unlock(); } -BusInOut& BusInOut::operator= (int v) { +BusInOut &BusInOut::operator= (int v) +{ // Underlying write is thread safe write(v); return *this; } -BusInOut& BusInOut::operator= (BusInOut& rhs) { +BusInOut &BusInOut::operator= (BusInOut &rhs) +{ // Underlying read is thread safe write(rhs.read()); return *this; } -DigitalInOut& BusInOut::operator[] (int index) { +DigitalInOut &BusInOut::operator[](int index) +{ // No lock needed since _pin is not modified outside the constructor MBED_ASSERT(index >= 0 && index <= 16); MBED_ASSERT(_pin[index]); return *_pin[index]; } -BusInOut::operator int() { +BusInOut::operator int() +{ // Underlying read is thread safe return read(); } -void BusInOut::lock() { +void BusInOut::lock() +{ _mutex.lock(); } -void BusInOut::unlock() { +void BusInOut::unlock() +{ _mutex.unlock(); } diff --git a/drivers/BusInOut.h b/drivers/BusInOut.h index 0be52cacc55..9bb4e995ae3 100644 --- a/drivers/BusInOut.h +++ b/drivers/BusInOut.h @@ -103,21 +103,22 @@ class BusInOut : private NonCopyable { * @returns * Binary mask of connected pins */ - int mask() { + int mask() + { // No lock needed since _nc_mask is not modified outside the constructor return _nc_mask; } - /** A shorthand for write() + /** A shorthand for write() * \sa BusInOut::write() - */ - BusInOut& operator= (int v); - BusInOut& operator= (BusInOut& rhs); + */ + BusInOut &operator= (int v); + BusInOut &operator= (BusInOut &rhs); /** Access to particular bit in random-iterator fashion * @param index Bit Position */ - DigitalInOut& operator[] (int index); + DigitalInOut &operator[](int index); /** A shorthand for read() * \sa BusInOut::read() @@ -127,7 +128,7 @@ class BusInOut : private NonCopyable { protected: virtual void lock(); virtual void unlock(); - DigitalInOut* _pin[16]; + DigitalInOut *_pin[16]; /* Mask of bus's NC pins * If bit[n] is set to 1 - pin is connected diff --git a/drivers/BusOut.cpp b/drivers/BusOut.cpp index 901955257a8..913ba197505 100644 --- a/drivers/BusOut.cpp +++ b/drivers/BusOut.cpp @@ -18,12 +18,13 @@ namespace mbed { -BusOut::BusOut(PinName p0, PinName p1, PinName p2, PinName p3, PinName p4, PinName p5, PinName p6, PinName p7, PinName p8, PinName p9, PinName p10, PinName p11, PinName p12, PinName p13, PinName p14, PinName p15) { +BusOut::BusOut(PinName p0, PinName p1, PinName p2, PinName p3, PinName p4, PinName p5, PinName p6, PinName p7, PinName p8, PinName p9, PinName p10, PinName p11, PinName p12, PinName p13, PinName p14, PinName p15) +{ PinName pins[16] = {p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15}; // No lock needed in the constructor _nc_mask = 0; - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { _pin[i] = (pins[i] != NC) ? new DigitalOut(pins[i]) : 0; if (pins[i] != NC) { _nc_mask |= (1 << i); @@ -31,10 +32,11 @@ BusOut::BusOut(PinName p0, PinName p1, PinName p2, PinName p3, PinName p4, PinNa } } -BusOut::BusOut(PinName pins[16]) { +BusOut::BusOut(PinName pins[16]) +{ // No lock needed in the constructor _nc_mask = 0; - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { _pin[i] = (pins[i] != NC) ? new DigitalOut(pins[i]) : 0; if (pins[i] != NC) { _nc_mask |= (1 << i); @@ -42,18 +44,20 @@ BusOut::BusOut(PinName pins[16]) { } } -BusOut::~BusOut() { +BusOut::~BusOut() +{ // No lock needed in the destructor - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { if (_pin[i] != 0) { delete _pin[i]; } } } -void BusOut::write(int value) { +void BusOut::write(int value) +{ lock(); - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { if (_pin[i] != 0) { _pin[i]->write((value >> i) & 1); } @@ -61,10 +65,11 @@ void BusOut::write(int value) { unlock(); } -int BusOut::read() { +int BusOut::read() +{ lock(); int v = 0; - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { if (_pin[i] != 0) { v |= _pin[i]->read() << i; } @@ -73,35 +78,41 @@ int BusOut::read() { return v; } -BusOut& BusOut::operator= (int v) { +BusOut &BusOut::operator= (int v) +{ // Underlying write is thread safe write(v); return *this; } -BusOut& BusOut::operator= (BusOut& rhs) { +BusOut &BusOut::operator= (BusOut &rhs) +{ // Underlying write is thread safe write(rhs.read()); return *this; } -DigitalOut& BusOut::operator[] (int index) { +DigitalOut &BusOut::operator[](int index) +{ // No lock needed since _pin is not modified outside the constructor MBED_ASSERT(index >= 0 && index <= 16); MBED_ASSERT(_pin[index]); return *_pin[index]; } -BusOut::operator int() { +BusOut::operator int() +{ // Underlying read is thread safe return read(); } -void BusOut::lock() { +void BusOut::lock() +{ _mutex.lock(); } -void BusOut::unlock() { +void BusOut::unlock() +{ _mutex.unlock(); } diff --git a/drivers/BusOut.h b/drivers/BusOut.h index d7612d45924..2f908b65d84 100644 --- a/drivers/BusOut.h +++ b/drivers/BusOut.h @@ -87,7 +87,8 @@ class BusOut : private NonCopyable { * @returns * Binary mask of connected pins */ - int mask() { + int mask() + { // No lock needed since _nc_mask is not modified outside the constructor return _nc_mask; } @@ -95,13 +96,13 @@ class BusOut : private NonCopyable { /** A shorthand for write() * \sa BusOut::write() */ - BusOut& operator= (int v); - BusOut& operator= (BusOut& rhs); + BusOut &operator= (int v); + BusOut &operator= (BusOut &rhs); /** Access to particular bit in random-iterator fashion * @param index Bit Position */ - DigitalOut& operator[] (int index); + DigitalOut &operator[](int index); /** A shorthand for read() * \sa BusOut::read() @@ -111,7 +112,7 @@ class BusOut : private NonCopyable { protected: virtual void lock(); virtual void unlock(); - DigitalOut* _pin[16]; + DigitalOut *_pin[16]; /* Mask of bus's NC pins * If bit[n] is set to 1 - pin is connected diff --git a/drivers/CAN.cpp b/drivers/CAN.cpp index a5e8e4266b9..2c0a53442f5 100644 --- a/drivers/CAN.cpp +++ b/drivers/CAN.cpp @@ -22,7 +22,8 @@ namespace mbed { -CAN::CAN(PinName rd, PinName td) : _can(), _irq() { +CAN::CAN(PinName rd, PinName td) : _can(), _irq() +{ // No lock needed in constructor for (size_t i = 0; i < sizeof _irq / sizeof _irq[0]; i++) { @@ -33,7 +34,8 @@ CAN::CAN(PinName rd, PinName td) : _can(), _irq() { can_irq_init(&_can, (&CAN::_irq_handler), (uint32_t)this); } -CAN::CAN(PinName rd, PinName td, int hz) : _can(), _irq() { +CAN::CAN(PinName rd, PinName td, int hz) : _can(), _irq() +{ // No lock needed in constructor for (size_t i = 0; i < sizeof _irq / sizeof _irq[0]; i++) { @@ -44,7 +46,8 @@ CAN::CAN(PinName rd, PinName td, int hz) : _can(), _irq() { can_irq_init(&_can, (&CAN::_irq_handler), (uint32_t)this); } -CAN::~CAN() { +CAN::~CAN() +{ // No lock needed in destructor // Detaching interrupts releases the sleep lock if it was locked @@ -55,68 +58,78 @@ CAN::~CAN() { can_free(&_can); } -int CAN::frequency(int f) { +int CAN::frequency(int f) +{ lock(); int ret = can_frequency(&_can, f); unlock(); return ret; } -int CAN::write(CANMessage msg) { +int CAN::write(CANMessage msg) +{ lock(); int ret = can_write(&_can, msg, 0); unlock(); return ret; } -int CAN::read(CANMessage &msg, int handle) { +int CAN::read(CANMessage &msg, int handle) +{ lock(); int ret = can_read(&_can, &msg, handle); unlock(); return ret; } -void CAN::reset() { +void CAN::reset() +{ lock(); can_reset(&_can); unlock(); } -unsigned char CAN::rderror() { +unsigned char CAN::rderror() +{ lock(); int ret = can_rderror(&_can); unlock(); return ret; } -unsigned char CAN::tderror() { +unsigned char CAN::tderror() +{ lock(); int ret = can_tderror(&_can); unlock(); return ret; } -void CAN::monitor(bool silent) { +void CAN::monitor(bool silent) +{ lock(); can_monitor(&_can, (silent) ? 1 : 0); unlock(); } -int CAN::mode(Mode mode) { +int CAN::mode(Mode mode) +{ lock(); int ret = can_mode(&_can, (CanMode)mode); unlock(); return ret; } -int CAN::filter(unsigned int id, unsigned int mask, CANFormat format, int handle) { +int CAN::filter(unsigned int id, unsigned int mask, CANFormat format, int handle) +{ lock(); int ret = can_filter(&_can, id, mask, format, handle); unlock(); return ret; } -void CAN::attach(Callback func, IrqType type) { +void CAN::attach(Callback func, IrqType type) +{ lock(); if (func) { // lock deep sleep only the first time @@ -136,18 +149,21 @@ void CAN::attach(Callback func, IrqType type) { unlock(); } -void CAN::_irq_handler(uint32_t id, CanIrqType type) { - CAN *handler = (CAN*)id; +void CAN::_irq_handler(uint32_t id, CanIrqType type) +{ + CAN *handler = (CAN *)id; if (handler->_irq[type]) { handler->_irq[type].call(); } } -void CAN::lock() { +void CAN::lock() +{ _mutex.lock(); } -void CAN::unlock() { +void CAN::unlock() +{ _mutex.unlock(); } diff --git a/drivers/CAN.h b/drivers/CAN.h index 668e32c256e..5f506f68adb 100644 --- a/drivers/CAN.h +++ b/drivers/CAN.h @@ -38,7 +38,8 @@ class CANMessage : public CAN_Message { public: /** Creates empty CAN message. */ - CANMessage() : CAN_Message() { + CANMessage() : CAN_Message() + { len = 8; type = CANData; format = CANStandard; @@ -54,12 +55,13 @@ class CANMessage : public CAN_Message { * @param _type Type of Data: Use enum CANType for valid parameter values * @param _format Data Format: Use enum CANFormat for valid parameter values */ - CANMessage(int _id, const char *_data, char _len = 8, CANType _type = CANData, CANFormat _format = CANStandard) { - len = _len & 0xF; - type = _type; - format = _format; - id = _id; - memcpy(data, _data, _len); + CANMessage(int _id, const char *_data, char _len = 8, CANType _type = CANData, CANFormat _format = CANStandard) + { + len = _len & 0xF; + type = _type; + format = _format; + id = _id; + memcpy(data, _data, _len); } /** Creates CAN remote message. @@ -67,12 +69,13 @@ class CANMessage : public CAN_Message { * @param _id Message ID * @param _format Data Format: Use enum CANType for valid parameter values */ - CANMessage(int _id, CANFormat _format = CANStandard) { - len = 0; - type = CANRemote; - format = _format; - id = _id; - memset(data, 0, 8); + CANMessage(int _id, CANFormat _format = CANStandard) + { + len = 0; + type = CANRemote; + format = _format; + id = _id; + memset(data, 0, 8); } }; @@ -235,48 +238,50 @@ class CAN : private NonCopyable { /** Attach a function to call whenever a CAN frame received interrupt is * generated. - * + * * This function locks the deep sleep while a callback is attached - * + * * @param func A pointer to a void function, or 0 to set as none * @param type Which CAN interrupt to attach the member function to (CAN::RxIrq for message received, CAN::TxIrq for transmitted or aborted, CAN::EwIrq for error warning, CAN::DoIrq for data overrun, CAN::WuIrq for wake-up, CAN::EpIrq for error passive, CAN::AlIrq for arbitration lost, CAN::BeIrq for bus error) */ - void attach(Callback func, IrqType type=RxIrq); - - /** Attach a member function to call whenever a CAN frame received interrupt - * is generated. - * - * @param obj pointer to the object to call the member function on - * @param method pointer to the member function to be called - * @param type Which CAN interrupt to attach the member function to (CAN::RxIrq for message received, TxIrq for transmitted or aborted, EwIrq for error warning, DoIrq for data overrun, WuIrq for wake-up, EpIrq for error passive, AlIrq for arbitration lost, BeIrq for bus error) - * @deprecated - * The attach function does not support cv-qualifiers. Replaced by - * attach(callback(obj, method), type). - */ + void attach(Callback func, IrqType type = RxIrq); + + /** Attach a member function to call whenever a CAN frame received interrupt + * is generated. + * + * @param obj pointer to the object to call the member function on + * @param method pointer to the member function to be called + * @param type Which CAN interrupt to attach the member function to (CAN::RxIrq for message received, TxIrq for transmitted or aborted, EwIrq for error warning, DoIrq for data overrun, WuIrq for wake-up, EpIrq for error passive, AlIrq for arbitration lost, BeIrq for bus error) + * @deprecated + * The attach function does not support cv-qualifiers. Replaced by + * attach(callback(obj, method), type). + */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "The attach function does not support cv-qualifiers. Replaced by " - "attach(callback(obj, method), type).") - void attach(T* obj, void (T::*method)(), IrqType type=RxIrq) { + "The attach function does not support cv-qualifiers. Replaced by " + "attach(callback(obj, method), type).") + void attach(T *obj, void (T::*method)(), IrqType type = RxIrq) + { // Underlying call thread safe attach(callback(obj, method), type); } - /** Attach a member function to call whenever a CAN frame received interrupt - * is generated. - * - * @param obj pointer to the object to call the member function on - * @param method pointer to the member function to be called - * @param type Which CAN interrupt to attach the member function to (CAN::RxIrq for message received, TxIrq for transmitted or aborted, EwIrq for error warning, DoIrq for data overrun, WuIrq for wake-up, EpIrq for error passive, AlIrq for arbitration lost, BeIrq for bus error) - * @deprecated - * The attach function does not support cv-qualifiers. Replaced by - * attach(callback(obj, method), type). - */ + /** Attach a member function to call whenever a CAN frame received interrupt + * is generated. + * + * @param obj pointer to the object to call the member function on + * @param method pointer to the member function to be called + * @param type Which CAN interrupt to attach the member function to (CAN::RxIrq for message received, TxIrq for transmitted or aborted, EwIrq for error warning, DoIrq for data overrun, WuIrq for wake-up, EpIrq for error passive, AlIrq for arbitration lost, BeIrq for bus error) + * @deprecated + * The attach function does not support cv-qualifiers. Replaced by + * attach(callback(obj, method), type). + */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "The attach function does not support cv-qualifiers. Replaced by " - "attach(callback(obj, method), type).") - void attach(T* obj, void (*method)(T*), IrqType type=RxIrq) { + "The attach function does not support cv-qualifiers. Replaced by " + "attach(callback(obj, method), type).") + void attach(T *obj, void (*method)(T *), IrqType type = RxIrq) + { // Underlying call thread safe attach(callback(obj, method), type); } diff --git a/drivers/DigitalIn.h b/drivers/DigitalIn.h index d35476c296b..1a2af01fa3a 100644 --- a/drivers/DigitalIn.h +++ b/drivers/DigitalIn.h @@ -55,7 +55,8 @@ class DigitalIn { * * @param pin DigitalIn pin to connect to */ - DigitalIn(PinName pin) : gpio() { + DigitalIn(PinName pin) : gpio() + { // No lock needed in the constructor gpio_init_in(&gpio, pin); } @@ -65,7 +66,8 @@ class DigitalIn { * @param pin DigitalIn pin to connect to * @param mode the initial mode of the pin */ - DigitalIn(PinName pin, PinMode mode) : gpio() { + DigitalIn(PinName pin, PinMode mode) : gpio() + { // No lock needed in the constructor gpio_init_in_ex(&gpio, pin, mode); } @@ -75,7 +77,8 @@ class DigitalIn { * An integer representing the state of the input pin, * 0 for logical 0, 1 for logical 1 */ - int read() { + int read() + { // Thread safe / atomic HAL call return gpio_read(&gpio); } @@ -84,7 +87,8 @@ class DigitalIn { * * @param pull PullUp, PullDown, PullNone, OpenDrain */ - void mode(PinMode pull) { + void mode(PinMode pull) + { core_util_critical_section_enter(); gpio_mode(&gpio, pull); core_util_critical_section_exit(); @@ -96,7 +100,8 @@ class DigitalIn { * Non zero value if pin is connected to uc GPIO * 0 if gpio object was initialized with NC */ - int is_connected() { + int is_connected() + { // Thread safe / atomic HAL call return gpio_is_connected(&gpio); } @@ -104,7 +109,8 @@ class DigitalIn { /** An operator shorthand for read() * \sa DigitalIn::read() */ - operator int() { + operator int() + { // Underlying read is thread safe return read(); } diff --git a/drivers/DigitalInOut.h b/drivers/DigitalInOut.h index cc524ff5107..a11fcad2c0f 100644 --- a/drivers/DigitalInOut.h +++ b/drivers/DigitalInOut.h @@ -36,7 +36,8 @@ class DigitalInOut { * * @param pin DigitalInOut pin to connect to */ - DigitalInOut(PinName pin) : gpio() { + DigitalInOut(PinName pin) : gpio() + { // No lock needed in the constructor gpio_init_in(&gpio, pin); } @@ -48,7 +49,8 @@ class DigitalInOut { * @param mode the initial mode of the pin * @param value the initial value of the pin if is an output */ - DigitalInOut(PinName pin, PinDirection direction, PinMode mode, int value) : gpio() { + DigitalInOut(PinName pin, PinDirection direction, PinMode mode, int value) : gpio() + { // No lock needed in the constructor gpio_init_inout(&gpio, pin, direction, mode, value); } @@ -58,7 +60,8 @@ class DigitalInOut { * @param value An integer specifying the pin output value, * 0 for logical 0, 1 (or any other non-zero value) for logical 1 */ - void write(int value) { + void write(int value) + { // Thread safe / atomic HAL call gpio_write(&gpio, value); } @@ -69,14 +72,16 @@ class DigitalInOut { * an integer representing the output setting of the pin if it is an output, * or read the input if set as an input */ - int read() { + int read() + { // Thread safe / atomic HAL call return gpio_read(&gpio); } /** Set as an output */ - void output() { + void output() + { core_util_critical_section_enter(); gpio_dir(&gpio, PIN_OUTPUT); core_util_critical_section_exit(); @@ -84,7 +89,8 @@ class DigitalInOut { /** Set as an input */ - void input() { + void input() + { core_util_critical_section_enter(); gpio_dir(&gpio, PIN_INPUT); core_util_critical_section_exit(); @@ -94,7 +100,8 @@ class DigitalInOut { * * @param pull PullUp, PullDown, PullNone, OpenDrain */ - void mode(PinMode pull) { + void mode(PinMode pull) + { core_util_critical_section_enter(); gpio_mode(&gpio, pull); core_util_critical_section_exit(); @@ -106,7 +113,8 @@ class DigitalInOut { * Non zero value if pin is connected to uc GPIO * 0 if gpio object was initialized with NC */ - int is_connected() { + int is_connected() + { // Thread safe / atomic HAL call return gpio_is_connected(&gpio); } @@ -114,7 +122,8 @@ class DigitalInOut { /** A shorthand for write() * \sa DigitalInOut::write() */ - DigitalInOut& operator= (int value) { + DigitalInOut &operator= (int value) + { // Underlying write is thread safe write(value); return *this; @@ -123,7 +132,8 @@ class DigitalInOut { /** A shorthand for write() * \sa DigitalInOut::write() */ - DigitalInOut& operator= (DigitalInOut& rhs) { + DigitalInOut &operator= (DigitalInOut &rhs) + { core_util_critical_section_enter(); write(rhs.read()); core_util_critical_section_exit(); @@ -133,7 +143,8 @@ class DigitalInOut { /** A shorthand for read() * \sa DigitalInOut::read() */ - operator int() { + operator int() + { // Underlying call is thread safe return read(); } diff --git a/drivers/DigitalOut.h b/drivers/DigitalOut.h index 06c57359e00..fb6d1be6c2d 100644 --- a/drivers/DigitalOut.h +++ b/drivers/DigitalOut.h @@ -50,7 +50,8 @@ class DigitalOut { * * @param pin DigitalOut pin to connect to */ - DigitalOut(PinName pin) : gpio() { + DigitalOut(PinName pin) : gpio() + { // No lock needed in the constructor gpio_init_out(&gpio, pin); } @@ -60,7 +61,8 @@ class DigitalOut { * @param pin DigitalOut pin to connect to * @param value the initial pin value */ - DigitalOut(PinName pin, int value) : gpio() { + DigitalOut(PinName pin, int value) : gpio() + { // No lock needed in the constructor gpio_init_out_ex(&gpio, pin, value); } @@ -70,7 +72,8 @@ class DigitalOut { * @param value An integer specifying the pin output value, * 0 for logical 0, 1 (or any other non-zero value) for logical 1 */ - void write(int value) { + void write(int value) + { // Thread safe / atomic HAL call gpio_write(&gpio, value); } @@ -81,7 +84,8 @@ class DigitalOut { * an integer representing the output setting of the pin, * 0 for logical 0, 1 for logical 1 */ - int read() { + int read() + { // Thread safe / atomic HAL call return gpio_read(&gpio); } @@ -92,7 +96,8 @@ class DigitalOut { * Non zero value if pin is connected to uc GPIO * 0 if gpio object was initialized with NC */ - int is_connected() { + int is_connected() + { // Thread safe / atomic HAL call return gpio_is_connected(&gpio); } @@ -100,7 +105,8 @@ class DigitalOut { /** A shorthand for write() * \sa DigitalOut::write() */ - DigitalOut& operator= (int value) { + DigitalOut &operator= (int value) + { // Underlying write is thread safe write(value); return *this; @@ -109,7 +115,8 @@ class DigitalOut { /** A shorthand for write() * \sa DigitalOut::write() */ - DigitalOut& operator= (DigitalOut& rhs) { + DigitalOut &operator= (DigitalOut &rhs) + { core_util_critical_section_enter(); write(rhs.read()); core_util_critical_section_exit(); @@ -119,7 +126,8 @@ class DigitalOut { /** A shorthand for read() * \sa DigitalOut::read() */ - operator int() { + operator int() + { // Underlying call is thread safe return read(); } diff --git a/drivers/Ethernet.cpp b/drivers/Ethernet.cpp index c275f4a99bf..6b0a2bfab6f 100644 --- a/drivers/Ethernet.cpp +++ b/drivers/Ethernet.cpp @@ -21,48 +21,72 @@ namespace mbed { -Ethernet::Ethernet() { +Ethernet::Ethernet() +{ ethernet_init(); } -Ethernet::~Ethernet() { +Ethernet::~Ethernet() +{ ethernet_free(); } -int Ethernet::write(const char *data, int size) { +int Ethernet::write(const char *data, int size) +{ return ethernet_write(data, size); } -int Ethernet::send() { +int Ethernet::send() +{ return ethernet_send(); } -int Ethernet::receive() { +int Ethernet::receive() +{ return ethernet_receive(); } -int Ethernet::read(char *data, int size) { +int Ethernet::read(char *data, int size) +{ return ethernet_read(data, size); } -void Ethernet::address(char *mac) { +void Ethernet::address(char *mac) +{ return ethernet_address(mac); } -int Ethernet::link() { +int Ethernet::link() +{ return ethernet_link(); } -void Ethernet::set_link(Mode mode) { +void Ethernet::set_link(Mode mode) +{ int speed = -1; int duplex = 0; - switch(mode) { - case AutoNegotiate : speed = -1; duplex = 0; break; - case HalfDuplex10 : speed = 0; duplex = 0; break; - case FullDuplex10 : speed = 0; duplex = 1; break; - case HalfDuplex100 : speed = 1; duplex = 0; break; - case FullDuplex100 : speed = 1; duplex = 1; break; + switch (mode) { + case AutoNegotiate : + speed = -1; + duplex = 0; + break; + case HalfDuplex10 : + speed = 0; + duplex = 0; + break; + case FullDuplex10 : + speed = 0; + duplex = 1; + break; + case HalfDuplex100 : + speed = 1; + duplex = 0; + break; + case FullDuplex100 : + speed = 1; + duplex = 1; + break; } ethernet_set_link(speed, duplex); diff --git a/drivers/FlashIAP.cpp b/drivers/FlashIAP.cpp index f36385a7e4c..b613ba2ff4a 100644 --- a/drivers/FlashIAP.cpp +++ b/drivers/FlashIAP.cpp @@ -99,7 +99,7 @@ int FlashIAP::program(const void *buffer, uint32_t addr, uint32_t size) // addr should be aligned to page size if (!is_aligned(addr, page_size) || (!buffer) || - ((addr + size) > (flash_start_addr + flash_size))) { + ((addr + size) > (flash_start_addr + flash_size))) { return -1; } @@ -135,7 +135,7 @@ bool FlashIAP::is_aligned_to_sector(uint32_t addr, uint32_t size) { uint32_t current_sector_size = flash_get_sector_size(&_flash, addr); if (!is_aligned(size, current_sector_size) || - !is_aligned(addr, current_sector_size)) { + !is_aligned(addr, current_sector_size)) { return false; } else { return true; @@ -152,7 +152,7 @@ int FlashIAP::erase(uint32_t addr, uint32_t size) if (erase_end_addr > flash_end_addr) { return -1; - } else if (erase_end_addr < flash_end_addr){ + } else if (erase_end_addr < flash_end_addr) { uint32_t following_sector_size = flash_get_sector_size(&_flash, erase_end_addr); if (!is_aligned(erase_end_addr, following_sector_size)) { return -1; diff --git a/drivers/FlashIAP.h b/drivers/FlashIAP.h index a818410c550..92a93996768 100644 --- a/drivers/FlashIAP.h +++ b/drivers/FlashIAP.h @@ -56,7 +56,7 @@ class FlashIAP : private NonCopyable { */ int deinit(); - /** Read data from a flash device. + /** Read data from a flash device. * * This method invokes memcpy - reads number of bytes from the address * @@ -90,7 +90,7 @@ class FlashIAP : private NonCopyable { /** Get the sector size at the defined address * - * Sector size might differ at address ranges. + * Sector size might differ at address ranges. * An example <0-0x1000, sector size=1024; 0x10000-0x20000, size=2048> * * @param addr Address of or inside the sector to query @@ -98,15 +98,15 @@ class FlashIAP : private NonCopyable { */ uint32_t get_sector_size(uint32_t addr) const; - /** Get the flash start address + /** Get the flash start address * - * @return Flash start address + * @return Flash start address */ uint32_t get_flash_start() const; /** Get the flash size * - * @return Flash size + * @return Flash size */ uint32_t get_flash_size() const; diff --git a/drivers/I2C.cpp b/drivers/I2C.cpp index 8be7a529fcf..52da58d5edf 100644 --- a/drivers/I2C.cpp +++ b/drivers/I2C.cpp @@ -41,7 +41,8 @@ I2C::I2C(PinName sda, PinName scl) : _owner = this; } -void I2C::frequency(int hz) { +void I2C::frequency(int hz) +{ lock(); _hz = hz; @@ -53,7 +54,8 @@ void I2C::frequency(int hz) { unlock(); } -void I2C::aquire() { +void I2C::aquire() +{ lock(); if (_owner != this) { i2c_frequency(&_i2c, _hz); @@ -63,7 +65,8 @@ void I2C::aquire() { } // write - Master Transmitter Mode -int I2C::write(int address, const char* data, int length, bool repeated) { +int I2C::write(int address, const char *data, int length, bool repeated) +{ lock(); aquire(); @@ -74,7 +77,8 @@ int I2C::write(int address, const char* data, int length, bool repeated) { return length != written; } -int I2C::write(int data) { +int I2C::write(int data) +{ lock(); int ret = i2c_byte_write(&_i2c, data); unlock(); @@ -82,7 +86,8 @@ int I2C::write(int data) { } // read - Master Reciever Mode -int I2C::read(int address, char* data, int length, bool repeated) { +int I2C::read(int address, char *data, int length, bool repeated) +{ lock(); aquire(); @@ -93,7 +98,8 @@ int I2C::read(int address, char* data, int length, bool repeated) { return length != read; } -int I2C::read(int ack) { +int I2C::read(int ack) +{ lock(); int ret; if (ack) { @@ -105,29 +111,33 @@ int I2C::read(int ack) { return ret; } -void I2C::start(void) { +void I2C::start(void) +{ lock(); i2c_start(&_i2c); unlock(); } -void I2C::stop(void) { +void I2C::stop(void) +{ lock(); i2c_stop(&_i2c); unlock(); } -void I2C::lock() { +void I2C::lock() +{ _mutex->lock(); } -void I2C::unlock() { +void I2C::unlock() +{ _mutex->unlock(); } #if DEVICE_I2C_ASYNCH -int I2C::transfer(int address, const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length, const event_callback_t& callback, int event, bool repeated) +int I2C::transfer(int address, const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length, const event_callback_t &callback, int event, bool repeated) { lock(); if (i2c_active(&_i2c)) { diff --git a/drivers/I2C.h b/drivers/I2C.h index 920a506eb75..03f58f2a154 100644 --- a/drivers/I2C.h +++ b/drivers/I2C.h @@ -151,7 +151,8 @@ class I2C : private NonCopyable { */ virtual void unlock(void); - virtual ~I2C() { + virtual ~I2C() + { // Do nothing } @@ -160,7 +161,7 @@ class I2C : private NonCopyable { /** Start non-blocking I2C transfer. * * This function locks the deep sleep until any event has occured - * + * * @param address 8/10 bit I2c slave address * @param tx_buffer The TX buffer with data to be transfered * @param tx_length The length of TX buffer in bytes @@ -171,13 +172,13 @@ class I2C : private NonCopyable { * @param repeated Repeated start, true - do not send stop at end * @return Zero if the transfer has started, or -1 if I2C peripheral is busy */ - int transfer(int address, const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length, const event_callback_t& callback, int event = I2C_EVENT_TRANSFER_COMPLETE, bool repeated = false); + int transfer(int address, const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length, const event_callback_t &callback, int event = I2C_EVENT_TRANSFER_COMPLETE, bool repeated = false); /** Abort the on-going I2C transfer */ void abort_transfer(); - protected: +protected: /** Lock deep sleep only if it is not yet locked */ void lock_deep_sleep(); diff --git a/drivers/I2CSlave.cpp b/drivers/I2CSlave.cpp index f168c2a6c74..b29b4e74e24 100644 --- a/drivers/I2CSlave.cpp +++ b/drivers/I2CSlave.cpp @@ -19,42 +19,51 @@ namespace mbed { -I2CSlave::I2CSlave(PinName sda, PinName scl) : _i2c() { +I2CSlave::I2CSlave(PinName sda, PinName scl) : _i2c() +{ i2c_init(&_i2c, sda, scl); i2c_frequency(&_i2c, 100000); i2c_slave_mode(&_i2c, 1); } -void I2CSlave::frequency(int hz) { +void I2CSlave::frequency(int hz) +{ i2c_frequency(&_i2c, hz); } -void I2CSlave::address(int address) { +void I2CSlave::address(int address) +{ int addr = (address & 0xFF) | 1; i2c_slave_address(&_i2c, 0, addr, 0); } -int I2CSlave::receive(void) { +int I2CSlave::receive(void) +{ return i2c_slave_receive(&_i2c); } -int I2CSlave::read(char *data, int length) { +int I2CSlave::read(char *data, int length) +{ return i2c_slave_read(&_i2c, data, length) != length; } -int I2CSlave::read(void) { +int I2CSlave::read(void) +{ return i2c_byte_read(&_i2c, 0); } -int I2CSlave::write(const char *data, int length) { +int I2CSlave::write(const char *data, int length) +{ return i2c_slave_write(&_i2c, data, length) != length; } -int I2CSlave::write(int data) { +int I2CSlave::write(int data) +{ return i2c_byte_write(&_i2c, data); } -void I2CSlave::stop(void) { +void I2CSlave::stop(void) +{ i2c_stop(&_i2c); } diff --git a/drivers/InterruptIn.cpp b/drivers/InterruptIn.cpp index 34f32104c31..5726ea9b003 100644 --- a/drivers/InterruptIn.cpp +++ b/drivers/InterruptIn.cpp @@ -20,32 +20,37 @@ namespace mbed { InterruptIn::InterruptIn(PinName pin) : gpio(), - gpio_irq(), - _rise(NULL), - _fall(NULL) { + gpio_irq(), + _rise(NULL), + _fall(NULL) +{ // No lock needed in the constructor gpio_irq_init(&gpio_irq, pin, (&InterruptIn::_irq_handler), (uint32_t)this); gpio_init_in(&gpio, pin); } -InterruptIn::~InterruptIn() { +InterruptIn::~InterruptIn() +{ // No lock needed in the destructor gpio_irq_free(&gpio_irq); } -int InterruptIn::read() { +int InterruptIn::read() +{ // Read only return gpio_read(&gpio); } -void InterruptIn::mode(PinMode pull) { +void InterruptIn::mode(PinMode pull) +{ core_util_critical_section_enter(); gpio_mode(&gpio, pull); core_util_critical_section_exit(); } -void InterruptIn::rise(Callback func) { +void InterruptIn::rise(Callback func) +{ core_util_critical_section_enter(); if (func) { _rise = func; @@ -57,7 +62,8 @@ void InterruptIn::rise(Callback func) { core_util_critical_section_exit(); } -void InterruptIn::fall(Callback func) { +void InterruptIn::fall(Callback func) +{ core_util_critical_section_enter(); if (func) { _fall = func; @@ -69,36 +75,41 @@ void InterruptIn::fall(Callback func) { core_util_critical_section_exit(); } -void InterruptIn::_irq_handler(uint32_t id, gpio_irq_event event) { - InterruptIn *handler = (InterruptIn*)id; +void InterruptIn::_irq_handler(uint32_t id, gpio_irq_event event) +{ + InterruptIn *handler = (InterruptIn *)id; switch (event) { - case IRQ_RISE: + case IRQ_RISE: if (handler->_rise) { handler->_rise(); } break; - case IRQ_FALL: + case IRQ_FALL: if (handler->_fall) { - handler->_fall(); + handler->_fall(); } break; - case IRQ_NONE: break; + case IRQ_NONE: + break; } } -void InterruptIn::enable_irq() { +void InterruptIn::enable_irq() +{ core_util_critical_section_enter(); gpio_irq_enable(&gpio_irq); core_util_critical_section_exit(); } -void InterruptIn::disable_irq() { +void InterruptIn::disable_irq() +{ core_util_critical_section_enter(); gpio_irq_disable(&gpio_irq); core_util_critical_section_exit(); } -InterruptIn::operator int() { +InterruptIn::operator int() +{ // Underlying call is atomic return read(); } diff --git a/drivers/InterruptIn.h b/drivers/InterruptIn.h index 0a122bdb039..79d97c03ea4 100644 --- a/drivers/InterruptIn.h +++ b/drivers/InterruptIn.h @@ -97,9 +97,10 @@ class InterruptIn : private NonCopyable { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "The rise function does not support cv-qualifiers. Replaced by " - "rise(callback(obj, method)).") - void rise(T *obj, M method) { + "The rise function does not support cv-qualifiers. Replaced by " + "rise(callback(obj, method)).") + void rise(T *obj, M method) + { core_util_critical_section_enter(); rise(callback(obj, method)); core_util_critical_section_exit(); @@ -121,9 +122,10 @@ class InterruptIn : private NonCopyable { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "The fall function does not support cv-qualifiers. Replaced by " - "fall(callback(obj, method)).") - void fall(T *obj, M method) { + "The fall function does not support cv-qualifiers. Replaced by " + "fall(callback(obj, method)).") + void fall(T *obj, M method) + { core_util_critical_section_enter(); fall(callback(obj, method)); core_util_critical_section_exit(); diff --git a/drivers/InterruptManager.cpp b/drivers/InterruptManager.cpp index 9c2b4c2acb8..f557cf43781 100644 --- a/drivers/InterruptManager.cpp +++ b/drivers/InterruptManager.cpp @@ -32,12 +32,13 @@ namespace mbed { typedef void (*pvoidf)(void); -InterruptManager* InterruptManager::_instance = (InterruptManager*)NULL; +InterruptManager *InterruptManager::_instance = (InterruptManager *)NULL; -InterruptManager* InterruptManager::get() { +InterruptManager *InterruptManager::get() +{ if (NULL == _instance) { - InterruptManager* temp = new InterruptManager(); + InterruptManager *temp = new InterruptManager(); // Atomically set _instance core_util_critical_section_enter(); @@ -55,28 +56,33 @@ InterruptManager* InterruptManager::get() { return _instance; } -InterruptManager::InterruptManager() { +InterruptManager::InterruptManager() +{ // No mutex needed in constructor - memset(_chains, 0, NVIC_NUM_VECTORS * sizeof(CallChain*)); + memset(_chains, 0, NVIC_NUM_VECTORS * sizeof(CallChain *)); } -void InterruptManager::destroy() { +void InterruptManager::destroy() +{ // Not a good idea to call this unless NO interrupt at all // is under the control of the handler; otherwise, a system crash // is very likely to occur if (NULL != _instance) { delete _instance; - _instance = (InterruptManager*)NULL; + _instance = (InterruptManager *)NULL; } } -InterruptManager::~InterruptManager() { - for(int i = 0; i < NVIC_NUM_VECTORS; i++) - if (NULL != _chains[i]) +InterruptManager::~InterruptManager() +{ + for (int i = 0; i < NVIC_NUM_VECTORS; i++) + if (NULL != _chains[i]) { delete _chains[i]; + } } -bool InterruptManager::must_replace_vector(IRQn_Type irq) { +bool InterruptManager::must_replace_vector(IRQn_Type irq) +{ lock(); int ret = false; @@ -90,19 +96,22 @@ bool InterruptManager::must_replace_vector(IRQn_Type irq) { return ret; } -pFunctionPointer_t InterruptManager::add_common(void (*function)(void), IRQn_Type irq, bool front) { +pFunctionPointer_t InterruptManager::add_common(void (*function)(void), IRQn_Type irq, bool front) +{ lock(); int irq_pos = get_irq_index(irq); bool change = must_replace_vector(irq); pFunctionPointer_t pf = front ? _chains[irq_pos]->add_front(function) : _chains[irq_pos]->add(function); - if (change) + if (change) { NVIC_SetVector(irq, (uint32_t)&InterruptManager::static_irq_helper); + } unlock(); return pf; } -bool InterruptManager::remove_handler(pFunctionPointer_t handler, IRQn_Type irq) { +bool InterruptManager::remove_handler(pFunctionPointer_t handler, IRQn_Type irq) +{ int irq_pos = get_irq_index(irq); bool ret = false; @@ -117,24 +126,29 @@ bool InterruptManager::remove_handler(pFunctionPointer_t handler, IRQn_Type irq) return ret; } -void InterruptManager::irq_helper() { +void InterruptManager::irq_helper() +{ _chains[__get_IPSR()]->call(); } -int InterruptManager::get_irq_index(IRQn_Type irq) { +int InterruptManager::get_irq_index(IRQn_Type irq) +{ // Pure function - no lock needed return (int)irq + NVIC_USER_IRQ_OFFSET; } -void InterruptManager::static_irq_helper() { +void InterruptManager::static_irq_helper() +{ InterruptManager::get()->irq_helper(); } -void InterruptManager::lock() { +void InterruptManager::lock() +{ _mutex.lock(); } -void InterruptManager::unlock() { +void InterruptManager::unlock() +{ _mutex.unlock(); } diff --git a/drivers/InterruptManager.h b/drivers/InterruptManager.h index ac10ebc8789..2a6a894a2ee 100644 --- a/drivers/InterruptManager.h +++ b/drivers/InterruptManager.h @@ -61,13 +61,13 @@ class InterruptManager : private NonCopyable { * @return the only instance of this class */ MBED_DEPRECATED_SINCE("mbed-os-5.6", "This class is not part of the " - "public API of mbed-os and is being removed in the future.") - static InterruptManager* get(); + "public API of mbed-os and is being removed in the future.") + static InterruptManager *get(); /** Destroy the current instance of the interrupt manager */ MBED_DEPRECATED_SINCE("mbed-os-5.6", "This class is not part of the " - "public API of mbed-os and is being removed in the future.") + "public API of mbed-os and is being removed in the future.") static void destroy(); /** Add a handler for an interrupt at the end of the handler list @@ -79,8 +79,9 @@ class InterruptManager : private NonCopyable { * The function object created for 'function' */ MBED_DEPRECATED_SINCE("mbed-os-5.6", "This class is not part of the " - "public API of mbed-os and is being removed in the future.") - pFunctionPointer_t add_handler(void (*function)(void), IRQn_Type irq) { + "public API of mbed-os and is being removed in the future.") + pFunctionPointer_t add_handler(void (*function)(void), IRQn_Type irq) + { // Underlying call is thread safe return add_common(function, irq); } @@ -94,8 +95,9 @@ class InterruptManager : private NonCopyable { * The function object created for 'function' */ MBED_DEPRECATED_SINCE("mbed-os-5.6", "This class is not part of the " - "public API of mbed-os and is being removed in the future.") - pFunctionPointer_t add_handler_front(void (*function)(void), IRQn_Type irq) { + "public API of mbed-os and is being removed in the future.") + pFunctionPointer_t add_handler_front(void (*function)(void), IRQn_Type irq) + { // Underlying call is thread safe return add_common(function, irq, true); } @@ -111,8 +113,9 @@ class InterruptManager : private NonCopyable { */ template MBED_DEPRECATED_SINCE("mbed-os-5.6", "This class is not part of the " - "public API of mbed-os and is being removed in the future.") - pFunctionPointer_t add_handler(T* tptr, void (T::*mptr)(void), IRQn_Type irq) { + "public API of mbed-os and is being removed in the future.") + pFunctionPointer_t add_handler(T *tptr, void (T::*mptr)(void), IRQn_Type irq) + { // Underlying call is thread safe return add_common(tptr, mptr, irq); } @@ -128,8 +131,9 @@ class InterruptManager : private NonCopyable { */ template MBED_DEPRECATED_SINCE("mbed-os-5.6", "This class is not part of the " - "public API of mbed-os and is being removed in the future.") - pFunctionPointer_t add_handler_front(T* tptr, void (T::*mptr)(void), IRQn_Type irq) { + "public API of mbed-os and is being removed in the future.") + pFunctionPointer_t add_handler_front(T *tptr, void (T::*mptr)(void), IRQn_Type irq) + { // Underlying call is thread safe return add_common(tptr, mptr, irq, true); } @@ -143,7 +147,7 @@ class InterruptManager : private NonCopyable { * true if the handler was found and removed, false otherwise */ MBED_DEPRECATED_SINCE("mbed-os-5.6", "This class is not part of the " - "public API of mbed-os and is being removed in the future.") + "public API of mbed-os and is being removed in the future.") bool remove_handler(pFunctionPointer_t handler, IRQn_Type irq); private: @@ -154,27 +158,29 @@ class InterruptManager : private NonCopyable { void unlock(); template - pFunctionPointer_t add_common(T *tptr, void (T::*mptr)(void), IRQn_Type irq, bool front=false) { + pFunctionPointer_t add_common(T *tptr, void (T::*mptr)(void), IRQn_Type irq, bool front = false) + { _mutex.lock(); int irq_pos = get_irq_index(irq); bool change = must_replace_vector(irq); pFunctionPointer_t pf = front ? _chains[irq_pos]->add_front(tptr, mptr) : _chains[irq_pos]->add(tptr, mptr); - if (change) + if (change) { NVIC_SetVector(irq, (uint32_t)&InterruptManager::static_irq_helper); + } _mutex.unlock(); return pf; } - pFunctionPointer_t add_common(void (*function)(void), IRQn_Type irq, bool front=false); + pFunctionPointer_t add_common(void (*function)(void), IRQn_Type irq, bool front = false); bool must_replace_vector(IRQn_Type irq); int get_irq_index(IRQn_Type irq); void irq_helper(); - void add_helper(void (*function)(void), IRQn_Type irq, bool front=false); + void add_helper(void (*function)(void), IRQn_Type irq, bool front = false); static void static_irq_helper(); - CallChain* _chains[NVIC_NUM_VECTORS]; - static InterruptManager* _instance; + CallChain *_chains[NVIC_NUM_VECTORS]; + static InterruptManager *_instance; PlatformMutex _mutex; }; diff --git a/drivers/LowPowerTicker.h b/drivers/LowPowerTicker.h index 2df8ef34ebe..b8c47001de7 100644 --- a/drivers/LowPowerTicker.h +++ b/drivers/LowPowerTicker.h @@ -35,10 +35,12 @@ namespace mbed { class LowPowerTicker : public Ticker, private NonCopyable { public: - LowPowerTicker() : Ticker(get_lp_ticker_data()) { + LowPowerTicker() : Ticker(get_lp_ticker_data()) + { } - virtual ~LowPowerTicker() { + virtual ~LowPowerTicker() + { } }; diff --git a/drivers/LowPowerTimeout.h b/drivers/LowPowerTimeout.h index 6aaefe2da81..a157d485ea4 100644 --- a/drivers/LowPowerTimeout.h +++ b/drivers/LowPowerTimeout.h @@ -35,7 +35,8 @@ namespace mbed { class LowPowerTimeout : public LowPowerTicker, private NonCopyable { private: - virtual void handler(void) { + virtual void handler(void) + { _function.call(); } }; diff --git a/drivers/LowPowerTimer.h b/drivers/LowPowerTimer.h index e7e00377d99..bd4bf7a0823 100644 --- a/drivers/LowPowerTimer.h +++ b/drivers/LowPowerTimer.h @@ -35,7 +35,8 @@ namespace mbed { class LowPowerTimer : public Timer, private NonCopyable { public: - LowPowerTimer() : Timer(get_lp_ticker_data()) { + LowPowerTimer() : Timer(get_lp_ticker_data()) + { } }; diff --git a/drivers/MbedCRC.cpp b/drivers/MbedCRC.cpp index 317cc8a78cb..a897bc21966 100644 --- a/drivers/MbedCRC.cpp +++ b/drivers/MbedCRC.cpp @@ -26,46 +26,46 @@ namespace mbed { */ template MbedCRC::MbedCRC(uint32_t initial_xor, uint32_t final_xor, bool reflect_data, bool reflect_remainder): - _initial_value(initial_xor), _final_xor(final_xor), _reflect_data(reflect_data), _reflect_remainder(reflect_remainder), _crc_table(NULL) + _initial_value(initial_xor), _final_xor(final_xor), _reflect_data(reflect_data), _reflect_remainder(reflect_remainder), _crc_table(NULL) { mbed_crc_ctor(); } template<> MbedCRC::MbedCRC(uint32_t initial_xor, uint32_t final_xor, bool reflect_data, bool reflect_remainder): - _initial_value(initial_xor), _final_xor(final_xor), _reflect_data(reflect_data), _reflect_remainder(reflect_remainder), - _crc_table((uint32_t *)Table_CRC_32bit_ANSI) + _initial_value(initial_xor), _final_xor(final_xor), _reflect_data(reflect_data), _reflect_remainder(reflect_remainder), + _crc_table((uint32_t *)Table_CRC_32bit_ANSI) { mbed_crc_ctor(); } template<> MbedCRC::MbedCRC(uint32_t initial_xor, uint32_t final_xor, bool reflect_data, bool reflect_remainder): - _initial_value(initial_xor), _final_xor(final_xor), _reflect_data(reflect_data), _reflect_remainder(reflect_remainder), - _crc_table((uint32_t *)Table_CRC_8bit_CCITT) + _initial_value(initial_xor), _final_xor(final_xor), _reflect_data(reflect_data), _reflect_remainder(reflect_remainder), + _crc_table((uint32_t *)Table_CRC_8bit_CCITT) { mbed_crc_ctor(); } template<> MbedCRC::MbedCRC(uint32_t initial_xor, uint32_t final_xor, bool reflect_data, bool reflect_remainder): - _initial_value(initial_xor), _final_xor(final_xor), _reflect_data(reflect_data), _reflect_remainder(reflect_remainder), - _crc_table((uint32_t *)Table_CRC_7Bit_SD) + _initial_value(initial_xor), _final_xor(final_xor), _reflect_data(reflect_data), _reflect_remainder(reflect_remainder), + _crc_table((uint32_t *)Table_CRC_7Bit_SD) { mbed_crc_ctor(); } template<> MbedCRC::MbedCRC(uint32_t initial_xor, uint32_t final_xor, bool reflect_data, bool reflect_remainder): - _initial_value(initial_xor), _final_xor(final_xor), _reflect_data(reflect_data), _reflect_remainder(reflect_remainder), - _crc_table((uint32_t *)Table_CRC_16bit_CCITT) + _initial_value(initial_xor), _final_xor(final_xor), _reflect_data(reflect_data), _reflect_remainder(reflect_remainder), + _crc_table((uint32_t *)Table_CRC_16bit_CCITT) { } template<> MbedCRC::MbedCRC(uint32_t initial_xor, uint32_t final_xor, bool reflect_data, bool reflect_remainder): - _initial_value(initial_xor), _final_xor(final_xor), _reflect_data(reflect_data), _reflect_remainder(reflect_remainder), - _crc_table((uint32_t *)Table_CRC_16bit_IBM) + _initial_value(initial_xor), _final_xor(final_xor), _reflect_data(reflect_data), _reflect_remainder(reflect_remainder), + _crc_table((uint32_t *)Table_CRC_16bit_IBM) { mbed_crc_ctor(); } diff --git a/drivers/MbedCRC.h b/drivers/MbedCRC.h index 3c2ad433d99..70b96830c22 100644 --- a/drivers/MbedCRC.h +++ b/drivers/MbedCRC.h @@ -103,9 +103,8 @@ typedef enum crc_polynomial { * @ingroup drivers */ -template -class MbedCRC -{ +template +class MbedCRC { public: typedef uint64_t crc_data_size_t; @@ -115,7 +114,7 @@ class MbedCRC * @param final_xor Final Xor value * @param reflect_data * @param reflect_remainder -* @note Default constructor without any arguments is valid only for supported CRC polynomials. :: crc_polynomial_t + * @note Default constructor without any arguments is valid only for supported CRC polynomials. :: crc_polynomial_t * MbedCRC ct; --- Valid POLY_7BIT_SD * MbedCRC <0x1021, 16> ct; --- Valid POLY_16BIT_CCITT * MbedCRC ct; --- Invalid, compilation error @@ -301,7 +300,7 @@ class MbedCRC */ uint32_t reflect_bytes(uint32_t data) const { - if(_reflect_data) { + if (_reflect_data) { uint32_t reflection = 0x0; for (uint8_t bit = 0; bit < 8; ++bit) { @@ -337,7 +336,7 @@ class MbedCRC data_byte = reflect_bytes(data[byte]); for (uint8_t bit = 8; bit > 0; --bit) { p_crc <<= 1; - if (( data_byte ^ p_crc) & get_top_bit()) { + if ((data_byte ^ p_crc) & get_top_bit()) { p_crc ^= polynomial; } data_byte <<= 1; @@ -361,13 +360,13 @@ class MbedCRC return 0; } - /** CRC computation using ROM tables - * - * @param buffer data buffer - * @param size size of the data - * @param crc CRC value is filled in, but the value is not the final - * @return 0 on success or a negative error code on failure - */ + /** CRC computation using ROM tables + * + * @param buffer data buffer + * @param size size of the data + * @param crc CRC value is filled in, but the value is not the final + * @return 0 on success or a negative error code on failure + */ int32_t table_compute_partial(const void *buffer, crc_data_size_t size, uint32_t *crc) const { MBED_ASSERT(crc != NULL); diff --git a/drivers/PortIn.h b/drivers/PortIn.h index 2796916fe25..62e48e1c19e 100644 --- a/drivers/PortIn.h +++ b/drivers/PortIn.h @@ -60,7 +60,8 @@ class PortIn { * @param port Port to connect to (Port0-Port5) * @param mask A bitmask to identify which bits in the port should be included (0 - ignore) */ - PortIn(PortName port, int mask = 0xFFFFFFFF) { + PortIn(PortName port, int mask = 0xFFFFFFFF) + { core_util_critical_section_enter(); port_init(&_port, port, mask, PIN_INPUT); core_util_critical_section_exit(); @@ -71,7 +72,8 @@ class PortIn { * @returns * An integer with each bit corresponding to associated port pin setting */ - int read() { + int read() + { return port_read(&_port); } @@ -79,7 +81,8 @@ class PortIn { * * @param mode PullUp, PullDown, PullNone, OpenDrain */ - void mode(PinMode mode) { + void mode(PinMode mode) + { core_util_critical_section_enter(); port_mode(&_port, mode); core_util_critical_section_exit(); @@ -87,7 +90,8 @@ class PortIn { /** A shorthand for read() */ - operator int() { + operator int() + { return read(); } diff --git a/drivers/PortInOut.h b/drivers/PortInOut.h index 4eb9ecb7292..00c972c2a0f 100644 --- a/drivers/PortInOut.h +++ b/drivers/PortInOut.h @@ -39,7 +39,8 @@ class PortInOut { * @param port Port to connect to (Port0-Port5) * @param mask A bitmask to identify which bits in the port should be included (0 - ignore) */ - PortInOut(PortName port, int mask = 0xFFFFFFFF) { + PortInOut(PortName port, int mask = 0xFFFFFFFF) + { core_util_critical_section_enter(); port_init(&_port, port, mask, PIN_INPUT); core_util_critical_section_exit(); @@ -49,7 +50,8 @@ class PortInOut { * * @param value An integer specifying a bit to write for every corresponding port pin */ - void write(int value) { + void write(int value) + { port_write(&_port, value); } @@ -58,13 +60,15 @@ class PortInOut { * @returns * An integer with each bit corresponding to associated port pin setting */ - int read() { + int read() + { return port_read(&_port); } /** Set as an output */ - void output() { + void output() + { core_util_critical_section_enter(); port_dir(&_port, PIN_OUTPUT); core_util_critical_section_exit(); @@ -72,7 +76,8 @@ class PortInOut { /** Set as an input */ - void input() { + void input() + { core_util_critical_section_enter(); port_dir(&_port, PIN_INPUT); core_util_critical_section_exit(); @@ -82,7 +87,8 @@ class PortInOut { * * @param mode PullUp, PullDown, PullNone, OpenDrain */ - void mode(PinMode mode) { + void mode(PinMode mode) + { core_util_critical_section_enter(); port_mode(&_port, mode); core_util_critical_section_exit(); @@ -91,7 +97,8 @@ class PortInOut { /** A shorthand for write() * \sa PortInOut::write() */ - PortInOut& operator= (int value) { + PortInOut &operator= (int value) + { write(value); return *this; } @@ -99,7 +106,8 @@ class PortInOut { /** A shorthand for write() * \sa PortInOut::write() */ - PortInOut& operator= (PortInOut& rhs) { + PortInOut &operator= (PortInOut &rhs) + { write(rhs.read()); return *this; } @@ -107,7 +115,8 @@ class PortInOut { /** A shorthand for read() * \sa PortInOut::read() */ - operator int() { + operator int() + { return read(); } diff --git a/drivers/PortOut.h b/drivers/PortOut.h index 9b8a76b60c3..ccdcc25dbf8 100644 --- a/drivers/PortOut.h +++ b/drivers/PortOut.h @@ -59,7 +59,8 @@ class PortOut { * @param port Port to connect to (Port0-Port5) * @param mask A bitmask to identify which bits in the port should be included (0 - ignore) */ - PortOut(PortName port, int mask = 0xFFFFFFFF) { + PortOut(PortName port, int mask = 0xFFFFFFFF) + { core_util_critical_section_enter(); port_init(&_port, port, mask, PIN_OUTPUT); core_util_critical_section_exit(); @@ -69,7 +70,8 @@ class PortOut { * * @param value An integer specifying a bit to write for every corresponding PortOut pin */ - void write(int value) { + void write(int value) + { port_write(&_port, value); } @@ -78,14 +80,16 @@ class PortOut { * @returns * An integer with each bit corresponding to associated PortOut pin setting */ - int read() { + int read() + { return port_read(&_port); } /** A shorthand for write() * \sa PortOut::write() */ - PortOut& operator= (int value) { + PortOut &operator= (int value) + { write(value); return *this; } @@ -93,7 +97,8 @@ class PortOut { /** A shorthand for read() * \sa PortOut::read() */ - PortOut& operator= (PortOut& rhs) { + PortOut &operator= (PortOut &rhs) + { write(rhs.read()); return *this; } @@ -101,7 +106,8 @@ class PortOut { /** A shorthand for read() * \sa PortOut::read() */ - operator int() { + operator int() + { return read(); } diff --git a/drivers/PwmOut.h b/drivers/PwmOut.h index 5f7bb478ae0..04e0a22618d 100644 --- a/drivers/PwmOut.h +++ b/drivers/PwmOut.h @@ -57,13 +57,15 @@ class PwmOut { * * @param pin PwmOut pin to connect to */ - PwmOut(PinName pin) : _deep_sleep_locked(false) { + PwmOut(PinName pin) : _deep_sleep_locked(false) + { core_util_critical_section_enter(); pwmout_init(&_pwm, pin); core_util_critical_section_exit(); } - ~PwmOut() { + ~PwmOut() + { core_util_critical_section_enter(); unlock_deep_sleep(); core_util_critical_section_exit(); @@ -76,7 +78,8 @@ class PwmOut { * 0.0f (representing on 0%) and 1.0f (representing on 100%). * Values outside this range will be saturated to 0.0f or 1.0f. */ - void write(float value) { + void write(float value) + { core_util_critical_section_enter(); lock_deep_sleep(); pwmout_write(&_pwm, value); @@ -93,7 +96,8 @@ class PwmOut { * @note * This value may not match exactly the value set by a previous write(). */ - float read() { + float read() + { core_util_critical_section_enter(); float val = pwmout_read(&_pwm); core_util_critical_section_exit(); @@ -107,7 +111,8 @@ class PwmOut { * The resolution is currently in microseconds; periods smaller than this * will be set to zero. */ - void period(float seconds) { + void period(float seconds) + { core_util_critical_section_enter(); pwmout_period(&_pwm, seconds); core_util_critical_section_exit(); @@ -116,7 +121,8 @@ class PwmOut { /** Set the PWM period, specified in milli-seconds (int), keeping the duty cycle the same. * @param ms Change the period of a PWM signal in milli-seconds without modifying the duty cycle */ - void period_ms(int ms) { + void period_ms(int ms) + { core_util_critical_section_enter(); pwmout_period_ms(&_pwm, ms); core_util_critical_section_exit(); @@ -125,7 +131,8 @@ class PwmOut { /** Set the PWM period, specified in micro-seconds (int), keeping the duty cycle the same. * @param us Change the period of a PWM signal in micro-seconds without modifying the duty cycle */ - void period_us(int us) { + void period_us(int us) + { core_util_critical_section_enter(); pwmout_period_us(&_pwm, us); core_util_critical_section_exit(); @@ -134,7 +141,8 @@ class PwmOut { /** Set the PWM pulsewidth, specified in seconds (float), keeping the period the same. * @param seconds Change the pulse width of a PWM signal specified in seconds (float) */ - void pulsewidth(float seconds) { + void pulsewidth(float seconds) + { core_util_critical_section_enter(); pwmout_pulsewidth(&_pwm, seconds); core_util_critical_section_exit(); @@ -143,16 +151,18 @@ class PwmOut { /** Set the PWM pulsewidth, specified in milli-seconds (int), keeping the period the same. * @param ms Change the pulse width of a PWM signal specified in milli-seconds */ - void pulsewidth_ms(int ms) { + void pulsewidth_ms(int ms) + { core_util_critical_section_enter(); pwmout_pulsewidth_ms(&_pwm, ms); core_util_critical_section_exit(); } /** Set the PWM pulsewidth, specified in micro-seconds (int), keeping the period the same. - * @param us Change the pulse width of a PWM signal specified in micro-seconds + * @param us Change the pulse width of a PWM signal specified in micro-seconds */ - void pulsewidth_us(int us) { + void pulsewidth_us(int us) + { core_util_critical_section_enter(); pwmout_pulsewidth_us(&_pwm, us); core_util_critical_section_exit(); @@ -161,7 +171,8 @@ class PwmOut { /** A operator shorthand for write() * \sa PwmOut::write() */ - PwmOut& operator= (float value) { + PwmOut &operator= (float value) + { // Underlying call is thread safe write(value); return *this; @@ -169,8 +180,9 @@ class PwmOut { /** A operator shorthand for write() * \sa PwmOut::write() - */ - PwmOut& operator= (PwmOut& rhs) { + */ + PwmOut &operator= (PwmOut &rhs) + { // Underlying call is thread safe write(rhs.read()); return *this; @@ -179,14 +191,16 @@ class PwmOut { /** An operator shorthand for read() * \sa PwmOut::read() */ - operator float() { + operator float() + { // Underlying call is thread safe return read(); } protected: /** Lock deep sleep only if it is not yet locked */ - void lock_deep_sleep() { + void lock_deep_sleep() + { if (_deep_sleep_locked == false) { sleep_manager_lock_deep_sleep(); _deep_sleep_locked = true; @@ -194,7 +208,8 @@ class PwmOut { } /** Unlock deep sleep in case it is locked */ - void unlock_deep_sleep() { + void unlock_deep_sleep() + { if (_deep_sleep_locked == true) { sleep_manager_unlock_deep_sleep(); _deep_sleep_locked = false; diff --git a/drivers/RawSerial.cpp b/drivers/RawSerial.cpp index 639586892ac..2943bd95206 100644 --- a/drivers/RawSerial.cpp +++ b/drivers/RawSerial.cpp @@ -25,28 +25,33 @@ namespace mbed { -RawSerial::RawSerial(PinName tx, PinName rx, int baud) : SerialBase(tx, rx, baud) { +RawSerial::RawSerial(PinName tx, PinName rx, int baud) : SerialBase(tx, rx, baud) +{ // No lock needed in the constructor } -int RawSerial::getc() { +int RawSerial::getc() +{ lock(); int ret = _base_getc(); unlock(); return ret; } -int RawSerial::putc(int c) { +int RawSerial::putc(int c) +{ lock(); int ret = _base_putc(c); unlock(); return ret; } -int RawSerial::puts(const char *str) { +int RawSerial::puts(const char *str) +{ lock(); - while (*str) + while (*str) { putc(*str ++); + } unlock(); return 0; } @@ -55,7 +60,8 @@ int RawSerial::puts(const char *str) { // means we can't call printf() directly, so we use sprintf() instead. // We only call malloc() for the sprintf() buffer if the buffer // length is above a certain threshold, otherwise we use just the stack. -int RawSerial::printf(const char *format, ...) { +int RawSerial::printf(const char *format, ...) +{ lock(); std::va_list arg; va_start(arg, format); @@ -80,13 +86,15 @@ int RawSerial::printf(const char *format, ...) { /** Acquire exclusive access to this serial port */ -void RawSerial::lock() { +void RawSerial::lock() +{ // No lock used - external synchronization required } /** Release exclusive access to this serial port */ -void RawSerial::unlock() { +void RawSerial::unlock() +{ // No lock used - external synchronization required } diff --git a/drivers/SPI.cpp b/drivers/SPI.cpp index 7bb94018d15..9157bcda1ce 100644 --- a/drivers/SPI.cpp +++ b/drivers/SPI.cpp @@ -29,23 +29,25 @@ CircularBuffer, TRANSACTION_QUEUE_SIZE_SPI> SPI::_transaction_b #endif SPI::SPI(PinName mosi, PinName miso, PinName sclk, PinName ssel) : - _spi(), + _spi(), #if DEVICE_SPI_ASYNCH - _irq(this), - _usage(DMA_USAGE_NEVER), - _deep_sleep_locked(false), + _irq(this), + _usage(DMA_USAGE_NEVER), + _deep_sleep_locked(false), #endif - _bits(8), - _mode(0), - _hz(1000000), - _write_fill(SPI_FILL_CHAR) { + _bits(8), + _mode(0), + _hz(1000000), + _write_fill(SPI_FILL_CHAR) +{ // No lock needed in the constructor spi_init(&_spi, mosi, miso, sclk, ssel); _acquire(); } -void SPI::format(int bits, int mode) { +void SPI::format(int bits, int mode) +{ lock(); _bits = bits; _mode = mode; @@ -60,7 +62,8 @@ void SPI::format(int bits, int mode) { unlock(); } -void SPI::frequency(int hz) { +void SPI::frequency(int hz) +{ lock(); _hz = hz; // If changing format while you are the owner than just @@ -74,13 +77,14 @@ void SPI::frequency(int hz) { unlock(); } -SPI* SPI::_owner = NULL; +SPI *SPI::_owner = NULL; SingletonPtr SPI::_mutex; // ignore the fact there are multiple physical spis, and always update if it wasnt us last -void SPI::aquire() { +void SPI::aquire() +{ lock(); - if (_owner != this) { + if (_owner != this) { spi_format(&_spi, _bits, _mode, 0); spi_frequency(&_spi, _hz); _owner = this; @@ -89,15 +93,17 @@ void SPI::aquire() { } // Note: Private function with no locking -void SPI::_acquire() { - if (_owner != this) { +void SPI::_acquire() +{ + if (_owner != this) { spi_format(&_spi, _bits, _mode, 0); spi_frequency(&_spi, _hz); _owner = this; } } -int SPI::write(int value) { +int SPI::write(int value) +{ lock(); _acquire(); int ret = spi_master_write(&_spi, value); @@ -105,7 +111,8 @@ int SPI::write(int value) { return ret; } -int SPI::write(const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length) { +int SPI::write(const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length) +{ lock(); _acquire(); int ret = spi_master_block_write(&_spi, tx_buffer, tx_length, rx_buffer, rx_length, _write_fill); @@ -113,15 +120,18 @@ int SPI::write(const char *tx_buffer, int tx_length, char *rx_buffer, int rx_len return ret; } -void SPI::lock() { +void SPI::lock() +{ _mutex->lock(); } -void SPI::unlock() { +void SPI::unlock() +{ _mutex->unlock(); } -void SPI::set_default_write_value(char data) { +void SPI::set_default_write_value(char data) +{ lock(); _write_fill = data; unlock(); @@ -129,7 +139,7 @@ void SPI::set_default_write_value(char data) { #if DEVICE_SPI_ASYNCH -int SPI::transfer(const void *tx_buffer, int tx_length, void *rx_buffer, int rx_length, unsigned char bit_width, const event_callback_t& callback, int event) +int SPI::transfer(const void *tx_buffer, int tx_length, void *rx_buffer, int rx_length, unsigned char bit_width, const event_callback_t &callback, int event) { if (spi_active(&_spi)) { return queue_transfer(tx_buffer, tx_length, rx_buffer, rx_length, bit_width, callback, event); @@ -170,7 +180,7 @@ int SPI::set_dma_usage(DMAUsage usage) return 0; } -int SPI::queue_transfer(const void *tx_buffer, int tx_length, void *rx_buffer, int rx_length, unsigned char bit_width, const event_callback_t& callback, int event) +int SPI::queue_transfer(const void *tx_buffer, int tx_length, void *rx_buffer, int rx_length, unsigned char bit_width, const event_callback_t &callback, int event) { #if TRANSACTION_QUEUE_SIZE_SPI transaction_t t; @@ -199,13 +209,13 @@ int SPI::queue_transfer(const void *tx_buffer, int tx_length, void *rx_buffer, i #endif } -void SPI::start_transfer(const void *tx_buffer, int tx_length, void *rx_buffer, int rx_length, unsigned char bit_width, const event_callback_t& callback, int event) +void SPI::start_transfer(const void *tx_buffer, int tx_length, void *rx_buffer, int rx_length, unsigned char bit_width, const event_callback_t &callback, int event) { lock_deep_sleep(); _acquire(); _callback = callback; _irq.callback(&SPI::irq_handler_asynch); - spi_master_transfer(&_spi, tx_buffer, tx_length, rx_buffer, rx_length, bit_width, _irq.entry(), event , _usage); + spi_master_transfer(&_spi, tx_buffer, tx_length, rx_buffer, rx_length, bit_width, _irq.entry(), event, _usage); } void SPI::lock_deep_sleep() @@ -235,8 +245,8 @@ void SPI::dequeue_transaction() { Transaction t; if (_transaction_buffer.pop(t)) { - SPI* obj = t.get_object(); - transaction_t* data = t.get_transaction(); + SPI *obj = t.get_object(); + transaction_t *data = t.get_transaction(); obj->start_transaction(data); } } diff --git a/drivers/SPI.h b/drivers/SPI.h index af102dc07c6..e46103b4901 100644 --- a/drivers/SPI.h +++ b/drivers/SPI.h @@ -86,7 +86,7 @@ class SPI : private NonCopyable { * @param sclk SPI Clock pin * @param ssel SPI chip select pin */ - SPI(PinName mosi, PinName miso, PinName sclk, PinName ssel=NC); + SPI(PinName mosi, PinName miso, PinName sclk, PinName ssel = NC); /** Configure the data transmission format * @@ -157,7 +157,7 @@ class SPI : private NonCopyable { /** Start non-blocking SPI transfer using 8bit buffers. * * This function locks the deep sleep until any event has occured - * + * * @param tx_buffer The TX buffer with data to be transfered. If NULL is passed, * the default SPI value is sent * @param tx_length The length of TX buffer in bytes @@ -169,11 +169,12 @@ class SPI : private NonCopyable { * @return Zero if the transfer has started, or -1 if SPI peripheral is busy */ template - int transfer(const Type *tx_buffer, int tx_length, Type *rx_buffer, int rx_length, const event_callback_t& callback, int event = SPI_EVENT_COMPLETE) { + int transfer(const Type *tx_buffer, int tx_length, Type *rx_buffer, int rx_length, const event_callback_t &callback, int event = SPI_EVENT_COMPLETE) + { if (spi_active(&_spi)) { - return queue_transfer(tx_buffer, tx_length, rx_buffer, rx_length, sizeof(Type)*8, callback, event); + return queue_transfer(tx_buffer, tx_length, rx_buffer, rx_length, sizeof(Type) * 8, callback, event); } - start_transfer(tx_buffer, tx_length, rx_buffer, rx_length, sizeof(Type)*8, callback, event); + start_transfer(tx_buffer, tx_length, rx_buffer, rx_length, sizeof(Type) * 8, callback, event); return 0; } @@ -215,7 +216,7 @@ class SPI : private NonCopyable { * @param event The logical OR of events to modify * @return Zero if the transfer has started or was added to the queue, or -1 if SPI peripheral is busy/buffer is full */ - int transfer(const void *tx_buffer, int tx_length, void *rx_buffer, int rx_length, unsigned char bit_width, const event_callback_t& callback, int event); + int transfer(const void *tx_buffer, int tx_length, void *rx_buffer, int rx_length, unsigned char bit_width, const event_callback_t &callback, int event); /** * @@ -230,7 +231,7 @@ class SPI : private NonCopyable { * @param event The logical OR of events to modify * @return Zero if a transfer was added to the queue, or -1 if the queue is full */ - int queue_transfer(const void *tx_buffer, int tx_length, void *rx_buffer, int rx_length, unsigned char bit_width, const event_callback_t& callback, int event); + int queue_transfer(const void *tx_buffer, int tx_length, void *rx_buffer, int rx_length, unsigned char bit_width, const event_callback_t &callback, int event); /** Configures a callback, spi peripheral and initiate a new transfer * @@ -244,7 +245,7 @@ class SPI : private NonCopyable { * @param callback The event callback function * @param event The logical OR of events to modify */ - void start_transfer(const void *tx_buffer, int tx_length, void *rx_buffer, int rx_length, unsigned char bit_width, const event_callback_t& callback, int event); + void start_transfer(const void *tx_buffer, int tx_length, void *rx_buffer, int rx_length, unsigned char bit_width, const event_callback_t &callback, int event); private: /** Lock deep sleep only if it is not yet locked */ @@ -272,7 +273,8 @@ class SPI : private NonCopyable { #endif public: - virtual ~SPI() { + virtual ~SPI() + { } protected: diff --git a/drivers/SPISlave.cpp b/drivers/SPISlave.cpp index 8ae263e5d86..1f826bb3433 100644 --- a/drivers/SPISlave.cpp +++ b/drivers/SPISlave.cpp @@ -24,32 +24,37 @@ SPISlave::SPISlave(PinName mosi, PinName miso, PinName sclk, PinName ssel) : _bits(8), _mode(0), _hz(1000000) - { +{ spi_init(&_spi, mosi, miso, sclk, ssel); spi_format(&_spi, _bits, _mode, 1); spi_frequency(&_spi, _hz); } -void SPISlave::format(int bits, int mode) { +void SPISlave::format(int bits, int mode) +{ _bits = bits; _mode = mode; spi_format(&_spi, _bits, _mode, 1); } -void SPISlave::frequency(int hz) { +void SPISlave::frequency(int hz) +{ _hz = hz; spi_frequency(&_spi, _hz); } -int SPISlave::receive(void) { - return(spi_slave_receive(&_spi)); +int SPISlave::receive(void) +{ + return (spi_slave_receive(&_spi)); } -int SPISlave::read(void) { - return(spi_slave_read(&_spi)); +int SPISlave::read(void) +{ + return (spi_slave_read(&_spi)); } -void SPISlave::reply(int value) { +void SPISlave::reply(int value) +{ spi_slave_write(&_spi, value); } diff --git a/drivers/Serial.cpp b/drivers/Serial.cpp index 8e3ce518a53..55e5a38bba5 100644 --- a/drivers/Serial.cpp +++ b/drivers/Serial.cpp @@ -20,27 +20,33 @@ namespace mbed { -Serial::Serial(PinName tx, PinName rx, const char *name, int baud) : SerialBase(tx, rx, baud), Stream(name) { +Serial::Serial(PinName tx, PinName rx, const char *name, int baud) : SerialBase(tx, rx, baud), Stream(name) +{ } -Serial::Serial(PinName tx, PinName rx, int baud): SerialBase(tx, rx, baud), Stream(NULL) { +Serial::Serial(PinName tx, PinName rx, int baud): SerialBase(tx, rx, baud), Stream(NULL) +{ } -int Serial::_getc() { +int Serial::_getc() +{ // Mutex is already held return _base_getc(); } -int Serial::_putc(int c) { +int Serial::_putc(int c) +{ // Mutex is already held return _base_putc(c); } -void Serial::lock() { +void Serial::lock() +{ _mutex.lock(); } -void Serial::unlock() { +void Serial::unlock() +{ _mutex.unlock(); } diff --git a/drivers/Serial.h b/drivers/Serial.h index 549943a47c0..11e237bffa4 100644 --- a/drivers/Serial.h +++ b/drivers/Serial.h @@ -68,7 +68,7 @@ class Serial : public SerialBase, public Stream, private NonCopyable { * @note * Either tx or rx may be specified as NC if unused */ - Serial(PinName tx, PinName rx, const char *name=NULL, int baud = MBED_CONF_PLATFORM_DEFAULT_SERIAL_BAUD_RATE); + Serial(PinName tx, PinName rx, const char *name = NULL, int baud = MBED_CONF_PLATFORM_DEFAULT_SERIAL_BAUD_RATE); /** Create a Serial port, connected to the specified transmit and receive pins, with the specified baud diff --git a/drivers/SerialBase.cpp b/drivers/SerialBase.cpp index ba5f9db3f25..b3f2399ac3e 100644 --- a/drivers/SerialBase.cpp +++ b/drivers/SerialBase.cpp @@ -24,11 +24,12 @@ namespace mbed { SerialBase::SerialBase(PinName tx, PinName rx, int baud) : #if DEVICE_SERIAL_ASYNCH - _thunk_irq(this), _tx_usage(DMA_USAGE_NEVER), - _rx_usage(DMA_USAGE_NEVER), _tx_callback(NULL), - _rx_callback(NULL), + _thunk_irq(this), _tx_usage(DMA_USAGE_NEVER), + _rx_usage(DMA_USAGE_NEVER), _tx_callback(NULL), + _rx_callback(NULL), #endif - _serial(), _baud(baud) { + _serial(), _baud(baud) +{ // No lock needed in the constructor for (size_t i = 0; i < sizeof _irq / sizeof _irq[0]; i++) { @@ -40,20 +41,23 @@ SerialBase::SerialBase(PinName tx, PinName rx, int baud) : serial_irq_handler(&_serial, SerialBase::_irq_handler, (uint32_t)this); } -void SerialBase::baud(int baudrate) { +void SerialBase::baud(int baudrate) +{ lock(); serial_baud(&_serial, baudrate); _baud = baudrate; unlock(); } -void SerialBase::format(int bits, Parity parity, int stop_bits) { +void SerialBase::format(int bits, Parity parity, int stop_bits) +{ lock(); serial_format(&_serial, bits, (SerialParity)parity, stop_bits); unlock(); } -int SerialBase::readable() { +int SerialBase::readable() +{ lock(); int ret = serial_readable(&_serial); unlock(); @@ -61,14 +65,16 @@ int SerialBase::readable() { } -int SerialBase::writeable() { +int SerialBase::writeable() +{ lock(); int ret = serial_writable(&_serial); unlock(); return ret; } -void SerialBase::attach(Callback func, IrqType type) { +void SerialBase::attach(Callback func, IrqType type) +{ lock(); // Disable interrupts when attaching interrupt handler core_util_critical_section_enter(); @@ -76,14 +82,14 @@ void SerialBase::attach(Callback func, IrqType type) { // lock deep sleep only the first time if (!_irq[type]) { sleep_manager_lock_deep_sleep(); - } + } _irq[type] = func; serial_irq_set(&_serial, (SerialIrq)type, 1); } else { // unlock deep sleep only the first time if (_irq[type]) { sleep_manager_unlock_deep_sleep(); - } + } _irq[type] = NULL; serial_irq_set(&_serial, (SerialIrq)type, 0); } @@ -91,45 +97,51 @@ void SerialBase::attach(Callback func, IrqType type) { unlock(); } -void SerialBase::_irq_handler(uint32_t id, SerialIrq irq_type) { - SerialBase *handler = (SerialBase*)id; +void SerialBase::_irq_handler(uint32_t id, SerialIrq irq_type) +{ + SerialBase *handler = (SerialBase *)id; if (handler->_irq[irq_type]) { handler->_irq[irq_type](); } } -int SerialBase::_base_getc() { +int SerialBase::_base_getc() +{ // Mutex is already held return serial_getc(&_serial); } -int SerialBase::_base_putc(int c) { +int SerialBase::_base_putc(int c) +{ // Mutex is already held serial_putc(&_serial, c); return c; } -void SerialBase::send_break() { +void SerialBase::send_break() +{ lock(); - // Wait for 1.5 frames before clearing the break condition - // This will have different effects on our platforms, but should - // ensure that we keep the break active for at least one frame. - // We consider a full frame (1 start bit + 8 data bits bits + - // 1 parity bit + 2 stop bits = 12 bits) for computation. - // One bit time (in us) = 1000000/_baud - // Twelve bits: 12000000/baud delay - // 1.5 frames: 18000000/baud delay - serial_break_set(&_serial); - wait_us(18000000/_baud); - serial_break_clear(&_serial); - unlock(); + // Wait for 1.5 frames before clearing the break condition + // This will have different effects on our platforms, but should + // ensure that we keep the break active for at least one frame. + // We consider a full frame (1 start bit + 8 data bits bits + + // 1 parity bit + 2 stop bits = 12 bits) for computation. + // One bit time (in us) = 1000000/_baud + // Twelve bits: 12000000/baud delay + // 1.5 frames: 18000000/baud delay + serial_break_set(&_serial); + wait_us(18000000 / _baud); + serial_break_clear(&_serial); + unlock(); } -void SerialBase::lock() { +void SerialBase::lock() +{ // Stub } -void SerialBase:: unlock() { +void SerialBase:: unlock() +{ // Stub } @@ -144,10 +156,11 @@ SerialBase::~SerialBase() } #if DEVICE_SERIAL_FC -void SerialBase::set_flow_control(Flow type, PinName flow1, PinName flow2) { +void SerialBase::set_flow_control(Flow type, PinName flow1, PinName flow2) +{ lock(); FlowControl flow_type = (FlowControl)type; - switch(type) { + switch (type) { case RTS: serial_set_flow_control(&_serial, flow_type, flow1, NC); break; @@ -170,7 +183,7 @@ void SerialBase::set_flow_control(Flow type, PinName flow1, PinName flow2) { #if DEVICE_SERIAL_ASYNCH -int SerialBase::write(const uint8_t *buffer, int length, const event_callback_t& callback, int event) +int SerialBase::write(const uint8_t *buffer, int length, const event_callback_t &callback, int event) { if (serial_tx_active(&_serial)) { return -1; // transaction ongoing @@ -179,7 +192,7 @@ int SerialBase::write(const uint8_t *buffer, int length, const event_callback_t& return 0; } -int SerialBase::write(const uint16_t *buffer, int length, const event_callback_t& callback, int event) +int SerialBase::write(const uint16_t *buffer, int length, const event_callback_t &callback, int event) { if (serial_tx_active(&_serial)) { return -1; // transaction ongoing @@ -188,7 +201,7 @@ int SerialBase::write(const uint16_t *buffer, int length, const event_callback_t return 0; } -void SerialBase::start_write(const void *buffer, int buffer_size, char buffer_width, const event_callback_t& callback, int event) +void SerialBase::start_write(const void *buffer, int buffer_size, char buffer_width, const event_callback_t &callback, int event) { _tx_callback = callback; @@ -235,27 +248,27 @@ int SerialBase::set_dma_usage_rx(DMAUsage usage) return 0; } -int SerialBase::read(uint8_t *buffer, int length, const event_callback_t& callback, int event, unsigned char char_match) +int SerialBase::read(uint8_t *buffer, int length, const event_callback_t &callback, int event, unsigned char char_match) { if (serial_rx_active(&_serial)) { return -1; // transaction ongoing } - start_read((void*)buffer, length, 8, callback, event, char_match); + start_read((void *)buffer, length, 8, callback, event, char_match); return 0; } -int SerialBase::read(uint16_t *buffer, int length, const event_callback_t& callback, int event, unsigned char char_match) +int SerialBase::read(uint16_t *buffer, int length, const event_callback_t &callback, int event, unsigned char char_match) { if (serial_rx_active(&_serial)) { return -1; // transaction ongoing } - start_read((void*)buffer, length, 16, callback, event, char_match); + start_read((void *)buffer, length, 16, callback, event, char_match); return 0; } -void SerialBase::start_read(void *buffer, int buffer_size, char buffer_width, const event_callback_t& callback, int event, unsigned char char_match) +void SerialBase::start_read(void *buffer, int buffer_size, char buffer_width, const event_callback_t &callback, int event, unsigned char char_match) { _rx_callback = callback; _thunk_irq.callback(&SerialBase::interrupt_handler_asynch); diff --git a/drivers/SerialBase.h b/drivers/SerialBase.h index faf29a06998..fffd51b2397 100644 --- a/drivers/SerialBase.h +++ b/drivers/SerialBase.h @@ -76,7 +76,7 @@ class SerialBase : private NonCopyable { * @param parity The parity used (SerialBase::None, SerialBase::Odd, SerialBase::Even, SerialBase::Forced1, SerialBase::Forced0; default = SerialBase::None) * @param stop_bits The number of stop bits (1 or 2; default = 1) */ - void format(int bits=8, Parity parity=SerialBase::None, int stop_bits=1); + void format(int bits = 8, Parity parity = SerialBase::None, int stop_bits = 1); /** Determine if there is a character available to read * @@ -99,7 +99,7 @@ class SerialBase : private NonCopyable { * @param func A pointer to a void function, or 0 to set as none * @param type Which serial interrupt to attach the member function to (Seriall::RxIrq for receive, TxIrq for transmit buffer empty) */ - void attach(Callback func, IrqType type=RxIrq); + void attach(Callback func, IrqType type = RxIrq); /** Attach a member function to call whenever a serial interrupt is generated * @@ -112,9 +112,10 @@ class SerialBase : private NonCopyable { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "The attach function does not support cv-qualifiers. Replaced by " - "attach(callback(obj, method), type).") - void attach(T *obj, void (T::*method)(), IrqType type=RxIrq) { + "The attach function does not support cv-qualifiers. Replaced by " + "attach(callback(obj, method), type).") + void attach(T *obj, void (T::*method)(), IrqType type = RxIrq) + { attach(callback(obj, method), type); } @@ -129,9 +130,10 @@ class SerialBase : private NonCopyable { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "The attach function does not support cv-qualifiers. Replaced by " - "attach(callback(obj, method), type).") - void attach(T *obj, void (*method)(T*), IrqType type=RxIrq) { + "The attach function does not support cv-qualifiers. Replaced by " + "attach(callback(obj, method), type).") + void attach(T *obj, void (*method)(T *), IrqType type = RxIrq) + { attach(callback(obj, method), type); } @@ -158,7 +160,7 @@ class SerialBase : private NonCopyable { * @param flow1 the first flow control pin (RTS for RTS or RTSCTS, CTS for CTS) * @param flow2 the second flow control pin (CTS for RTSCTS) */ - void set_flow_control(Flow type, PinName flow1=NC, PinName flow2=NC); + void set_flow_control(Flow type, PinName flow1 = NC, PinName flow2 = NC); #endif static void _irq_handler(uint32_t id, SerialIrq irq_type); @@ -168,24 +170,24 @@ class SerialBase : private NonCopyable { /** Begin asynchronous write using 8bit buffer. The completition invokes registered TX event callback * * This function locks the deep sleep until any event has occured - * + * * @param buffer The buffer where received data will be stored * @param length The buffer length in bytes * @param callback The event callback function * @param event The logical OR of TX events */ - int write(const uint8_t *buffer, int length, const event_callback_t& callback, int event = SERIAL_EVENT_TX_COMPLETE); + int write(const uint8_t *buffer, int length, const event_callback_t &callback, int event = SERIAL_EVENT_TX_COMPLETE); /** Begin asynchronous write using 16bit buffer. The completition invokes registered TX event callback * * This function locks the deep sleep until any event has occured - * + * * @param buffer The buffer where received data will be stored * @param length The buffer length in bytes * @param callback The event callback function * @param event The logical OR of TX events */ - int write(const uint16_t *buffer, int length, const event_callback_t& callback, int event = SERIAL_EVENT_TX_COMPLETE); + int write(const uint16_t *buffer, int length, const event_callback_t &callback, int event = SERIAL_EVENT_TX_COMPLETE); /** Abort the on-going write transfer */ @@ -194,26 +196,26 @@ class SerialBase : private NonCopyable { /** Begin asynchronous reading using 8bit buffer. The completition invokes registred RX event callback. * * This function locks the deep sleep until any event has occured - * + * * @param buffer The buffer where received data will be stored * @param length The buffer length in bytes * @param callback The event callback function * @param event The logical OR of RX events * @param char_match The matching character */ - int read(uint8_t *buffer, int length, const event_callback_t& callback, int event = SERIAL_EVENT_RX_COMPLETE, unsigned char char_match = SERIAL_RESERVED_CHAR_MATCH); + int read(uint8_t *buffer, int length, const event_callback_t &callback, int event = SERIAL_EVENT_RX_COMPLETE, unsigned char char_match = SERIAL_RESERVED_CHAR_MATCH); /** Begin asynchronous reading using 16bit buffer. The completition invokes registred RX event callback. * * This function locks the deep sleep until any event has occured - * + * * @param buffer The buffer where received data will be stored * @param length The buffer length in bytes * @param callback The event callback function * @param event The logical OR of RX events * @param char_match The matching character */ - int read(uint16_t *buffer, int length, const event_callback_t& callback, int event = SERIAL_EVENT_RX_COMPLETE, unsigned char char_match = SERIAL_RESERVED_CHAR_MATCH); + int read(uint16_t *buffer, int length, const event_callback_t &callback, int event = SERIAL_EVENT_RX_COMPLETE, unsigned char char_match = SERIAL_RESERVED_CHAR_MATCH); /** Abort the on-going read transfer */ @@ -234,8 +236,8 @@ class SerialBase : private NonCopyable { int set_dma_usage_rx(DMAUsage usage); protected: - void start_read(void *buffer, int buffer_size, char buffer_width, const event_callback_t& callback, int event, unsigned char char_match); - void start_write(const void *buffer, int buffer_size, char buffer_width, const event_callback_t& callback, int event); + void start_read(void *buffer, int buffer_size, char buffer_width, const event_callback_t &callback, int event, unsigned char char_match); + void start_write(const void *buffer, int buffer_size, char buffer_width, const event_callback_t &callback, int event); void interrupt_handler_asynch(void); #endif diff --git a/drivers/Ticker.cpp b/drivers/Ticker.cpp index c2589c0d808..efa3efb9c00 100644 --- a/drivers/Ticker.cpp +++ b/drivers/Ticker.cpp @@ -22,11 +22,12 @@ namespace mbed { -void Ticker::detach() { +void Ticker::detach() +{ core_util_critical_section_enter(); remove(); // unlocked only if we were attached (we locked it) and this is not low power ticker - if(_function && _lock_deepsleep) { + if (_function && _lock_deepsleep) { sleep_manager_unlock_deep_sleep(); } @@ -34,7 +35,8 @@ void Ticker::detach() { core_util_critical_section_exit(); } -void Ticker::setup(us_timestamp_t t) { +void Ticker::setup(us_timestamp_t t) +{ core_util_critical_section_enter(); remove(); _delay = t; @@ -42,7 +44,8 @@ void Ticker::setup(us_timestamp_t t) { core_util_critical_section_exit(); } -void Ticker::handler() { +void Ticker::handler() +{ insert_absolute(event.timestamp + _delay); if (_function) { _function(); diff --git a/drivers/Ticker.h b/drivers/Ticker.h index 646f8261c8c..e3c5b5dd04a 100644 --- a/drivers/Ticker.h +++ b/drivers/Ticker.h @@ -66,11 +66,13 @@ namespace mbed { class Ticker : public TimerEvent, private NonCopyable { public: - Ticker() : TimerEvent(), _function(0), _lock_deepsleep(true) { + Ticker() : TimerEvent(), _function(0), _lock_deepsleep(true) + { } // When low power ticker is in use, then do not disable deep-sleep. - Ticker(const ticker_data_t *data) : TimerEvent(data), _function(0), _lock_deepsleep(true) { + Ticker(const ticker_data_t *data) : TimerEvent(data), _function(0), _lock_deepsleep(true) + { #if DEVICE_LOWPOWERTIMER _lock_deepsleep = (data != get_lp_ticker_data()); #endif @@ -81,7 +83,8 @@ class Ticker : public TimerEvent, private NonCopyable { * @param func pointer to the function to be called * @param t the time between calls in seconds */ - void attach(Callback func, float t) { + void attach(Callback func, float t) + { attach_us(func, t * 1000000.0f); } @@ -96,9 +99,10 @@ class Ticker : public TimerEvent, private NonCopyable { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "The attach function does not support cv-qualifiers. Replaced by " - "attach(callback(obj, method), t).") - void attach(T *obj, M method, float t) { + "The attach function does not support cv-qualifiers. Replaced by " + "attach(callback(obj, method), t).") + void attach(T *obj, M method, float t) + { attach(callback(obj, method), t); } @@ -112,10 +116,11 @@ class Ticker : public TimerEvent, private NonCopyable { * for threads scheduling. * */ - void attach_us(Callback func, us_timestamp_t t) { + void attach_us(Callback func, us_timestamp_t t) + { core_util_critical_section_enter(); // lock only for the initial callback setup and this is not low power ticker - if(!_function && _lock_deepsleep) { + if (!_function && _lock_deepsleep) { sleep_manager_lock_deep_sleep(); } _function = func; @@ -134,13 +139,15 @@ class Ticker : public TimerEvent, private NonCopyable { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "The attach_us function does not support cv-qualifiers. Replaced by " - "attach_us(callback(obj, method), t).") - void attach_us(T *obj, M method, us_timestamp_t t) { + "The attach_us function does not support cv-qualifiers. Replaced by " + "attach_us(callback(obj, method), t).") + void attach_us(T *obj, M method, us_timestamp_t t) + { attach_us(Callback(obj, method), t); } - virtual ~Ticker() { + virtual ~Ticker() + { detach(); } diff --git a/drivers/Timeout.cpp b/drivers/Timeout.cpp index 40c7d9f0533..210d494bf68 100644 --- a/drivers/Timeout.cpp +++ b/drivers/Timeout.cpp @@ -17,7 +17,8 @@ namespace mbed { -void Timeout::handler() { +void Timeout::handler() +{ _function.call(); } diff --git a/drivers/Timer.cpp b/drivers/Timer.cpp index f523974e6b4..feac86ed500 100644 --- a/drivers/Timer.cpp +++ b/drivers/Timer.cpp @@ -21,21 +21,24 @@ namespace mbed { -Timer::Timer() : _running(), _start(), _time(), _ticker_data(get_us_ticker_data()), _lock_deepsleep(true) { +Timer::Timer() : _running(), _start(), _time(), _ticker_data(get_us_ticker_data()), _lock_deepsleep(true) +{ reset(); } -Timer::Timer(const ticker_data_t *data) : _running(), _start(), _time(), _ticker_data(data), _lock_deepsleep(true) { +Timer::Timer(const ticker_data_t *data) : _running(), _start(), _time(), _ticker_data(data), _lock_deepsleep(true) +{ reset(); #if DEVICE_LOWPOWERTIMER _lock_deepsleep = (data != get_lp_ticker_data()); #endif } -Timer::~Timer() { +Timer::~Timer() +{ core_util_critical_section_enter(); if (_running) { - if(_lock_deepsleep) { + if (_lock_deepsleep) { sleep_manager_unlock_deep_sleep(); } } @@ -43,10 +46,11 @@ Timer::~Timer() { core_util_critical_section_exit(); } -void Timer::start() { +void Timer::start() +{ core_util_critical_section_enter(); if (!_running) { - if(_lock_deepsleep) { + if (_lock_deepsleep) { sleep_manager_lock_deep_sleep(); } _start = ticker_read_us(_ticker_data); @@ -55,11 +59,12 @@ void Timer::start() { core_util_critical_section_exit(); } -void Timer::stop() { +void Timer::stop() +{ core_util_critical_section_enter(); _time += slicetime(); if (_running) { - if(_lock_deepsleep) { + if (_lock_deepsleep) { sleep_manager_unlock_deep_sleep(); } } @@ -67,26 +72,31 @@ void Timer::stop() { core_util_critical_section_exit(); } -int Timer::read_us() { +int Timer::read_us() +{ return read_high_resolution_us(); } -float Timer::read() { +float Timer::read() +{ return (float)read_us() / 1000000.0f; } -int Timer::read_ms() { +int Timer::read_ms() +{ return read_high_resolution_us() / 1000; } -us_timestamp_t Timer::read_high_resolution_us() { +us_timestamp_t Timer::read_high_resolution_us() +{ core_util_critical_section_enter(); us_timestamp_t time = _time + slicetime(); core_util_critical_section_exit(); return time; } -us_timestamp_t Timer::slicetime() { +us_timestamp_t Timer::slicetime() +{ us_timestamp_t ret = 0; core_util_critical_section_enter(); if (_running) { @@ -96,14 +106,16 @@ us_timestamp_t Timer::slicetime() { return ret; } -void Timer::reset() { +void Timer::reset() +{ core_util_critical_section_enter(); _start = ticker_read_us(_ticker_data); _time = 0; core_util_critical_section_exit(); } -Timer::operator float() { +Timer::operator float() +{ return read(); } diff --git a/drivers/TimerEvent.cpp b/drivers/TimerEvent.cpp index d7a7c1c2a44..ddf495f681a 100644 --- a/drivers/TimerEvent.cpp +++ b/drivers/TimerEvent.cpp @@ -22,33 +22,40 @@ namespace mbed { -TimerEvent::TimerEvent() : event(), _ticker_data(get_us_ticker_data()) { +TimerEvent::TimerEvent() : event(), _ticker_data(get_us_ticker_data()) +{ ticker_set_handler(_ticker_data, (&TimerEvent::irq)); } -TimerEvent::TimerEvent(const ticker_data_t *data) : event(), _ticker_data(data) { +TimerEvent::TimerEvent(const ticker_data_t *data) : event(), _ticker_data(data) +{ ticker_set_handler(_ticker_data, (&TimerEvent::irq)); } -void TimerEvent::irq(uint32_t id) { - TimerEvent *timer_event = (TimerEvent*)id; +void TimerEvent::irq(uint32_t id) +{ + TimerEvent *timer_event = (TimerEvent *)id; timer_event->handler(); } -TimerEvent::~TimerEvent() { +TimerEvent::~TimerEvent() +{ remove(); } // insert in to linked list -void TimerEvent::insert(timestamp_t timestamp) { +void TimerEvent::insert(timestamp_t timestamp) +{ ticker_insert_event(_ticker_data, &event, timestamp, (uint32_t)this); } -void TimerEvent::insert_absolute(us_timestamp_t timestamp) { +void TimerEvent::insert_absolute(us_timestamp_t timestamp) +{ ticker_insert_event_us(_ticker_data, &event, timestamp, (uint32_t)this); } -void TimerEvent::remove() { +void TimerEvent::remove() +{ ticker_remove_event(_ticker_data, &event); } diff --git a/drivers/UARTSerial.cpp b/drivers/UARTSerial.cpp index 2c590c12769..8bd39e30166 100644 --- a/drivers/UARTSerial.cpp +++ b/drivers/UARTSerial.cpp @@ -29,11 +29,11 @@ namespace mbed { UARTSerial::UARTSerial(PinName tx, PinName rx, int baud) : - SerialBase(tx, rx, baud), - _blocking(true), - _tx_irq_enabled(false), - _rx_irq_enabled(true), - _dcd_irq(NULL) + SerialBase(tx, rx, baud), + _blocking(true), + _tx_irq_enabled(false), + _rx_irq_enabled(true), + _dcd_irq(NULL) { /* Attatch IRQ routines to the serial device. */ SerialBase::attach(callback(this, &UARTSerial::rx_irq), RxIrq); @@ -56,7 +56,7 @@ void UARTSerial::set_baud(int baud) void UARTSerial::set_data_carrier_detect(PinName dcd_pin, bool active_high) { - delete _dcd_irq; + delete _dcd_irq; _dcd_irq = NULL; if (dcd_pin != NC) { @@ -121,7 +121,8 @@ int UARTSerial::sync() return 0; } -void UARTSerial::sigio(Callback func) { +void UARTSerial::sigio(Callback func) +{ core_util_critical_section_enter(); _sigio_cb = func; if (_sigio_cb) { @@ -133,7 +134,7 @@ void UARTSerial::sigio(Callback func) { core_util_critical_section_exit(); } -ssize_t UARTSerial::write(const void* buffer, size_t length) +ssize_t UARTSerial::write(const void *buffer, size_t length) { size_t data_written = 0; const char *buf_ptr = static_cast(buffer); @@ -178,10 +179,10 @@ ssize_t UARTSerial::write(const void* buffer, size_t length) api_unlock(); - return data_written != 0 ? (ssize_t) data_written : (ssize_t) -EAGAIN; + return data_written != 0 ? (ssize_t) data_written : (ssize_t) - EAGAIN; } -ssize_t UARTSerial::read(void* buffer, size_t length) +ssize_t UARTSerial::read(void *buffer, size_t length) { size_t data_read = 0; @@ -235,7 +236,8 @@ void UARTSerial::wake() } } -short UARTSerial::poll(short events) const { +short UARTSerial::poll(short events) const +{ short revents = 0; /* Check the Circular Buffer if space available for writing out */ diff --git a/drivers/UARTSerial.h b/drivers/UARTSerial.h index 026215b36d1..e6573f7a3e2 100644 --- a/drivers/UARTSerial.h +++ b/drivers/UARTSerial.h @@ -42,7 +42,7 @@ namespace mbed { /** \addtogroup drivers */ /** Class providing buffered UART communication functionality using separate circular buffer for send and receive channels - * + * * @ingroup drivers */ @@ -81,7 +81,7 @@ class UARTSerial : private SerialBase, public FileHandle, private NonCopyable { * @param f Function to execute when the event is dispatched */ template - Event(EventQueue *q, F f) { + Event(EventQueue *q, F f) + { _event = static_cast( - equeue_alloc(&q->_equeue, sizeof(struct event) + sizeof(F))); + equeue_alloc(&q->_equeue, sizeof(struct event) + sizeof(F))); if (_event) { _event->equeue = &q->_equeue; @@ -61,7 +62,7 @@ class Event { _event->post = &Event::event_post; _event->dtor = &Event::event_dtor; - new (_event+1) F(f); + new (_event + 1) F(f); _event->ref = 1; } @@ -69,7 +70,8 @@ class Event { /** Copy constructor for events */ - Event(const Event &e) { + Event(const Event &e) + { _event = 0; if (e._event) { _event = e._event; @@ -79,7 +81,8 @@ class Event { /** Assignment operator for events */ - Event &operator=(const Event &that) { + Event &operator=(const Event &that) + { if (this != &that) { this->~Event(); new (this) Event(that); @@ -90,7 +93,8 @@ class Event { /** Destructor for events */ - ~Event() { + ~Event() + { if (_event) { _event->ref -= 1; if (_event->ref == 0) { @@ -104,7 +108,8 @@ class Event { * * @param delay Millisecond delay before dispatching the event */ - void delay(int delay) { + void delay(int delay) + { if (_event) { _event->delay = delay; } @@ -114,7 +119,8 @@ class Event { * * @param period Millisecond period for repeatedly dispatching an event */ - void period(int period) { + void period(int period) + { if (_event) { _event->period = period; } @@ -132,7 +138,8 @@ class Event { * be passed to EventQueue::cancel, or an id of 0 if * there is not enough memory to allocate the event. */ - int post() const { + int post() const + { if (!_event) { return 0; } @@ -144,7 +151,8 @@ class Event { /** Posts an event onto the underlying event queue, returning void * */ - void call() const { + void call() const + { MBED_UNUSED int id = post(); MBED_ASSERT(id); } @@ -152,7 +160,8 @@ class Event { /** Posts an event onto the underlying event queue, returning void * */ - void operator()() const { + void operator()() const + { return call(); } @@ -160,8 +169,9 @@ class Event { * * @param func Event to call passed as a void pointer */ - static void thunk(void *func) { - return static_cast(func)->call(); + static void thunk(void *func) + { + return static_cast(func)->call(); } /** Cancels the most recently posted event @@ -175,7 +185,8 @@ class Event { * function does not garuntee that the event will not execute after it * returns, as the event may have already begun executing. */ - void cancel() const { + void cancel() const + { if (_event) { equeue_cancel(_event->equeue, _event->id); } @@ -198,14 +209,15 @@ class Event { // Event attributes template - static int event_post(struct event *e) { + static int event_post(struct event *e) + { typedef EventQueue::context00 C; void *p = equeue_alloc(e->equeue, sizeof(C)); if (!p) { return 0; } - new (p) C(*(F*)(e + 1)); + new (p) C(*(F *)(e + 1)); equeue_event_delay(p, e->delay); equeue_event_period(p, e->period); equeue_event_dtor(p, &EventQueue::function_dtor); @@ -213,8 +225,9 @@ class Event { } template - static void event_dtor(struct event *e) { - ((F*)(e + 1))->~F(); + static void event_dtor(struct event *e) + { + ((F *)(e + 1))->~F(); } public: @@ -227,7 +240,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0) { + Event(EventQueue *q, F f, C0 c0) + { new (this) Event(q, EventQueue::context10(f, c0)); } @@ -240,7 +254,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1) { + Event(EventQueue *q, F f, C0 c0, C1 c1) + { new (this) Event(q, EventQueue::context20(f, c0, c1)); } @@ -253,7 +268,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2) { + Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2) + { new (this) Event(q, EventQueue::context30(f, c0, c1, c2)); } @@ -266,7 +282,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3) { + Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3) + { new (this) Event(q, EventQueue::context40(f, c0, c1, c2, c3)); } @@ -279,7 +296,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { + Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) + { new (this) Event(q, EventQueue::context50(f, c0, c1, c2, c3, c4)); } @@ -287,7 +305,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0), B0 b0) { + Event(EventQueue *q, T *obj, R(T::*method)(B0), B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -295,7 +314,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0) const, B0 b0) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0) const, B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -303,7 +323,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0) volatile, B0 b0) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0) volatile, B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -311,7 +332,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0) const volatile, B0 b0) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0) const volatile, B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -319,7 +341,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1), B0 b0, B1 b1) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1), B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -327,7 +350,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1) const, B0 b0, B1 b1) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1) const, B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -335,7 +359,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1) volatile, B0 b0, B1 b1) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1) volatile, B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -343,7 +368,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1) const volatile, B0 b0, B1 b1) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1) const volatile, B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -351,7 +377,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, B2), B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, B2), B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -359,7 +386,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, B2) const, B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, B2) const, B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -367,7 +395,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, B2) volatile, B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, B2) volatile, B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -375,7 +404,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, B2) const volatile, B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, B2) const volatile, B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -383,7 +413,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, B2, B3), B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, B2, B3), B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -391,7 +422,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, B2, B3) const, B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, B2, B3) const, B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -399,7 +431,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, B2, B3) volatile, B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, B2, B3) volatile, B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -407,7 +440,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, B2, B3) const volatile, B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, B2, B3) const volatile, B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -415,7 +449,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, B2, B3, B4), B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, B2, B3, B4), B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } @@ -423,7 +458,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, B2, B3, B4) const, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, B2, B3, B4) const, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } @@ -431,7 +467,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4) volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4) volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } @@ -439,7 +476,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4) const volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4) const volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } }; @@ -462,9 +500,10 @@ class Event { * @param f Function to execute when the event is dispatched */ template - Event(EventQueue *q, F f) { + Event(EventQueue *q, F f) + { _event = static_cast( - equeue_alloc(&q->_equeue, sizeof(struct event) + sizeof(F))); + equeue_alloc(&q->_equeue, sizeof(struct event) + sizeof(F))); if (_event) { _event->equeue = &q->_equeue; @@ -475,7 +514,7 @@ class Event { _event->post = &Event::event_post; _event->dtor = &Event::event_dtor; - new (_event+1) F(f); + new (_event + 1) F(f); _event->ref = 1; } @@ -483,7 +522,8 @@ class Event { /** Copy constructor for events */ - Event(const Event &e) { + Event(const Event &e) + { _event = 0; if (e._event) { _event = e._event; @@ -493,7 +533,8 @@ class Event { /** Assignment operator for events */ - Event &operator=(const Event &that) { + Event &operator=(const Event &that) + { if (this != &that) { this->~Event(); new (this) Event(that); @@ -504,7 +545,8 @@ class Event { /** Destructor for events */ - ~Event() { + ~Event() + { if (_event) { _event->ref -= 1; if (_event->ref == 0) { @@ -518,7 +560,8 @@ class Event { * * @param delay Millisecond delay before dispatching the event */ - void delay(int delay) { + void delay(int delay) + { if (_event) { _event->delay = delay; } @@ -528,7 +571,8 @@ class Event { * * @param period Millisecond period for repeatedly dispatching an event */ - void period(int period) { + void period(int period) + { if (_event) { _event->period = period; } @@ -547,7 +591,8 @@ class Event { * be passed to EventQueue::cancel, or an id of 0 if * there is not enough memory to allocate the event. */ - int post(A0 a0) const { + int post(A0 a0) const + { if (!_event) { return 0; } @@ -560,7 +605,8 @@ class Event { * * @param a0 Argument to pass to the event */ - void call(A0 a0) const { + void call(A0 a0) const + { MBED_UNUSED int id = post(a0); MBED_ASSERT(id); } @@ -569,7 +615,8 @@ class Event { * * @param a0 Argument to pass to the event */ - void operator()(A0 a0) const { + void operator()(A0 a0) const + { return call(a0); } @@ -578,8 +625,9 @@ class Event { * @param func Event to call passed as a void pointer * @param a0 Argument to pass to the event */ - static void thunk(void *func, A0 a0) { - return static_cast(func)->call(a0); + static void thunk(void *func, A0 a0) + { + return static_cast(func)->call(a0); } /** Cancels the most recently posted event @@ -593,7 +641,8 @@ class Event { * function does not garuntee that the event will not execute after it * returns, as the event may have already begun executing. */ - void cancel() const { + void cancel() const + { if (_event) { equeue_cancel(_event->equeue, _event->id); } @@ -616,14 +665,15 @@ class Event { // Event attributes template - static int event_post(struct event *e, A0 a0) { + static int event_post(struct event *e, A0 a0) + { typedef EventQueue::context10 C; void *p = equeue_alloc(e->equeue, sizeof(C)); if (!p) { return 0; } - new (p) C(*(F*)(e + 1), a0); + new (p) C(*(F *)(e + 1), a0); equeue_event_delay(p, e->delay); equeue_event_period(p, e->period); equeue_event_dtor(p, &EventQueue::function_dtor); @@ -631,8 +681,9 @@ class Event { } template - static void event_dtor(struct event *e) { - ((F*)(e + 1))->~F(); + static void event_dtor(struct event *e) + { + ((F *)(e + 1))->~F(); } public: @@ -645,7 +696,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0) { + Event(EventQueue *q, F f, C0 c0) + { new (this) Event(q, EventQueue::context11(f, c0)); } @@ -658,7 +710,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1) { + Event(EventQueue *q, F f, C0 c0, C1 c1) + { new (this) Event(q, EventQueue::context21(f, c0, c1)); } @@ -671,7 +724,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2) { + Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2) + { new (this) Event(q, EventQueue::context31(f, c0, c1, c2)); } @@ -684,7 +738,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3) { + Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3) + { new (this) Event(q, EventQueue::context41(f, c0, c1, c2, c3)); } @@ -697,7 +752,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { + Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) + { new (this) Event(q, EventQueue::context51(f, c0, c1, c2, c3, c4)); } @@ -705,7 +761,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, A0), B0 b0) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, A0), B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -713,7 +770,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, A0) const, B0 b0) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, A0) const, B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -721,7 +779,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, A0) volatile, B0 b0) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, A0) volatile, B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -729,7 +788,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, A0) const volatile, B0 b0) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, A0) const volatile, B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -737,7 +797,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, A0), B0 b0, B1 b1) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, A0), B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -745,7 +806,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, A0) const, B0 b0, B1 b1) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, A0) const, B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -753,7 +815,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, A0) volatile, B0 b0, B1 b1) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, A0) volatile, B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -761,7 +824,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, A0) const volatile, B0 b0, B1 b1) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, A0) const volatile, B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -769,7 +833,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, B2, A0), B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, B2, A0), B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -777,7 +842,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, B2, A0) const, B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, B2, A0) const, B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -785,7 +851,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, B2, A0) volatile, B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, B2, A0) volatile, B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -793,7 +860,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, B2, A0) const volatile, B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, B2, A0) const volatile, B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -801,7 +869,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, B2, B3, A0), B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, B2, B3, A0), B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -809,7 +878,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, B2, B3, A0) const, B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, B2, B3, A0) const, B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -817,7 +887,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0) volatile, B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0) volatile, B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -825,7 +896,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0) const volatile, B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0) const volatile, B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -833,7 +905,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0), B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0), B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } @@ -841,7 +914,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0) const, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0) const, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } @@ -849,7 +923,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0) volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0) volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } @@ -857,7 +932,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0) const volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0) const volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } }; @@ -880,9 +956,10 @@ class Event { * @param f Function to execute when the event is dispatched */ template - Event(EventQueue *q, F f) { + Event(EventQueue *q, F f) + { _event = static_cast( - equeue_alloc(&q->_equeue, sizeof(struct event) + sizeof(F))); + equeue_alloc(&q->_equeue, sizeof(struct event) + sizeof(F))); if (_event) { _event->equeue = &q->_equeue; @@ -893,7 +970,7 @@ class Event { _event->post = &Event::event_post; _event->dtor = &Event::event_dtor; - new (_event+1) F(f); + new (_event + 1) F(f); _event->ref = 1; } @@ -901,7 +978,8 @@ class Event { /** Copy constructor for events */ - Event(const Event &e) { + Event(const Event &e) + { _event = 0; if (e._event) { _event = e._event; @@ -911,7 +989,8 @@ class Event { /** Assignment operator for events */ - Event &operator=(const Event &that) { + Event &operator=(const Event &that) + { if (this != &that) { this->~Event(); new (this) Event(that); @@ -922,7 +1001,8 @@ class Event { /** Destructor for events */ - ~Event() { + ~Event() + { if (_event) { _event->ref -= 1; if (_event->ref == 0) { @@ -936,7 +1016,8 @@ class Event { * * @param delay Millisecond delay before dispatching the event */ - void delay(int delay) { + void delay(int delay) + { if (_event) { _event->delay = delay; } @@ -946,7 +1027,8 @@ class Event { * * @param period Millisecond period for repeatedly dispatching an event */ - void period(int period) { + void period(int period) + { if (_event) { _event->period = period; } @@ -965,7 +1047,8 @@ class Event { * be passed to EventQueue::cancel, or an id of 0 if * there is not enough memory to allocate the event. */ - int post(A0 a0, A1 a1) const { + int post(A0 a0, A1 a1) const + { if (!_event) { return 0; } @@ -978,7 +1061,8 @@ class Event { * * @param a0,a1 Arguments to pass to the event */ - void call(A0 a0, A1 a1) const { + void call(A0 a0, A1 a1) const + { MBED_UNUSED int id = post(a0, a1); MBED_ASSERT(id); } @@ -987,7 +1071,8 @@ class Event { * * @param a0,a1 Arguments to pass to the event */ - void operator()(A0 a0, A1 a1) const { + void operator()(A0 a0, A1 a1) const + { return call(a0, a1); } @@ -996,8 +1081,9 @@ class Event { * @param func Event to call passed as a void pointer * @param a0,a1 Arguments to pass to the event */ - static void thunk(void *func, A0 a0, A1 a1) { - return static_cast(func)->call(a0, a1); + static void thunk(void *func, A0 a0, A1 a1) + { + return static_cast(func)->call(a0, a1); } /** Cancels the most recently posted event @@ -1011,7 +1097,8 @@ class Event { * function does not garuntee that the event will not execute after it * returns, as the event may have already begun executing. */ - void cancel() const { + void cancel() const + { if (_event) { equeue_cancel(_event->equeue, _event->id); } @@ -1034,14 +1121,15 @@ class Event { // Event attributes template - static int event_post(struct event *e, A0 a0, A1 a1) { + static int event_post(struct event *e, A0 a0, A1 a1) + { typedef EventQueue::context20 C; void *p = equeue_alloc(e->equeue, sizeof(C)); if (!p) { return 0; } - new (p) C(*(F*)(e + 1), a0, a1); + new (p) C(*(F *)(e + 1), a0, a1); equeue_event_delay(p, e->delay); equeue_event_period(p, e->period); equeue_event_dtor(p, &EventQueue::function_dtor); @@ -1049,8 +1137,9 @@ class Event { } template - static void event_dtor(struct event *e) { - ((F*)(e + 1))->~F(); + static void event_dtor(struct event *e) + { + ((F *)(e + 1))->~F(); } public: @@ -1063,7 +1152,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0) { + Event(EventQueue *q, F f, C0 c0) + { new (this) Event(q, EventQueue::context12(f, c0)); } @@ -1076,7 +1166,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1) { + Event(EventQueue *q, F f, C0 c0, C1 c1) + { new (this) Event(q, EventQueue::context22(f, c0, c1)); } @@ -1089,7 +1180,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2) { + Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2) + { new (this) Event(q, EventQueue::context32(f, c0, c1, c2)); } @@ -1102,7 +1194,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3) { + Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3) + { new (this) Event(q, EventQueue::context42(f, c0, c1, c2, c3)); } @@ -1115,7 +1208,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { + Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) + { new (this) Event(q, EventQueue::context52(f, c0, c1, c2, c3, c4)); } @@ -1123,7 +1217,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, A0, A1), B0 b0) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, A0, A1), B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -1131,7 +1226,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, A0, A1) const, B0 b0) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, A0, A1) const, B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -1139,7 +1235,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, A0, A1) volatile, B0 b0) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, A0, A1) volatile, B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -1147,7 +1244,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, A0, A1) const volatile, B0 b0) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, A0, A1) const volatile, B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -1155,7 +1253,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, A0, A1), B0 b0, B1 b1) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, A0, A1), B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -1163,7 +1262,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, A0, A1) const, B0 b0, B1 b1) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, A0, A1) const, B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -1171,7 +1271,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, A0, A1) volatile, B0 b0, B1 b1) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, A0, A1) volatile, B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -1179,7 +1280,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, A0, A1) const volatile, B0 b0, B1 b1) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, A0, A1) const volatile, B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -1187,7 +1289,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, B2, A0, A1), B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, B2, A0, A1), B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -1195,7 +1298,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, B2, A0, A1) const, B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, B2, A0, A1) const, B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -1203,7 +1307,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1) volatile, B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1) volatile, B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -1211,7 +1316,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1) const volatile, B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1) const volatile, B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -1219,7 +1325,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1), B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1), B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -1227,7 +1334,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1) const, B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1) const, B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -1235,7 +1343,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1) volatile, B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1) volatile, B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -1243,7 +1352,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1) const volatile, B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1) const volatile, B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -1251,7 +1361,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1), B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1), B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } @@ -1259,7 +1370,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1) const, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1) const, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } @@ -1267,7 +1379,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1) volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1) volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } @@ -1275,7 +1388,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1) const volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1) const volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } }; @@ -1298,9 +1412,10 @@ class Event { * @param f Function to execute when the event is dispatched */ template - Event(EventQueue *q, F f) { + Event(EventQueue *q, F f) + { _event = static_cast( - equeue_alloc(&q->_equeue, sizeof(struct event) + sizeof(F))); + equeue_alloc(&q->_equeue, sizeof(struct event) + sizeof(F))); if (_event) { _event->equeue = &q->_equeue; @@ -1311,7 +1426,7 @@ class Event { _event->post = &Event::event_post; _event->dtor = &Event::event_dtor; - new (_event+1) F(f); + new (_event + 1) F(f); _event->ref = 1; } @@ -1319,7 +1434,8 @@ class Event { /** Copy constructor for events */ - Event(const Event &e) { + Event(const Event &e) + { _event = 0; if (e._event) { _event = e._event; @@ -1329,7 +1445,8 @@ class Event { /** Assignment operator for events */ - Event &operator=(const Event &that) { + Event &operator=(const Event &that) + { if (this != &that) { this->~Event(); new (this) Event(that); @@ -1340,7 +1457,8 @@ class Event { /** Destructor for events */ - ~Event() { + ~Event() + { if (_event) { _event->ref -= 1; if (_event->ref == 0) { @@ -1354,7 +1472,8 @@ class Event { * * @param delay Millisecond delay before dispatching the event */ - void delay(int delay) { + void delay(int delay) + { if (_event) { _event->delay = delay; } @@ -1364,7 +1483,8 @@ class Event { * * @param period Millisecond period for repeatedly dispatching an event */ - void period(int period) { + void period(int period) + { if (_event) { _event->period = period; } @@ -1383,7 +1503,8 @@ class Event { * be passed to EventQueue::cancel, or an id of 0 if * there is not enough memory to allocate the event. */ - int post(A0 a0, A1 a1, A2 a2) const { + int post(A0 a0, A1 a1, A2 a2) const + { if (!_event) { return 0; } @@ -1396,7 +1517,8 @@ class Event { * * @param a0,a1,a2 Arguments to pass to the event */ - void call(A0 a0, A1 a1, A2 a2) const { + void call(A0 a0, A1 a1, A2 a2) const + { MBED_UNUSED int id = post(a0, a1, a2); MBED_ASSERT(id); } @@ -1405,7 +1527,8 @@ class Event { * * @param a0,a1,a2 Arguments to pass to the event */ - void operator()(A0 a0, A1 a1, A2 a2) const { + void operator()(A0 a0, A1 a1, A2 a2) const + { return call(a0, a1, a2); } @@ -1414,8 +1537,9 @@ class Event { * @param func Event to call passed as a void pointer * @param a0,a1,a2 Arguments to pass to the event */ - static void thunk(void *func, A0 a0, A1 a1, A2 a2) { - return static_cast(func)->call(a0, a1, a2); + static void thunk(void *func, A0 a0, A1 a1, A2 a2) + { + return static_cast(func)->call(a0, a1, a2); } /** Cancels the most recently posted event @@ -1429,7 +1553,8 @@ class Event { * function does not garuntee that the event will not execute after it * returns, as the event may have already begun executing. */ - void cancel() const { + void cancel() const + { if (_event) { equeue_cancel(_event->equeue, _event->id); } @@ -1452,14 +1577,15 @@ class Event { // Event attributes template - static int event_post(struct event *e, A0 a0, A1 a1, A2 a2) { + static int event_post(struct event *e, A0 a0, A1 a1, A2 a2) + { typedef EventQueue::context30 C; void *p = equeue_alloc(e->equeue, sizeof(C)); if (!p) { return 0; } - new (p) C(*(F*)(e + 1), a0, a1, a2); + new (p) C(*(F *)(e + 1), a0, a1, a2); equeue_event_delay(p, e->delay); equeue_event_period(p, e->period); equeue_event_dtor(p, &EventQueue::function_dtor); @@ -1467,8 +1593,9 @@ class Event { } template - static void event_dtor(struct event *e) { - ((F*)(e + 1))->~F(); + static void event_dtor(struct event *e) + { + ((F *)(e + 1))->~F(); } public: @@ -1481,7 +1608,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0) { + Event(EventQueue *q, F f, C0 c0) + { new (this) Event(q, EventQueue::context13(f, c0)); } @@ -1494,7 +1622,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1) { + Event(EventQueue *q, F f, C0 c0, C1 c1) + { new (this) Event(q, EventQueue::context23(f, c0, c1)); } @@ -1507,7 +1636,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2) { + Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2) + { new (this) Event(q, EventQueue::context33(f, c0, c1, c2)); } @@ -1520,7 +1650,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3) { + Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3) + { new (this) Event(q, EventQueue::context43(f, c0, c1, c2, c3)); } @@ -1533,7 +1664,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { + Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) + { new (this) Event(q, EventQueue::context53(f, c0, c1, c2, c3, c4)); } @@ -1541,7 +1673,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, A0, A1, A2), B0 b0) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, A0, A1, A2), B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -1549,7 +1682,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, A0, A1, A2) const, B0 b0) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, A0, A1, A2) const, B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -1557,7 +1691,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, A0, A1, A2) volatile, B0 b0) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, A0, A1, A2) volatile, B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -1565,7 +1700,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, A0, A1, A2) const volatile, B0 b0) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, A0, A1, A2) const volatile, B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -1573,7 +1709,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, A0, A1, A2), B0 b0, B1 b1) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, A0, A1, A2), B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -1581,7 +1718,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, A0, A1, A2) const, B0 b0, B1 b1) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, A0, A1, A2) const, B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -1589,7 +1727,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, A0, A1, A2) volatile, B0 b0, B1 b1) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, A0, A1, A2) volatile, B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -1597,7 +1736,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, A0, A1, A2) const volatile, B0 b0, B1 b1) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, A0, A1, A2) const volatile, B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -1605,7 +1745,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2), B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2), B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -1613,7 +1754,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2) const, B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2) const, B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -1621,7 +1763,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2) volatile, B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2) volatile, B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -1629,7 +1772,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2) const volatile, B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2) const volatile, B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -1637,7 +1781,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2), B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2), B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -1645,7 +1790,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2) const, B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2) const, B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -1653,7 +1799,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2) volatile, B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2) volatile, B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -1661,7 +1808,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2) const volatile, B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2) const volatile, B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -1669,7 +1817,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2), B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2), B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } @@ -1677,7 +1826,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2) const, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2) const, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } @@ -1685,7 +1835,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2) volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2) volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } @@ -1693,7 +1844,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2) const volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2) const volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } }; @@ -1716,9 +1868,10 @@ class Event { * @param f Function to execute when the event is dispatched */ template - Event(EventQueue *q, F f) { + Event(EventQueue *q, F f) + { _event = static_cast( - equeue_alloc(&q->_equeue, sizeof(struct event) + sizeof(F))); + equeue_alloc(&q->_equeue, sizeof(struct event) + sizeof(F))); if (_event) { _event->equeue = &q->_equeue; @@ -1729,7 +1882,7 @@ class Event { _event->post = &Event::event_post; _event->dtor = &Event::event_dtor; - new (_event+1) F(f); + new (_event + 1) F(f); _event->ref = 1; } @@ -1737,7 +1890,8 @@ class Event { /** Copy constructor for events */ - Event(const Event &e) { + Event(const Event &e) + { _event = 0; if (e._event) { _event = e._event; @@ -1747,7 +1901,8 @@ class Event { /** Assignment operator for events */ - Event &operator=(const Event &that) { + Event &operator=(const Event &that) + { if (this != &that) { this->~Event(); new (this) Event(that); @@ -1758,7 +1913,8 @@ class Event { /** Destructor for events */ - ~Event() { + ~Event() + { if (_event) { _event->ref -= 1; if (_event->ref == 0) { @@ -1772,7 +1928,8 @@ class Event { * * @param delay Millisecond delay before dispatching the event */ - void delay(int delay) { + void delay(int delay) + { if (_event) { _event->delay = delay; } @@ -1782,7 +1939,8 @@ class Event { * * @param period Millisecond period for repeatedly dispatching an event */ - void period(int period) { + void period(int period) + { if (_event) { _event->period = period; } @@ -1801,7 +1959,8 @@ class Event { * be passed to EventQueue::cancel, or an id of 0 if * there is not enough memory to allocate the event. */ - int post(A0 a0, A1 a1, A2 a2, A3 a3) const { + int post(A0 a0, A1 a1, A2 a2, A3 a3) const + { if (!_event) { return 0; } @@ -1814,7 +1973,8 @@ class Event { * * @param a0,a1,a2,a3 Arguments to pass to the event */ - void call(A0 a0, A1 a1, A2 a2, A3 a3) const { + void call(A0 a0, A1 a1, A2 a2, A3 a3) const + { MBED_UNUSED int id = post(a0, a1, a2, a3); MBED_ASSERT(id); } @@ -1823,7 +1983,8 @@ class Event { * * @param a0,a1,a2,a3 Arguments to pass to the event */ - void operator()(A0 a0, A1 a1, A2 a2, A3 a3) const { + void operator()(A0 a0, A1 a1, A2 a2, A3 a3) const + { return call(a0, a1, a2, a3); } @@ -1832,8 +1993,9 @@ class Event { * @param func Event to call passed as a void pointer * @param a0,a1,a2,a3 Arguments to pass to the event */ - static void thunk(void *func, A0 a0, A1 a1, A2 a2, A3 a3) { - return static_cast(func)->call(a0, a1, a2, a3); + static void thunk(void *func, A0 a0, A1 a1, A2 a2, A3 a3) + { + return static_cast(func)->call(a0, a1, a2, a3); } /** Cancels the most recently posted event @@ -1847,7 +2009,8 @@ class Event { * function does not garuntee that the event will not execute after it * returns, as the event may have already begun executing. */ - void cancel() const { + void cancel() const + { if (_event) { equeue_cancel(_event->equeue, _event->id); } @@ -1870,14 +2033,15 @@ class Event { // Event attributes template - static int event_post(struct event *e, A0 a0, A1 a1, A2 a2, A3 a3) { + static int event_post(struct event *e, A0 a0, A1 a1, A2 a2, A3 a3) + { typedef EventQueue::context40 C; void *p = equeue_alloc(e->equeue, sizeof(C)); if (!p) { return 0; } - new (p) C(*(F*)(e + 1), a0, a1, a2, a3); + new (p) C(*(F *)(e + 1), a0, a1, a2, a3); equeue_event_delay(p, e->delay); equeue_event_period(p, e->period); equeue_event_dtor(p, &EventQueue::function_dtor); @@ -1885,8 +2049,9 @@ class Event { } template - static void event_dtor(struct event *e) { - ((F*)(e + 1))->~F(); + static void event_dtor(struct event *e) + { + ((F *)(e + 1))->~F(); } public: @@ -1899,7 +2064,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0) { + Event(EventQueue *q, F f, C0 c0) + { new (this) Event(q, EventQueue::context14(f, c0)); } @@ -1912,7 +2078,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1) { + Event(EventQueue *q, F f, C0 c0, C1 c1) + { new (this) Event(q, EventQueue::context24(f, c0, c1)); } @@ -1925,7 +2092,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2) { + Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2) + { new (this) Event(q, EventQueue::context34(f, c0, c1, c2)); } @@ -1938,7 +2106,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3) { + Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3) + { new (this) Event(q, EventQueue::context44(f, c0, c1, c2, c3)); } @@ -1951,7 +2120,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { + Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) + { new (this) Event(q, EventQueue::context54(f, c0, c1, c2, c3, c4)); } @@ -1959,7 +2129,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, A0, A1, A2, A3), B0 b0) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, A0, A1, A2, A3), B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -1967,7 +2138,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, A0, A1, A2, A3) const, B0 b0) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, A0, A1, A2, A3) const, B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -1975,7 +2147,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, A0, A1, A2, A3) volatile, B0 b0) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, A0, A1, A2, A3) volatile, B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -1983,7 +2156,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, A0, A1, A2, A3) const volatile, B0 b0) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, A0, A1, A2, A3) const volatile, B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -1991,7 +2165,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3), B0 b0, B1 b1) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3), B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -1999,7 +2174,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3) const, B0 b0, B1 b1) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3) const, B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -2007,7 +2183,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3) volatile, B0 b0, B1 b1) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3) volatile, B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -2015,7 +2192,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3) const volatile, B0 b0, B1 b1) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3) const volatile, B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -2023,7 +2201,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3), B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3), B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -2031,7 +2210,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3) const, B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3) const, B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -2039,7 +2219,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3) volatile, B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3) volatile, B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -2047,7 +2228,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3) const volatile, B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3) const volatile, B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -2055,7 +2237,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3), B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3), B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -2063,7 +2246,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3) const, B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3) const, B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -2071,7 +2255,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3) volatile, B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3) volatile, B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -2079,7 +2264,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3) const volatile, B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3) const volatile, B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -2087,7 +2273,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3), B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3), B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } @@ -2095,7 +2282,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3) const, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3) const, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } @@ -2103,7 +2291,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3) volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3) volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } @@ -2111,7 +2300,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3) const volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3) const volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } }; @@ -2134,9 +2324,10 @@ class Event { * @param f Function to execute when the event is dispatched */ template - Event(EventQueue *q, F f) { + Event(EventQueue *q, F f) + { _event = static_cast( - equeue_alloc(&q->_equeue, sizeof(struct event) + sizeof(F))); + equeue_alloc(&q->_equeue, sizeof(struct event) + sizeof(F))); if (_event) { _event->equeue = &q->_equeue; @@ -2147,7 +2338,7 @@ class Event { _event->post = &Event::event_post; _event->dtor = &Event::event_dtor; - new (_event+1) F(f); + new (_event + 1) F(f); _event->ref = 1; } @@ -2155,7 +2346,8 @@ class Event { /** Copy constructor for events */ - Event(const Event &e) { + Event(const Event &e) + { _event = 0; if (e._event) { _event = e._event; @@ -2165,7 +2357,8 @@ class Event { /** Assignment operator for events */ - Event &operator=(const Event &that) { + Event &operator=(const Event &that) + { if (this != &that) { this->~Event(); new (this) Event(that); @@ -2176,7 +2369,8 @@ class Event { /** Destructor for events */ - ~Event() { + ~Event() + { if (_event) { _event->ref -= 1; if (_event->ref == 0) { @@ -2190,7 +2384,8 @@ class Event { * * @param delay Millisecond delay before dispatching the event */ - void delay(int delay) { + void delay(int delay) + { if (_event) { _event->delay = delay; } @@ -2200,7 +2395,8 @@ class Event { * * @param period Millisecond period for repeatedly dispatching an event */ - void period(int period) { + void period(int period) + { if (_event) { _event->period = period; } @@ -2219,7 +2415,8 @@ class Event { * be passed to EventQueue::cancel, or an id of 0 if * there is not enough memory to allocate the event. */ - int post(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) const { + int post(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) const + { if (!_event) { return 0; } @@ -2232,7 +2429,8 @@ class Event { * * @param a0,a1,a2,a3,a4 Arguments to pass to the event */ - void call(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) const { + void call(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) const + { MBED_UNUSED int id = post(a0, a1, a2, a3, a4); MBED_ASSERT(id); } @@ -2241,7 +2439,8 @@ class Event { * * @param a0,a1,a2,a3,a4 Arguments to pass to the event */ - void operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) const { + void operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) const + { return call(a0, a1, a2, a3, a4); } @@ -2250,8 +2449,9 @@ class Event { * @param func Event to call passed as a void pointer * @param a0,a1,a2,a3,a4 Arguments to pass to the event */ - static void thunk(void *func, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { - return static_cast(func)->call(a0, a1, a2, a3, a4); + static void thunk(void *func, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { + return static_cast(func)->call(a0, a1, a2, a3, a4); } /** Cancels the most recently posted event @@ -2265,7 +2465,8 @@ class Event { * function does not garuntee that the event will not execute after it * returns, as the event may have already begun executing. */ - void cancel() const { + void cancel() const + { if (_event) { equeue_cancel(_event->equeue, _event->id); } @@ -2288,14 +2489,15 @@ class Event { // Event attributes template - static int event_post(struct event *e, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + static int event_post(struct event *e, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { typedef EventQueue::context50 C; void *p = equeue_alloc(e->equeue, sizeof(C)); if (!p) { return 0; } - new (p) C(*(F*)(e + 1), a0, a1, a2, a3, a4); + new (p) C(*(F *)(e + 1), a0, a1, a2, a3, a4); equeue_event_delay(p, e->delay); equeue_event_period(p, e->period); equeue_event_dtor(p, &EventQueue::function_dtor); @@ -2303,8 +2505,9 @@ class Event { } template - static void event_dtor(struct event *e) { - ((F*)(e + 1))->~F(); + static void event_dtor(struct event *e) + { + ((F *)(e + 1))->~F(); } public: @@ -2317,7 +2520,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0) { + Event(EventQueue *q, F f, C0 c0) + { new (this) Event(q, EventQueue::context15(f, c0)); } @@ -2330,7 +2534,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1) { + Event(EventQueue *q, F f, C0 c0, C1 c1) + { new (this) Event(q, EventQueue::context25(f, c0, c1)); } @@ -2343,7 +2548,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2) { + Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2) + { new (this) Event(q, EventQueue::context35(f, c0, c1, c2)); } @@ -2356,7 +2562,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3) { + Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3) + { new (this) Event(q, EventQueue::context45(f, c0, c1, c2, c3)); } @@ -2369,7 +2576,8 @@ class Event { * arguments to the underlying callback. */ template - Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { + Event(EventQueue *q, F f, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) + { new (this) Event(q, EventQueue::context55(f, c0, c1, c2, c3, c4)); } @@ -2377,7 +2585,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, A0, A1, A2, A3, A4), B0 b0) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, A0, A1, A2, A3, A4), B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -2385,7 +2594,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, A0, A1, A2, A3, A4) const, B0 b0) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, A0, A1, A2, A3, A4) const, B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -2393,7 +2603,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, A0, A1, A2, A3, A4) volatile, B0 b0) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, A0, A1, A2, A3, A4) volatile, B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -2401,7 +2612,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, A0, A1, A2, A3, A4) const volatile, B0 b0) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, A0, A1, A2, A3, A4) const volatile, B0 b0) + { new (this) Event(q, mbed::callback(obj, method), b0); } @@ -2409,7 +2621,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3, A4), B0 b0, B1 b1) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3, A4), B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -2417,7 +2630,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3, A4) const, B0 b0, B1 b1) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3, A4) const, B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -2425,7 +2639,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3, A4) volatile, B0 b0, B1 b1) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3, A4) volatile, B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -2433,7 +2648,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3, A4) const volatile, B0 b0, B1 b1) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3, A4) const volatile, B0 b0, B1 b1) + { new (this) Event(q, mbed::callback(obj, method), b0, b1); } @@ -2441,7 +2657,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3, A4), B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3, A4), B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -2449,7 +2666,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3, A4) const, B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3, A4) const, B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -2457,7 +2675,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3, A4) volatile, B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3, A4) volatile, B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -2465,7 +2684,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3, A4) const volatile, B0 b0, B1 b1, B2 b2) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3, A4) const volatile, B0 b0, B1 b1, B2 b2) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2); } @@ -2473,7 +2693,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4), B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4), B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -2481,7 +2702,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4) const, B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4) const, B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -2489,7 +2711,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4) volatile, B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4) volatile, B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -2497,7 +2720,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4) const volatile, B0 b0, B1 b1, B2 b2, B3 b3) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4) const volatile, B0 b0, B1 b1, B2 b2, B3 b3) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3); } @@ -2505,7 +2729,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4), B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4), B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } @@ -2513,7 +2738,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4) const, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, const T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4) const, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } @@ -2521,7 +2747,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4) volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4) volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } @@ -2529,7 +2756,8 @@ class Event { * @see Event::Event */ template - Event(EventQueue *q, const volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4) const volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) { + Event(EventQueue *q, const volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4) const volatile, B0 b0, B1 b1, B2 b2, B3 b3, B4 b4) + { new (this) Event(q, mbed::callback(obj, method), b0, b1, b2, b3, b4); } }; @@ -2541,1082 +2769,1298 @@ class Event { // Convenience functions declared here to avoid cyclic // dependency between Event and EventQueue template -Event EventQueue::event(R (*func)()) { +Event EventQueue::event(R(*func)()) +{ return Event(this, func); } template -Event EventQueue::event(T *obj, R (T::*method)()) { +Event EventQueue::event(T *obj, R(T::*method)()) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(const T *obj, R (T::*method)() const) { +Event EventQueue::event(const T *obj, R(T::*method)() const) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(volatile T *obj, R (T::*method)() volatile) { +Event EventQueue::event(volatile T *obj, R(T::*method)() volatile) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)() const volatile) { +Event EventQueue::event(const volatile T *obj, R(T::*method)() const volatile) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(mbed::Callback cb) { +Event EventQueue::event(mbed::Callback cb) +{ return Event(this, cb); } template -Event EventQueue::event(R (*func)(B0), C0 c0) { +Event EventQueue::event(R(*func)(B0), C0 c0) +{ return Event(this, func, c0); } template -Event EventQueue::event(T *obj, R (T::*method)(B0), C0 c0) { +Event EventQueue::event(T *obj, R(T::*method)(B0), C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0) const, C0 c0) { +Event EventQueue::event(const T *obj, R(T::*method)(B0) const, C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0) volatile, C0 c0) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0) volatile, C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0) const volatile, C0 c0) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0) const volatile, C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(mbed::Callback cb, C0 c0) { +Event EventQueue::event(mbed::Callback cb, C0 c0) +{ return Event(this, cb, c0); } template -Event EventQueue::event(R (*func)(B0, B1), C0 c0, C1 c1) { +Event EventQueue::event(R(*func)(B0, B1), C0 c0, C1 c1) +{ return Event(this, func, c0, c1); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1), C0 c0, C1 c1) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1), C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1) const, C0 c0, C1 c1) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1) const, C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1) volatile, C0 c0, C1 c1) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1) volatile, C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1) const volatile, C0 c0, C1 c1) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1) const volatile, C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1) +{ return Event(this, cb, c0, c1); } template -Event EventQueue::event(R (*func)(B0, B1, B2), C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(R(*func)(B0, B1, B2), C0 c0, C1 c1, C2 c2) +{ return Event(this, func, c0, c1, c2); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, B2), C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, B2), C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, B2) const, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, B2) const, C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, B2) volatile, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, B2) volatile, C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, B2) const volatile, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, B2) const volatile, C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2) +{ return Event(this, cb, c0, c1, c2); } template -Event EventQueue::event(R (*func)(B0, B1, B2, B3), C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(R(*func)(B0, B1, B2, B3), C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, func, c0, c1, c2, c3); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, B2, B3), C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, B2, B3), C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, B2, B3) const, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, B2, B3) const, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, B2, B3) volatile, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, B2, B3) volatile, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3) const volatile, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3) const volatile, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, cb, c0, c1, c2, c3); } template -Event EventQueue::event(R (*func)(B0, B1, B2, B3, B4), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(R(*func)(B0, B1, B2, B3, B4), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, func, c0, c1, c2, c3, c4); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, B2, B3, B4), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, B2, B3, B4), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, B2, B3, B4) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, B2, B3, B4) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, cb, c0, c1, c2, c3, c4); } template -Event EventQueue::event(R (*func)(A0)) { +Event EventQueue::event(R(*func)(A0)) +{ return Event(this, func); } template -Event EventQueue::event(T *obj, R (T::*method)(A0)) { +Event EventQueue::event(T *obj, R(T::*method)(A0)) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(const T *obj, R (T::*method)(A0) const) { +Event EventQueue::event(const T *obj, R(T::*method)(A0) const) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(A0) volatile) { +Event EventQueue::event(volatile T *obj, R(T::*method)(A0) volatile) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(A0) const volatile) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(A0) const volatile) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(mbed::Callback cb) { +Event EventQueue::event(mbed::Callback cb) +{ return Event(this, cb); } template -Event EventQueue::event(R (*func)(B0, A0), C0 c0) { +Event EventQueue::event(R(*func)(B0, A0), C0 c0) +{ return Event(this, func, c0); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, A0), C0 c0) { +Event EventQueue::event(T *obj, R(T::*method)(B0, A0), C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, A0) const, C0 c0) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, A0) const, C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, A0) volatile, C0 c0) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, A0) volatile, C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, A0) const volatile, C0 c0) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, A0) const volatile, C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(mbed::Callback cb, C0 c0) { +Event EventQueue::event(mbed::Callback cb, C0 c0) +{ return Event(this, cb, c0); } template -Event EventQueue::event(R (*func)(B0, B1, A0), C0 c0, C1 c1) { +Event EventQueue::event(R(*func)(B0, B1, A0), C0 c0, C1 c1) +{ return Event(this, func, c0, c1); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, A0), C0 c0, C1 c1) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, A0), C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, A0) const, C0 c0, C1 c1) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, A0) const, C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, A0) volatile, C0 c0, C1 c1) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, A0) volatile, C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, A0) const volatile, C0 c0, C1 c1) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, A0) const volatile, C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1) +{ return Event(this, cb, c0, c1); } template -Event EventQueue::event(R (*func)(B0, B1, B2, A0), C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(R(*func)(B0, B1, B2, A0), C0 c0, C1 c1, C2 c2) +{ return Event(this, func, c0, c1, c2); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, B2, A0), C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, B2, A0), C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, B2, A0) const, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, B2, A0) const, C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, B2, A0) volatile, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, B2, A0) volatile, C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, B2, A0) const volatile, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, B2, A0) const volatile, C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2) +{ return Event(this, cb, c0, c1, c2); } template -Event EventQueue::event(R (*func)(B0, B1, B2, B3, A0), C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(R(*func)(B0, B1, B2, B3, A0), C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, func, c0, c1, c2, c3); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, B2, B3, A0), C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, B2, B3, A0), C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, B2, B3, A0) const, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, B2, B3, A0) const, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0) volatile, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0) volatile, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0) const volatile, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0) const volatile, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, cb, c0, c1, c2, c3); } template -Event EventQueue::event(R (*func)(B0, B1, B2, B3, B4, A0), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(R(*func)(B0, B1, B2, B3, B4, A0), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, func, c0, c1, c2, c3, c4); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, cb, c0, c1, c2, c3, c4); } template -Event EventQueue::event(R (*func)(A0, A1)) { +Event EventQueue::event(R(*func)(A0, A1)) +{ return Event(this, func); } template -Event EventQueue::event(T *obj, R (T::*method)(A0, A1)) { +Event EventQueue::event(T *obj, R(T::*method)(A0, A1)) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(const T *obj, R (T::*method)(A0, A1) const) { +Event EventQueue::event(const T *obj, R(T::*method)(A0, A1) const) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(A0, A1) volatile) { +Event EventQueue::event(volatile T *obj, R(T::*method)(A0, A1) volatile) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(A0, A1) const volatile) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(A0, A1) const volatile) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(mbed::Callback cb) { +Event EventQueue::event(mbed::Callback cb) +{ return Event(this, cb); } template -Event EventQueue::event(R (*func)(B0, A0, A1), C0 c0) { +Event EventQueue::event(R(*func)(B0, A0, A1), C0 c0) +{ return Event(this, func, c0); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, A0, A1), C0 c0) { +Event EventQueue::event(T *obj, R(T::*method)(B0, A0, A1), C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, A0, A1) const, C0 c0) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, A0, A1) const, C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, A0, A1) volatile, C0 c0) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, A0, A1) volatile, C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, A0, A1) const volatile, C0 c0) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, A0, A1) const volatile, C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(mbed::Callback cb, C0 c0) { +Event EventQueue::event(mbed::Callback cb, C0 c0) +{ return Event(this, cb, c0); } template -Event EventQueue::event(R (*func)(B0, B1, A0, A1), C0 c0, C1 c1) { +Event EventQueue::event(R(*func)(B0, B1, A0, A1), C0 c0, C1 c1) +{ return Event(this, func, c0, c1); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, A0, A1), C0 c0, C1 c1) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, A0, A1), C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, A0, A1) const, C0 c0, C1 c1) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, A0, A1) const, C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, A0, A1) volatile, C0 c0, C1 c1) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, A0, A1) volatile, C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, A0, A1) const volatile, C0 c0, C1 c1) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, A0, A1) const volatile, C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1) +{ return Event(this, cb, c0, c1); } template -Event EventQueue::event(R (*func)(B0, B1, B2, A0, A1), C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(R(*func)(B0, B1, B2, A0, A1), C0 c0, C1 c1, C2 c2) +{ return Event(this, func, c0, c1, c2); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, B2, A0, A1), C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, B2, A0, A1), C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, B2, A0, A1) const, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, B2, A0, A1) const, C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1) volatile, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1) volatile, C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1) const volatile, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1) const volatile, C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2) +{ return Event(this, cb, c0, c1, c2); } template -Event EventQueue::event(R (*func)(B0, B1, B2, B3, A0, A1), C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(R(*func)(B0, B1, B2, B3, A0, A1), C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, func, c0, c1, c2, c3); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1), C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1), C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1) const, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1) const, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1) volatile, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1) volatile, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1) const volatile, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1) const volatile, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, cb, c0, c1, c2, c3); } template -Event EventQueue::event(R (*func)(B0, B1, B2, B3, B4, A0, A1), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(R(*func)(B0, B1, B2, B3, B4, A0, A1), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, func, c0, c1, c2, c3, c4); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, cb, c0, c1, c2, c3, c4); } template -Event EventQueue::event(R (*func)(A0, A1, A2)) { +Event EventQueue::event(R(*func)(A0, A1, A2)) +{ return Event(this, func); } template -Event EventQueue::event(T *obj, R (T::*method)(A0, A1, A2)) { +Event EventQueue::event(T *obj, R(T::*method)(A0, A1, A2)) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(const T *obj, R (T::*method)(A0, A1, A2) const) { +Event EventQueue::event(const T *obj, R(T::*method)(A0, A1, A2) const) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(A0, A1, A2) volatile) { +Event EventQueue::event(volatile T *obj, R(T::*method)(A0, A1, A2) volatile) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(A0, A1, A2) const volatile) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(A0, A1, A2) const volatile) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(mbed::Callback cb) { +Event EventQueue::event(mbed::Callback cb) +{ return Event(this, cb); } template -Event EventQueue::event(R (*func)(B0, A0, A1, A2), C0 c0) { +Event EventQueue::event(R(*func)(B0, A0, A1, A2), C0 c0) +{ return Event(this, func, c0); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, A0, A1, A2), C0 c0) { +Event EventQueue::event(T *obj, R(T::*method)(B0, A0, A1, A2), C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, A0, A1, A2) const, C0 c0) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, A0, A1, A2) const, C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, A0, A1, A2) volatile, C0 c0) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, A0, A1, A2) volatile, C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, A0, A1, A2) const volatile, C0 c0) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, A0, A1, A2) const volatile, C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(mbed::Callback cb, C0 c0) { +Event EventQueue::event(mbed::Callback cb, C0 c0) +{ return Event(this, cb, c0); } template -Event EventQueue::event(R (*func)(B0, B1, A0, A1, A2), C0 c0, C1 c1) { +Event EventQueue::event(R(*func)(B0, B1, A0, A1, A2), C0 c0, C1 c1) +{ return Event(this, func, c0, c1); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, A0, A1, A2), C0 c0, C1 c1) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, A0, A1, A2), C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, A0, A1, A2) const, C0 c0, C1 c1) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, A0, A1, A2) const, C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, A0, A1, A2) volatile, C0 c0, C1 c1) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, A0, A1, A2) volatile, C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, A0, A1, A2) const volatile, C0 c0, C1 c1) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, A0, A1, A2) const volatile, C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1) +{ return Event(this, cb, c0, c1); } template -Event EventQueue::event(R (*func)(B0, B1, B2, A0, A1, A2), C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(R(*func)(B0, B1, B2, A0, A1, A2), C0 c0, C1 c1, C2 c2) +{ return Event(this, func, c0, c1, c2); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2), C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2), C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2) const, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2) const, C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2) volatile, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2) volatile, C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2) const volatile, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2) const volatile, C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2) +{ return Event(this, cb, c0, c1, c2); } template -Event EventQueue::event(R (*func)(B0, B1, B2, B3, A0, A1, A2), C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(R(*func)(B0, B1, B2, B3, A0, A1, A2), C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, func, c0, c1, c2, c3); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2), C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2), C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2) const, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2) const, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2) volatile, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2) volatile, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2) const volatile, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2) const volatile, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, cb, c0, c1, c2, c3); } template -Event EventQueue::event(R (*func)(B0, B1, B2, B3, B4, A0, A1, A2), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(R(*func)(B0, B1, B2, B3, B4, A0, A1, A2), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, func, c0, c1, c2, c3, c4); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, cb, c0, c1, c2, c3, c4); } template -Event EventQueue::event(R (*func)(A0, A1, A2, A3)) { +Event EventQueue::event(R(*func)(A0, A1, A2, A3)) +{ return Event(this, func); } template -Event EventQueue::event(T *obj, R (T::*method)(A0, A1, A2, A3)) { +Event EventQueue::event(T *obj, R(T::*method)(A0, A1, A2, A3)) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(const T *obj, R (T::*method)(A0, A1, A2, A3) const) { +Event EventQueue::event(const T *obj, R(T::*method)(A0, A1, A2, A3) const) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(A0, A1, A2, A3) volatile) { +Event EventQueue::event(volatile T *obj, R(T::*method)(A0, A1, A2, A3) volatile) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(A0, A1, A2, A3) const volatile) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(A0, A1, A2, A3) const volatile) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(mbed::Callback cb) { +Event EventQueue::event(mbed::Callback cb) +{ return Event(this, cb); } template -Event EventQueue::event(R (*func)(B0, A0, A1, A2, A3), C0 c0) { +Event EventQueue::event(R(*func)(B0, A0, A1, A2, A3), C0 c0) +{ return Event(this, func, c0); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, A0, A1, A2, A3), C0 c0) { +Event EventQueue::event(T *obj, R(T::*method)(B0, A0, A1, A2, A3), C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, A0, A1, A2, A3) const, C0 c0) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, A0, A1, A2, A3) const, C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, A0, A1, A2, A3) volatile, C0 c0) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, A0, A1, A2, A3) volatile, C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, A0, A1, A2, A3) const volatile, C0 c0) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, A0, A1, A2, A3) const volatile, C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(mbed::Callback cb, C0 c0) { +Event EventQueue::event(mbed::Callback cb, C0 c0) +{ return Event(this, cb, c0); } template -Event EventQueue::event(R (*func)(B0, B1, A0, A1, A2, A3), C0 c0, C1 c1) { +Event EventQueue::event(R(*func)(B0, B1, A0, A1, A2, A3), C0 c0, C1 c1) +{ return Event(this, func, c0, c1); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3), C0 c0, C1 c1) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3), C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3) const, C0 c0, C1 c1) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3) const, C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3) volatile, C0 c0, C1 c1) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3) volatile, C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3) const volatile, C0 c0, C1 c1) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3) const volatile, C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1) +{ return Event(this, cb, c0, c1); } template -Event EventQueue::event(R (*func)(B0, B1, B2, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(R(*func)(B0, B1, B2, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2) +{ return Event(this, func, c0, c1, c2); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3) const, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3) const, C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3) volatile, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3) volatile, C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3) const volatile, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3) const volatile, C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2) +{ return Event(this, cb, c0, c1, c2); } template -Event EventQueue::event(R (*func)(B0, B1, B2, B3, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(R(*func)(B0, B1, B2, B3, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, func, c0, c1, c2, c3); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3) const, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3) const, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3) volatile, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3) volatile, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3) const volatile, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3) const volatile, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, cb, c0, c1, c2, c3); } template -Event EventQueue::event(R (*func)(B0, B1, B2, B3, B4, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(R(*func)(B0, B1, B2, B3, B4, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, func, c0, c1, c2, c3, c4); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, cb, c0, c1, c2, c3, c4); } template -Event EventQueue::event(R (*func)(A0, A1, A2, A3, A4)) { +Event EventQueue::event(R(*func)(A0, A1, A2, A3, A4)) +{ return Event(this, func); } template -Event EventQueue::event(T *obj, R (T::*method)(A0, A1, A2, A3, A4)) { +Event EventQueue::event(T *obj, R(T::*method)(A0, A1, A2, A3, A4)) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(const T *obj, R (T::*method)(A0, A1, A2, A3, A4) const) { +Event EventQueue::event(const T *obj, R(T::*method)(A0, A1, A2, A3, A4) const) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(A0, A1, A2, A3, A4) volatile) { +Event EventQueue::event(volatile T *obj, R(T::*method)(A0, A1, A2, A3, A4) volatile) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(A0, A1, A2, A3, A4) const volatile) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(A0, A1, A2, A3, A4) const volatile) +{ return Event(this, mbed::callback(obj, method)); } template -Event EventQueue::event(mbed::Callback cb) { +Event EventQueue::event(mbed::Callback cb) +{ return Event(this, cb); } template -Event EventQueue::event(R (*func)(B0, A0, A1, A2, A3, A4), C0 c0) { +Event EventQueue::event(R(*func)(B0, A0, A1, A2, A3, A4), C0 c0) +{ return Event(this, func, c0); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, A0, A1, A2, A3, A4), C0 c0) { +Event EventQueue::event(T *obj, R(T::*method)(B0, A0, A1, A2, A3, A4), C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, A0, A1, A2, A3, A4) const, C0 c0) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, A0, A1, A2, A3, A4) const, C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, A0, A1, A2, A3, A4) volatile, C0 c0) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, A0, A1, A2, A3, A4) volatile, C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, A0, A1, A2, A3, A4) const volatile, C0 c0) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, A0, A1, A2, A3, A4) const volatile, C0 c0) +{ return Event(this, mbed::callback(obj, method), c0); } template -Event EventQueue::event(mbed::Callback cb, C0 c0) { +Event EventQueue::event(mbed::Callback cb, C0 c0) +{ return Event(this, cb, c0); } template -Event EventQueue::event(R (*func)(B0, B1, A0, A1, A2, A3, A4), C0 c0, C1 c1) { +Event EventQueue::event(R(*func)(B0, B1, A0, A1, A2, A3, A4), C0 c0, C1 c1) +{ return Event(this, func, c0, c1); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3, A4), C0 c0, C1 c1) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3, A4), C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3, A4) const, C0 c0, C1 c1) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3, A4) const, C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3, A4) volatile, C0 c0, C1 c1) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3, A4) volatile, C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3, A4) const volatile, C0 c0, C1 c1) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3, A4) const volatile, C0 c0, C1 c1) +{ return Event(this, mbed::callback(obj, method), c0, c1); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1) +{ return Event(this, cb, c0, c1); } template -Event EventQueue::event(R (*func)(B0, B1, B2, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(R(*func)(B0, B1, B2, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2) +{ return Event(this, func, c0, c1, c2); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3, A4) const, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3, A4) const, C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3, A4) volatile, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3, A4) volatile, C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3, A4) const volatile, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3, A4) const volatile, C0 c0, C1 c1, C2 c2) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2) +{ return Event(this, cb, c0, c1, c2); } template -Event EventQueue::event(R (*func)(B0, B1, B2, B3, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(R(*func)(B0, B1, B2, B3, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, func, c0, c1, c2, c3); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4) const, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4) const, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4) volatile, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4) volatile, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4) const volatile, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4) const volatile, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3) +{ return Event(this, cb, c0, c1, c2, c3); } template -Event EventQueue::event(R (*func)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(R(*func)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, func, c0, c1, c2, c3, c4); } template -Event EventQueue::event(T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(const T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(const T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, mbed::callback(obj, method), c0, c1, c2, c3, c4); } template -Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) { +Event EventQueue::event(mbed::Callback cb, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) +{ return Event(this, cb, c0, c1, c2, c3, c4); } diff --git a/events/EventQueue.cpp b/events/EventQueue.cpp index 420f31bda47..4b3449b86e2 100644 --- a/events/EventQueue.cpp +++ b/events/EventQueue.cpp @@ -19,7 +19,8 @@ #include "mbed.h" -EventQueue::EventQueue(unsigned event_size, unsigned char *event_pointer) { +EventQueue::EventQueue(unsigned event_size, unsigned char *event_pointer) +{ if (!event_pointer) { equeue_create(&_equeue, event_size); } else { @@ -27,27 +28,33 @@ EventQueue::EventQueue(unsigned event_size, unsigned char *event_pointer) { } } -EventQueue::~EventQueue() { +EventQueue::~EventQueue() +{ equeue_destroy(&_equeue); } -void EventQueue::dispatch(int ms) { +void EventQueue::dispatch(int ms) +{ return equeue_dispatch(&_equeue, ms); } -void EventQueue::break_dispatch() { +void EventQueue::break_dispatch() +{ return equeue_break(&_equeue); } -unsigned EventQueue::tick() { +unsigned EventQueue::tick() +{ return equeue_tick(); } -void EventQueue::cancel(int id) { +void EventQueue::cancel(int id) +{ return equeue_cancel(&_equeue, id); } -void EventQueue::background(Callback update) { +void EventQueue::background(Callback update) +{ _update = update; if (_update) { @@ -57,7 +64,8 @@ void EventQueue::background(Callback update) { } } -void EventQueue::chain(EventQueue *target) { +void EventQueue::chain(EventQueue *target) +{ if (target) { equeue_chain(&_equeue, &target->_equeue); } else { diff --git a/events/EventQueue.h b/events/EventQueue.h index 9b15edb6fa9..c067d23977f 100644 --- a/events/EventQueue.h +++ b/events/EventQueue.h @@ -60,7 +60,7 @@ class EventQueue : private mbed::NonCopyable { * @param buffer Pointer to buffer to use for events * (default to NULL) */ - EventQueue(unsigned size=EVENTS_QUEUE_SIZE, unsigned char *buffer=NULL); + EventQueue(unsigned size = EVENTS_QUEUE_SIZE, unsigned char *buffer = NULL); /** Destroy an EventQueue */ @@ -80,16 +80,19 @@ class EventQueue : private mbed::NonCopyable { * value will dispatch events indefinitely * (default to -1) */ - void dispatch(int ms=-1); + void dispatch(int ms = -1); /** Dispatch events without a timeout * - * This is equivalent to EventQueue::dispatch with no arguments, but + * This is equivalent to EventQueue::dispatch with no arguments, but * avoids overload ambiguities when passed as a callback. * * @see EventQueue::dispatch */ - void dispatch_forever() { dispatch(); } + void dispatch_forever() + { + dispatch(); + } /** Break out of a running event loop * @@ -100,7 +103,7 @@ class EventQueue : private mbed::NonCopyable { /** Millisecond counter * - * Returns the underlying tick of the event queue represented as the + * Returns the underlying tick of the event queue represented as the * number of milliseconds that have passed since an arbitrary point in * time. Intentionally overflows to 0 after 2^32-1. * @@ -173,7 +176,8 @@ class EventQueue : private mbed::NonCopyable { * enough memory to allocate the event. */ template - int call(F f) { + int call(F f) + { void *p = equeue_alloc(&_equeue, sizeof(F)); if (!p) { return 0; @@ -190,7 +194,8 @@ class EventQueue : private mbed::NonCopyable { * @param a0 Argument to pass to the callback */ template - int call(F f, A0 a0) { + int call(F f, A0 a0) + { return call(context10(f, a0)); } @@ -200,7 +205,8 @@ class EventQueue : private mbed::NonCopyable { * @param a0,a1 Arguments to pass to the callback */ template - int call(F f, A0 a0, A1 a1) { + int call(F f, A0 a0, A1 a1) + { return call(context20(f, a0, a1)); } @@ -210,7 +216,8 @@ class EventQueue : private mbed::NonCopyable { * @param a0,a1,a2 Arguments to pass to the callback */ template - int call(F f, A0 a0, A1 a1, A2 a2) { + int call(F f, A0 a0, A1 a1, A2 a2) + { return call(context30(f, a0, a1, a2)); } @@ -220,7 +227,8 @@ class EventQueue : private mbed::NonCopyable { * @param a0,a1,a2,a3 Arguments to pass to the callback */ template - int call(F f, A0 a0, A1 a1, A2 a2, A3 a3) { + int call(F f, A0 a0, A1 a1, A2 a2, A3 a3) + { return call(context40(f, a0, a1, a2, a3)); } @@ -230,7 +238,8 @@ class EventQueue : private mbed::NonCopyable { * @param a0,a1,a2,a3,a4 Arguments to pass to the callback */ template - int call(F f, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + int call(F f, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { return call(context50(f, a0, a1, a2, a3, a4)); } @@ -238,7 +247,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(T *obj, R (T::*method)()) { + int call(T *obj, R(T::*method)()) + { return call(mbed::callback(obj, method)); } @@ -246,7 +256,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(const T *obj, R (T::*method)() const) { + int call(const T *obj, R(T::*method)() const) + { return call(mbed::callback(obj, method)); } @@ -254,7 +265,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(volatile T *obj, R (T::*method)() volatile) { + int call(volatile T *obj, R(T::*method)() volatile) + { return call(mbed::callback(obj, method)); } @@ -262,7 +274,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(const volatile T *obj, R (T::*method)() const volatile) { + int call(const volatile T *obj, R(T::*method)() const volatile) + { return call(mbed::callback(obj, method)); } @@ -270,7 +283,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(T *obj, R (T::*method)(A0), A0 a0) { + int call(T *obj, R(T::*method)(A0), A0 a0) + { return call(mbed::callback(obj, method), a0); } @@ -278,7 +292,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(const T *obj, R (T::*method)(A0) const, A0 a0) { + int call(const T *obj, R(T::*method)(A0) const, A0 a0) + { return call(mbed::callback(obj, method), a0); } @@ -286,7 +301,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(volatile T *obj, R (T::*method)(A0) volatile, A0 a0) { + int call(volatile T *obj, R(T::*method)(A0) volatile, A0 a0) + { return call(mbed::callback(obj, method), a0); } @@ -294,7 +310,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(const volatile T *obj, R (T::*method)(A0) const volatile, A0 a0) { + int call(const volatile T *obj, R(T::*method)(A0) const volatile, A0 a0) + { return call(mbed::callback(obj, method), a0); } @@ -302,7 +319,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(T *obj, R (T::*method)(A0, A1), A0 a0, A1 a1) { + int call(T *obj, R(T::*method)(A0, A1), A0 a0, A1 a1) + { return call(mbed::callback(obj, method), a0, a1); } @@ -310,7 +328,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(const T *obj, R (T::*method)(A0, A1) const, A0 a0, A1 a1) { + int call(const T *obj, R(T::*method)(A0, A1) const, A0 a0, A1 a1) + { return call(mbed::callback(obj, method), a0, a1); } @@ -318,7 +337,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(volatile T *obj, R (T::*method)(A0, A1) volatile, A0 a0, A1 a1) { + int call(volatile T *obj, R(T::*method)(A0, A1) volatile, A0 a0, A1 a1) + { return call(mbed::callback(obj, method), a0, a1); } @@ -326,7 +346,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(const volatile T *obj, R (T::*method)(A0, A1) const volatile, A0 a0, A1 a1) { + int call(const volatile T *obj, R(T::*method)(A0, A1) const volatile, A0 a0, A1 a1) + { return call(mbed::callback(obj, method), a0, a1); } @@ -334,7 +355,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(T *obj, R (T::*method)(A0, A1, A2), A0 a0, A1 a1, A2 a2) { + int call(T *obj, R(T::*method)(A0, A1, A2), A0 a0, A1 a1, A2 a2) + { return call(mbed::callback(obj, method), a0, a1, a2); } @@ -342,7 +364,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(const T *obj, R (T::*method)(A0, A1, A2) const, A0 a0, A1 a1, A2 a2) { + int call(const T *obj, R(T::*method)(A0, A1, A2) const, A0 a0, A1 a1, A2 a2) + { return call(mbed::callback(obj, method), a0, a1, a2); } @@ -350,7 +373,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(volatile T *obj, R (T::*method)(A0, A1, A2) volatile, A0 a0, A1 a1, A2 a2) { + int call(volatile T *obj, R(T::*method)(A0, A1, A2) volatile, A0 a0, A1 a1, A2 a2) + { return call(mbed::callback(obj, method), a0, a1, a2); } @@ -358,7 +382,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(const volatile T *obj, R (T::*method)(A0, A1, A2) const volatile, A0 a0, A1 a1, A2 a2) { + int call(const volatile T *obj, R(T::*method)(A0, A1, A2) const volatile, A0 a0, A1 a1, A2 a2) + { return call(mbed::callback(obj, method), a0, a1, a2); } @@ -366,7 +391,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(T *obj, R (T::*method)(A0, A1, A2, A3), A0 a0, A1 a1, A2 a2, A3 a3) { + int call(T *obj, R(T::*method)(A0, A1, A2, A3), A0 a0, A1 a1, A2 a2, A3 a3) + { return call(mbed::callback(obj, method), a0, a1, a2, a3); } @@ -374,7 +400,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(const T *obj, R (T::*method)(A0, A1, A2, A3) const, A0 a0, A1 a1, A2 a2, A3 a3) { + int call(const T *obj, R(T::*method)(A0, A1, A2, A3) const, A0 a0, A1 a1, A2 a2, A3 a3) + { return call(mbed::callback(obj, method), a0, a1, a2, a3); } @@ -382,7 +409,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(volatile T *obj, R (T::*method)(A0, A1, A2, A3) volatile, A0 a0, A1 a1, A2 a2, A3 a3) { + int call(volatile T *obj, R(T::*method)(A0, A1, A2, A3) volatile, A0 a0, A1 a1, A2 a2, A3 a3) + { return call(mbed::callback(obj, method), a0, a1, a2, a3); } @@ -390,7 +418,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(const volatile T *obj, R (T::*method)(A0, A1, A2, A3) const volatile, A0 a0, A1 a1, A2 a2, A3 a3) { + int call(const volatile T *obj, R(T::*method)(A0, A1, A2, A3) const volatile, A0 a0, A1 a1, A2 a2, A3 a3) + { return call(mbed::callback(obj, method), a0, a1, a2, a3); } @@ -398,7 +427,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(T *obj, R (T::*method)(A0, A1, A2, A3, A4), A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + int call(T *obj, R(T::*method)(A0, A1, A2, A3, A4), A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { return call(mbed::callback(obj, method), a0, a1, a2, a3, a4); } @@ -406,7 +436,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(const T *obj, R (T::*method)(A0, A1, A2, A3, A4) const, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + int call(const T *obj, R(T::*method)(A0, A1, A2, A3, A4) const, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { return call(mbed::callback(obj, method), a0, a1, a2, a3, a4); } @@ -414,7 +445,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(volatile T *obj, R (T::*method)(A0, A1, A2, A3, A4) volatile, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + int call(volatile T *obj, R(T::*method)(A0, A1, A2, A3, A4) volatile, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { return call(mbed::callback(obj, method), a0, a1, a2, a3, a4); } @@ -422,7 +454,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call */ template - int call(const volatile T *obj, R (T::*method)(A0, A1, A2, A3, A4) const volatile, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + int call(const volatile T *obj, R(T::*method)(A0, A1, A2, A3, A4) const volatile, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { return call(mbed::callback(obj, method), a0, a1, a2, a3, a4); } @@ -441,7 +474,8 @@ class EventQueue : private mbed::NonCopyable { * enough memory to allocate the event. */ template - int call_in(int ms, F f) { + int call_in(int ms, F f) + { void *p = equeue_alloc(&_equeue, sizeof(F)); if (!p) { return 0; @@ -460,7 +494,8 @@ class EventQueue : private mbed::NonCopyable { * @param a0 Argument to pass to the callback */ template - int call_in(int ms, F f, A0 a0) { + int call_in(int ms, F f, A0 a0) + { return call_in(ms, context10(f, a0)); } @@ -471,7 +506,8 @@ class EventQueue : private mbed::NonCopyable { * @param a0,a1 Arguments to pass to the callback */ template - int call_in(int ms, F f, A0 a0, A1 a1) { + int call_in(int ms, F f, A0 a0, A1 a1) + { return call_in(ms, context20(f, a0, a1)); } @@ -482,7 +518,8 @@ class EventQueue : private mbed::NonCopyable { * @param a0,a1,a2 Arguments to pass to the callback */ template - int call_in(int ms, F f, A0 a0, A1 a1, A2 a2) { + int call_in(int ms, F f, A0 a0, A1 a1, A2 a2) + { return call_in(ms, context30(f, a0, a1, a2)); } @@ -493,7 +530,8 @@ class EventQueue : private mbed::NonCopyable { * @param a0,a1,a2,a3 Arguments to pass to the callback */ template - int call_in(int ms, F f, A0 a0, A1 a1, A2 a2, A3 a3) { + int call_in(int ms, F f, A0 a0, A1 a1, A2 a2, A3 a3) + { return call_in(ms, context40(f, a0, a1, a2, a3)); } @@ -504,7 +542,8 @@ class EventQueue : private mbed::NonCopyable { * @param a0,a1,a2,a3,a4 Arguments to pass to the callback */ template - int call_in(int ms, F f, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + int call_in(int ms, F f, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { return call_in(ms, context50(f, a0, a1, a2, a3, a4)); } @@ -512,7 +551,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, T *obj, R (T::*method)()) { + int call_in(int ms, T *obj, R(T::*method)()) + { return call_in(ms, mbed::callback(obj, method)); } @@ -520,7 +560,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, const T *obj, R (T::*method)() const) { + int call_in(int ms, const T *obj, R(T::*method)() const) + { return call_in(ms, mbed::callback(obj, method)); } @@ -528,7 +569,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, volatile T *obj, R (T::*method)() volatile) { + int call_in(int ms, volatile T *obj, R(T::*method)() volatile) + { return call_in(ms, mbed::callback(obj, method)); } @@ -536,7 +578,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, const volatile T *obj, R (T::*method)() const volatile) { + int call_in(int ms, const volatile T *obj, R(T::*method)() const volatile) + { return call_in(ms, mbed::callback(obj, method)); } @@ -544,7 +587,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, T *obj, R (T::*method)(A0), A0 a0) { + int call_in(int ms, T *obj, R(T::*method)(A0), A0 a0) + { return call_in(ms, mbed::callback(obj, method), a0); } @@ -552,7 +596,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, const T *obj, R (T::*method)(A0) const, A0 a0) { + int call_in(int ms, const T *obj, R(T::*method)(A0) const, A0 a0) + { return call_in(ms, mbed::callback(obj, method), a0); } @@ -560,7 +605,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, volatile T *obj, R (T::*method)(A0) volatile, A0 a0) { + int call_in(int ms, volatile T *obj, R(T::*method)(A0) volatile, A0 a0) + { return call_in(ms, mbed::callback(obj, method), a0); } @@ -568,7 +614,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, const volatile T *obj, R (T::*method)(A0) const volatile, A0 a0) { + int call_in(int ms, const volatile T *obj, R(T::*method)(A0) const volatile, A0 a0) + { return call_in(ms, mbed::callback(obj, method), a0); } @@ -576,7 +623,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, T *obj, R (T::*method)(A0, A1), A0 a0, A1 a1) { + int call_in(int ms, T *obj, R(T::*method)(A0, A1), A0 a0, A1 a1) + { return call_in(ms, mbed::callback(obj, method), a0, a1); } @@ -584,7 +632,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, const T *obj, R (T::*method)(A0, A1) const, A0 a0, A1 a1) { + int call_in(int ms, const T *obj, R(T::*method)(A0, A1) const, A0 a0, A1 a1) + { return call_in(ms, mbed::callback(obj, method), a0, a1); } @@ -592,7 +641,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, volatile T *obj, R (T::*method)(A0, A1) volatile, A0 a0, A1 a1) { + int call_in(int ms, volatile T *obj, R(T::*method)(A0, A1) volatile, A0 a0, A1 a1) + { return call_in(ms, mbed::callback(obj, method), a0, a1); } @@ -600,7 +650,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, const volatile T *obj, R (T::*method)(A0, A1) const volatile, A0 a0, A1 a1) { + int call_in(int ms, const volatile T *obj, R(T::*method)(A0, A1) const volatile, A0 a0, A1 a1) + { return call_in(ms, mbed::callback(obj, method), a0, a1); } @@ -608,7 +659,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, T *obj, R (T::*method)(A0, A1, A2), A0 a0, A1 a1, A2 a2) { + int call_in(int ms, T *obj, R(T::*method)(A0, A1, A2), A0 a0, A1 a1, A2 a2) + { return call_in(ms, mbed::callback(obj, method), a0, a1, a2); } @@ -616,7 +668,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, const T *obj, R (T::*method)(A0, A1, A2) const, A0 a0, A1 a1, A2 a2) { + int call_in(int ms, const T *obj, R(T::*method)(A0, A1, A2) const, A0 a0, A1 a1, A2 a2) + { return call_in(ms, mbed::callback(obj, method), a0, a1, a2); } @@ -624,7 +677,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, volatile T *obj, R (T::*method)(A0, A1, A2) volatile, A0 a0, A1 a1, A2 a2) { + int call_in(int ms, volatile T *obj, R(T::*method)(A0, A1, A2) volatile, A0 a0, A1 a1, A2 a2) + { return call_in(ms, mbed::callback(obj, method), a0, a1, a2); } @@ -632,7 +686,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, const volatile T *obj, R (T::*method)(A0, A1, A2) const volatile, A0 a0, A1 a1, A2 a2) { + int call_in(int ms, const volatile T *obj, R(T::*method)(A0, A1, A2) const volatile, A0 a0, A1 a1, A2 a2) + { return call_in(ms, mbed::callback(obj, method), a0, a1, a2); } @@ -640,7 +695,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, T *obj, R (T::*method)(A0, A1, A2, A3), A0 a0, A1 a1, A2 a2, A3 a3) { + int call_in(int ms, T *obj, R(T::*method)(A0, A1, A2, A3), A0 a0, A1 a1, A2 a2, A3 a3) + { return call_in(ms, mbed::callback(obj, method), a0, a1, a2, a3); } @@ -648,7 +704,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, const T *obj, R (T::*method)(A0, A1, A2, A3) const, A0 a0, A1 a1, A2 a2, A3 a3) { + int call_in(int ms, const T *obj, R(T::*method)(A0, A1, A2, A3) const, A0 a0, A1 a1, A2 a2, A3 a3) + { return call_in(ms, mbed::callback(obj, method), a0, a1, a2, a3); } @@ -656,7 +713,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, volatile T *obj, R (T::*method)(A0, A1, A2, A3) volatile, A0 a0, A1 a1, A2 a2, A3 a3) { + int call_in(int ms, volatile T *obj, R(T::*method)(A0, A1, A2, A3) volatile, A0 a0, A1 a1, A2 a2, A3 a3) + { return call_in(ms, mbed::callback(obj, method), a0, a1, a2, a3); } @@ -664,7 +722,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, const volatile T *obj, R (T::*method)(A0, A1, A2, A3) const volatile, A0 a0, A1 a1, A2 a2, A3 a3) { + int call_in(int ms, const volatile T *obj, R(T::*method)(A0, A1, A2, A3) const volatile, A0 a0, A1 a1, A2 a2, A3 a3) + { return call_in(ms, mbed::callback(obj, method), a0, a1, a2, a3); } @@ -672,7 +731,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, T *obj, R (T::*method)(A0, A1, A2, A3, A4), A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + int call_in(int ms, T *obj, R(T::*method)(A0, A1, A2, A3, A4), A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { return call_in(ms, mbed::callback(obj, method), a0, a1, a2, a3, a4); } @@ -680,7 +740,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, const T *obj, R (T::*method)(A0, A1, A2, A3, A4) const, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + int call_in(int ms, const T *obj, R(T::*method)(A0, A1, A2, A3, A4) const, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { return call_in(ms, mbed::callback(obj, method), a0, a1, a2, a3, a4); } @@ -688,7 +749,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, volatile T *obj, R (T::*method)(A0, A1, A2, A3, A4) volatile, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + int call_in(int ms, volatile T *obj, R(T::*method)(A0, A1, A2, A3, A4) volatile, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { return call_in(ms, mbed::callback(obj, method), a0, a1, a2, a3, a4); } @@ -696,7 +758,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_in */ template - int call_in(int ms, const volatile T *obj, R (T::*method)(A0, A1, A2, A3, A4) const volatile, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + int call_in(int ms, const volatile T *obj, R(T::*method)(A0, A1, A2, A3, A4) const volatile, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { return call_in(ms, mbed::callback(obj, method), a0, a1, a2, a3, a4); } @@ -715,7 +778,8 @@ class EventQueue : private mbed::NonCopyable { * enough memory to allocate the event. */ template - int call_every(int ms, F f) { + int call_every(int ms, F f) + { void *p = equeue_alloc(&_equeue, sizeof(F)); if (!p) { return 0; @@ -735,7 +799,8 @@ class EventQueue : private mbed::NonCopyable { * @param ms Period of the event in milliseconds */ template - int call_every(int ms, F f, A0 a0) { + int call_every(int ms, F f, A0 a0) + { return call_every(ms, context10(f, a0)); } @@ -746,7 +811,8 @@ class EventQueue : private mbed::NonCopyable { * @param ms Period of the event in milliseconds */ template - int call_every(int ms, F f, A0 a0, A1 a1) { + int call_every(int ms, F f, A0 a0, A1 a1) + { return call_every(ms, context20(f, a0, a1)); } @@ -757,7 +823,8 @@ class EventQueue : private mbed::NonCopyable { * @param ms Period of the event in milliseconds */ template - int call_every(int ms, F f, A0 a0, A1 a1, A2 a2) { + int call_every(int ms, F f, A0 a0, A1 a1, A2 a2) + { return call_every(ms, context30(f, a0, a1, a2)); } @@ -768,7 +835,8 @@ class EventQueue : private mbed::NonCopyable { * @param ms Period of the event in milliseconds */ template - int call_every(int ms, F f, A0 a0, A1 a1, A2 a2, A3 a3) { + int call_every(int ms, F f, A0 a0, A1 a1, A2 a2, A3 a3) + { return call_every(ms, context40(f, a0, a1, a2, a3)); } @@ -779,7 +847,8 @@ class EventQueue : private mbed::NonCopyable { * @param ms Period of the event in milliseconds */ template - int call_every(int ms, F f, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + int call_every(int ms, F f, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { return call_every(ms, context50(f, a0, a1, a2, a3, a4)); } @@ -787,7 +856,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, T *obj, R (T::*method)()) { + int call_every(int ms, T *obj, R(T::*method)()) + { return call_every(ms, mbed::callback(obj, method)); } @@ -795,7 +865,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, const T *obj, R (T::*method)() const) { + int call_every(int ms, const T *obj, R(T::*method)() const) + { return call_every(ms, mbed::callback(obj, method)); } @@ -803,7 +874,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, volatile T *obj, R (T::*method)() volatile) { + int call_every(int ms, volatile T *obj, R(T::*method)() volatile) + { return call_every(ms, mbed::callback(obj, method)); } @@ -811,7 +883,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, const volatile T *obj, R (T::*method)() const volatile) { + int call_every(int ms, const volatile T *obj, R(T::*method)() const volatile) + { return call_every(ms, mbed::callback(obj, method)); } @@ -819,7 +892,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, T *obj, R (T::*method)(A0), A0 a0) { + int call_every(int ms, T *obj, R(T::*method)(A0), A0 a0) + { return call_every(ms, mbed::callback(obj, method), a0); } @@ -827,7 +901,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, const T *obj, R (T::*method)(A0) const, A0 a0) { + int call_every(int ms, const T *obj, R(T::*method)(A0) const, A0 a0) + { return call_every(ms, mbed::callback(obj, method), a0); } @@ -835,7 +910,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, volatile T *obj, R (T::*method)(A0) volatile, A0 a0) { + int call_every(int ms, volatile T *obj, R(T::*method)(A0) volatile, A0 a0) + { return call_every(ms, mbed::callback(obj, method), a0); } @@ -843,7 +919,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, const volatile T *obj, R (T::*method)(A0) const volatile, A0 a0) { + int call_every(int ms, const volatile T *obj, R(T::*method)(A0) const volatile, A0 a0) + { return call_every(ms, mbed::callback(obj, method), a0); } @@ -851,7 +928,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, T *obj, R (T::*method)(A0, A1), A0 a0, A1 a1) { + int call_every(int ms, T *obj, R(T::*method)(A0, A1), A0 a0, A1 a1) + { return call_every(ms, mbed::callback(obj, method), a0, a1); } @@ -859,7 +937,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, const T *obj, R (T::*method)(A0, A1) const, A0 a0, A1 a1) { + int call_every(int ms, const T *obj, R(T::*method)(A0, A1) const, A0 a0, A1 a1) + { return call_every(ms, mbed::callback(obj, method), a0, a1); } @@ -867,7 +946,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, volatile T *obj, R (T::*method)(A0, A1) volatile, A0 a0, A1 a1) { + int call_every(int ms, volatile T *obj, R(T::*method)(A0, A1) volatile, A0 a0, A1 a1) + { return call_every(ms, mbed::callback(obj, method), a0, a1); } @@ -875,7 +955,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, const volatile T *obj, R (T::*method)(A0, A1) const volatile, A0 a0, A1 a1) { + int call_every(int ms, const volatile T *obj, R(T::*method)(A0, A1) const volatile, A0 a0, A1 a1) + { return call_every(ms, mbed::callback(obj, method), a0, a1); } @@ -883,7 +964,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, T *obj, R (T::*method)(A0, A1, A2), A0 a0, A1 a1, A2 a2) { + int call_every(int ms, T *obj, R(T::*method)(A0, A1, A2), A0 a0, A1 a1, A2 a2) + { return call_every(ms, mbed::callback(obj, method), a0, a1, a2); } @@ -891,7 +973,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, const T *obj, R (T::*method)(A0, A1, A2) const, A0 a0, A1 a1, A2 a2) { + int call_every(int ms, const T *obj, R(T::*method)(A0, A1, A2) const, A0 a0, A1 a1, A2 a2) + { return call_every(ms, mbed::callback(obj, method), a0, a1, a2); } @@ -899,7 +982,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, volatile T *obj, R (T::*method)(A0, A1, A2) volatile, A0 a0, A1 a1, A2 a2) { + int call_every(int ms, volatile T *obj, R(T::*method)(A0, A1, A2) volatile, A0 a0, A1 a1, A2 a2) + { return call_every(ms, mbed::callback(obj, method), a0, a1, a2); } @@ -907,7 +991,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, const volatile T *obj, R (T::*method)(A0, A1, A2) const volatile, A0 a0, A1 a1, A2 a2) { + int call_every(int ms, const volatile T *obj, R(T::*method)(A0, A1, A2) const volatile, A0 a0, A1 a1, A2 a2) + { return call_every(ms, mbed::callback(obj, method), a0, a1, a2); } @@ -915,7 +1000,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, T *obj, R (T::*method)(A0, A1, A2, A3), A0 a0, A1 a1, A2 a2, A3 a3) { + int call_every(int ms, T *obj, R(T::*method)(A0, A1, A2, A3), A0 a0, A1 a1, A2 a2, A3 a3) + { return call_every(ms, mbed::callback(obj, method), a0, a1, a2, a3); } @@ -923,7 +1009,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, const T *obj, R (T::*method)(A0, A1, A2, A3) const, A0 a0, A1 a1, A2 a2, A3 a3) { + int call_every(int ms, const T *obj, R(T::*method)(A0, A1, A2, A3) const, A0 a0, A1 a1, A2 a2, A3 a3) + { return call_every(ms, mbed::callback(obj, method), a0, a1, a2, a3); } @@ -931,7 +1018,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, volatile T *obj, R (T::*method)(A0, A1, A2, A3) volatile, A0 a0, A1 a1, A2 a2, A3 a3) { + int call_every(int ms, volatile T *obj, R(T::*method)(A0, A1, A2, A3) volatile, A0 a0, A1 a1, A2 a2, A3 a3) + { return call_every(ms, mbed::callback(obj, method), a0, a1, a2, a3); } @@ -939,7 +1027,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, const volatile T *obj, R (T::*method)(A0, A1, A2, A3) const volatile, A0 a0, A1 a1, A2 a2, A3 a3) { + int call_every(int ms, const volatile T *obj, R(T::*method)(A0, A1, A2, A3) const volatile, A0 a0, A1 a1, A2 a2, A3 a3) + { return call_every(ms, mbed::callback(obj, method), a0, a1, a2, a3); } @@ -947,7 +1036,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, T *obj, R (T::*method)(A0, A1, A2, A3, A4), A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + int call_every(int ms, T *obj, R(T::*method)(A0, A1, A2, A3, A4), A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { return call_every(ms, mbed::callback(obj, method), a0, a1, a2, a3, a4); } @@ -955,7 +1045,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, const T *obj, R (T::*method)(A0, A1, A2, A3, A4) const, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + int call_every(int ms, const T *obj, R(T::*method)(A0, A1, A2, A3, A4) const, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { return call_every(ms, mbed::callback(obj, method), a0, a1, a2, a3, a4); } @@ -963,7 +1054,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, volatile T *obj, R (T::*method)(A0, A1, A2, A3, A4) volatile, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + int call_every(int ms, volatile T *obj, R(T::*method)(A0, A1, A2, A3, A4) volatile, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { return call_every(ms, mbed::callback(obj, method), a0, a1, a2, a3, a4); } @@ -971,7 +1063,8 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::call_every */ template - int call_every(int ms, const volatile T *obj, R (T::*method)(A0, A1, A2, A3, A4) const volatile, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + int call_every(int ms, const volatile T *obj, R(T::*method)(A0, A1, A2, A3, A4) const volatile, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { return call_every(ms, mbed::callback(obj, method), a0, a1, a2, a3, a4); } @@ -985,31 +1078,31 @@ class EventQueue : private mbed::NonCopyable { * @return Event that will dispatch on the specific queue */ template - Event event(R (*func)()); + Event event(R(*func)()); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)()); + Event event(T *obj, R(T::*method)()); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)() const); + Event event(const T *obj, R(T::*method)() const); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)() volatile); + Event event(volatile T *obj, R(T::*method)() volatile); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)() const volatile); + Event event(const volatile T *obj, R(T::*method)() const volatile); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1021,31 +1114,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0), C0 c0); + Event event(R(*func)(B0), C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0), C0 c0); + Event event(T *obj, R(T::*method)(B0), C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0) const, C0 c0); + Event event(const T *obj, R(T::*method)(B0) const, C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0) volatile, C0 c0); + Event event(volatile T *obj, R(T::*method)(B0) volatile, C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0) const volatile, C0 c0); + Event event(const volatile T *obj, R(T::*method)(B0) const volatile, C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1057,31 +1150,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1), C0 c0, C1 c1); + Event event(R(*func)(B0, B1), C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1), C0 c0, C1 c1); + Event event(T *obj, R(T::*method)(B0, B1), C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1) const, C0 c0, C1 c1); + Event event(const T *obj, R(T::*method)(B0, B1) const, C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1) volatile, C0 c0, C1 c1); + Event event(volatile T *obj, R(T::*method)(B0, B1) volatile, C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1) const volatile, C0 c0, C1 c1); + Event event(const volatile T *obj, R(T::*method)(B0, B1) const volatile, C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1093,31 +1186,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, B2), C0 c0, C1 c1, C2 c2); + Event event(R(*func)(B0, B1, B2), C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, B2), C0 c0, C1 c1, C2 c2); + Event event(T *obj, R(T::*method)(B0, B1, B2), C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, B2) const, C0 c0, C1 c1, C2 c2); + Event event(const T *obj, R(T::*method)(B0, B1, B2) const, C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, B2) volatile, C0 c0, C1 c1, C2 c2); + Event event(volatile T *obj, R(T::*method)(B0, B1, B2) volatile, C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, B2) const volatile, C0 c0, C1 c1, C2 c2); + Event event(const volatile T *obj, R(T::*method)(B0, B1, B2) const volatile, C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1129,31 +1222,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, B2, B3), C0 c0, C1 c1, C2 c2, C3 c3); + Event event(R(*func)(B0, B1, B2, B3), C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, B2, B3), C0 c0, C1 c1, C2 c2, C3 c3); + Event event(T *obj, R(T::*method)(B0, B1, B2, B3), C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, B2, B3) const, C0 c0, C1 c1, C2 c2, C3 c3); + Event event(const T *obj, R(T::*method)(B0, B1, B2, B3) const, C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, B2, B3) volatile, C0 c0, C1 c1, C2 c2, C3 c3); + Event event(volatile T *obj, R(T::*method)(B0, B1, B2, B3) volatile, C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3) const volatile, C0 c0, C1 c1, C2 c2, C3 c3); + Event event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3) const volatile, C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1165,31 +1258,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, B2, B3, B4), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(R(*func)(B0, B1, B2, B3, B4), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, B2, B3, B4), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(T *obj, R(T::*method)(B0, B1, B2, B3, B4), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, B2, B3, B4) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(const T *obj, R(T::*method)(B0, B1, B2, B3, B4) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1201,31 +1294,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(A0)); + Event event(R(*func)(A0)); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(A0)); + Event event(T *obj, R(T::*method)(A0)); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(A0) const); + Event event(const T *obj, R(T::*method)(A0) const); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(A0) volatile); + Event event(volatile T *obj, R(T::*method)(A0) volatile); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(A0) const volatile); + Event event(const volatile T *obj, R(T::*method)(A0) const volatile); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1237,31 +1330,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, A0), C0 c0); + Event event(R(*func)(B0, A0), C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, A0), C0 c0); + Event event(T *obj, R(T::*method)(B0, A0), C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, A0) const, C0 c0); + Event event(const T *obj, R(T::*method)(B0, A0) const, C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, A0) volatile, C0 c0); + Event event(volatile T *obj, R(T::*method)(B0, A0) volatile, C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, A0) const volatile, C0 c0); + Event event(const volatile T *obj, R(T::*method)(B0, A0) const volatile, C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1273,31 +1366,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, A0), C0 c0, C1 c1); + Event event(R(*func)(B0, B1, A0), C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, A0), C0 c0, C1 c1); + Event event(T *obj, R(T::*method)(B0, B1, A0), C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, A0) const, C0 c0, C1 c1); + Event event(const T *obj, R(T::*method)(B0, B1, A0) const, C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, A0) volatile, C0 c0, C1 c1); + Event event(volatile T *obj, R(T::*method)(B0, B1, A0) volatile, C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, A0) const volatile, C0 c0, C1 c1); + Event event(const volatile T *obj, R(T::*method)(B0, B1, A0) const volatile, C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1309,31 +1402,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, B2, A0), C0 c0, C1 c1, C2 c2); + Event event(R(*func)(B0, B1, B2, A0), C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, B2, A0), C0 c0, C1 c1, C2 c2); + Event event(T *obj, R(T::*method)(B0, B1, B2, A0), C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, B2, A0) const, C0 c0, C1 c1, C2 c2); + Event event(const T *obj, R(T::*method)(B0, B1, B2, A0) const, C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, B2, A0) volatile, C0 c0, C1 c1, C2 c2); + Event event(volatile T *obj, R(T::*method)(B0, B1, B2, A0) volatile, C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, B2, A0) const volatile, C0 c0, C1 c1, C2 c2); + Event event(const volatile T *obj, R(T::*method)(B0, B1, B2, A0) const volatile, C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1345,31 +1438,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, B2, B3, A0), C0 c0, C1 c1, C2 c2, C3 c3); + Event event(R(*func)(B0, B1, B2, B3, A0), C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, B2, B3, A0), C0 c0, C1 c1, C2 c2, C3 c3); + Event event(T *obj, R(T::*method)(B0, B1, B2, B3, A0), C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, B2, B3, A0) const, C0 c0, C1 c1, C2 c2, C3 c3); + Event event(const T *obj, R(T::*method)(B0, B1, B2, B3, A0) const, C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0) volatile, C0 c0, C1 c1, C2 c2, C3 c3); + Event event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0) volatile, C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0) const volatile, C0 c0, C1 c1, C2 c2, C3 c3); + Event event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0) const volatile, C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1381,31 +1474,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, B2, B3, B4, A0), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(R(*func)(B0, B1, B2, B3, B4, A0), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(const T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1417,31 +1510,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(A0, A1)); + Event event(R(*func)(A0, A1)); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(A0, A1)); + Event event(T *obj, R(T::*method)(A0, A1)); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(A0, A1) const); + Event event(const T *obj, R(T::*method)(A0, A1) const); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(A0, A1) volatile); + Event event(volatile T *obj, R(T::*method)(A0, A1) volatile); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(A0, A1) const volatile); + Event event(const volatile T *obj, R(T::*method)(A0, A1) const volatile); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1453,31 +1546,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, A0, A1), C0 c0); + Event event(R(*func)(B0, A0, A1), C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, A0, A1), C0 c0); + Event event(T *obj, R(T::*method)(B0, A0, A1), C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, A0, A1) const, C0 c0); + Event event(const T *obj, R(T::*method)(B0, A0, A1) const, C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, A0, A1) volatile, C0 c0); + Event event(volatile T *obj, R(T::*method)(B0, A0, A1) volatile, C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, A0, A1) const volatile, C0 c0); + Event event(const volatile T *obj, R(T::*method)(B0, A0, A1) const volatile, C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1489,31 +1582,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, A0, A1), C0 c0, C1 c1); + Event event(R(*func)(B0, B1, A0, A1), C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, A0, A1), C0 c0, C1 c1); + Event event(T *obj, R(T::*method)(B0, B1, A0, A1), C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, A0, A1) const, C0 c0, C1 c1); + Event event(const T *obj, R(T::*method)(B0, B1, A0, A1) const, C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, A0, A1) volatile, C0 c0, C1 c1); + Event event(volatile T *obj, R(T::*method)(B0, B1, A0, A1) volatile, C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, A0, A1) const volatile, C0 c0, C1 c1); + Event event(const volatile T *obj, R(T::*method)(B0, B1, A0, A1) const volatile, C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1525,31 +1618,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, B2, A0, A1), C0 c0, C1 c1, C2 c2); + Event event(R(*func)(B0, B1, B2, A0, A1), C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, B2, A0, A1), C0 c0, C1 c1, C2 c2); + Event event(T *obj, R(T::*method)(B0, B1, B2, A0, A1), C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, B2, A0, A1) const, C0 c0, C1 c1, C2 c2); + Event event(const T *obj, R(T::*method)(B0, B1, B2, A0, A1) const, C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1) volatile, C0 c0, C1 c1, C2 c2); + Event event(volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1) volatile, C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1) const volatile, C0 c0, C1 c1, C2 c2); + Event event(const volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1) const volatile, C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1561,31 +1654,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, B2, B3, A0, A1), C0 c0, C1 c1, C2 c2, C3 c3); + Event event(R(*func)(B0, B1, B2, B3, A0, A1), C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1), C0 c0, C1 c1, C2 c2, C3 c3); + Event event(T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1), C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1) const, C0 c0, C1 c1, C2 c2, C3 c3); + Event event(const T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1) const, C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1) volatile, C0 c0, C1 c1, C2 c2, C3 c3); + Event event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1) volatile, C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1) const volatile, C0 c0, C1 c1, C2 c2, C3 c3); + Event event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1) const volatile, C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1597,31 +1690,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, B2, B3, B4, A0, A1), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(R(*func)(B0, B1, B2, B3, B4, A0, A1), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(const T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1633,31 +1726,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(A0, A1, A2)); + Event event(R(*func)(A0, A1, A2)); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(A0, A1, A2)); + Event event(T *obj, R(T::*method)(A0, A1, A2)); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(A0, A1, A2) const); + Event event(const T *obj, R(T::*method)(A0, A1, A2) const); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(A0, A1, A2) volatile); + Event event(volatile T *obj, R(T::*method)(A0, A1, A2) volatile); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(A0, A1, A2) const volatile); + Event event(const volatile T *obj, R(T::*method)(A0, A1, A2) const volatile); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1669,31 +1762,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, A0, A1, A2), C0 c0); + Event event(R(*func)(B0, A0, A1, A2), C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, A0, A1, A2), C0 c0); + Event event(T *obj, R(T::*method)(B0, A0, A1, A2), C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, A0, A1, A2) const, C0 c0); + Event event(const T *obj, R(T::*method)(B0, A0, A1, A2) const, C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, A0, A1, A2) volatile, C0 c0); + Event event(volatile T *obj, R(T::*method)(B0, A0, A1, A2) volatile, C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, A0, A1, A2) const volatile, C0 c0); + Event event(const volatile T *obj, R(T::*method)(B0, A0, A1, A2) const volatile, C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1705,31 +1798,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, A0, A1, A2), C0 c0, C1 c1); + Event event(R(*func)(B0, B1, A0, A1, A2), C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, A0, A1, A2), C0 c0, C1 c1); + Event event(T *obj, R(T::*method)(B0, B1, A0, A1, A2), C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, A0, A1, A2) const, C0 c0, C1 c1); + Event event(const T *obj, R(T::*method)(B0, B1, A0, A1, A2) const, C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, A0, A1, A2) volatile, C0 c0, C1 c1); + Event event(volatile T *obj, R(T::*method)(B0, B1, A0, A1, A2) volatile, C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, A0, A1, A2) const volatile, C0 c0, C1 c1); + Event event(const volatile T *obj, R(T::*method)(B0, B1, A0, A1, A2) const volatile, C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1741,31 +1834,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, B2, A0, A1, A2), C0 c0, C1 c1, C2 c2); + Event event(R(*func)(B0, B1, B2, A0, A1, A2), C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2), C0 c0, C1 c1, C2 c2); + Event event(T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2), C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2) const, C0 c0, C1 c1, C2 c2); + Event event(const T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2) const, C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2) volatile, C0 c0, C1 c1, C2 c2); + Event event(volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2) volatile, C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2) const volatile, C0 c0, C1 c1, C2 c2); + Event event(const volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2) const volatile, C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1777,31 +1870,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, B2, B3, A0, A1, A2), C0 c0, C1 c1, C2 c2, C3 c3); + Event event(R(*func)(B0, B1, B2, B3, A0, A1, A2), C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2), C0 c0, C1 c1, C2 c2, C3 c3); + Event event(T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2), C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2) const, C0 c0, C1 c1, C2 c2, C3 c3); + Event event(const T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2) const, C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2) volatile, C0 c0, C1 c1, C2 c2, C3 c3); + Event event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2) volatile, C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2) const volatile, C0 c0, C1 c1, C2 c2, C3 c3); + Event event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2) const volatile, C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1813,31 +1906,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, B2, B3, B4, A0, A1, A2), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(R(*func)(B0, B1, B2, B3, B4, A0, A1, A2), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(const T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1849,31 +1942,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(A0, A1, A2, A3)); + Event event(R(*func)(A0, A1, A2, A3)); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(A0, A1, A2, A3)); + Event event(T *obj, R(T::*method)(A0, A1, A2, A3)); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(A0, A1, A2, A3) const); + Event event(const T *obj, R(T::*method)(A0, A1, A2, A3) const); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(A0, A1, A2, A3) volatile); + Event event(volatile T *obj, R(T::*method)(A0, A1, A2, A3) volatile); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(A0, A1, A2, A3) const volatile); + Event event(const volatile T *obj, R(T::*method)(A0, A1, A2, A3) const volatile); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1885,31 +1978,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, A0, A1, A2, A3), C0 c0); + Event event(R(*func)(B0, A0, A1, A2, A3), C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, A0, A1, A2, A3), C0 c0); + Event event(T *obj, R(T::*method)(B0, A0, A1, A2, A3), C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, A0, A1, A2, A3) const, C0 c0); + Event event(const T *obj, R(T::*method)(B0, A0, A1, A2, A3) const, C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, A0, A1, A2, A3) volatile, C0 c0); + Event event(volatile T *obj, R(T::*method)(B0, A0, A1, A2, A3) volatile, C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, A0, A1, A2, A3) const volatile, C0 c0); + Event event(const volatile T *obj, R(T::*method)(B0, A0, A1, A2, A3) const volatile, C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1921,31 +2014,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, A0, A1, A2, A3), C0 c0, C1 c1); + Event event(R(*func)(B0, B1, A0, A1, A2, A3), C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3), C0 c0, C1 c1); + Event event(T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3), C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3) const, C0 c0, C1 c1); + Event event(const T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3) const, C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3) volatile, C0 c0, C1 c1); + Event event(volatile T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3) volatile, C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3) const volatile, C0 c0, C1 c1); + Event event(const volatile T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3) const volatile, C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1957,31 +2050,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, B2, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2); + Event event(R(*func)(B0, B1, B2, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2); + Event event(T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3) const, C0 c0, C1 c1, C2 c2); + Event event(const T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3) const, C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3) volatile, C0 c0, C1 c1, C2 c2); + Event event(volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3) volatile, C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3) const volatile, C0 c0, C1 c1, C2 c2); + Event event(const volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3) const volatile, C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event @@ -1993,31 +2086,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, B2, B3, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2, C3 c3); + Event event(R(*func)(B0, B1, B2, B3, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2, C3 c3); + Event event(T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3) const, C0 c0, C1 c1, C2 c2, C3 c3); + Event event(const T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3) const, C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3) volatile, C0 c0, C1 c1, C2 c2, C3 c3); + Event event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3) volatile, C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3) const volatile, C0 c0, C1 c1, C2 c2, C3 c3); + Event event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3) const volatile, C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event @@ -2029,31 +2122,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, B2, B3, B4, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(R(*func)(B0, B1, B2, B3, B4, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(const T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event @@ -2065,31 +2158,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(A0, A1, A2, A3, A4)); + Event event(R(*func)(A0, A1, A2, A3, A4)); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(A0, A1, A2, A3, A4)); + Event event(T *obj, R(T::*method)(A0, A1, A2, A3, A4)); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(A0, A1, A2, A3, A4) const); + Event event(const T *obj, R(T::*method)(A0, A1, A2, A3, A4) const); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(A0, A1, A2, A3, A4) volatile); + Event event(volatile T *obj, R(T::*method)(A0, A1, A2, A3, A4) volatile); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(A0, A1, A2, A3, A4) const volatile); + Event event(const volatile T *obj, R(T::*method)(A0, A1, A2, A3, A4) const volatile); /** Creates an event bound to the event queue * @see EventQueue::event @@ -2101,31 +2194,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, A0, A1, A2, A3, A4), C0 c0); + Event event(R(*func)(B0, A0, A1, A2, A3, A4), C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, A0, A1, A2, A3, A4), C0 c0); + Event event(T *obj, R(T::*method)(B0, A0, A1, A2, A3, A4), C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, A0, A1, A2, A3, A4) const, C0 c0); + Event event(const T *obj, R(T::*method)(B0, A0, A1, A2, A3, A4) const, C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, A0, A1, A2, A3, A4) volatile, C0 c0); + Event event(volatile T *obj, R(T::*method)(B0, A0, A1, A2, A3, A4) volatile, C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, A0, A1, A2, A3, A4) const volatile, C0 c0); + Event event(const volatile T *obj, R(T::*method)(B0, A0, A1, A2, A3, A4) const volatile, C0 c0); /** Creates an event bound to the event queue * @see EventQueue::event @@ -2137,31 +2230,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, A0, A1, A2, A3, A4), C0 c0, C1 c1); + Event event(R(*func)(B0, B1, A0, A1, A2, A3, A4), C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3, A4), C0 c0, C1 c1); + Event event(T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3, A4), C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3, A4) const, C0 c0, C1 c1); + Event event(const T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3, A4) const, C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3, A4) volatile, C0 c0, C1 c1); + Event event(volatile T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3, A4) volatile, C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, A0, A1, A2, A3, A4) const volatile, C0 c0, C1 c1); + Event event(const volatile T *obj, R(T::*method)(B0, B1, A0, A1, A2, A3, A4) const volatile, C0 c0, C1 c1); /** Creates an event bound to the event queue * @see EventQueue::event @@ -2173,31 +2266,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, B2, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2); + Event event(R(*func)(B0, B1, B2, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2); + Event event(T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3, A4) const, C0 c0, C1 c1, C2 c2); + Event event(const T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3, A4) const, C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3, A4) volatile, C0 c0, C1 c1, C2 c2); + Event event(volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3, A4) volatile, C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, B2, A0, A1, A2, A3, A4) const volatile, C0 c0, C1 c1, C2 c2); + Event event(const volatile T *obj, R(T::*method)(B0, B1, B2, A0, A1, A2, A3, A4) const volatile, C0 c0, C1 c1, C2 c2); /** Creates an event bound to the event queue * @see EventQueue::event @@ -2209,31 +2302,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, B2, B3, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2, C3 c3); + Event event(R(*func)(B0, B1, B2, B3, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2, C3 c3); + Event event(T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4) const, C0 c0, C1 c1, C2 c2, C3 c3); + Event event(const T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4) const, C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4) volatile, C0 c0, C1 c1, C2 c2, C3 c3); + Event event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4) volatile, C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4) const volatile, C0 c0, C1 c1, C2 c2, C3 c3); + Event event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, A0, A1, A2, A3, A4) const volatile, C0 c0, C1 c1, C2 c2, C3 c3); /** Creates an event bound to the event queue * @see EventQueue::event @@ -2245,31 +2338,31 @@ class EventQueue : private mbed::NonCopyable { * @see EventQueue::event */ template - Event event(R (*func)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(R(*func)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4), C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(const T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4) const, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4) volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event */ template - Event event(const volatile T *obj, R (T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); + Event event(const volatile T *obj, R(T::*method)(B0, B1, B2, B3, B4, A0, A1, A2, A3, A4) const volatile, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4); /** Creates an event bound to the event queue * @see EventQueue::event @@ -2285,13 +2378,15 @@ class EventQueue : private mbed::NonCopyable { // Function attributes template - static void function_call(void *p) { - (*(F*)p)(); + static void function_call(void *p) + { + (*(F *)p)(); } template - static void function_dtor(void *p) { - ((F*)p)->~F(); + static void function_dtor(void *p) + { + ((F *)p)->~F(); } // Context structures @@ -2302,67 +2397,88 @@ class EventQueue : private mbed::NonCopyable { context00(F f) : f(f) {} - void operator()() { + void operator()() + { f(); } }; template struct context10 { - F f; C0 c0; + F f; + C0 c0; context10(F f, C0 c0) : f(f), c0(c0) {} - void operator()() { + void operator()() + { f(c0); } }; template struct context20 { - F f; C0 c0; C1 c1; + F f; + C0 c0; + C1 c1; context20(F f, C0 c0, C1 c1) : f(f), c0(c0), c1(c1) {} - void operator()() { + void operator()() + { f(c0, c1); } }; template struct context30 { - F f; C0 c0; C1 c1; C2 c2; + F f; + C0 c0; + C1 c1; + C2 c2; context30(F f, C0 c0, C1 c1, C2 c2) : f(f), c0(c0), c1(c1), c2(c2) {} - void operator()() { + void operator()() + { f(c0, c1, c2); } }; template struct context40 { - F f; C0 c0; C1 c1; C2 c2; C3 c3; + F f; + C0 c0; + C1 c1; + C2 c2; + C3 c3; context40(F f, C0 c0, C1 c1, C2 c2, C3 c3) : f(f), c0(c0), c1(c1), c2(c2), c3(c3) {} - void operator()() { + void operator()() + { f(c0, c1, c2, c3); } }; template struct context50 { - F f; C0 c0; C1 c1; C2 c2; C3 c3; C4 c4; + F f; + C0 c0; + C1 c1; + C2 c2; + C3 c3; + C4 c4; context50(F f, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) : f(f), c0(c0), c1(c1), c2(c2), c3(c3), c4(c4) {} - void operator()() { + void operator()() + { f(c0, c1, c2, c3, c4); } }; @@ -2374,67 +2490,88 @@ class EventQueue : private mbed::NonCopyable { context01(F f) : f(f) {} - void operator()(A0 a0) { + void operator()(A0 a0) + { f(a0); } }; template struct context11 { - F f; C0 c0; + F f; + C0 c0; context11(F f, C0 c0) : f(f), c0(c0) {} - void operator()(A0 a0) { + void operator()(A0 a0) + { f(c0, a0); } }; template struct context21 { - F f; C0 c0; C1 c1; + F f; + C0 c0; + C1 c1; context21(F f, C0 c0, C1 c1) : f(f), c0(c0), c1(c1) {} - void operator()(A0 a0) { + void operator()(A0 a0) + { f(c0, c1, a0); } }; template struct context31 { - F f; C0 c0; C1 c1; C2 c2; + F f; + C0 c0; + C1 c1; + C2 c2; context31(F f, C0 c0, C1 c1, C2 c2) : f(f), c0(c0), c1(c1), c2(c2) {} - void operator()(A0 a0) { + void operator()(A0 a0) + { f(c0, c1, c2, a0); } }; template struct context41 { - F f; C0 c0; C1 c1; C2 c2; C3 c3; + F f; + C0 c0; + C1 c1; + C2 c2; + C3 c3; context41(F f, C0 c0, C1 c1, C2 c2, C3 c3) : f(f), c0(c0), c1(c1), c2(c2), c3(c3) {} - void operator()(A0 a0) { + void operator()(A0 a0) + { f(c0, c1, c2, c3, a0); } }; template struct context51 { - F f; C0 c0; C1 c1; C2 c2; C3 c3; C4 c4; + F f; + C0 c0; + C1 c1; + C2 c2; + C3 c3; + C4 c4; context51(F f, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) : f(f), c0(c0), c1(c1), c2(c2), c3(c3), c4(c4) {} - void operator()(A0 a0) { + void operator()(A0 a0) + { f(c0, c1, c2, c3, c4, a0); } }; @@ -2446,67 +2583,88 @@ class EventQueue : private mbed::NonCopyable { context02(F f) : f(f) {} - void operator()(A0 a0, A1 a1) { + void operator()(A0 a0, A1 a1) + { f(a0, a1); } }; template struct context12 { - F f; C0 c0; + F f; + C0 c0; context12(F f, C0 c0) : f(f), c0(c0) {} - void operator()(A0 a0, A1 a1) { + void operator()(A0 a0, A1 a1) + { f(c0, a0, a1); } }; template struct context22 { - F f; C0 c0; C1 c1; + F f; + C0 c0; + C1 c1; context22(F f, C0 c0, C1 c1) : f(f), c0(c0), c1(c1) {} - void operator()(A0 a0, A1 a1) { + void operator()(A0 a0, A1 a1) + { f(c0, c1, a0, a1); } }; template struct context32 { - F f; C0 c0; C1 c1; C2 c2; + F f; + C0 c0; + C1 c1; + C2 c2; context32(F f, C0 c0, C1 c1, C2 c2) : f(f), c0(c0), c1(c1), c2(c2) {} - void operator()(A0 a0, A1 a1) { + void operator()(A0 a0, A1 a1) + { f(c0, c1, c2, a0, a1); } }; template struct context42 { - F f; C0 c0; C1 c1; C2 c2; C3 c3; + F f; + C0 c0; + C1 c1; + C2 c2; + C3 c3; context42(F f, C0 c0, C1 c1, C2 c2, C3 c3) : f(f), c0(c0), c1(c1), c2(c2), c3(c3) {} - void operator()(A0 a0, A1 a1) { + void operator()(A0 a0, A1 a1) + { f(c0, c1, c2, c3, a0, a1); } }; template struct context52 { - F f; C0 c0; C1 c1; C2 c2; C3 c3; C4 c4; + F f; + C0 c0; + C1 c1; + C2 c2; + C3 c3; + C4 c4; context52(F f, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) : f(f), c0(c0), c1(c1), c2(c2), c3(c3), c4(c4) {} - void operator()(A0 a0, A1 a1) { + void operator()(A0 a0, A1 a1) + { f(c0, c1, c2, c3, c4, a0, a1); } }; @@ -2518,67 +2676,88 @@ class EventQueue : private mbed::NonCopyable { context03(F f) : f(f) {} - void operator()(A0 a0, A1 a1, A2 a2) { + void operator()(A0 a0, A1 a1, A2 a2) + { f(a0, a1, a2); } }; template struct context13 { - F f; C0 c0; + F f; + C0 c0; context13(F f, C0 c0) : f(f), c0(c0) {} - void operator()(A0 a0, A1 a1, A2 a2) { + void operator()(A0 a0, A1 a1, A2 a2) + { f(c0, a0, a1, a2); } }; template struct context23 { - F f; C0 c0; C1 c1; + F f; + C0 c0; + C1 c1; context23(F f, C0 c0, C1 c1) : f(f), c0(c0), c1(c1) {} - void operator()(A0 a0, A1 a1, A2 a2) { + void operator()(A0 a0, A1 a1, A2 a2) + { f(c0, c1, a0, a1, a2); } }; template struct context33 { - F f; C0 c0; C1 c1; C2 c2; + F f; + C0 c0; + C1 c1; + C2 c2; context33(F f, C0 c0, C1 c1, C2 c2) : f(f), c0(c0), c1(c1), c2(c2) {} - void operator()(A0 a0, A1 a1, A2 a2) { + void operator()(A0 a0, A1 a1, A2 a2) + { f(c0, c1, c2, a0, a1, a2); } }; template struct context43 { - F f; C0 c0; C1 c1; C2 c2; C3 c3; + F f; + C0 c0; + C1 c1; + C2 c2; + C3 c3; context43(F f, C0 c0, C1 c1, C2 c2, C3 c3) : f(f), c0(c0), c1(c1), c2(c2), c3(c3) {} - void operator()(A0 a0, A1 a1, A2 a2) { + void operator()(A0 a0, A1 a1, A2 a2) + { f(c0, c1, c2, c3, a0, a1, a2); } }; template struct context53 { - F f; C0 c0; C1 c1; C2 c2; C3 c3; C4 c4; + F f; + C0 c0; + C1 c1; + C2 c2; + C3 c3; + C4 c4; context53(F f, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) : f(f), c0(c0), c1(c1), c2(c2), c3(c3), c4(c4) {} - void operator()(A0 a0, A1 a1, A2 a2) { + void operator()(A0 a0, A1 a1, A2 a2) + { f(c0, c1, c2, c3, c4, a0, a1, a2); } }; @@ -2590,67 +2769,88 @@ class EventQueue : private mbed::NonCopyable { context04(F f) : f(f) {} - void operator()(A0 a0, A1 a1, A2 a2, A3 a3) { + void operator()(A0 a0, A1 a1, A2 a2, A3 a3) + { f(a0, a1, a2, a3); } }; template struct context14 { - F f; C0 c0; + F f; + C0 c0; context14(F f, C0 c0) : f(f), c0(c0) {} - void operator()(A0 a0, A1 a1, A2 a2, A3 a3) { + void operator()(A0 a0, A1 a1, A2 a2, A3 a3) + { f(c0, a0, a1, a2, a3); } }; template struct context24 { - F f; C0 c0; C1 c1; + F f; + C0 c0; + C1 c1; context24(F f, C0 c0, C1 c1) : f(f), c0(c0), c1(c1) {} - void operator()(A0 a0, A1 a1, A2 a2, A3 a3) { + void operator()(A0 a0, A1 a1, A2 a2, A3 a3) + { f(c0, c1, a0, a1, a2, a3); } }; template struct context34 { - F f; C0 c0; C1 c1; C2 c2; + F f; + C0 c0; + C1 c1; + C2 c2; context34(F f, C0 c0, C1 c1, C2 c2) : f(f), c0(c0), c1(c1), c2(c2) {} - void operator()(A0 a0, A1 a1, A2 a2, A3 a3) { + void operator()(A0 a0, A1 a1, A2 a2, A3 a3) + { f(c0, c1, c2, a0, a1, a2, a3); } }; template struct context44 { - F f; C0 c0; C1 c1; C2 c2; C3 c3; + F f; + C0 c0; + C1 c1; + C2 c2; + C3 c3; context44(F f, C0 c0, C1 c1, C2 c2, C3 c3) : f(f), c0(c0), c1(c1), c2(c2), c3(c3) {} - void operator()(A0 a0, A1 a1, A2 a2, A3 a3) { + void operator()(A0 a0, A1 a1, A2 a2, A3 a3) + { f(c0, c1, c2, c3, a0, a1, a2, a3); } }; template struct context54 { - F f; C0 c0; C1 c1; C2 c2; C3 c3; C4 c4; + F f; + C0 c0; + C1 c1; + C2 c2; + C3 c3; + C4 c4; context54(F f, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) : f(f), c0(c0), c1(c1), c2(c2), c3(c3), c4(c4) {} - void operator()(A0 a0, A1 a1, A2 a2, A3 a3) { + void operator()(A0 a0, A1 a1, A2 a2, A3 a3) + { f(c0, c1, c2, c3, c4, a0, a1, a2, a3); } }; @@ -2662,67 +2862,88 @@ class EventQueue : private mbed::NonCopyable { context05(F f) : f(f) {} - void operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + void operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { f(a0, a1, a2, a3, a4); } }; template struct context15 { - F f; C0 c0; + F f; + C0 c0; context15(F f, C0 c0) : f(f), c0(c0) {} - void operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + void operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { f(c0, a0, a1, a2, a3, a4); } }; template struct context25 { - F f; C0 c0; C1 c1; + F f; + C0 c0; + C1 c1; context25(F f, C0 c0, C1 c1) : f(f), c0(c0), c1(c1) {} - void operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + void operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { f(c0, c1, a0, a1, a2, a3, a4); } }; template struct context35 { - F f; C0 c0; C1 c1; C2 c2; + F f; + C0 c0; + C1 c1; + C2 c2; context35(F f, C0 c0, C1 c1, C2 c2) : f(f), c0(c0), c1(c1), c2(c2) {} - void operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + void operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { f(c0, c1, c2, a0, a1, a2, a3, a4); } }; template struct context45 { - F f; C0 c0; C1 c1; C2 c2; C3 c3; + F f; + C0 c0; + C1 c1; + C2 c2; + C3 c3; context45(F f, C0 c0, C1 c1, C2 c2, C3 c3) : f(f), c0(c0), c1(c1), c2(c2), c3(c3) {} - void operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + void operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { f(c0, c1, c2, c3, a0, a1, a2, a3, a4); } }; template struct context55 { - F f; C0 c0; C1 c1; C2 c2; C3 c3; C4 c4; + F f; + C0 c0; + C1 c1; + C2 c2; + C3 c3; + C4 c4; context55(F f, C0 c0, C1 c1, C2 c2, C3 c3, C4 c4) : f(f), c0(c0), c1(c1), c2(c2), c3(c3), c4(c4) {} - void operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { + void operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { f(c0, c1, c2, c3, c4, a0, a1, a2, a3, a4); } }; diff --git a/events/equeue/equeue.c b/events/equeue/equeue.c index 54b29e89b1c..f10fd75f688 100644 --- a/events/equeue/equeue.c +++ b/events/equeue/equeue.c @@ -23,19 +23,22 @@ // calculate the relative-difference between absolute times while // correctly handling overflow conditions -static inline int equeue_tickdiff(unsigned a, unsigned b) { +static inline int equeue_tickdiff(unsigned a, unsigned b) +{ return (int)(unsigned)(a - b); } // calculate the relative-difference between absolute times, but // also clamp to zero, resulting in only non-zero values. -static inline int equeue_clampdiff(unsigned a, unsigned b) { +static inline int equeue_clampdiff(unsigned a, unsigned b) +{ int diff = equeue_tickdiff(a, b); - return ~(diff >> (8*sizeof(int)-1)) & diff; + return ~(diff >> (8 * sizeof(int) -1)) & diff; } // Increment the unique id in an event, hiding the event from cancel -static inline void equeue_incid(equeue_t *q, struct equeue_event *e) { +static inline void equeue_incid(equeue_t *q, struct equeue_event *e) +{ e->id += 1; if ((e->id << q->npw2) == 0) { e->id = 1; @@ -44,7 +47,8 @@ static inline void equeue_incid(equeue_t *q, struct equeue_event *e) { // equeue lifetime management -int equeue_create(equeue_t *q, size_t size) { +int equeue_create(equeue_t *q, size_t size) +{ // dynamically allocate the specified buffer void *buffer = malloc(size); if (!buffer) { @@ -56,7 +60,8 @@ int equeue_create(equeue_t *q, size_t size) { return err; } -int equeue_create_inplace(equeue_t *q, size_t size, void *buffer) { +int equeue_create_inplace(equeue_t *q, size_t size, void *buffer) +{ // setup queue around provided buffer q->buffer = buffer; q->allocated = 0; @@ -99,7 +104,8 @@ int equeue_create_inplace(equeue_t *q, size_t size, void *buffer) { return 0; } -void equeue_destroy(equeue_t *q) { +void equeue_destroy(equeue_t *q) +{ // call destructors on pending events for (struct equeue_event *es = q->queue; es; es = es->next) { for (struct equeue_event *e = q->queue; e; e = e->sibling) { @@ -123,10 +129,11 @@ void equeue_destroy(equeue_t *q) { // equeue chunk allocation functions -static struct equeue_event *equeue_mem_alloc(equeue_t *q, size_t size) { +static struct equeue_event *equeue_mem_alloc(equeue_t *q, size_t size) +{ // add event overhead size += sizeof(struct equeue_event); - size = (size + sizeof(void*)-1) & ~(sizeof(void*)-1); + size = (size + sizeof(void *) -1) & ~(sizeof(void *) -1); equeue_mutex_lock(&q->memlock); @@ -162,7 +169,8 @@ static struct equeue_event *equeue_mem_alloc(equeue_t *q, size_t size) { return 0; } -static void equeue_mem_dealloc(equeue_t *q, struct equeue_event *e) { +static void equeue_mem_dealloc(equeue_t *q, struct equeue_event *e) +{ equeue_mutex_lock(&q->memlock); // stick chunk into list of chunks @@ -183,7 +191,8 @@ static void equeue_mem_dealloc(equeue_t *q, struct equeue_event *e) { equeue_mutex_unlock(&q->memlock); } -void *equeue_alloc(equeue_t *q, size_t size) { +void *equeue_alloc(equeue_t *q, size_t size) +{ struct equeue_event *e = equeue_mem_alloc(q, size); if (!e) { return 0; @@ -196,11 +205,12 @@ void *equeue_alloc(equeue_t *q, size_t size) { return e + 1; } -void equeue_dealloc(equeue_t *q, void *p) { - struct equeue_event *e = (struct equeue_event*)p - 1; +void equeue_dealloc(equeue_t *q, void *p) +{ + struct equeue_event *e = (struct equeue_event *)p - 1; if (e->dtor) { - e->dtor(e+1); + e->dtor(e + 1); } equeue_mem_dealloc(q, e); @@ -208,7 +218,8 @@ void equeue_dealloc(equeue_t *q, void *p) { // equeue scheduling functions -static int equeue_enqueue(equeue_t *q, struct equeue_event *e, unsigned tick) { +static int equeue_enqueue(equeue_t *q, struct equeue_event *e, unsigned tick) +{ // setup event and hash local id with buffer offset for unique id int id = (e->id << q->npw2) | ((unsigned char *)e - q->buffer); e->target = tick + equeue_clampdiff(e->target, tick); @@ -245,9 +256,9 @@ static int equeue_enqueue(equeue_t *q, struct equeue_event *e, unsigned tick) { // notify background timer if ((q->background.update && q->background.active) && - (q->queue == e && !e->sibling)) { + (q->queue == e && !e->sibling)) { q->background.update(q->background.timer, - equeue_clampdiff(e->target, tick)); + equeue_clampdiff(e->target, tick)); } equeue_mutex_unlock(&q->queuelock); @@ -255,10 +266,11 @@ static int equeue_enqueue(equeue_t *q, struct equeue_event *e, unsigned tick) { return id; } -static struct equeue_event *equeue_unqueue(equeue_t *q, int id) { +static struct equeue_event *equeue_unqueue(equeue_t *q, int id) +{ // decode event from unique id and check that the local id matches struct equeue_event *e = (struct equeue_event *) - &q->buffer[id & ((1 << q->npw2)-1)]; + &q->buffer[id & ((1 << q->npw2) - 1)]; equeue_mutex_lock(&q->queuelock); if (e->id != id >> q->npw2) { @@ -298,7 +310,8 @@ static struct equeue_event *equeue_unqueue(equeue_t *q, int id) { return e; } -static struct equeue_event *equeue_dequeue(equeue_t *q, unsigned target) { +static struct equeue_event *equeue_dequeue(equeue_t *q, unsigned target) +{ equeue_mutex_lock(&q->queuelock); // find all expired events and mark a new generation @@ -342,8 +355,9 @@ static struct equeue_event *equeue_dequeue(equeue_t *q, unsigned target) { return head; } -int equeue_post(equeue_t *q, void (*cb)(void*), void *p) { - struct equeue_event *e = (struct equeue_event*)p - 1; +int equeue_post(equeue_t *q, void (*cb)(void *), void *p) +{ + struct equeue_event *e = (struct equeue_event *)p - 1; unsigned tick = equeue_tick(); e->cb = cb; e->target = tick + e->target; @@ -353,7 +367,8 @@ int equeue_post(equeue_t *q, void (*cb)(void*), void *p) { return id; } -void equeue_cancel(equeue_t *q, int id) { +void equeue_cancel(equeue_t *q, int id) +{ if (!id) { return; } @@ -364,14 +379,16 @@ void equeue_cancel(equeue_t *q, int id) { } } -void equeue_break(equeue_t *q) { +void equeue_break(equeue_t *q) +{ equeue_mutex_lock(&q->queuelock); q->breaks++; equeue_mutex_unlock(&q->queuelock); equeue_sema_signal(&q->eventsema); } -void equeue_dispatch(equeue_t *q, int ms) { +void equeue_dispatch(equeue_t *q, int ms) +{ unsigned tick = equeue_tick(); unsigned timeout = tick + ms; q->background.active = false; @@ -397,7 +414,7 @@ void equeue_dispatch(equeue_t *q, int ms) { equeue_enqueue(q, e, equeue_tick()); } else { equeue_incid(q, e); - equeue_dealloc(q, e+1); + equeue_dealloc(q, e + 1); } } @@ -413,7 +430,7 @@ void equeue_dispatch(equeue_t *q, int ms) { equeue_mutex_lock(&q->queuelock); if (q->background.update && q->queue) { q->background.update(q->background.timer, - equeue_clampdiff(q->queue->target, tick)); + equeue_clampdiff(q->queue->target, tick)); } q->background.active = true; equeue_mutex_unlock(&q->queuelock); @@ -453,34 +470,39 @@ void equeue_dispatch(equeue_t *q, int ms) { // event functions -void equeue_event_delay(void *p, int ms) { - struct equeue_event *e = (struct equeue_event*)p - 1; +void equeue_event_delay(void *p, int ms) +{ + struct equeue_event *e = (struct equeue_event *)p - 1; e->target = ms; } -void equeue_event_period(void *p, int ms) { - struct equeue_event *e = (struct equeue_event*)p - 1; +void equeue_event_period(void *p, int ms) +{ + struct equeue_event *e = (struct equeue_event *)p - 1; e->period = ms; } -void equeue_event_dtor(void *p, void (*dtor)(void *)) { - struct equeue_event *e = (struct equeue_event*)p - 1; +void equeue_event_dtor(void *p, void (*dtor)(void *)) +{ + struct equeue_event *e = (struct equeue_event *)p - 1; e->dtor = dtor; } // simple callbacks struct ecallback { - void (*cb)(void*); + void (*cb)(void *); void *data; }; -static void ecallback_dispatch(void *p) { - struct ecallback *e = (struct ecallback*)p; +static void ecallback_dispatch(void *p) +{ + struct ecallback *e = (struct ecallback *)p; e->cb(e->data); } -int equeue_call(equeue_t *q, void (*cb)(void*), void *data) { +int equeue_call(equeue_t *q, void (*cb)(void *), void *data) +{ struct ecallback *e = equeue_alloc(q, sizeof(struct ecallback)); if (!e) { return 0; @@ -491,7 +513,8 @@ int equeue_call(equeue_t *q, void (*cb)(void*), void *data) { return equeue_post(q, ecallback_dispatch, e); } -int equeue_call_in(equeue_t *q, int ms, void (*cb)(void*), void *data) { +int equeue_call_in(equeue_t *q, int ms, void (*cb)(void *), void *data) +{ struct ecallback *e = equeue_alloc(q, sizeof(struct ecallback)); if (!e) { return 0; @@ -503,7 +526,8 @@ int equeue_call_in(equeue_t *q, int ms, void (*cb)(void*), void *data) { return equeue_post(q, ecallback_dispatch, e); } -int equeue_call_every(equeue_t *q, int ms, void (*cb)(void*), void *data) { +int equeue_call_every(equeue_t *q, int ms, void (*cb)(void *), void *data) +{ struct ecallback *e = equeue_alloc(q, sizeof(struct ecallback)); if (!e) { return 0; @@ -519,7 +543,8 @@ int equeue_call_every(equeue_t *q, int ms, void (*cb)(void*), void *data) { // backgrounding void equeue_background(equeue_t *q, - void (*update)(void *timer, int ms), void *timer) { + void (*update)(void *timer, int ms), void *timer) +{ equeue_mutex_lock(&q->queuelock); if (q->background.update) { q->background.update(q->background.timer, -1); @@ -530,7 +555,7 @@ void equeue_background(equeue_t *q, if (q->background.update && q->queue) { q->background.update(q->background.timer, - equeue_clampdiff(q->queue->target, equeue_tick())); + equeue_clampdiff(q->queue->target, equeue_tick())); } q->background.active = true; equeue_mutex_unlock(&q->queuelock); @@ -542,11 +567,13 @@ struct equeue_chain_context { int id; }; -static void equeue_chain_dispatch(void *p) { +static void equeue_chain_dispatch(void *p) +{ equeue_dispatch((equeue_t *)p, 0); } -static void equeue_chain_update(void *p, int ms) { +static void equeue_chain_update(void *p, int ms) +{ struct equeue_chain_context *c = (struct equeue_chain_context *)p; equeue_cancel(c->target, c->id); @@ -557,14 +584,15 @@ static void equeue_chain_update(void *p, int ms) { } } -void equeue_chain(equeue_t *q, equeue_t *target) { +void equeue_chain(equeue_t *q, equeue_t *target) +{ if (!target) { equeue_background(q, 0, 0); return; } struct equeue_chain_context *c = equeue_alloc(q, - sizeof(struct equeue_chain_context)); + sizeof(struct equeue_chain_context)); c->q = q; c->target = target; diff --git a/events/equeue/equeue.h b/events/equeue/equeue.h index 80ee9c70280..092f1198330 100644 --- a/events/equeue/equeue.h +++ b/events/equeue/equeue.h @@ -199,7 +199,7 @@ void equeue_cancel(equeue_t *queue, int id); // of hardware timers or even other event loops, allowing an event queue to // be effectively backgrounded. void equeue_background(equeue_t *queue, - void (*update)(void *timer, int ms), void *timer); + void (*update)(void *timer, int ms), void *timer); // Chain an event queue onto another event queue // diff --git a/events/equeue/equeue_mbed.cpp b/events/equeue/equeue_mbed.cpp index 7b1fd2f03fa..fba1d98a241 100644 --- a/events/equeue/equeue_mbed.cpp +++ b/events/equeue/equeue_mbed.cpp @@ -37,20 +37,22 @@ static bool equeue_tick_inited = false; static volatile unsigned equeue_minutes = 0; static unsigned equeue_timer[ - (sizeof(ALIAS_TIMER)+sizeof(unsigned)-1)/sizeof(unsigned)]; + (sizeof(ALIAS_TIMER) + sizeof(unsigned) - 1) / sizeof(unsigned)]; static unsigned equeue_ticker[ - (sizeof(ALIAS_TICKER)+sizeof(unsigned)-1)/sizeof(unsigned)]; + (sizeof(ALIAS_TICKER) + sizeof(unsigned) - 1) / sizeof(unsigned)]; -static void equeue_tick_update() { - equeue_minutes += reinterpret_cast(equeue_timer)->read_ms(); - reinterpret_cast(equeue_timer)->reset(); +static void equeue_tick_update() +{ + equeue_minutes += reinterpret_cast(equeue_timer)->read_ms(); + reinterpret_cast(equeue_timer)->reset(); } -static void equeue_tick_init() { +static void equeue_tick_init() +{ MBED_STATIC_ASSERT(sizeof(equeue_timer) >= sizeof(ALIAS_TIMER), - "The equeue_timer buffer must fit the class Timer"); + "The equeue_timer buffer must fit the class Timer"); MBED_STATIC_ASSERT(sizeof(equeue_ticker) >= sizeof(ALIAS_TICKER), - "The equeue_ticker buffer must fit the class Ticker"); + "The equeue_ticker buffer must fit the class Ticker"); ALIAS_TIMER *timer = new (equeue_timer) ALIAS_TIMER; ALIAS_TICKER *ticker = new (equeue_ticker) ALIAS_TICKER; @@ -61,7 +63,8 @@ static void equeue_tick_init() { equeue_tick_inited = true; } -unsigned equeue_tick() { +unsigned equeue_tick() +{ if (!equeue_tick_inited) { equeue_tick_init(); } @@ -71,7 +74,7 @@ unsigned equeue_tick() { do { minutes = equeue_minutes; - ms = reinterpret_cast(equeue_timer)->read_ms(); + ms = reinterpret_cast(equeue_timer)->read_ms(); } while (minutes != equeue_minutes); return minutes + ms; @@ -79,14 +82,19 @@ unsigned equeue_tick() { // Mutex operations -int equeue_mutex_create(equeue_mutex_t *m) { return 0; } +int equeue_mutex_create(equeue_mutex_t *m) +{ + return 0; +} void equeue_mutex_destroy(equeue_mutex_t *m) { } -void equeue_mutex_lock(equeue_mutex_t *m) { +void equeue_mutex_lock(equeue_mutex_t *m) +{ core_util_critical_section_enter(); } -void equeue_mutex_unlock(equeue_mutex_t *m) { +void equeue_mutex_unlock(equeue_mutex_t *m) +{ core_util_critical_section_exit(); } @@ -94,7 +102,8 @@ void equeue_mutex_unlock(equeue_mutex_t *m) { // Semaphore operations #ifdef MBED_CONF_RTOS_PRESENT -int equeue_sema_create(equeue_sema_t *s) { +int equeue_sema_create(equeue_sema_t *s) +{ osEventFlagsAttr_t attr; memset(&attr, 0, sizeof(attr)); attr.cb_mem = &s->mem; @@ -104,15 +113,18 @@ int equeue_sema_create(equeue_sema_t *s) { return !s->id ? -1 : 0; } -void equeue_sema_destroy(equeue_sema_t *s) { +void equeue_sema_destroy(equeue_sema_t *s) +{ osEventFlagsDelete(s->id); } -void equeue_sema_signal(equeue_sema_t *s) { +void equeue_sema_signal(equeue_sema_t *s) +{ osEventFlagsSet(s->id, 1); } -bool equeue_sema_wait(equeue_sema_t *s, int ms) { +bool equeue_sema_wait(equeue_sema_t *s, int ms) +{ if (ms < 0) { ms = osWaitForever; } @@ -123,29 +135,34 @@ bool equeue_sema_wait(equeue_sema_t *s, int ms) { #else // Semaphore operations -int equeue_sema_create(equeue_sema_t *s) { +int equeue_sema_create(equeue_sema_t *s) +{ *s = false; return 0; } -void equeue_sema_destroy(equeue_sema_t *s) { +void equeue_sema_destroy(equeue_sema_t *s) +{ } -void equeue_sema_signal(equeue_sema_t *s) { +void equeue_sema_signal(equeue_sema_t *s) +{ *s = 1; } -static void equeue_sema_timeout(equeue_sema_t *s) { +static void equeue_sema_timeout(equeue_sema_t *s) +{ *s = -1; } -bool equeue_sema_wait(equeue_sema_t *s, int ms) { +bool equeue_sema_wait(equeue_sema_t *s, int ms) +{ int signal = 0; ALIAS_TIMEOUT timeout; if (ms == 0) { return false; } else if (ms > 0) { - timeout.attach_us(callback(equeue_sema_timeout, s), ms*1000); + timeout.attach_us(callback(equeue_sema_timeout, s), ms * 1000); } core_util_critical_section_enter(); diff --git a/events/equeue/equeue_posix.c b/events/equeue/equeue_posix.c index 5d0c9309fdd..02ebad794b8 100644 --- a/events/equeue/equeue_posix.c +++ b/events/equeue/equeue_posix.c @@ -25,33 +25,39 @@ // Tick operations -unsigned equeue_tick(void) { +unsigned equeue_tick(void) +{ struct timeval tv; gettimeofday(&tv, 0); - return (unsigned)(tv.tv_sec*1000 + tv.tv_usec/1000); + return (unsigned)(tv.tv_sec * 1000 + tv.tv_usec / 1000); } // Mutex operations -int equeue_mutex_create(equeue_mutex_t *m) { +int equeue_mutex_create(equeue_mutex_t *m) +{ return pthread_mutex_init(m, 0); } -void equeue_mutex_destroy(equeue_mutex_t *m) { +void equeue_mutex_destroy(equeue_mutex_t *m) +{ pthread_mutex_destroy(m); } -void equeue_mutex_lock(equeue_mutex_t *m) { +void equeue_mutex_lock(equeue_mutex_t *m) +{ pthread_mutex_lock(m); } -void equeue_mutex_unlock(equeue_mutex_t *m) { +void equeue_mutex_unlock(equeue_mutex_t *m) +{ pthread_mutex_unlock(m); } // Semaphore operations -int equeue_sema_create(equeue_sema_t *s) { +int equeue_sema_create(equeue_sema_t *s) +{ int err = pthread_mutex_init(&s->mutex, 0); if (err) { return err; @@ -66,19 +72,22 @@ int equeue_sema_create(equeue_sema_t *s) { return 0; } -void equeue_sema_destroy(equeue_sema_t *s) { +void equeue_sema_destroy(equeue_sema_t *s) +{ pthread_cond_destroy(&s->cond); pthread_mutex_destroy(&s->mutex); } -void equeue_sema_signal(equeue_sema_t *s) { +void equeue_sema_signal(equeue_sema_t *s) +{ pthread_mutex_lock(&s->mutex); s->signal = true; pthread_cond_signal(&s->cond); pthread_mutex_unlock(&s->mutex); } -bool equeue_sema_wait(equeue_sema_t *s, int ms) { +bool equeue_sema_wait(equeue_sema_t *s, int ms) +{ pthread_mutex_lock(&s->mutex); if (!s->signal) { if (ms < 0) { @@ -88,8 +97,8 @@ bool equeue_sema_wait(equeue_sema_t *s, int ms) { gettimeofday(&tv, 0); struct timespec ts = { - .tv_sec = ms/1000 + tv.tv_sec, - .tv_nsec = ms*1000000 + tv.tv_usec*1000, + .tv_sec = ms / 1000 + tv.tv_sec, + .tv_nsec = ms * 1000000 + tv.tv_usec * 1000, }; pthread_cond_timedwait(&s->cond, &s->mutex, &ts); diff --git a/events/equeue/tests/prof.c b/events/equeue/tests/prof.c index 20d5ac514b6..82b5c93e0c1 100644 --- a/events/equeue/tests/prof.c +++ b/events/equeue/tests/prof.c @@ -113,20 +113,23 @@ static const char *prof_units; // Various test functions -void no_func(void *eh) { +void no_func(void *eh) +{ } // Actual performance tests -void baseline_prof(void) { +void baseline_prof(void) +{ prof_loop() { prof_start(); - __asm__ volatile (""); + __asm__ volatile(""); prof_stop(); } } -void equeue_tick_prof(void) { +void equeue_tick_prof(void) +{ prof_volatile(unsigned) res; prof_loop() { prof_start(); @@ -135,9 +138,10 @@ void equeue_tick_prof(void) { } } -void equeue_alloc_prof(void) { +void equeue_alloc_prof(void) +{ struct equeue q; - equeue_create(&q, 32*EQUEUE_EVENT_SIZE); + equeue_create(&q, 32 * EQUEUE_EVENT_SIZE); prof_loop() { prof_start(); @@ -150,9 +154,10 @@ void equeue_alloc_prof(void) { equeue_destroy(&q); } -void equeue_alloc_many_prof(int count) { +void equeue_alloc_many_prof(int count) +{ struct equeue q; - equeue_create(&q, count*EQUEUE_EVENT_SIZE); + equeue_create(&q, count * EQUEUE_EVENT_SIZE); void *es[count]; @@ -175,7 +180,8 @@ void equeue_alloc_many_prof(int count) { equeue_destroy(&q); } -void equeue_post_prof(void) { +void equeue_post_prof(void) +{ struct equeue q; equeue_create(&q, EQUEUE_EVENT_SIZE); @@ -192,11 +198,12 @@ void equeue_post_prof(void) { equeue_destroy(&q); } -void equeue_post_many_prof(int count) { +void equeue_post_many_prof(int count) +{ struct equeue q; - equeue_create(&q, count*EQUEUE_EVENT_SIZE); + equeue_create(&q, count * EQUEUE_EVENT_SIZE); - for (int i = 0; i < count-1; i++) { + for (int i = 0; i < count - 1; i++) { equeue_call(&q, no_func, 0); } @@ -213,7 +220,8 @@ void equeue_post_many_prof(int count) { equeue_destroy(&q); } -void equeue_post_future_prof(void) { +void equeue_post_future_prof(void) +{ struct equeue q; equeue_create(&q, EQUEUE_EVENT_SIZE); @@ -231,11 +239,12 @@ void equeue_post_future_prof(void) { equeue_destroy(&q); } -void equeue_post_future_many_prof(int count) { +void equeue_post_future_many_prof(int count) +{ struct equeue q; - equeue_create(&q, count*EQUEUE_EVENT_SIZE); + equeue_create(&q, count * EQUEUE_EVENT_SIZE); - for (int i = 0; i < count-1; i++) { + for (int i = 0; i < count - 1; i++) { equeue_call(&q, no_func, 0); } @@ -253,7 +262,8 @@ void equeue_post_future_many_prof(int count) { equeue_destroy(&q); } -void equeue_dispatch_prof(void) { +void equeue_dispatch_prof(void) +{ struct equeue q; equeue_create(&q, EQUEUE_EVENT_SIZE); @@ -268,9 +278,10 @@ void equeue_dispatch_prof(void) { equeue_destroy(&q); } -void equeue_dispatch_many_prof(int count) { +void equeue_dispatch_many_prof(int count) +{ struct equeue q; - equeue_create(&q, count*EQUEUE_EVENT_SIZE); + equeue_create(&q, count * EQUEUE_EVENT_SIZE); prof_loop() { for (int i = 0; i < count; i++) { @@ -285,7 +296,8 @@ void equeue_dispatch_many_prof(int count) { equeue_destroy(&q); } -void equeue_cancel_prof(void) { +void equeue_cancel_prof(void) +{ struct equeue q; equeue_create(&q, EQUEUE_EVENT_SIZE); @@ -300,11 +312,12 @@ void equeue_cancel_prof(void) { equeue_destroy(&q); } -void equeue_cancel_many_prof(int count) { +void equeue_cancel_many_prof(int count) +{ struct equeue q; - equeue_create(&q, count*EQUEUE_EVENT_SIZE); + equeue_create(&q, count * EQUEUE_EVENT_SIZE); - for (int i = 0; i < count-1; i++) { + for (int i = 0; i < count - 1; i++) { equeue_call(&q, no_func, 0); } @@ -319,8 +332,9 @@ void equeue_cancel_many_prof(int count) { equeue_destroy(&q); } -void equeue_alloc_size_prof(void) { - size_t size = 32*EQUEUE_EVENT_SIZE; +void equeue_alloc_size_prof(void) +{ + size_t size = 32 * EQUEUE_EVENT_SIZE; struct equeue q; equeue_create(&q, size); @@ -331,8 +345,9 @@ void equeue_alloc_size_prof(void) { equeue_destroy(&q); } -void equeue_alloc_many_size_prof(int count) { - size_t size = count*EQUEUE_EVENT_SIZE; +void equeue_alloc_many_size_prof(int count) +{ + size_t size = count * EQUEUE_EVENT_SIZE; struct equeue q; equeue_create(&q, size); @@ -346,8 +361,9 @@ void equeue_alloc_many_size_prof(int count) { equeue_destroy(&q); } -void equeue_alloc_fragmented_size_prof(int count) { - size_t size = count*EQUEUE_EVENT_SIZE; +void equeue_alloc_fragmented_size_prof(int count) +{ + size_t size = count * EQUEUE_EVENT_SIZE; struct equeue q; equeue_create(&q, size); @@ -362,11 +378,11 @@ void equeue_alloc_fragmented_size_prof(int count) { equeue_dealloc(&q, es[i]); } - for (int i = count-1; i >= 0; i--) { + for (int i = count - 1; i >= 0; i--) { es[i] = equeue_alloc(&q, (i % 4) * sizeof(int)); } - for (int i = count-1; i >= 0; i--) { + for (int i = count - 1; i >= 0; i--) { equeue_dealloc(&q, es[i]); } @@ -381,7 +397,8 @@ void equeue_alloc_fragmented_size_prof(int count) { // Entry point -int main() { +int main() +{ printf("beginning profiling...\n"); prof_baseline(baseline_prof); diff --git a/events/equeue/tests/tests.c b/events/equeue/tests/tests.c index 57212de22d9..3699856b2c3 100644 --- a/events/equeue/tests/tests.c +++ b/events/equeue/tests/tests.c @@ -51,14 +51,17 @@ static int test_failure; // Test functions -void pass_func(void *eh) { +void pass_func(void *eh) +{ } -void simple_func(void *p) { +void simple_func(void *p) +{ (*(int *)p)++; } -void sloth_func(void *p) { +void sloth_func(void *p) +{ usleep(10000); (*(int *)p)++; } @@ -68,8 +71,9 @@ struct indirect { uint8_t buffer[7]; }; -void indirect_func(void *p) { - struct indirect *i = (struct indirect*)p; +void indirect_func(void *p) +{ + struct indirect *i = (struct indirect *)p; (*i->touched)++; } @@ -78,8 +82,9 @@ struct timing { unsigned delay; }; -void timing_func(void *p) { - struct timing *timing = (struct timing*)p; +void timing_func(void *p) +{ + struct timing *timing = (struct timing *)p; unsigned tick = equeue_tick(); unsigned t1 = timing->delay; @@ -95,8 +100,9 @@ struct fragment { struct timing timing; }; -void fragment_func(void *p) { - struct fragment *fragment = (struct fragment*)p; +void fragment_func(void *p) +{ + struct fragment *fragment = (struct fragment *)p; timing_func(&fragment->timing); struct fragment *nfragment = equeue_alloc(fragment->q, fragment->size); @@ -114,7 +120,8 @@ struct cancel { int id; }; -void cancel_func(void *p) { +void cancel_func(void *p) +{ struct cancel *cancel = (struct cancel *)p; equeue_cancel(cancel->q, cancel->id); } @@ -125,7 +132,8 @@ struct nest { void *data; }; -void nest_func(void *p) { +void nest_func(void *p) +{ struct nest *nest = (struct nest *)p; equeue_call(nest->q, nest->cb, nest->data); @@ -134,7 +142,8 @@ void nest_func(void *p) { // Simple call tests -void simple_call_test(void) { +void simple_call_test(void) +{ equeue_t q; int err = equeue_create(&q, 2048); test_assert(!err); @@ -147,7 +156,8 @@ void simple_call_test(void) { equeue_destroy(&q); } -void simple_call_in_test(void) { +void simple_call_in_test(void) +{ equeue_t q; int err = equeue_create(&q, 2048); test_assert(!err); @@ -162,7 +172,8 @@ void simple_call_in_test(void) { equeue_destroy(&q); } -void simple_call_every_test(void) { +void simple_call_every_test(void) +{ equeue_t q; int err = equeue_create(&q, 2048); test_assert(!err); @@ -177,7 +188,8 @@ void simple_call_every_test(void) { equeue_destroy(&q); } -void simple_post_test(void) { +void simple_post_test(void) +{ equeue_t q; int err = equeue_create(&q, 2048); test_assert(!err); @@ -197,7 +209,8 @@ void simple_post_test(void) { } // Misc tests -void destructor_test(void) { +void destructor_test(void) +{ equeue_t q; int err = equeue_create(&q, 2048); test_assert(!err); @@ -253,7 +266,8 @@ void destructor_test(void) { test_assert(touched == 3); } -void allocation_failure_test(void) { +void allocation_failure_test(void) +{ equeue_t q; int err = equeue_create(&q, 2048); test_assert(!err); @@ -269,19 +283,20 @@ void allocation_failure_test(void) { equeue_destroy(&q); } -void cancel_test(int N) { +void cancel_test(int N) +{ equeue_t q; int err = equeue_create(&q, 2048); test_assert(!err); bool touched = false; - int *ids = malloc(N*sizeof(int)); + int *ids = malloc(N * sizeof(int)); for (int i = 0; i < N; i++) { ids[i] = equeue_call(&q, simple_func, &touched); } - for (int i = N-1; i >= 0; i--) { + for (int i = N - 1; i >= 0; i--) { equeue_cancel(&q, ids[i]); } @@ -293,7 +308,8 @@ void cancel_test(int N) { equeue_destroy(&q); } -void cancel_inflight_test(void) { +void cancel_inflight_test(void) +{ equeue_t q; int err = equeue_create(&q, 2048); test_assert(!err); @@ -328,7 +344,8 @@ void cancel_inflight_test(void) { equeue_destroy(&q); } -void cancel_unnecessarily_test(void) { +void cancel_unnecessarily_test(void) +{ equeue_t q; int err = equeue_create(&q, 2048); test_assert(!err); @@ -356,7 +373,8 @@ void cancel_unnecessarily_test(void) { equeue_destroy(&q); } -void loop_protect_test(void) { +void loop_protect_test(void) +{ equeue_t q; int err = equeue_create(&q, 2048); test_assert(!err); @@ -376,7 +394,8 @@ void loop_protect_test(void) { equeue_destroy(&q); } -void break_test(void) { +void break_test(void) +{ equeue_t q; int err = equeue_create(&q, 2048); test_assert(!err); @@ -391,7 +410,8 @@ void break_test(void) { equeue_destroy(&q); } -void period_test(void) { +void period_test(void) +{ equeue_t q; int err = equeue_create(&q, 2048); test_assert(!err); @@ -405,7 +425,8 @@ void period_test(void) { equeue_destroy(&q); } -void nested_test(void) { +void nested_test(void) +{ equeue_t q; int err = equeue_create(&q, 2048); test_assert(!err); @@ -442,7 +463,8 @@ void nested_test(void) { equeue_destroy(&q); } -void sloth_test(void) { +void sloth_test(void) +{ equeue_t q; int err = equeue_create(&q, 2048); test_assert(!err); @@ -463,13 +485,15 @@ void sloth_test(void) { equeue_destroy(&q); } -void *multithread_thread(void *p) { +void *multithread_thread(void *p) +{ equeue_t *q = (equeue_t *)p; equeue_dispatch(q, -1); return 0; } -void multithread_test(void) { +void multithread_test(void) +{ equeue_t q; int err = equeue_create(&q, 2048); test_assert(!err); @@ -491,11 +515,13 @@ void multithread_test(void) { equeue_destroy(&q); } -void background_func(void *p, int ms) { +void background_func(void *p, int ms) +{ *(unsigned *)p = ms; } -void background_test(void) { +void background_test(void) +{ equeue_t q; int err = equeue_create(&q, 2048); test_assert(!err); @@ -522,7 +548,8 @@ void background_test(void) { test_assert(ms == -1); } -void chain_test(void) { +void chain_test(void) +{ equeue_t q1; int err = equeue_create(&q1, 2048); test_assert(!err); @@ -562,7 +589,8 @@ void chain_test(void) { equeue_destroy(&q2); } -void unchain_test(void) { +void unchain_test(void) +{ equeue_t q1; int err = equeue_create(&q1, 2048); test_assert(!err); @@ -596,9 +624,10 @@ void unchain_test(void) { } // Barrage tests -void simple_barrage_test(int N) { +void simple_barrage_test(int N) +{ equeue_t q; - int err = equeue_create(&q, N*(EQUEUE_EVENT_SIZE+sizeof(struct timing))); + int err = equeue_create(&q, N * (EQUEUE_EVENT_SIZE + sizeof(struct timing))); test_assert(!err); for (int i = 0; i < N; i++) { @@ -606,7 +635,7 @@ void simple_barrage_test(int N) { test_assert(timing); timing->tick = equeue_tick(); - timing->delay = (i+1)*100; + timing->delay = (i + 1) * 100; equeue_event_delay(timing, timing->delay); equeue_event_period(timing, timing->delay); @@ -614,33 +643,34 @@ void simple_barrage_test(int N) { test_assert(id); } - equeue_dispatch(&q, N*100); + equeue_dispatch(&q, N * 100); equeue_destroy(&q); } -void fragmenting_barrage_test(int N) { +void fragmenting_barrage_test(int N) +{ equeue_t q; int err = equeue_create(&q, - 2*N*(EQUEUE_EVENT_SIZE+sizeof(struct fragment)+N*sizeof(int))); + 2 * N * (EQUEUE_EVENT_SIZE + sizeof(struct fragment) + N * sizeof(int))); test_assert(!err); for (int i = 0; i < N; i++) { - size_t size = sizeof(struct fragment) + i*sizeof(int); + size_t size = sizeof(struct fragment) + i * sizeof(int); struct fragment *fragment = equeue_alloc(&q, size); test_assert(fragment); fragment->q = &q; fragment->size = size; fragment->timing.tick = equeue_tick(); - fragment->timing.delay = (i+1)*100; + fragment->timing.delay = (i + 1) * 100; equeue_event_delay(fragment, fragment->timing.delay); int id = equeue_post(&q, fragment_func, fragment); test_assert(id); } - equeue_dispatch(&q, N*100); + equeue_dispatch(&q, N * 100); equeue_destroy(&q); } @@ -651,20 +681,22 @@ struct ethread { int ms; }; -static void *ethread_dispatch(void *p) { - struct ethread *t = (struct ethread*)p; +static void *ethread_dispatch(void *p) +{ + struct ethread *t = (struct ethread *)p; equeue_dispatch(t->q, t->ms); return 0; } -void multithreaded_barrage_test(int N) { +void multithreaded_barrage_test(int N) +{ equeue_t q; - int err = equeue_create(&q, N*(EQUEUE_EVENT_SIZE+sizeof(struct timing))); + int err = equeue_create(&q, N * (EQUEUE_EVENT_SIZE + sizeof(struct timing))); test_assert(!err); struct ethread t; t.q = &q; - t.ms = N*100; + t.ms = N * 100; err = pthread_create(&t.thread, 0, ethread_dispatch, &t); test_assert(!err); @@ -673,7 +705,7 @@ void multithreaded_barrage_test(int N) { test_assert(timing); timing->tick = equeue_tick(); - timing->delay = (i+1)*100; + timing->delay = (i + 1) * 100; equeue_event_delay(timing, timing->delay); equeue_event_period(timing, timing->delay); @@ -688,7 +720,8 @@ void multithreaded_barrage_test(int N) { } -int main() { +int main() +{ printf("beginning tests...\n"); test_run(simple_call_test); diff --git a/features/FEATURE_BLE/ble/ArrayView.h b/features/FEATURE_BLE/ble/ArrayView.h index d2a2b6d1357..f9891d3ad88 100644 --- a/features/FEATURE_BLE/ble/ArrayView.h +++ b/features/FEATURE_BLE/ble/ArrayView.h @@ -69,8 +69,8 @@ struct ArrayView { * @post a call to size() will return array_size and data() will return * array_tpr. */ - ArrayView(T* array_ptr, size_t array_size) : - _array(array_ptr), _size(array_size) { } + ArrayView(T *array_ptr, size_t array_size) : + _array(array_ptr), _size(array_size) { } /** * Construct an array view from the reference to an array. @@ -83,8 +83,8 @@ struct ArrayView { * a pointer to elements. */ template - ArrayView(T (&elements)[Size]): - _array(elements), _size(Size) { } + ArrayView(T(&elements)[Size]): + _array(elements), _size(Size) { } /** * Return the size of the array viewed. @@ -93,7 +93,7 @@ struct ArrayView { */ size_t size() const { - return _size; + return _size; } /** @@ -105,9 +105,9 @@ struct ArrayView { * * @pre index shall be less than size(). */ - T& operator[](size_t index) + T &operator[](size_t index) { - return _array[index]; + return _array[index]; } /** @@ -119,9 +119,9 @@ struct ArrayView { * * @pre index shall be less than size(). */ - const T& operator[](size_t index) const + const T &operator[](size_t index) const { - return _array[index]; + return _array[index]; } /** @@ -129,7 +129,7 @@ struct ArrayView { * * @return The raw pointer to the array. */ - T* data() + T *data() { return _array; } @@ -139,7 +139,7 @@ struct ArrayView { * * @return The raw pointer to the array. */ - const T* data() const + const T *data() const { return _array; } @@ -153,17 +153,17 @@ struct ArrayView { * @return True if arrays in input have the same size and the same content * and false otherwise. */ - friend bool operator==(const ArrayView& lhs, const ArrayView& rhs) + friend bool operator==(const ArrayView &lhs, const ArrayView &rhs) { - if (lhs.size() != rhs.size()) { - return false; - } + if (lhs.size() != rhs.size()) { + return false; + } - if (lhs.data() == rhs.data()) { - return true; - } + if (lhs.data() == rhs.data()) { + return true; + } - return memcmp(lhs.data(), rhs.data(), lhs.size()) == 0; + return memcmp(lhs.data(), rhs.data(), lhs.size()) == 0; } /** @@ -175,13 +175,13 @@ struct ArrayView { * @return True if arrays in input do not have the same size or the same * content and false otherwise. */ - friend bool operator!=(const ArrayView& lhs, const ArrayView& rhs) + friend bool operator!=(const ArrayView &lhs, const ArrayView &rhs) { - return !(lhs == rhs); + return !(lhs == rhs); } private: - T* const _array; + T *const _array; const size_t _size; }; @@ -200,7 +200,7 @@ struct ArrayView { * created 'inline'. */ template -ArrayView make_ArrayView(T (&elements)[Size]) +ArrayView make_ArrayView(T(&elements)[Size]) { return ArrayView(elements); } @@ -219,7 +219,7 @@ ArrayView make_ArrayView(T (&elements)[Size]) * created 'inline'. */ template -ArrayView make_ArrayView(T* array_ptr, size_t array_size) +ArrayView make_ArrayView(T *array_ptr, size_t array_size) { return ArrayView(array_ptr, array_size); } @@ -237,7 +237,7 @@ ArrayView make_ArrayView(T* array_ptr, size_t array_size) * created 'inline'. */ template -ArrayView make_const_ArrayView(T (&elements)[Size]) +ArrayView make_const_ArrayView(T(&elements)[Size]) { return ArrayView(elements); } @@ -256,7 +256,7 @@ ArrayView make_const_ArrayView(T (&elements)[Size]) * created 'inline'. */ template -ArrayView make_const_ArrayView(T* array_ptr, size_t array_size) +ArrayView make_const_ArrayView(T *array_ptr, size_t array_size) { return ArrayView(array_ptr, array_size); } diff --git a/features/FEATURE_BLE/ble/BLE.h b/features/FEATURE_BLE/ble/BLE.h index 66bb545c3e5..4f16073eb13 100644 --- a/features/FEATURE_BLE/ble/BLE.h +++ b/features/FEATURE_BLE/ble/BLE.h @@ -132,8 +132,7 @@ class BLEInstanceBase; * } * @endcode */ -class BLE -{ +class BLE { public: /** * Opaque type used to store the ID of a BLE instance. @@ -178,7 +177,8 @@ class BLE * * @return Instance id of this BLE instance. */ - InstanceID_t getInstanceID(void) const { + InstanceID_t getInstanceID(void) const + { return instanceID; } @@ -192,14 +192,14 @@ class BLE /** * The ble instance which have events to process. */ - BLE& ble; + BLE &ble; }; /** * Events to process event handler */ - typedef FunctionPointerWithContext - OnEventsToProcessCallback_t; + typedef FunctionPointerWithContext + OnEventsToProcessCallback_t; /** * Register a callback called when the BLE stack has pending work. @@ -209,7 +209,7 @@ class BLE * * @param on_event_cb Callback invoked when there are new events to process. */ - void onEventsToProcess(const OnEventsToProcessCallback_t& on_event_cb); + void onEventsToProcess(const OnEventsToProcessCallback_t &on_event_cb); /** * Process ALL pending events living in the BLE stack and return once all @@ -229,7 +229,7 @@ class BLE /** * Reference to the BLE object that has been initialized */ - BLE& ble; + BLE &ble; /** * Error status of the initialization. @@ -283,7 +283,8 @@ class BLE * @attention This should be called before using anything else in the BLE * API. */ - ble_error_t init(InitializationCompleteCallback_t completion_cb = NULL) { + ble_error_t init(InitializationCompleteCallback_t completion_cb = NULL) + { FunctionPointerWithContext callback(completion_cb); return initImplementation(callback); } @@ -299,7 +300,8 @@ class BLE * initialization is complete. */ template - ble_error_t init(T *object, void (T::*completion_cb)(InitializationCompleteCallbackContext *context)) { + ble_error_t init(T *object, void (T::*completion_cb)(InitializationCompleteCallbackContext *context)) + { FunctionPointerWithContext callback(object, completion_cb); return initImplementation(callback); } @@ -357,7 +359,7 @@ class BLE * * @return A reference to a GattServer object associated to this BLE instance. */ - GattServer& gattServer(); + GattServer &gattServer(); /** * A const alternative to gattServer(). @@ -365,7 +367,7 @@ class BLE * @return A const reference to a GattServer object associated to this BLE * instance. */ - const GattServer& gattServer() const; + const GattServer &gattServer() const; /** * Accessors to GattClient. All GattClient related functionality requires @@ -373,7 +375,7 @@ class BLE * * @return A reference to a GattClient object associated to this BLE instance. */ - GattClient& gattClient(); + GattClient &gattClient(); /** * A const alternative to gattClient(). @@ -381,7 +383,7 @@ class BLE * @return A const reference to a GattClient object associated to this BLE * instance. */ - const GattClient& gattClient() const; + const GattClient &gattClient() const; /** * Accessors to SecurityManager. All SecurityManager-related functionality @@ -390,7 +392,7 @@ class BLE * @return A reference to a SecurityManager object associated to this BLE * instance. */ - SecurityManager& securityManager(); + SecurityManager &securityManager(); /** * A const alternative to securityManager(). @@ -398,7 +400,7 @@ class BLE * @return A const reference to a SecurityManager object associated to this * BLE instance. */ - const SecurityManager& securityManager() const; + const SecurityManager &securityManager() const; /** * Translate error code into a printable string. @@ -407,7 +409,7 @@ class BLE * * @return A pointer to a const string describing the error. */ - static const char* errorToString(ble_error_t error); + static const char *errorToString(ble_error_t error); /* * Deprecation alert! @@ -457,7 +459,8 @@ class BLE ble_error_t setAddress( BLEProtocol::AddressType_t type, const BLEProtocol::AddressBytes_t address - ) { + ) + { return gap().setAddress(type, address); } @@ -473,7 +476,8 @@ class BLE MBED_DEPRECATED("Use ble.gap().getAddress(...)") ble_error_t getAddress( BLEProtocol::AddressType_t *typeP, BLEProtocol::AddressBytes_t address - ) { + ) + { return gap().getAddress(typeP, address); } @@ -486,7 +490,8 @@ class BLE * ble.gap().setAdvertisingType(...). */ MBED_DEPRECATED("Use ble.gap().setAdvertisingType(...)") - void setAdvertisingType(GapAdvertisingParams::AdvertisingType advType) { + void setAdvertisingType(GapAdvertisingParams::AdvertisingType advType) + { gap().setAdvertisingType(advType); } @@ -517,7 +522,8 @@ class BLE * code depending on the old semantics needs to be updated accordingly. */ MBED_DEPRECATED("Use ble.gap().setAdvertisingInterval(...)") - void setAdvertisingInterval(uint16_t interval) { + void setAdvertisingInterval(uint16_t interval) + { gap().setAdvertisingInterval(interval); } @@ -530,7 +536,8 @@ class BLE * ble.gap().getMinAdvertisingInterval(...). */ MBED_DEPRECATED("Use ble.gap().getMinAdvertisingInterval(...)") - uint16_t getMinAdvertisingInterval(void) const { + uint16_t getMinAdvertisingInterval(void) const + { return gap().getMinAdvertisingInterval(); } @@ -543,7 +550,8 @@ class BLE * ble.gap().getMinNonConnectableAdvertisingInterval(...). */ MBED_DEPRECATED("Use ble.gap().getMinNonConnectableAdvertisingInterval(...)") - uint16_t getMinNonConnectableAdvertisingInterval(void) const { + uint16_t getMinNonConnectableAdvertisingInterval(void) const + { return gap().getMinNonConnectableAdvertisingInterval(); } @@ -556,7 +564,8 @@ class BLE * ble.gap().getMaxAdvertisingInterval(...). */ MBED_DEPRECATED("Use ble.gap().getMaxAdvertisingInterval(...)") - uint16_t getMaxAdvertisingInterval(void) const { + uint16_t getMaxAdvertisingInterval(void) const + { return gap().getMaxAdvertisingInterval(); } @@ -571,7 +580,8 @@ class BLE * ble.gap().setAdvertisingTimeout(...). */ MBED_DEPRECATED("Use ble.gap().setAdvertisingTimeout(...)") - void setAdvertisingTimeout(uint16_t timeout) { + void setAdvertisingTimeout(uint16_t timeout) + { gap().setAdvertisingTimeout(timeout); } @@ -587,7 +597,8 @@ class BLE * ble.gap().setAdvertisingParams(...). */ MBED_DEPRECATED("Use ble.gap().setAdvertisingParams(...)") - void setAdvertisingParams(const GapAdvertisingParams &advParams) { + void setAdvertisingParams(const GapAdvertisingParams &advParams) + { gap().setAdvertisingParams(advParams); } @@ -601,7 +612,8 @@ class BLE * ble.gap().getAdvertisingParams(...). */ MBED_DEPRECATED("Use ble.gap().getAdvertisingParams(...)") - const GapAdvertisingParams &getAdvertisingParams(void) const { + const GapAdvertisingParams &getAdvertisingParams(void) const + { return gap().getAdvertisingParams(); } @@ -622,7 +634,8 @@ class BLE * ble.gap().accumulateAdvertisingPayload(flags). */ MBED_DEPRECATED("Use ble.gap().accumulateAdvertisingPayload(flags)") - ble_error_t accumulateAdvertisingPayload(uint8_t flags) { + ble_error_t accumulateAdvertisingPayload(uint8_t flags) + { return gap().accumulateAdvertisingPayload(flags); } @@ -642,7 +655,8 @@ class BLE * ble.gap().accumulateAdvertisingPayload(appearance). */ MBED_DEPRECATED("Use ble.gap().accumulateAdvertisingPayload(appearance)") - ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::Appearance app) { + ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::Appearance app) + { return gap().accumulateAdvertisingPayload(app); } @@ -662,7 +676,8 @@ class BLE * ble.gap().accumulateAdvertisingPayloadTxPower(txPower). */ MBED_DEPRECATED("Use ble.gap().accumulateAdvertisingPayloadTxPower(...)") - ble_error_t accumulateAdvertisingPayloadTxPower(int8_t power) { + ble_error_t accumulateAdvertisingPayloadTxPower(int8_t power) + { return gap().accumulateAdvertisingPayloadTxPower(power); } @@ -682,7 +697,8 @@ class BLE * be replaced with ble.gap().accumulateAdvertisingPayload(...). */ MBED_DEPRECATED("Use ble.gap().accumulateAdvertisingPayload(...)") - ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len) { + ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len) + { return gap().accumulateAdvertisingPayload(type, data, len); } @@ -697,7 +713,8 @@ class BLE * ble.gap().setAdvertisingPayload(...). */ MBED_DEPRECATED("Use ble.gap().setAdvertisingData(...)") - ble_error_t setAdvertisingData(const GapAdvertisingData &advData) { + ble_error_t setAdvertisingData(const GapAdvertisingData &advData) + { return gap().setAdvertisingPayload(advData); } @@ -711,7 +728,8 @@ class BLE * ble.gap().getAdvertisingPayload()(...). */ MBED_DEPRECATED("Use ble.gap().getAdvertisingData(...)") - const GapAdvertisingData &getAdvertisingData(void) const { + const GapAdvertisingData &getAdvertisingData(void) const + { return gap().getAdvertisingPayload(); } @@ -726,7 +744,8 @@ class BLE * ble.gap().clearAdvertisingPayload(...). */ MBED_DEPRECATED("Use ble.gap().clearAdvertisingPayload(...)") - void clearAdvertisingPayload(void) { + void clearAdvertisingPayload(void) + { gap().clearAdvertisingPayload(); } @@ -745,7 +764,8 @@ class BLE * implicitly. */ MBED_DEPRECATED("Use ble.gap().setAdvertisingPayload(...)") - ble_error_t setAdvertisingPayload(void) { + ble_error_t setAdvertisingPayload(void) + { return BLE_ERROR_NONE; } @@ -763,7 +783,8 @@ class BLE * ble.gap().accumulateScanResponse(...). */ MBED_DEPRECATED("Use ble.gap().accumulateScanResponse(...)") - ble_error_t accumulateScanResponse(GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len) { + ble_error_t accumulateScanResponse(GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len) + { return gap().accumulateScanResponse(type, data, len); } @@ -777,7 +798,8 @@ class BLE * ble.gap().clearScanResponse(...). */ MBED_DEPRECATED("Use ble.gap().clearScanResponse(...)") - void clearScanResponse(void) { + void clearScanResponse(void) + { gap().clearScanResponse(); } @@ -790,7 +812,8 @@ class BLE * ble.gap().startAdvertising(...). */ MBED_DEPRECATED("Use ble.gap().startAdvertising(...)") - ble_error_t startAdvertising(void) { + ble_error_t startAdvertising(void) + { return gap().startAdvertising(); } @@ -803,7 +826,8 @@ class BLE * ble.gap().stopAdvertising(...). */ MBED_DEPRECATED("Use ble.gap().stopAdvertising(...)") - ble_error_t stopAdvertising(void) { + ble_error_t stopAdvertising(void) + { return gap().stopAdvertising(); } @@ -840,7 +864,8 @@ class BLE ble_error_t setScanParams(uint16_t interval = GapScanningParams::SCAN_INTERVAL_MAX, uint16_t window = GapScanningParams::SCAN_WINDOW_MAX, uint16_t timeout = 0, - bool activeScanning = false) { + bool activeScanning = false) + { return gap().setScanParams(interval, window, timeout, activeScanning); } @@ -865,7 +890,8 @@ class BLE * ble.gap().setScanInterval(interval). */ MBED_DEPRECATED("Use ble.gap().setScanInterval(...)") - ble_error_t setScanInterval(uint16_t interval) { + ble_error_t setScanInterval(uint16_t interval) + { return gap().setScanInterval(interval); } @@ -890,7 +916,8 @@ class BLE * ble.gap().setScanWindow(window). */ MBED_DEPRECATED("Use ble.gap().setScanWindow(...)") - ble_error_t setScanWindow(uint16_t window) { + ble_error_t setScanWindow(uint16_t window) + { return gap().setScanWindow(window); } @@ -917,7 +944,8 @@ class BLE * ble.gap().setScanTimeout(...). */ MBED_DEPRECATED("Use ble.gap().setScanTimeout(...)") - ble_error_t setScanTimeout(uint16_t timeout) { + ble_error_t setScanTimeout(uint16_t timeout) + { return gap().setScanTimeout(timeout); } @@ -936,7 +964,8 @@ class BLE * ble.gap().setActiveScanning(...). */ MBED_DEPRECATED("Use ble.gap().setActiveScan(...)") - void setActiveScan(bool activeScanning) { + void setActiveScan(bool activeScanning) + { gap().setActiveScanning(activeScanning); } @@ -955,7 +984,8 @@ class BLE * ble.gap().startScan(callback). */ MBED_DEPRECATED("Use ble.gap().startScan(callback)") - ble_error_t startScan(void (*callback)(const Gap::AdvertisementCallbackParams_t *params)) { + ble_error_t startScan(void (*callback)(const Gap::AdvertisementCallbackParams_t *params)) + { return gap().startScan(callback); } @@ -982,7 +1012,8 @@ class BLE * ble.gap().stopScan(). */ MBED_DEPRECATED("Use ble.gap().stopScan()") - ble_error_t stopScan(void) { + ble_error_t stopScan(void) + { return gap().stopScan(); } @@ -1009,7 +1040,8 @@ class BLE ble_error_t connect(const BLEProtocol::AddressBytes_t peerAddr, BLEProtocol::AddressType_t peerAddrType = BLEProtocol::AddressType::RANDOM_STATIC, const Gap::ConnectionParams_t *connectionParams = NULL, - const GapScanningParams *scanParams = NULL) { + const GapScanningParams *scanParams = NULL) + { return gap().connect(peerAddr, peerAddrType, connectionParams, scanParams); } @@ -1023,7 +1055,8 @@ class BLE * The reason for disconnection; sent back to the peer. */ MBED_DEPRECATED("Use ble.gap().disconnect(...)") - ble_error_t disconnect(Gap::Handle_t connectionHandle, Gap::DisconnectionReason_t reason) { + ble_error_t disconnect(Gap::Handle_t connectionHandle, Gap::DisconnectionReason_t reason) + { return gap().disconnect(connectionHandle, reason); } @@ -1045,7 +1078,8 @@ class BLE * connection. */ MBED_DEPRECATED("Use ble.gap().disconnect(...)") - ble_error_t disconnect(Gap::DisconnectionReason_t reason) { + ble_error_t disconnect(Gap::DisconnectionReason_t reason) + { return gap().disconnect(reason); } @@ -1059,7 +1093,8 @@ class BLE * ble.gap().getState(). */ MBED_DEPRECATED("Use ble.gap().getGapState(...)") - Gap::GapState_t getGapState(void) const { + Gap::GapState_t getGapState(void) const + { return gap().getState(); } @@ -1081,7 +1116,8 @@ class BLE * ble.gap().getPreferredConnectionParams(). */ MBED_DEPRECATED("Use ble.gap().getPreferredConnectionParams(...)") - ble_error_t getPreferredConnectionParams(Gap::ConnectionParams_t *params) { + ble_error_t getPreferredConnectionParams(Gap::ConnectionParams_t *params) + { return gap().getPreferredConnectionParams(params); } @@ -1099,7 +1135,8 @@ class BLE * ble.gap().setPreferredConnectionParams(). */ MBED_DEPRECATED("Use ble.gap().setPreferredConnectionParams(...)") - ble_error_t setPreferredConnectionParams(const Gap::ConnectionParams_t *params) { + ble_error_t setPreferredConnectionParams(const Gap::ConnectionParams_t *params) + { return gap().setPreferredConnectionParams(params); } @@ -1119,7 +1156,8 @@ class BLE * ble.gap().updateConnectionParams(). */ MBED_DEPRECATED("Use ble.gap().updateConnectionParams(...)") - ble_error_t updateConnectionParams(Gap::Handle_t handle, const Gap::ConnectionParams_t *params) { + ble_error_t updateConnectionParams(Gap::Handle_t handle, const Gap::ConnectionParams_t *params) + { return gap().updateConnectionParams(handle, params); } @@ -1134,7 +1172,8 @@ class BLE * ble.gap().setDeviceName(). */ MBED_DEPRECATED("Use ble.gap().setDeviceName(...)") - ble_error_t setDeviceName(const uint8_t *deviceName) { + ble_error_t setDeviceName(const uint8_t *deviceName) + { return gap().setDeviceName(deviceName); } @@ -1162,7 +1201,8 @@ class BLE * ble.gap().getDeviceName(). */ MBED_DEPRECATED("Use ble.gap().getDeviceName(...)") - ble_error_t getDeviceName(uint8_t *deviceName, unsigned *lengthP) { + ble_error_t getDeviceName(uint8_t *deviceName, unsigned *lengthP) + { return gap().getDeviceName(deviceName, lengthP); } @@ -1177,7 +1217,8 @@ class BLE * ble.gap().setAppearance(). */ MBED_DEPRECATED("Use ble.gap().setAppearance(...)") - ble_error_t setAppearance(GapAdvertisingData::Appearance appearance) { + ble_error_t setAppearance(GapAdvertisingData::Appearance appearance) + { return gap().setAppearance(appearance); } @@ -1192,7 +1233,8 @@ class BLE * ble.gap().getAppearance(). */ MBED_DEPRECATED("Use ble.gap().getAppearance(...)") - ble_error_t getAppearance(GapAdvertisingData::Appearance *appearanceP) { + ble_error_t getAppearance(GapAdvertisingData::Appearance *appearanceP) + { return gap().getAppearance(appearanceP); } @@ -1206,7 +1248,8 @@ class BLE * ble.gap().setTxPower(). */ MBED_DEPRECATED("Use ble.gap().setTxPower(...)") - ble_error_t setTxPower(int8_t txPower) { + ble_error_t setTxPower(int8_t txPower) + { return gap().setTxPower(txPower); } @@ -1224,7 +1267,8 @@ class BLE * ble.gap().getPermittedTxPowerValues(). */ MBED_DEPRECATED("Use ble.gap().getPermittedTxPowerValues(...)") - void getPermittedTxPowerValues(const int8_t **valueArrayPP, size_t *countP) { + void getPermittedTxPowerValues(const int8_t **valueArrayPP, size_t *countP) + { gap().getPermittedTxPowerValues(valueArrayPP, countP); } @@ -1238,7 +1282,8 @@ class BLE * ble.gattServer().addService(). */ MBED_DEPRECATED("Use ble.gattServer().addService(...)") - ble_error_t addService(GattService &service) { + ble_error_t addService(GattService &service) + { return gattServer().addService(service); } @@ -1263,7 +1308,8 @@ class BLE * ble.gattServer().read(). */ MBED_DEPRECATED("Use ble.gattServer().read(...)") - ble_error_t readCharacteristicValue(GattAttribute::Handle_t attributeHandle, uint8_t *buffer, uint16_t *lengthP) { + ble_error_t readCharacteristicValue(GattAttribute::Handle_t attributeHandle, uint8_t *buffer, uint16_t *lengthP) + { return gattServer().read(attributeHandle, buffer, lengthP); } @@ -1294,7 +1340,8 @@ class BLE * ble.gattServer().read(). */ MBED_DEPRECATED("Use ble.gattServer().read(...)") - ble_error_t readCharacteristicValue(Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, uint8_t *buffer, uint16_t *lengthP) { + ble_error_t readCharacteristicValue(Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, uint8_t *buffer, uint16_t *lengthP) + { return gattServer().read(connectionHandle, attributeHandle, buffer, lengthP); } @@ -1325,7 +1372,8 @@ class BLE ble_error_t updateCharacteristicValue(GattAttribute::Handle_t attributeHandle, const uint8_t *value, uint16_t size, - bool localOnly = false) { + bool localOnly = false) + { return gattServer().write(attributeHandle, value, size, localOnly); } @@ -1361,7 +1409,8 @@ class BLE GattAttribute::Handle_t attributeHandle, const uint8_t *value, uint16_t size, - bool localOnly = false) { + bool localOnly = false) + { return gattServer().write(connectionHandle, attributeHandle, value, size, localOnly); } @@ -1389,7 +1438,8 @@ class BLE ble_error_t initializeSecurity(bool enableBonding = true, bool requireMITM = true, SecurityManager::SecurityIOCapabilities_t iocaps = SecurityManager::IO_CAPS_NONE, - const SecurityManager::Passkey_t passkey = NULL) { + const SecurityManager::Passkey_t passkey = NULL) + { return securityManager().init(enableBonding, requireMITM, iocaps, passkey); } @@ -1407,7 +1457,8 @@ class BLE * ble.securityManager().getLinkSecurity(...). */ MBED_DEPRECATED("ble.securityManager().getLinkSecurity(...)") - ble_error_t getLinkSecurity(Gap::Handle_t connectionHandle, SecurityManager::LinkSecurityStatus_t *securityStatusP) { + ble_error_t getLinkSecurity(Gap::Handle_t connectionHandle, SecurityManager::LinkSecurityStatus_t *securityStatusP) + { return securityManager().getLinkSecurity(connectionHandle, securityStatusP); } @@ -1425,7 +1476,8 @@ class BLE * ble.securityManager().purgeAllBondingState(). */ MBED_DEPRECATED("ble.securityManager().purgeAllBondingState(...)") - ble_error_t purgeAllBondingState(void) { + ble_error_t purgeAllBondingState(void) + { return securityManager().purgeAllBondingState(); } @@ -1439,7 +1491,8 @@ class BLE * ble.gap().onTimeout(callback). */ MBED_DEPRECATED("ble.gap().onTimeout(callback)") - void onTimeout(Gap::TimeoutEventCallback_t timeoutCallback) { + void onTimeout(Gap::TimeoutEventCallback_t timeoutCallback) + { gap().onTimeout(timeoutCallback); } @@ -1452,7 +1505,8 @@ class BLE * ble.gap().onConnection(callback). */ MBED_DEPRECATED("ble.gap().onConnection(callback)") - void onConnection(Gap::ConnectionEventCallback_t connectionCallback) { + void onConnection(Gap::ConnectionEventCallback_t connectionCallback) + { gap().onConnection(connectionCallback); } @@ -1465,7 +1519,8 @@ class BLE * ble.gap().onDisconnection(callback). */ MBED_DEPRECATED("ble.gap().onDisconnection(callback)") - void onDisconnection(Gap::DisconnectionEventCallback_t disconnectionCallback) { + void onDisconnection(Gap::DisconnectionEventCallback_t disconnectionCallback) + { gap().onDisconnection(disconnectionCallback); } @@ -1480,7 +1535,8 @@ class BLE */ template MBED_DEPRECATED("ble.gap().onDisconnection(callback)") - void onDisconnection(T *tptr, void (T::*mptr)(const Gap::DisconnectionCallbackParams_t*)) { + void onDisconnection(T *tptr, void (T::*mptr)(const Gap::DisconnectionCallbackParams_t *)) + { gap().onDisconnection(tptr, mptr); } @@ -1506,7 +1562,8 @@ class BLE * ble.gap().onRadioNotification(...). */ MBED_DEPRECATED("ble.gap().onRadioNotification(...)") - void onRadioNotification(void (*callback)(bool)) { + void onRadioNotification(void (*callback)(bool)) + { gap().onRadioNotification(callback); } @@ -1527,7 +1584,8 @@ class BLE * ble.gattServer().onDataSent(...). */ MBED_DEPRECATED("ble.gattServer().onDataSent(...)") - void onDataSent(void (*callback)(unsigned count)) { + void onDataSent(void (*callback)(unsigned count)) + { gattServer().onDataSent(callback); } @@ -1542,7 +1600,8 @@ class BLE */ template MBED_DEPRECATED("ble.gattServer().onDataSent(...)") - void onDataSent(T * objPtr, void (T::*memberPtr)(unsigned count)) { + void onDataSent(T *objPtr, void (T::*memberPtr)(unsigned count)) + { gattServer().onDataSent(objPtr, memberPtr); } @@ -1567,7 +1626,8 @@ class BLE * ble.gattServer().onDataWritten(...). */ MBED_DEPRECATED("ble.gattServer().onDataWritten(...)") - void onDataWritten(void (*callback)(const GattWriteCallbackParams *eventDataP)) { + void onDataWritten(void (*callback)(const GattWriteCallbackParams *eventDataP)) + { gattServer().onDataWritten(callback); } @@ -1582,7 +1642,8 @@ class BLE */ template MBED_DEPRECATED("ble.gattServer().onDataWritten(...)") - void onDataWritten(T * objPtr, void (T::*memberPtr)(const GattWriteCallbackParams *context)) { + void onDataWritten(T *objPtr, void (T::*memberPtr)(const GattWriteCallbackParams *context)) + { gattServer().onDataWritten(objPtr, memberPtr); } @@ -1611,7 +1672,8 @@ class BLE * ble.gattServer().onDataRead(...). */ MBED_DEPRECATED("ble.gattServer().onDataRead(...)") - ble_error_t onDataRead(void (*callback)(const GattReadCallbackParams *eventDataP)) { + ble_error_t onDataRead(void (*callback)(const GattReadCallbackParams *eventDataP)) + { return gattServer().onDataRead(callback); } @@ -1626,7 +1688,8 @@ class BLE */ template MBED_DEPRECATED("ble.gattServer().onDataRead(...)") - ble_error_t onDataRead(T * objPtr, void (T::*memberPtr)(const GattReadCallbackParams *context)) { + ble_error_t onDataRead(T *objPtr, void (T::*memberPtr)(const GattReadCallbackParams *context)) + { return gattServer().onDataRead(objPtr, memberPtr); } @@ -1640,7 +1703,8 @@ class BLE * ble.gattServer().onUpdatesEnabled(callback). */ MBED_DEPRECATED("ble.gattServer().onUpdatesEnabled(...)") - void onUpdatesEnabled(GattServer::EventCallback_t callback) { + void onUpdatesEnabled(GattServer::EventCallback_t callback) + { gattServer().onUpdatesEnabled(callback); } @@ -1654,7 +1718,8 @@ class BLE * ble.gattServer().onUpdatesDisabled(callback). */ MBED_DEPRECATED("ble.gattServer().onUpdatesDisabled(...)") - void onUpdatesDisabled(GattServer::EventCallback_t callback) { + void onUpdatesDisabled(GattServer::EventCallback_t callback) + { gattServer().onUpdatesDisabled(callback); } @@ -1668,7 +1733,8 @@ class BLE * ble.gattServer().onConfirmationReceived(callback). */ MBED_DEPRECATED("ble.gattServer().onConfirmationReceived(...)") - void onConfirmationReceived(GattServer::EventCallback_t callback) { + void onConfirmationReceived(GattServer::EventCallback_t callback) + { gattServer().onConfirmationReceived(callback); } @@ -1685,7 +1751,8 @@ class BLE * ble.securityManager().onSecuritySetupInitiated(callback). */ MBED_DEPRECATED("ble.securityManager().onSecuritySetupInitiated(callback)") - void onSecuritySetupInitiated(SecurityManager::SecuritySetupInitiatedCallback_t callback) { + void onSecuritySetupInitiated(SecurityManager::SecuritySetupInitiatedCallback_t callback) + { securityManager().onSecuritySetupInitiated(callback); } @@ -1701,7 +1768,8 @@ class BLE * ble.securityManager().onSecuritySetupCompleted(callback). */ MBED_DEPRECATED("ble.securityManager().onSecuritySetupCompleted(callback)") - void onSecuritySetupCompleted(SecurityManager::SecuritySetupCompletedCallback_t callback) { + void onSecuritySetupCompleted(SecurityManager::SecuritySetupCompletedCallback_t callback) + { securityManager().onSecuritySetupCompleted(callback); } @@ -1719,7 +1787,8 @@ class BLE * ble.securityManager().onLinkSecured(callback). */ MBED_DEPRECATED("ble.securityManager().onLinkSecured(callback)") - void onLinkSecured(SecurityManager::LinkSecuredCallback_t callback) { + void onLinkSecured(SecurityManager::LinkSecuredCallback_t callback) + { securityManager().onLinkSecured(callback); } @@ -1733,7 +1802,8 @@ class BLE * ble.securityManager().onSecurityContextStored(callback). */ MBED_DEPRECATED("ble.securityManager().onSecurityContextStored(callback)") - void onSecurityContextStored(SecurityManager::HandleSpecificEvent_t callback) { + void onSecurityContextStored(SecurityManager::HandleSpecificEvent_t callback) + { securityManager().onSecurityContextStored(callback); } @@ -1750,7 +1820,8 @@ class BLE * ble.securityManager().onPasskeyDisplay(callback). */ MBED_DEPRECATED("ble.securityManager().onPasskeyDisplay(callback)") - void onPasskeyDisplay(SecurityManager::PasskeyDisplayCallback_t callback) { + void onPasskeyDisplay(SecurityManager::PasskeyDisplayCallback_t callback) + { return securityManager().onPasskeyDisplay(callback); } @@ -1778,7 +1849,7 @@ class BLE private: // Prevent copy construction and copy assignment of BLE. - BLE(const BLE&); + BLE(const BLE &); BLE &operator=(const BLE &); private: diff --git a/features/FEATURE_BLE/ble/BLEInstanceBase.h b/features/FEATURE_BLE/ble/BLEInstanceBase.h index d7ff34cb71a..4193e4bf017 100644 --- a/features/FEATURE_BLE/ble/BLEInstanceBase.h +++ b/features/FEATURE_BLE/ble/BLEInstanceBase.h @@ -51,8 +51,7 @@ class GattClient; * * @see BLE */ -class BLEInstanceBase -{ +class BLEInstanceBase { public: /** * Base constructor. @@ -114,7 +113,7 @@ class BLEInstanceBase */ virtual ble_error_t init( BLE::InstanceID_t instanceID, - FunctionPointerWithContext initCallback + FunctionPointerWithContext initCallback ) = 0; /** @@ -247,8 +246,8 @@ class BLEInstanceBase private: // this class is not a value type. // prohibit copy construction and copy assignement - BLEInstanceBase(const BLEInstanceBase&); - BLEInstanceBase &operator=(const BLEInstanceBase&); + BLEInstanceBase(const BLEInstanceBase &); + BLEInstanceBase &operator=(const BLEInstanceBase &); }; /** diff --git a/features/FEATURE_BLE/ble/BLEProtocol.h b/features/FEATURE_BLE/ble/BLEProtocol.h index 4fdcb59bc5c..065c24c3711 100644 --- a/features/FEATURE_BLE/ble/BLEProtocol.h +++ b/features/FEATURE_BLE/ble/BLEProtocol.h @@ -33,106 +33,107 @@ */ namespace BLEProtocol { +/** + * Container for the enumeration of BLE address types. + * + * @note Adding a struct to encapsulate the contained enumeration prevents + * polluting the BLEProtocol namespace with the enumerated values. It also + * allows type-aliases for the enumeration while retaining the enumerated + * values. i.e. doing: + * + * @code + * typedef AddressType AliasedType; + * @endcode + * + * would allow the use of AliasedType::PUBLIC in code. + * + * @note see Bluetooth Standard version 4.2 [Vol 6, Part B] section 1.3 . + */ +struct AddressType { /** - * Container for the enumeration of BLE address types. - * - * @note Adding a struct to encapsulate the contained enumeration prevents - * polluting the BLEProtocol namespace with the enumerated values. It also - * allows type-aliases for the enumeration while retaining the enumerated - * values. i.e. doing: - * - * @code - * typedef AddressType AliasedType; - * @endcode - * - * would allow the use of AliasedType::PUBLIC in code. - * - * @note see Bluetooth Standard version 4.2 [Vol 6, Part B] section 1.3 . + * Address-types for Protocol addresses. */ - struct AddressType { + enum Type { + /** + * Public device address. + */ + PUBLIC = 0, + /** - * Address-types for Protocol addresses. + * Random static device address. */ - enum Type { - /** - * Public device address. - */ - PUBLIC = 0, - - /** - * Random static device address. - */ - RANDOM_STATIC, - - /** - * Private resolvable device address. - */ - RANDOM_PRIVATE_RESOLVABLE, - - /** - * Private non-resolvable device address. - */ - RANDOM_PRIVATE_NON_RESOLVABLE - }; + RANDOM_STATIC, + + /** + * Private resolvable device address. + */ + RANDOM_PRIVATE_RESOLVABLE, + + /** + * Private non-resolvable device address. + */ + RANDOM_PRIVATE_NON_RESOLVABLE }; +}; + +/** + * Alias for AddressType::Type + */ +typedef AddressType::Type AddressType_t; + +/** + * Length (in octets) of the BLE MAC address. + */ +static const size_t ADDR_LEN = 6; + +/** + * 48-bit address, in LSB format. + */ +typedef uint8_t AddressBytes_t[ADDR_LEN]; +/** + * BLE address representation. + * + * It contains an address-type (::AddressType_t) and the address value + * (::AddressBytes_t). + */ +struct Address_t { /** - * Alias for AddressType::Type + * Construct an Address_t object with the supplied type and address. + * + * @param[in] typeIn The BLE address type. + * @param[in] addressIn The BLE address. + * + * @post type is equal to typeIn and address is equal to the content + * present in addressIn. */ - typedef AddressType::Type AddressType_t; + Address_t(AddressType_t typeIn, const AddressBytes_t &addressIn) : + type(typeIn) + { + std::copy(addressIn, addressIn + ADDR_LEN, address); + } /** - * Length (in octets) of the BLE MAC address. + * Empty constructor. + * + * @note The address constructed with the empty constructor is not + * valid. + * + * @post type is equal to PUBLIC and the address value is equal to + * 00:00:00:00:00:00 */ - static const size_t ADDR_LEN = 6; + Address_t(void) : type(), address() { } /** - * 48-bit address, in LSB format. + * Type of the BLE device address. */ - typedef uint8_t AddressBytes_t[ADDR_LEN]; + AddressType_t type; /** - * BLE address representation. - * - * It contains an address-type (::AddressType_t) and the address value - * (::AddressBytes_t). + * Value of the device address. */ - struct Address_t { - /** - * Construct an Address_t object with the supplied type and address. - * - * @param[in] typeIn The BLE address type. - * @param[in] addressIn The BLE address. - * - * @post type is equal to typeIn and address is equal to the content - * present in addressIn. - */ - Address_t(AddressType_t typeIn, const AddressBytes_t &addressIn) : - type(typeIn) { - std::copy(addressIn, addressIn + ADDR_LEN, address); - } - - /** - * Empty constructor. - * - * @note The address constructed with the empty constructor is not - * valid. - * - * @post type is equal to PUBLIC and the address value is equal to - * 00:00:00:00:00:00 - */ - Address_t(void) : type(), address() { } - - /** - * Type of the BLE device address. - */ - AddressType_t type; - - /** - * Value of the device address. - */ - AddressBytes_t address; - }; + AddressBytes_t address; +}; }; /** diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 856f3ca84d5..085472605a7 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -48,12 +48,12 @@ typedef uintptr_t connection_handle_t; typedef uint16_t attribute_handle_t; - /** - * Inclusive range of GATT attributes handles. - * - * @note Instances can be constructed with the help of the factory function - * attribute_handle_range(). - */ +/** + * Inclusive range of GATT attributes handles. + * + * @note Instances can be constructed with the help of the factory function + * attribute_handle_range(). + */ struct attribute_handle_range_t { /** * Beginning of the range. @@ -75,7 +75,8 @@ struct attribute_handle_range_t { */ friend bool operator==( const attribute_handle_range_t &lhs, const attribute_handle_range_t &rhs - ) { + ) + { return (lhs.begin == rhs.begin) && (lhs.end == rhs.end); } @@ -89,7 +90,8 @@ struct attribute_handle_range_t { */ friend bool operator!=( const attribute_handle_range_t &lhs, const attribute_handle_range_t &rhs - ) { + ) + { return !(lhs == rhs); } }; @@ -111,7 +113,8 @@ struct attribute_handle_range_t { static inline attribute_handle_range_t attribute_handle_range( attribute_handle_t begin, attribute_handle_t end -) { +) +{ attribute_handle_range_t result = { begin, end @@ -201,7 +204,8 @@ class PasskeyAscii { /** * Default to all zeroes */ - PasskeyAscii() { + PasskeyAscii() + { memset(ascii, NUMBER_OFFSET, PASSKEY_LEN); } @@ -210,7 +214,8 @@ class PasskeyAscii { * * @param[in] passkey value of the data. */ - PasskeyAscii(const uint8_t* passkey) { + PasskeyAscii(const uint8_t *passkey) + { if (passkey) { memcpy(ascii, passkey, PASSKEY_LEN); } else { @@ -223,7 +228,8 @@ class PasskeyAscii { * * @param[in] passkey value of the data. */ - PasskeyAscii(passkey_num_t passkey) { + PasskeyAscii(passkey_num_t passkey) + { for (int i = 5, m = 100000; i >= 0; --i, m /= 10) { uint32_t result = passkey / m; ascii[i] = NUMBER_OFFSET + result; @@ -234,7 +240,8 @@ class PasskeyAscii { /** * Cast to number. */ - operator passkey_num_t() { + operator passkey_num_t() + { return to_num(ascii); } @@ -243,7 +250,8 @@ class PasskeyAscii { * @param[in] ascii ASCII string of 6 digits stored as ASCII characters * @return Passkey as a number. */ - static uint32_t to_num(const uint8_t *ascii) { + static uint32_t to_num(const uint8_t *ascii) + { uint32_t passkey = 0; for (size_t i = 0, m = 1; i < PASSKEY_LEN; ++i, m *= 10) { passkey += (ascii[i] - NUMBER_OFFSET) * m; @@ -254,7 +262,8 @@ class PasskeyAscii { /** * Return the pointer to the buffer holding the string. */ - uint8_t* value() { + uint8_t *value() + { return ascii; } private: @@ -266,7 +275,8 @@ struct byte_array_t { /** * Default to all zeroes */ - byte_array_t() { + byte_array_t() + { memset(_value, 0x00, sizeof(_value)); } @@ -275,7 +285,8 @@ struct byte_array_t { * * @param[in] input_value value of the data. */ - byte_array_t(const uint8_t *input_value) { + byte_array_t(const uint8_t *input_value) + { memcpy(_value, input_value, sizeof(_value)); } @@ -285,49 +296,56 @@ struct byte_array_t { * @param[in] input_value pointer to buffer. * @param[in] size buffer size */ - byte_array_t(const uint8_t* input_value, size_t size) { + byte_array_t(const uint8_t *input_value, size_t size) + { memcpy(_value, input_value, size); } /** * Equal operator between two octet types. */ - friend bool operator==(const byte_array_t& lhs, const byte_array_t& rhs) { + friend bool operator==(const byte_array_t &lhs, const byte_array_t &rhs) + { return memcmp(lhs._value, rhs._value, sizeof(lhs._value)) == 0; } /** * Non equal operator between two octet types. */ - friend bool operator!=(const byte_array_t& lhs, const byte_array_t& rhs) { + friend bool operator!=(const byte_array_t &lhs, const byte_array_t &rhs) + { return !(lhs == rhs); } /** * Subscript operator to access data content */ - uint8_t& operator[](uint8_t i) { + uint8_t &operator[](uint8_t i) + { return _value[i]; } /** * Return the pointer to the buffer holding data. */ - const uint8_t* data() const { + const uint8_t *data() const + { return _value; } /** * Return the pointer to the buffer holding data. */ - uint8_t* buffer() { + uint8_t *buffer() + { return _value; } /** * Size in byte of a data. */ - static size_t size() { + static size_t size() + { return array_size; } @@ -365,7 +383,8 @@ struct address_t : public byte_array_t<6> { /** * Create an invalid mac address, equal to FF:FF:FF:FF:FF:FF */ - address_t() { + address_t() + { memset(_value, 0xFF, sizeof(_value)); } @@ -374,7 +393,8 @@ struct address_t : public byte_array_t<6> { * * @param[in] input_value value of the data. */ - address_t(const uint8_t *input_value) { + address_t(const uint8_t *input_value) + { memcpy(_value, input_value, sizeof(_value)); } }; diff --git a/features/FEATURE_BLE/ble/CallChainOfFunctionPointersWithContext.h b/features/FEATURE_BLE/ble/CallChainOfFunctionPointersWithContext.h index 96887ddb1a5..62cd8c47094 100644 --- a/features/FEATURE_BLE/ble/CallChainOfFunctionPointersWithContext.h +++ b/features/FEATURE_BLE/ble/CallChainOfFunctionPointersWithContext.h @@ -157,14 +157,14 @@ class CallChainOfFunctionPointersWithContext : pFunctionPointerWithContext_t previous = NULL; while (current) { - if(*current == toDetach) { - if(previous == NULL) { - if(currentCalled == current) { + if (*current == toDetach) { + if (previous == NULL) { + if (currentCalled == current) { currentCalled = NULL; } chainHead = current->getNext(); } else { - if(currentCalled == current) { + if (currentCalled == current) { currentCalled = previous; } previous->chainAsNext(current->getNext()); @@ -212,7 +212,7 @@ class CallChainOfFunctionPointersWithContext : */ void call(ContextType context) { - ((const CallChainOfFunctionPointersWithContext*) this)->call(context); + ((const CallChainOfFunctionPointersWithContext *) this)->call(context); } /** @@ -224,10 +224,10 @@ class CallChainOfFunctionPointersWithContext : { currentCalled = chainHead; - while(currentCalled) { + while (currentCalled) { currentCalled->call(context); // if this was the head and the call removed the head - if(currentCalled == NULL) { + if (currentCalled == NULL) { currentCalled = chainHead; } else { currentCalled = currentCalled->getNext(); @@ -326,10 +326,10 @@ class CallChainOfFunctionPointersWithContext : /* Disallow copy constructor and assignment operators. */ private: CallChainOfFunctionPointersWithContext( - const CallChainOfFunctionPointersWithContext& + const CallChainOfFunctionPointersWithContext & ); CallChainOfFunctionPointersWithContext &operator=( - const CallChainOfFunctionPointersWithContext& + const CallChainOfFunctionPointersWithContext & ); }; diff --git a/features/FEATURE_BLE/ble/CharacteristicDescriptorDiscovery.h b/features/FEATURE_BLE/ble/CharacteristicDescriptorDiscovery.h index fff183fdafa..2e59f76b5df 100644 --- a/features/FEATURE_BLE/ble/CharacteristicDescriptorDiscovery.h +++ b/features/FEATURE_BLE/ble/CharacteristicDescriptorDiscovery.h @@ -84,7 +84,7 @@ class CharacteristicDescriptorDiscovery { /** * Characteristic for which descriptors has been discovered. */ - const DiscoveredCharacteristic& characteristic; + const DiscoveredCharacteristic &characteristic; /** * Status of the discovery operation. @@ -111,8 +111,8 @@ class CharacteristicDescriptorDiscovery { * GattClient::discoverCharacteristicDescriptors * DiscoveredCharacteristic::discoverDescriptors */ - typedef FunctionPointerWithContext - DiscoveryCallback_t; + typedef FunctionPointerWithContext + DiscoveryCallback_t; /** * Handler of Characteristic descriptor discovery ended event. @@ -128,8 +128,8 @@ class CharacteristicDescriptorDiscovery { * GattClient::discoverCharacteristicDescriptors * DiscoveredCharacteristic::discoverDescriptors */ - typedef FunctionPointerWithContext - TerminationCallback_t; + typedef FunctionPointerWithContext + TerminationCallback_t; }; /** diff --git a/features/FEATURE_BLE/ble/DiscoveredCharacteristic.h b/features/FEATURE_BLE/ble/DiscoveredCharacteristic.h index effc887851f..37a6ca7f537 100644 --- a/features/FEATURE_BLE/ble/DiscoveredCharacteristic.h +++ b/features/FEATURE_BLE/ble/DiscoveredCharacteristic.h @@ -99,23 +99,23 @@ class DiscoveredCharacteristic { * @note If set, descriptors of the characteristic contain a Server * Characteristic Configuration Descriptor. */ - uint8_t _broadcast :1; + uint8_t _broadcast : 1; /** * If set, the value of the characteristic can be read. */ - uint8_t _read :1; + uint8_t _read : 1; /** * If set, a write command can write the characteristic value * (write without response). */ - uint8_t _writeWoResp :1; + uint8_t _writeWoResp : 1; /** * If set, clients can issue requests to write the characteristic. */ - uint8_t _write :1; + uint8_t _write : 1; /** * If set, the server can emit notifications of the Characteristic Value @@ -124,7 +124,7 @@ class DiscoveredCharacteristic { * @note If set, descriptors of the characteristic contain a Client * Characteristic Configuration Descriptor. */ - uint8_t _notify :1; + uint8_t _notify : 1; /** * If set, the server can emit indication of the Characteristic Value @@ -133,12 +133,12 @@ class DiscoveredCharacteristic { * @note If set, descriptors of the characteristic contain a Client * Characteristic Configuration Descriptor. */ - uint8_t _indicate :1; + uint8_t _indicate : 1; /** * If set, signed write of the Characteristic Value is supported. */ - uint8_t _authSignedWrite :1; + uint8_t _authSignedWrite : 1; public: /** @@ -432,7 +432,8 @@ class DiscoveredCharacteristic { const GattClient::WriteCallback_t &onWrite ) const; - void setupLongUUID(UUID::LongUUIDBytes_t longUUID, UUID::ByteOrder_t order = UUID::MSB) { + void setupLongUUID(UUID::LongUUIDBytes_t longUUID, UUID::ByteOrder_t order = UUID::MSB) + { uuid.setupLong(longUUID, order); } @@ -515,7 +516,7 @@ class DiscoveredCharacteristic { * * @return The GattClient, which can operate on this characteristic. */ - GattClient* getGattClient() + GattClient *getGattClient() { return gattc; } @@ -525,7 +526,7 @@ class DiscoveredCharacteristic { * * @return The GattClient, which can operate on this characteristic. */ - const GattClient* getGattClient() const + const GattClient *getGattClient() const { return gattc; } @@ -551,8 +552,9 @@ class DiscoveredCharacteristic { * @return true if operands are equals and false otherwise. */ friend bool operator==( - const DiscoveredCharacteristic& lhs, const DiscoveredCharacteristic& rhs - ) { + const DiscoveredCharacteristic &lhs, const DiscoveredCharacteristic &rhs + ) + { return lhs.gattc == rhs.gattc && lhs.uuid == rhs.uuid && lhs.props == rhs.props && @@ -571,8 +573,9 @@ class DiscoveredCharacteristic { * @return true if operands are not equal and false otherwise. */ friend bool operator !=( - const DiscoveredCharacteristic& lhs, const DiscoveredCharacteristic& rhs - ) { + const DiscoveredCharacteristic &lhs, const DiscoveredCharacteristic &rhs + ) + { return !(lhs == rhs); } @@ -584,7 +587,8 @@ class DiscoveredCharacteristic { declHandle(GattAttribute::INVALID_HANDLE), valueHandle(GattAttribute::INVALID_HANDLE), lastHandle(GattAttribute::INVALID_HANDLE), - connHandle() { + connHandle() + { } protected: diff --git a/features/FEATURE_BLE/ble/DiscoveredCharacteristicDescriptor.h b/features/FEATURE_BLE/ble/DiscoveredCharacteristicDescriptor.h index bb64c74486d..e8b15f75612 100644 --- a/features/FEATURE_BLE/ble/DiscoveredCharacteristicDescriptor.h +++ b/features/FEATURE_BLE/ble/DiscoveredCharacteristicDescriptor.h @@ -79,7 +79,8 @@ class DiscoveredCharacteristicDescriptor { ) : _client(client), _connectionHandle(connectionHandle), _uuid(uuid), - _gattHandle(attributeHandle) { + _gattHandle(attributeHandle) + { } /** @@ -87,7 +88,7 @@ class DiscoveredCharacteristicDescriptor { * * @return GattClient, which can operate on this descriptor. */ - GattClient* getGattClient() + GattClient *getGattClient() { return _client; } @@ -97,7 +98,7 @@ class DiscoveredCharacteristicDescriptor { * * @return GattClient, which can operate on this descriptor. */ - const GattClient* getGattClient() const + const GattClient *getGattClient() const { return _client; } @@ -119,7 +120,7 @@ class DiscoveredCharacteristicDescriptor { * * @return UUID of this descriptor. */ - const UUID& getUUID(void) const + const UUID &getUUID(void) const { return _uuid; } diff --git a/features/FEATURE_BLE/ble/DiscoveredService.h b/features/FEATURE_BLE/ble/DiscoveredService.h index 867c286eb06..7ff5e0aed3d 100644 --- a/features/FEATURE_BLE/ble/DiscoveredService.h +++ b/features/FEATURE_BLE/ble/DiscoveredService.h @@ -65,7 +65,7 @@ class DiscoveredService { * * @return A reference to the start handle. */ - const GattAttribute::Handle_t& getStartHandle(void) const + const GattAttribute::Handle_t &getStartHandle(void) const { return startHandle; } @@ -75,7 +75,7 @@ class DiscoveredService { * * @return A reference to the end handle. */ - const GattAttribute::Handle_t& getEndHandle(void) const + const GattAttribute::Handle_t &getEndHandle(void) const { return endHandle; } @@ -90,7 +90,8 @@ class DiscoveredService { DiscoveredService() : uuid(UUID::ShortUUIDBytes_t(0)), startHandle(GattAttribute::INVALID_HANDLE), - endHandle(GattAttribute::INVALID_HANDLE) { + endHandle(GattAttribute::INVALID_HANDLE) + { } /** @@ -109,7 +110,8 @@ class DiscoveredService { UUID uuidIn, GattAttribute::Handle_t startHandleIn, GattAttribute::Handle_t endHandleIn - ) { + ) + { uuid = uuidIn; startHandle = startHandleIn; endHandle = endHandleIn; @@ -129,7 +131,8 @@ class DiscoveredService { void setup( GattAttribute::Handle_t startHandleIn, GattAttribute::Handle_t endHandleIn - ) { + ) + { startHandle = startHandleIn; endHandle = endHandleIn; } @@ -147,8 +150,9 @@ class DiscoveredService { void setupLongUUID( UUID::LongUUIDBytes_t longUUID, UUID::ByteOrder_t order = UUID::MSB - ) { - uuid.setupLong(longUUID, order); + ) + { + uuid.setupLong(longUUID, order); } diff --git a/features/FEATURE_BLE/ble/FunctionPointerWithContext.h b/features/FEATURE_BLE/ble/FunctionPointerWithContext.h index 83507b7715e..590786d50d7 100644 --- a/features/FEATURE_BLE/ble/FunctionPointerWithContext.h +++ b/features/FEATURE_BLE/ble/FunctionPointerWithContext.h @@ -94,7 +94,8 @@ class FunctionPointerWithContext : public SafeBool(object); memcpy( _memberFunctionAndPointer._memberFunction, - (char*) &member, + (char *) &member, sizeof(member) ); _caller = &FunctionPointerWithContext::membercaller; @@ -167,7 +168,7 @@ class FunctionPointerWithContext : public SafeBoolcall(context); + ((const FunctionPointerWithContext *) this)->call(context); } /** @@ -249,7 +250,8 @@ class FunctionPointerWithContext : public SafeBool - static void membercaller(cpFunctionPointerWithContext_t self, ContextType context) { + static void membercaller(cpFunctionPointerWithContext_t self, ContextType context) + { if (self->_memberFunctionAndPointer._object) { T *o = static_cast(self->_memberFunctionAndPointer._object); void (T::*m)(ContextType); - memcpy((char*) &m, self->_memberFunctionAndPointer._memberFunction, sizeof(m)); + memcpy((char *) &m, self->_memberFunctionAndPointer._memberFunction, sizeof(m)); (o->*m)(context); } } - static void functioncaller(cpFunctionPointerWithContext_t self, ContextType context) { + static void functioncaller(cpFunctionPointerWithContext_t self, ContextType context) + { if (self->_function) { self->_function(context); } @@ -285,7 +289,7 @@ class FunctionPointerWithContext : public SafeBool FunctionPointerWithContext makeFunctionPointer( T *object, void (T::*member)(ContextType context) -) { +) +{ return FunctionPointerWithContext(object, member); } diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index d42c5826fc5..e083bf5e7ad 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -621,7 +621,7 @@ class Gap { * @see Gap::startScan(). */ typedef FunctionPointerWithContext - AdvertisementReportCallback_t; + AdvertisementReportCallback_t; /** * Connection events. @@ -769,7 +769,7 @@ class Gap { * @see Gap::onTimeout(). */ typedef CallChainOfFunctionPointersWithContext - TimeoutEventCallbackChain_t; + TimeoutEventCallbackChain_t; /** * Connection event handler. @@ -777,7 +777,7 @@ class Gap { * @see Gap::onConnection(). */ typedef FunctionPointerWithContext - ConnectionEventCallback_t; + ConnectionEventCallback_t; /** * Callchain of connection event handlers. @@ -785,23 +785,23 @@ class Gap { * @see Gap::onConnection(). */ typedef CallChainOfFunctionPointersWithContext - ConnectionEventCallbackChain_t; + ConnectionEventCallbackChain_t; /** * Disconnection event handler. * * @see Gap::onDisconnection(). */ - typedef FunctionPointerWithContext - DisconnectionEventCallback_t; + typedef FunctionPointerWithContext + DisconnectionEventCallback_t; /** * Callchain of disconnection event handlers. * * @see Gap::onDisconnection(). */ - typedef CallChainOfFunctionPointersWithContext - DisconnectionEventCallbackChain_t; + typedef CallChainOfFunctionPointersWithContext + DisconnectionEventCallbackChain_t; /** * Radio notification event handler. @@ -823,7 +823,7 @@ class Gap { * @see Gap::onShutdown(). */ typedef CallChainOfFunctionPointersWithContext - GapShutdownCallbackChain_t; + GapShutdownCallbackChain_t; /* * The following functions are meant to be overridden in the platform-specific subclass. @@ -849,7 +849,8 @@ class Gap { virtual ble_error_t setAddress( BLEProtocol::AddressType_t type, const BLEProtocol::AddressBytes_t address - ) { + ) + { /* avoid compiler warnings about unused variables */ (void)type; (void)address; @@ -870,7 +871,8 @@ class Gap { virtual ble_error_t getAddress( BLEProtocol::AddressType_t *typeP, BLEProtocol::AddressBytes_t address - ) { + ) + { /* Avoid compiler warnings about unused variables. */ (void)typeP; (void)address; @@ -969,7 +971,8 @@ class Gap { BLEProtocol::AddressType_t peerAddrType, const ConnectionParams_t *connectionParams, const GapScanningParams *scanParams - ) { + ) + { /* Avoid compiler warnings about unused variables. */ (void)peerAddr; (void)peerAddrType; @@ -1001,14 +1004,15 @@ class Gap { DeprecatedAddressType_t peerAddrType, const ConnectionParams_t *connectionParams, const GapScanningParams *scanParams - ) { + ) + { return connect( - peerAddr, - (BLEProtocol::AddressType_t) - peerAddrType, - connectionParams, - scanParams - ); + peerAddr, + (BLEProtocol::AddressType_t) + peerAddrType, + connectionParams, + scanParams + ); } /** @@ -1026,7 +1030,8 @@ class Gap { */ virtual ble_error_t disconnect( Handle_t connectionHandle, DisconnectionReason_t reason - ) { + ) + { /* avoid compiler warnings about unused variables */ (void)connectionHandle; (void)reason; @@ -1049,7 +1054,8 @@ class Gap { * @return BLE_ERROR_NONE if disconnection was successful. */ MBED_DEPRECATED("Use disconnect(Handle_t, DisconnectionReason_t) instead.") - virtual ble_error_t disconnect(DisconnectionReason_t reason) { + virtual ble_error_t disconnect(DisconnectionReason_t reason) + { /* Avoid compiler warnings about unused variables. */ (void)reason; @@ -1092,7 +1098,8 @@ class Gap { */ virtual ble_error_t setPreferredConnectionParams( const ConnectionParams_t *params - ) { + ) + { /* Avoid compiler warnings about unused variables. */ (void)params; @@ -1116,7 +1123,8 @@ class Gap { virtual ble_error_t updateConnectionParams( Handle_t handle, const ConnectionParams_t *params - ) { + ) + { /* avoid compiler warnings about unused variables */ (void)handle; (void)params; @@ -1135,7 +1143,8 @@ class Gap { * * @return BLE_ERROR_NONE if the device name was set correctly. */ - virtual ble_error_t setDeviceName(const uint8_t *deviceName) { + virtual ble_error_t setDeviceName(const uint8_t *deviceName) + { /* Avoid compiler warnings about unused variables. */ (void)deviceName; @@ -1238,7 +1247,8 @@ class Gap { */ virtual void getPermittedTxPowerValues( const int8_t **valueArrayPP, size_t *countP - ) { + ) + { /* Avoid compiler warnings about unused variables. */ (void)valueArrayPP; (void)countP; @@ -1610,7 +1620,8 @@ class Gap { */ ble_error_t accumulateAdvertisingPayload( GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len - ) { + ) + { GapAdvertisingData advPayloadCopy = _advPayload; ble_error_t rc; if ((rc = advPayloadCopy.addData(type, data, len)) != BLE_ERROR_NONE) { @@ -1651,7 +1662,8 @@ class Gap { */ ble_error_t updateAdvertisingPayload( GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len - ) { + ) + { GapAdvertisingData advPayloadCopy = _advPayload; ble_error_t rc; if ((rc = advPayloadCopy.updateData(type, data, len)) != BLE_ERROR_NONE) { @@ -1707,7 +1719,8 @@ class Gap { */ ble_error_t accumulateScanResponse( GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len - ) { + ) + { GapAdvertisingData scanResponseCopy = _scanResponse; ble_error_t rc; if ((rc = scanResponseCopy.addData(type, data, len)) != BLE_ERROR_NONE) { @@ -1728,7 +1741,8 @@ class Gap { * @note This should be followed by a call to Gap::setAdvertisingPayload() * or Gap::startAdvertising() before the update takes effect. */ - void clearScanResponse(void) { + void clearScanResponse(void) + { _scanResponse.clear(); setAdvertisingData(_advPayload, _scanResponse); } @@ -1770,11 +1784,12 @@ class Gap { uint16_t window = GapScanningParams::SCAN_WINDOW_MAX, uint16_t timeout = 0, bool activeScanning = false - ) { + ) + { ble_error_t rc; if (((rc = _scanningParams.setInterval(interval)) == BLE_ERROR_NONE) && - ((rc = _scanningParams.setWindow(window)) == BLE_ERROR_NONE) && - ((rc = _scanningParams.setTimeout(timeout)) == BLE_ERROR_NONE)) { + ((rc = _scanningParams.setWindow(window)) == BLE_ERROR_NONE) && + ((rc = _scanningParams.setTimeout(timeout)) == BLE_ERROR_NONE)) { _scanningParams.setActiveScanning(activeScanning); return BLE_ERROR_NONE; } @@ -1888,7 +1903,8 @@ class Gap { */ ble_error_t startScan( void (*callback)(const AdvertisementCallbackParams_t *params) - ) { + ) + { ble_error_t err = BLE_ERROR_NONE; if (callback) { if ((err = startRadioScan(_scanningParams)) == BLE_ERROR_NONE) { @@ -1921,7 +1937,8 @@ class Gap { ble_error_t startScan( T *object, void (T::*callbackMember)(const AdvertisementCallbackParams_t *params) - ) { + ) + { ble_error_t err = BLE_ERROR_NONE; if (object && callbackMember) { if ((err = startRadioScan(_scanningParams)) == BLE_ERROR_NONE) { @@ -2039,7 +2056,7 @@ class Gap { * * @return A reference to the timeout event callbacks chain. */ - TimeoutEventCallbackChain_t& onTimeout() + TimeoutEventCallbackChain_t &onTimeout() { return timeoutCallbackChain; } @@ -2065,7 +2082,7 @@ class Gap { * @note A callback may be unregistered using onConnection().detach(callback). */ template - void onConnection(T *tptr, void (T::*mptr)(const ConnectionCallbackParams_t*)) + void onConnection(T *tptr, void (T::*mptr)(const ConnectionCallbackParams_t *)) { connectionCallChain.add(tptr, mptr); } @@ -2079,7 +2096,7 @@ class Gap { * * @return A reference to the connection event callbacks chain. */ - ConnectionEventCallbackChain_t& onConnection() + ConnectionEventCallbackChain_t &onConnection() { return connectionCallChain; } @@ -2105,7 +2122,7 @@ class Gap { * @note A callback may be unregistered using onDisconnection().detach(callback). */ template - void onDisconnection(T *tptr, void (T::*mptr)(const DisconnectionCallbackParams_t*)) + void onDisconnection(T *tptr, void (T::*mptr)(const DisconnectionCallbackParams_t *)) { disconnectionCallChain.add(tptr, mptr); } @@ -2119,7 +2136,7 @@ class Gap { * * @return A reference to the disconnection event callbacks chain. */ - DisconnectionEventCallbackChain_t& onDisconnection() + DisconnectionEventCallbackChain_t &onDisconnection() { return disconnectionCallChain; } @@ -2170,7 +2187,7 @@ class Gap { * @note To unregister a shutdown event handler, use * onShutdown().detach(callback). */ - void onShutdown(const GapShutdownCallback_t& callback) + void onShutdown(const GapShutdownCallback_t &callback) { shutdownCallChain.add(callback); } @@ -2196,7 +2213,7 @@ class Gap { * * @return A reference to the shutdown event callback chain. */ - GapShutdownCallbackChain_t& onShutdown() + GapShutdownCallbackChain_t &onShutdown() { return shutdownCallChain; } @@ -2264,7 +2281,8 @@ class Gap { radioNotificationCallback(), onAdvertisementReport(), connectionCallChain(), - disconnectionCallChain() { + disconnectionCallChain() + { _advPayload.clear(); _scanResponse.clear(); } @@ -2294,7 +2312,8 @@ class Gap { BLEProtocol::AddressType_t ownAddrType, const BLEProtocol::AddressBytes_t ownAddr, const ConnectionParams_t *connectionParams - ) { + ) + { /* Update Gap state */ state.advertising = 0; state.connected = 1; @@ -2358,10 +2377,11 @@ class Gap { uint8_t advertisingDataLen, const uint8_t *advertisingData, BLEProtocol::AddressType_t addressType = BLEProtocol::AddressType::RANDOM_STATIC - ) { - // FIXME: remove default parameter for addressType when ST shield is merged; - // this has been added to mitigate the lack of dependency management in - // testing jobs .... + ) + { + // FIXME: remove default parameter for addressType when ST shield is merged; + // this has been added to mitigate the lack of dependency management in + // testing jobs .... AdvertisementCallbackParams_t params; memcpy(params.peerAddr, peerAddr, ADDR_LEN); @@ -2470,7 +2490,7 @@ class Gap { private: /* Disallow copy and assignment. */ Gap(const Gap &); - Gap& operator=(const Gap &); + Gap &operator=(const Gap &); }; /** diff --git a/features/FEATURE_BLE/ble/GapAdvertisingData.h b/features/FEATURE_BLE/ble/GapAdvertisingData.h index 991c144f57e..fbbcc4f2f47 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingData.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingData.h @@ -110,8 +110,7 @@ * errors such as adding an exclusive AD field twice in the advertising * or scan response payload. */ -class GapAdvertisingData -{ +class GapAdvertisingData { public: /*! * List of standard Advertising Data types. @@ -537,7 +536,8 @@ class GapAdvertisingData GapAdvertisingData(void) : _payload(), _payloadLen(0), - _appearance(GENERIC_TAG) { + _appearance(GENERIC_TAG) + { } /** @@ -563,7 +563,7 @@ class GapAdvertisingData ble_error_t addData(DataType_t advDataType, const uint8_t *payload, uint8_t len) { /* Find field */ - uint8_t* field = findField(advDataType); + uint8_t *field = findField(advDataType); if (field) { /* Field type already exists, either add to field or replace */ @@ -589,7 +589,7 @@ class GapAdvertisingData ble_error_t updateData(DataType_t advDataType, const uint8_t *payload, uint8_t len) { /* Find field */ - uint8_t* field = findField(advDataType); + uint8_t *field = findField(advDataType); if (field) { /* Field type already exists, replace field contents */ @@ -706,10 +706,10 @@ class GapAdvertisingData * element being the length of the field followed by the value of the field. * @return NULL if the field is not present in the payload. */ - const uint8_t* findField(DataType_t type) const + const uint8_t *findField(DataType_t type) const { /* Scan through advertisement data */ - for (uint8_t idx = 0; idx < _payloadLen; ) { + for (uint8_t idx = 0; idx < _payloadLen;) { uint8_t fieldType = _payload[idx + 1]; if (fieldType == type) { @@ -768,11 +768,11 @@ class GapAdvertisingData * element being the length of the field followed by the value of the field. * @return NULL if the field is not present in the payload. */ - uint8_t* findField(DataType_t type) + uint8_t *findField(DataType_t type) { - return const_cast( - static_cast(this)->findField(type) - ); + return const_cast( + static_cast(this)->findField(type) + ); } /** @@ -798,11 +798,12 @@ class GapAdvertisingData DataType_t advDataType, const uint8_t *payload, uint8_t len, - uint8_t* field - ) { + uint8_t *field + ) + { ble_error_t result = BLE_ERROR_BUFFER_OVERFLOW; - switch(advDataType) { + switch (advDataType) { /* These fields have the new data appended if there is sufficient space. */ case INCOMPLETE_LIST_16BIT_SERVICE_IDS: case COMPLETE_LIST_16BIT_SERVICE_IDS: @@ -811,40 +812,40 @@ class GapAdvertisingData case INCOMPLETE_LIST_128BIT_SERVICE_IDS: case COMPLETE_LIST_128BIT_SERVICE_IDS: case LIST_128BIT_SOLICITATION_IDS: { - /* Check if data fits */ - if ((_payloadLen + len) <= GAP_ADVERTISING_DATA_MAX_PAYLOAD) { - /* - * Make room for new field by moving the remainder of the - * advertisement payload "to the right" starting after the - * TYPE field. - */ - uint8_t* end = &_payload[_payloadLen]; - - while (&field[1] < end) { - end[len] = *end; - end--; + /* Check if data fits */ + if ((_payloadLen + len) <= GAP_ADVERTISING_DATA_MAX_PAYLOAD) { + /* + * Make room for new field by moving the remainder of the + * advertisement payload "to the right" starting after the + * TYPE field. + */ + uint8_t *end = &_payload[_payloadLen]; + + while (&field[1] < end) { + end[len] = *end; + end--; + } + + /* Insert new data */ + for (uint8_t idx = 0; idx < len; idx++) { + field[2 + idx] = payload[idx]; + } + + /* Increment lengths */ + field[0] += len; + _payloadLen += len; + + result = BLE_ERROR_NONE; } - /* Insert new data */ - for (uint8_t idx = 0; idx < len; idx++) { - field[2 + idx] = payload[idx]; - } - - /* Increment lengths */ - field[0] += len; - _payloadLen += len; - - result = BLE_ERROR_NONE; + break; } - - break; - } /* These fields are overwritten with the new value */ default: { - result = updateField(advDataType, payload, len, field); + result = updateField(advDataType, payload, len, field); - break; - } + break; + } } return result; @@ -866,8 +867,9 @@ class GapAdvertisingData DataType_t advDataType, const uint8_t *payload, uint8_t len, - uint8_t* field - ) { + uint8_t *field + ) + { ble_error_t result = BLE_ERROR_BUFFER_OVERFLOW; uint8_t dataLength = field[0] - 1; diff --git a/features/FEATURE_BLE/ble/GapEvents.h b/features/FEATURE_BLE/ble/GapEvents.h index 7e190dfae5b..130dd9dae9d 100644 --- a/features/FEATURE_BLE/ble/GapEvents.h +++ b/features/FEATURE_BLE/ble/GapEvents.h @@ -28,8 +28,7 @@ @deprecated Do not use; it is not used by BLE API. */ -class GapEvents -{ +class GapEvents { public: /*! \brief diff --git a/features/FEATURE_BLE/ble/GapScanningParams.h b/features/FEATURE_BLE/ble/GapScanningParams.h index 7ff43295c02..8369d3920ea 100644 --- a/features/FEATURE_BLE/ble/GapScanningParams.h +++ b/features/FEATURE_BLE/ble/GapScanningParams.h @@ -230,7 +230,7 @@ class GapScanningParams { private: /* Disallow copy constructor. */ GapScanningParams(const GapScanningParams &); - GapScanningParams& operator =(const GapScanningParams &in); + GapScanningParams &operator =(const GapScanningParams &in); }; /** diff --git a/features/FEATURE_BLE/ble/GattAttribute.h b/features/FEATURE_BLE/ble/GattAttribute.h index 59bb7285bc1..a868913f61d 100644 --- a/features/FEATURE_BLE/ble/GattAttribute.h +++ b/features/FEATURE_BLE/ble/GattAttribute.h @@ -114,7 +114,8 @@ class GattAttribute { _lenMax(maxLen), _len(len), _hasVariableLen(hasVariableLen), - _handle() { + _handle() + { } public: @@ -243,7 +244,7 @@ class GattAttribute { private: /* Disallow copy and assignment. */ GattAttribute(const GattAttribute &); - GattAttribute& operator=(const GattAttribute &); + GattAttribute &operator=(const GattAttribute &); }; /** diff --git a/features/FEATURE_BLE/ble/GattCharacteristic.h b/features/FEATURE_BLE/ble/GattCharacteristic.h index 671665f4e50..7d924757280 100644 --- a/features/FEATURE_BLE/ble/GattCharacteristic.h +++ b/features/FEATURE_BLE/ble/GattCharacteristic.h @@ -1377,7 +1377,8 @@ class GattCharacteristic { enabledReadAuthorization(false), enabledWriteAuthorization(false), readAuthorizationCallback(), - writeAuthorizationCallback() { + writeAuthorizationCallback() + { } public: @@ -1405,7 +1406,8 @@ class GattCharacteristic { */ void setWriteAuthorizationCallback( void (*callback)(GattWriteAuthCallbackParams *) - ) { + ) + { writeAuthorizationCallback.attach(callback); enabledWriteAuthorization = true; } @@ -1426,7 +1428,8 @@ class GattCharacteristic { void setWriteAuthorizationCallback( T *object, void (T::*member)(GattWriteAuthCallbackParams *) - ) { + ) + { writeAuthorizationCallback.attach(object, member); enabledWriteAuthorization = true; } @@ -1443,7 +1446,8 @@ class GattCharacteristic { */ void setReadAuthorizationCallback( void (*callback)(GattReadAuthCallbackParams *) - ) { + ) + { readAuthorizationCallback.attach(callback); enabledReadAuthorization = true; } @@ -1465,7 +1469,8 @@ class GattCharacteristic { void setReadAuthorizationCallback( T *object, void (T::*member)(GattReadAuthCallbackParams *) - ) { + ) + { readAuthorizationCallback.attach(object, member); enabledReadAuthorization = true; } @@ -1536,7 +1541,7 @@ class GattCharacteristic { * * @return A reference to the characteristic's value attribute. */ - GattAttribute& getValueAttribute() + GattAttribute &getValueAttribute() { return _valueAttribute; } @@ -1546,7 +1551,7 @@ class GattCharacteristic { * * @return A const reference to the characteristic's value attribute. */ - const GattAttribute& getValueAttribute() const + const GattAttribute &getValueAttribute() const { return _valueAttribute; } @@ -1680,18 +1685,18 @@ class GattCharacteristic { * The registered callback handler for read authorization reply. */ FunctionPointerWithContext - readAuthorizationCallback; + readAuthorizationCallback; /** * The registered callback handler for write authorization reply. */ FunctionPointerWithContext - writeAuthorizationCallback; + writeAuthorizationCallback; private: /* Disallow copy and assignment. */ GattCharacteristic(const GattCharacteristic &); - GattCharacteristic& operator=(const GattCharacteristic &); + GattCharacteristic &operator=(const GattCharacteristic &); }; /** @@ -1725,15 +1730,16 @@ class ReadOnlyGattCharacteristic : public GattCharacteristic { GattAttribute *descriptors[] = NULL, unsigned numDescriptors = 0 ) : GattCharacteristic( - uuid, - reinterpret_cast(valuePtr), - sizeof(T), - sizeof(T), - BLE_GATT_CHAR_PROPERTIES_READ | additionalProperties, - descriptors, - numDescriptors, - false - ) { + uuid, + reinterpret_cast(valuePtr), + sizeof(T), + sizeof(T), + BLE_GATT_CHAR_PROPERTIES_READ | additionalProperties, + descriptors, + numDescriptors, + false + ) + { } }; @@ -1768,14 +1774,15 @@ class WriteOnlyGattCharacteristic : public GattCharacteristic { GattAttribute *descriptors[] = NULL, unsigned numDescriptors = 0 ) : GattCharacteristic( - uuid, - reinterpret_cast(valuePtr), - sizeof(T), - sizeof(T), - BLE_GATT_CHAR_PROPERTIES_WRITE | additionalProperties, - descriptors, - numDescriptors - ) { + uuid, + reinterpret_cast(valuePtr), + sizeof(T), + sizeof(T), + BLE_GATT_CHAR_PROPERTIES_WRITE | additionalProperties, + descriptors, + numDescriptors + ) + { } }; @@ -1810,14 +1817,15 @@ class ReadWriteGattCharacteristic : public GattCharacteristic { GattAttribute *descriptors[] = NULL, unsigned numDescriptors = 0 ) : GattCharacteristic( - uuid, - reinterpret_cast(valuePtr), - sizeof(T), - sizeof(T), - BLE_GATT_CHAR_PROPERTIES_READ | BLE_GATT_CHAR_PROPERTIES_WRITE | additionalProperties, - descriptors, - numDescriptors - ) { + uuid, + reinterpret_cast(valuePtr), + sizeof(T), + sizeof(T), + BLE_GATT_CHAR_PROPERTIES_READ | BLE_GATT_CHAR_PROPERTIES_WRITE | additionalProperties, + descriptors, + numDescriptors + ) + { } }; @@ -1853,14 +1861,15 @@ class WriteOnlyArrayGattCharacteristic : public GattCharacteristic { GattAttribute *descriptors[] = NULL, unsigned numDescriptors = 0 ) : GattCharacteristic( - uuid, - reinterpret_cast(valuePtr), - sizeof(T) * NUM_ELEMENTS, - sizeof(T) * NUM_ELEMENTS, - BLE_GATT_CHAR_PROPERTIES_WRITE | additionalProperties, - descriptors, - numDescriptors - ) { + uuid, + reinterpret_cast(valuePtr), + sizeof(T) * NUM_ELEMENTS, + sizeof(T) * NUM_ELEMENTS, + BLE_GATT_CHAR_PROPERTIES_WRITE | additionalProperties, + descriptors, + numDescriptors + ) + { } }; @@ -1897,15 +1906,16 @@ class ReadOnlyArrayGattCharacteristic : public GattCharacteristic { GattAttribute *descriptors[] = NULL, unsigned numDescriptors = 0 ) : GattCharacteristic( - uuid, - reinterpret_cast(valuePtr), - sizeof(T) * NUM_ELEMENTS, - sizeof(T) * NUM_ELEMENTS, - BLE_GATT_CHAR_PROPERTIES_READ | additionalProperties, - descriptors, - numDescriptors, - false - ) { + uuid, + reinterpret_cast(valuePtr), + sizeof(T) * NUM_ELEMENTS, + sizeof(T) * NUM_ELEMENTS, + BLE_GATT_CHAR_PROPERTIES_READ | additionalProperties, + descriptors, + numDescriptors, + false + ) + { } }; @@ -1942,14 +1952,15 @@ class ReadWriteArrayGattCharacteristic : public GattCharacteristic { GattAttribute *descriptors[] = NULL, unsigned numDescriptors = 0 ) : GattCharacteristic( - uuid, - reinterpret_cast(valuePtr), - sizeof(T) * NUM_ELEMENTS, - sizeof(T) * NUM_ELEMENTS, - BLE_GATT_CHAR_PROPERTIES_READ | BLE_GATT_CHAR_PROPERTIES_WRITE | additionalProperties, - descriptors, - numDescriptors - ) { + uuid, + reinterpret_cast(valuePtr), + sizeof(T) * NUM_ELEMENTS, + sizeof(T) * NUM_ELEMENTS, + BLE_GATT_CHAR_PROPERTIES_READ | BLE_GATT_CHAR_PROPERTIES_WRITE | additionalProperties, + descriptors, + numDescriptors + ) + { } }; diff --git a/features/FEATURE_BLE/ble/GattClient.h b/features/FEATURE_BLE/ble/GattClient.h index 137304bc236..b0624038569 100644 --- a/features/FEATURE_BLE/ble/GattClient.h +++ b/features/FEATURE_BLE/ble/GattClient.h @@ -88,14 +88,14 @@ class GattClient { * * @see GattClient::onDataRead(). */ - typedef FunctionPointerWithContext - ReadCallback_t; + typedef FunctionPointerWithContext + ReadCallback_t; /** * Callchain of attribute read event handlers. */ - typedef CallChainOfFunctionPointersWithContext - ReadCallbackChain_t; + typedef CallChainOfFunctionPointersWithContext + ReadCallbackChain_t; /** * GATT write operations. @@ -123,32 +123,32 @@ class GattClient { * * @see GattClient::onDataWrite(). */ - typedef FunctionPointerWithContext - WriteCallback_t; + typedef FunctionPointerWithContext + WriteCallback_t; /** * Callchain of attribute write event handlers. * * @see GattClient::onDataWrite(). */ - typedef CallChainOfFunctionPointersWithContext - WriteCallbackChain_t; + typedef CallChainOfFunctionPointersWithContext + WriteCallbackChain_t; /** * Handle value notification/indication event handler. * * @see to GattClient::onHVX(). */ - typedef FunctionPointerWithContext - HVXCallback_t; + typedef FunctionPointerWithContext + HVXCallback_t; /** * Callchain of handle value notification/indication event handlers. * * @see GattClient::onHVX(). */ - typedef CallChainOfFunctionPointersWithContext - HVXCallbackChain_t; + typedef CallChainOfFunctionPointersWithContext + HVXCallbackChain_t; /** * Shutdown event handler. @@ -156,7 +156,7 @@ class GattClient { * @see GattClient::onShutdown(). */ typedef FunctionPointerWithContext - GattClientShutdownCallback_t; + GattClientShutdownCallback_t; /** @@ -165,7 +165,7 @@ class GattClient { * @see to GattClient::onShutown(). */ typedef CallChainOfFunctionPointersWithContext - GattClientShutdownCallbackChain_t; + GattClientShutdownCallbackChain_t; /* * The following functions are meant to be overridden in the platform @@ -231,7 +231,8 @@ class GattClient { ServiceDiscovery::CharacteristicCallback_t cc = NULL, const UUID &matchingServiceUUID = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN), const UUID &matchingCharacteristicUUIDIn = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN) - ) { + ) + { /* Avoid compiler warnings about unused variables. */ (void)connectionHandle; (void)sc; @@ -277,15 +278,16 @@ class GattClient { Gap::Handle_t connectionHandle, ServiceDiscovery::ServiceCallback_t callback, const UUID &matchingServiceUUID = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN) - ) { + ) + { /* We take advantage of the property * that providing NULL for the characteristic callback results in * characteristic discovery being skipped for each matching * service. This allows for an inexpensive method to discover only * services. Porters are free to override this. */ return launchServiceDiscovery( - connectionHandle, callback, NULL, matchingServiceUUID - ); + connectionHandle, callback, NULL, matchingServiceUUID + ); } /** @@ -319,7 +321,8 @@ class GattClient { ServiceDiscovery::ServiceCallback_t callback, GattAttribute::Handle_t startHandle, GattAttribute::Handle_t endHandle - ) { + ) + { /* Avoid compiler warnings about unused variables. */ (void)connectionHandle; (void)callback; @@ -391,7 +394,8 @@ class GattClient { Gap::Handle_t connHandle, GattAttribute::Handle_t attributeHandle, uint16_t offset - ) const { + ) const + { /* Avoid compiler warnings about unused variables. */ (void)connHandle; (void)attributeHandle; @@ -445,7 +449,8 @@ class GattClient { GattAttribute::Handle_t attributeHandle, size_t length, const uint8_t *value - ) const { + ) const + { /* Avoid compiler warnings about unused variables. */ (void)cmd; (void)connHandle; @@ -485,7 +490,7 @@ class GattClient { * @note It is possible to unregister an handler by using * onDataRead().detach(callback). */ - ReadCallbackChain_t& onDataRead() + ReadCallbackChain_t &onDataRead() { return onDataReadCallbackChain; } @@ -517,7 +522,7 @@ class GattClient { * @note It is possible to unregister an handler by using * onDataWritten().detach(callback). */ - WriteCallbackChain_t& onDataWritten() + WriteCallbackChain_t &onDataWritten() { return onDataWriteCallbackChain; } @@ -548,7 +553,8 @@ class GattClient { */ virtual void onServiceDiscoveryTermination( ServiceDiscovery::TerminationCallback_t callback - ) { + ) + { (void)callback; /* Avoid compiler warnings about ununsed variables. */ /* Requesting action from porters: override this API if this capability @@ -578,10 +584,11 @@ class GattClient { * procedure has been launched successfully otherwise an appropriate error. */ virtual ble_error_t discoverCharacteristicDescriptors( - const DiscoveredCharacteristic& characteristic, - const CharacteristicDescriptorDiscovery::DiscoveryCallback_t& discoveryCallback, - const CharacteristicDescriptorDiscovery::TerminationCallback_t& terminationCallback - ) { + const DiscoveredCharacteristic &characteristic, + const CharacteristicDescriptorDiscovery::DiscoveryCallback_t &discoveryCallback, + const CharacteristicDescriptorDiscovery::TerminationCallback_t &terminationCallback + ) + { (void) characteristic; (void) discoveryCallback; (void) terminationCallback; @@ -601,8 +608,9 @@ class GattClient { * in input otherwise false. */ virtual bool isCharacteristicDescriptorDiscoveryActive( - const DiscoveredCharacteristic& characteristic - ) const { + const DiscoveredCharacteristic &characteristic + ) const + { (void) characteristic; /* Requesting action from porter(s): override this API if this capability is supported. */ @@ -619,8 +627,9 @@ class GattClient { * being discovered. */ virtual void terminateCharacteristicDescriptorDiscovery( - const DiscoveredCharacteristic& characteristic - ) { + const DiscoveredCharacteristic &characteristic + ) + { /* Requesting action from porter(s): override this API if this capability is supported. */ (void) characteristic; @@ -653,7 +662,7 @@ class GattClient { * * @see BLE::shutdown() */ - void onShutdown(const GattClientShutdownCallback_t& callback) + void onShutdown(const GattClientShutdownCallback_t &callback) { shutdownCallChain.add(callback); } @@ -683,7 +692,7 @@ class GattClient { * * @note onShutdown().detach(callback) may be used to unregister an handler. */ - GattClientShutdownCallbackChain_t& onShutdown() + GattClientShutdownCallbackChain_t &onShutdown() { return shutdownCallChain; } @@ -697,7 +706,8 @@ class GattClient { * * @note It is possible to unregister callbacks using onHVX().detach(callback). */ - HVXCallbackChain_t& onHVX() { + HVXCallbackChain_t &onHVX() + { return onHVXCallbackChain; } @@ -812,7 +822,7 @@ class GattClient { private: /* Disallow copy and assignment. */ GattClient(const GattClient &); - GattClient& operator=(const GattClient &); + GattClient &operator=(const GattClient &); }; /** diff --git a/features/FEATURE_BLE/ble/GattServer.h b/features/FEATURE_BLE/ble/GattServer.h index 6704e6db58d..b6065c2e6ab 100644 --- a/features/FEATURE_BLE/ble/GattServer.h +++ b/features/FEATURE_BLE/ble/GattServer.h @@ -100,7 +100,7 @@ class GattServer { * @see onDataSent(). */ typedef CallChainOfFunctionPointersWithContext - DataSentCallbackChain_t; + DataSentCallbackChain_t; /** * Event handler invoked when the client has written an attribute of the @@ -108,32 +108,32 @@ class GattServer { * * @see onDataWritten(). */ - typedef FunctionPointerWithContext - DataWrittenCallback_t; + typedef FunctionPointerWithContext + DataWrittenCallback_t; /** * Callchain of DataWrittenCallback_t objects. * * @see onDataWritten(). */ - typedef CallChainOfFunctionPointersWithContext - DataWrittenCallbackChain_t; + typedef CallChainOfFunctionPointersWithContext + DataWrittenCallbackChain_t; /** * Event handler invoked when the client has read an attribute of the server. * * @see onDataRead(). */ - typedef FunctionPointerWithContext - DataReadCallback_t; + typedef FunctionPointerWithContext + DataReadCallback_t; /** * Callchain of DataReadCallback_t. * * @see onDataRead(). */ - typedef CallChainOfFunctionPointersWithContext - DataReadCallbackChain_t; + typedef CallChainOfFunctionPointersWithContext + DataReadCallbackChain_t; /** * Event handler invoked when the GattServer is reset. @@ -141,15 +141,15 @@ class GattServer { * @see onShutdown() reset() */ typedef FunctionPointerWithContext - GattServerShutdownCallback_t; + GattServerShutdownCallback_t; /** * Callchain of GattServerShutdownCallback_t. * * @see onShutdown() reset() */ - typedef CallChainOfFunctionPointersWithContext - GattServerShutdownCallbackChain_t; + typedef CallChainOfFunctionPointersWithContext + GattServerShutdownCallbackChain_t; /** * Event handler that handles subscription to characteristic updates, @@ -171,7 +171,8 @@ class GattServer { dataReadCallChain(), updatesEnabledCallback(NULL), updatesDisabledCallback(NULL), - confirmationReceivedCallback(NULL) { + confirmationReceivedCallback(NULL) + { } /* @@ -235,7 +236,8 @@ class GattServer { GattAttribute::Handle_t attributeHandle, uint8_t buffer[], uint16_t *lengthP - ) { + ) + { /* Avoid compiler warnings about unused variables. */ (void)attributeHandle; (void)buffer; @@ -269,7 +271,8 @@ class GattServer { GattAttribute::Handle_t attributeHandle, uint8_t *buffer, uint16_t *lengthP - ) { + ) + { /* Avoid compiler warnings about unused variables. */ (void)connectionHandle; (void)attributeHandle; @@ -301,7 +304,8 @@ class GattServer { const uint8_t *value, uint16_t size, bool localOnly = false - ) { + ) + { /* Avoid compiler warnings about unused variables. */ (void)attributeHandle; (void)value; @@ -340,7 +344,8 @@ class GattServer { const uint8_t *value, uint16_t size, bool localOnly = false - ) { + ) + { /* Avoid compiler warnings about unused variables. */ (void)connectionHandle; (void)attributeHandle; @@ -367,7 +372,8 @@ class GattServer { virtual ble_error_t areUpdatesEnabled( const GattCharacteristic &characteristic, bool *enabledP - ) { + ) + { /* Avoid compiler warnings about unused variables. */ (void)characteristic; (void)enabledP; @@ -394,7 +400,8 @@ class GattServer { Gap::Handle_t connectionHandle, const GattCharacteristic &characteristic, bool *enabledP - ) { + ) + { /* Avoid compiler warnings about unused variables. */ (void)connectionHandle; (void)characteristic; @@ -491,7 +498,8 @@ class GattServer { void onDataWritten( T *objPtr, void (T::*memberPtr)(const GattWriteCallbackParams *context) - ) { + ) + { dataWrittenCallChain.add(objPtr, memberPtr); } @@ -551,7 +559,8 @@ class GattServer { ble_error_t onDataRead( T *objPtr, void (T::*memberPtr)(const GattReadCallbackParams *context) - ) { + ) + { if (!isOnDataReadAvailable()) { return BLE_ERROR_NOT_IMPLEMENTED; } @@ -622,7 +631,7 @@ class GattServer { * @note It is possible to unregister callbacks using * onShutdown().detach(callback). */ - GattServerShutdownCallbackChain_t& onShutdown() + GattServerShutdownCallbackChain_t &onShutdown() { return shutdownCallChain; } @@ -709,7 +718,8 @@ class GattServer { void handleEvent( GattServerEvents::gattEvent_e type, GattAttribute::Handle_t attributeHandle - ) { + ) + { switch (type) { case GattServerEvents::GATT_EVENT_UPDATES_ENABLED: if (updatesEnabledCallback) { @@ -831,7 +841,7 @@ class GattServer { private: /* Disallow copy and assignment. */ GattServer(const GattServer &); - GattServer& operator=(const GattServer &); + GattServer &operator=(const GattServer &); }; /** diff --git a/features/FEATURE_BLE/ble/GattServerEvents.h b/features/FEATURE_BLE/ble/GattServerEvents.h index 8aea1e05fb0..7281ce0246d 100644 --- a/features/FEATURE_BLE/ble/GattServerEvents.h +++ b/features/FEATURE_BLE/ble/GattServerEvents.h @@ -31,8 +31,7 @@ * * @attention This class is not part of the public API. */ -class GattServerEvents -{ +class GattServerEvents { public: /** * Enumeration of events, which a GattServer diff --git a/features/FEATURE_BLE/ble/GattService.h b/features/FEATURE_BLE/ble/GattService.h index 2148be1dcba..108b6458a5f 100644 --- a/features/FEATURE_BLE/ble/GattService.h +++ b/features/FEATURE_BLE/ble/GattService.h @@ -154,7 +154,8 @@ class GattService { _primaryServiceID(uuid), _characteristicCount(numCharacteristics), _characteristics(characteristics), - _handle(0) { + _handle(0) + { } /** diff --git a/features/FEATURE_BLE/ble/SafeBool.h b/features/FEATURE_BLE/ble/SafeBool.h index 8b135b5e5fb..05fccb99084 100644 --- a/features/FEATURE_BLE/ble/SafeBool.h +++ b/features/FEATURE_BLE/ble/SafeBool.h @@ -38,8 +38,8 @@ namespace SafeBool_ { * the trueTag function. */ class base { - template - friend class SafeBool; + template + friend class SafeBool; protected: /** @@ -116,8 +116,8 @@ class SafeBool : public SafeBool_::base { */ operator BoolType_t() const { - return (static_cast(this))->toBool() - ? &SafeBool::trueTag : 0; + return (static_cast(this))->toBool() + ? &SafeBool::trueTag : 0; } }; @@ -127,7 +127,7 @@ class SafeBool : public SafeBool_::base { * @attention Will generate a compile time error if instantiated. */ template -void operator==(const SafeBool& lhs,const SafeBool& rhs) +void operator==(const SafeBool &lhs, const SafeBool &rhs) { lhs.invalidTag(); // return false; @@ -138,8 +138,8 @@ void operator==(const SafeBool& lhs,const SafeBool& rhs) * * @attention Will generate a compile time error if instantiated. */ -template -void operator!=(const SafeBool& lhs,const SafeBool& rhs) +template +void operator!=(const SafeBool &lhs, const SafeBool &rhs) { lhs.invalidTag(); // return false; diff --git a/features/FEATURE_BLE/ble/SafeEnum.h b/features/FEATURE_BLE/ble/SafeEnum.h index 0f9a0a55540..34aa00955da 100644 --- a/features/FEATURE_BLE/ble/SafeEnum.h +++ b/features/FEATURE_BLE/ble/SafeEnum.h @@ -111,7 +111,7 @@ struct SafeEnum { /** * Construction of an enumeration value. */ - SafeEnum(LayoutType value) : _value(value) { } + SafeEnum(LayoutType value) : _value(value) { } /** * Equal to operator for SafeEnum instances. @@ -122,9 +122,10 @@ struct SafeEnum { * @return true if the inner value of lhs and rhs are equal and false * otherwise. */ - friend bool operator==(SafeEnum lhs, SafeEnum rhs) { - return lhs._value == rhs._value; - } + friend bool operator==(SafeEnum lhs, SafeEnum rhs) + { + return lhs._value == rhs._value; + } /** * Not equal to operator for SafeEnum instances. @@ -135,19 +136,21 @@ struct SafeEnum { * @return true if the inner value of lhs and rhs are not equal and false * otherwise. */ - friend bool operator!=(SafeEnum lhs, SafeEnum rhs) { - return !(lhs == rhs); - } + friend bool operator!=(SafeEnum lhs, SafeEnum rhs) + { + return !(lhs == rhs); + } /** * Explicit access to the inner value of the SafeEnum instance. */ - LayoutType value() const { - return _value; - } + LayoutType value() const + { + return _value; + } private: - LayoutType _value; + LayoutType _value; }; } // namespace ble diff --git a/features/FEATURE_BLE/ble/SecurityManager.h b/features/FEATURE_BLE/ble/SecurityManager.h index a01882959a5..5df46297353 100644 --- a/features/FEATURE_BLE/ble/SecurityManager.h +++ b/features/FEATURE_BLE/ble/SecurityManager.h @@ -104,7 +104,7 @@ * |<- pairingResult() <---------------| |----------------> pairingResult() -->| * | | | | | | * \endverbatim - * + * * @note the requestPairing() call isn't required to trigger pairing. Pairing will also be triggered * if you request encryption and authentication and no bonding information is available. The sequence will * be the same save for the lack of explicit requestPairing() call. @@ -122,7 +122,7 @@ * |<- linkEncryptionResult() <--------| |---------> linkEncryptionResult() -->| * | | | | | | * \endverbatim - * + * * @note if bonding information is not available, pairing will be triggered * * @@ -150,7 +150,7 @@ * |<- pairingResult() <---------------| |----------------> pairingResult() -->| * | | | | | | * \endverbatim - * + * */ class SecurityManager { @@ -249,7 +249,8 @@ class SecurityManager { * * @param[in] connectionHandle connection connectionHandle */ - virtual void pairingRequest(ble::connection_handle_t connectionHandle) { + virtual void pairingRequest(ble::connection_handle_t connectionHandle) + { (void)connectionHandle; } @@ -259,7 +260,8 @@ class SecurityManager { * @param[in] connectionHandle connection connectionHandle * @param[in] result result of the pairing indicating success or reason for failure */ - virtual void pairingResult(ble::connection_handle_t connectionHandle, SecurityCompletionStatus_t result) { + virtual void pairingResult(ble::connection_handle_t connectionHandle, SecurityCompletionStatus_t result) + { (void)connectionHandle; (void)result; } @@ -273,7 +275,8 @@ class SecurityManager { * * @param[in] whitelist pointer to the whitelist filled with entries based on bonding information */ - virtual void whitelistFromBondTable(Gap::Whitelist_t* whitelist) { + virtual void whitelistFromBondTable(Gap::Whitelist_t *whitelist) + { (void)whitelist; } @@ -287,7 +290,8 @@ class SecurityManager { * @param[in] connectionHandle connection connectionHandle * @param[in] result encryption state of the link */ - virtual void linkEncryptionResult(ble::connection_handle_t connectionHandle, ble::link_encryption_t result) { + virtual void linkEncryptionResult(ble::connection_handle_t connectionHandle, ble::link_encryption_t result) + { (void)connectionHandle; (void)result; } @@ -302,7 +306,8 @@ class SecurityManager { * @param[in] connectionHandle connection connectionHandle * @param[in] passkey 6 digit passkey to be displayed */ - virtual void passkeyDisplay(ble::connection_handle_t connectionHandle, const SecurityManager::Passkey_t passkey) { + virtual void passkeyDisplay(ble::connection_handle_t connectionHandle, const SecurityManager::Passkey_t passkey) + { (void)connectionHandle; (void)passkey; } @@ -316,7 +321,8 @@ class SecurityManager { * * @param[in] connectionHandle connection connectionHandle */ - virtual void confirmationRequest(ble::connection_handle_t connectionHandle) { + virtual void confirmationRequest(ble::connection_handle_t connectionHandle) + { (void)connectionHandle; } @@ -326,7 +332,8 @@ class SecurityManager { * * @param[in] connectionHandle connection connectionHandle */ - virtual void passkeyRequest(ble::connection_handle_t connectionHandle) { + virtual void passkeyRequest(ble::connection_handle_t connectionHandle) + { (void)connectionHandle; } @@ -336,7 +343,8 @@ class SecurityManager { * @param[in] connectionHandle connection connectionHandle * @param[in] keypress type of keypress event */ - virtual void keypressNotification(ble::connection_handle_t connectionHandle, SecurityManager::Keypress_t keypress) { + virtual void keypressNotification(ble::connection_handle_t connectionHandle, SecurityManager::Keypress_t keypress) + { (void)connectionHandle; (void)keypress; } @@ -346,7 +354,8 @@ class SecurityManager { * * @param[in] connectionHandle connection connectionHandle */ - virtual void legacyPairingOobRequest(ble::connection_handle_t connectionHandle) { + virtual void legacyPairingOobRequest(ble::connection_handle_t connectionHandle) + { (void)connectionHandle; } @@ -357,7 +366,8 @@ class SecurityManager { * @param[in] temporaryKey temporary key to be used in legacy pairing */ virtual void legacyPairingOobGenerated(const ble::address_t *address, - const ble::oob_tk_t *temporaryKey) { + const ble::oob_tk_t *temporaryKey) + { (void)address; (void)temporaryKey; } @@ -372,7 +382,8 @@ class SecurityManager { */ virtual void oobGenerated(const ble::address_t *address, const ble::oob_lesc_value_t *random, - const ble::oob_confirm_t *confirm) { + const ble::oob_confirm_t *confirm) + { (void)address; (void)random; (void)confirm; @@ -389,7 +400,8 @@ class SecurityManager { * @param[in] csrk signing key, pointer only valid during call * @param[in] authenticated indicates if the signing key is authenticated */ - virtual void signingKey(ble::connection_handle_t connectionHandle, const ble::csrk_t *csrk, bool authenticated) { + virtual void signingKey(ble::connection_handle_t connectionHandle, const ble::csrk_t *csrk, bool authenticated) + { (void)connectionHandle; (void)csrk; (void)authenticated; @@ -424,7 +436,8 @@ class SecurityManager { bool requireMITM = true, SecurityIOCapabilities_t iocaps = IO_CAPS_NONE, const Passkey_t passkey = NULL, - bool signing = true) { + bool signing = true) + { /* Avoid compiler warnings about unused variables. */ (void)enableBonding; (void)requireMITM; @@ -447,7 +460,8 @@ class SecurityManager { * * @return BLE_ERROR_NONE on success. */ - virtual ble_error_t reset(void) { + virtual ble_error_t reset(void) + { /* Notify that the instance is about to shutdown */ shutdownCallChain.call(this); shutdownCallChain.clear(); @@ -463,7 +477,8 @@ class SecurityManager { * @param[in] enable if true the stack will attempt to preserve bonding information on reset. * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t preserveBondingStateOnReset(bool enable) { + virtual ble_error_t preserveBondingStateOnReset(bool enable) + { /* Avoid compiler warnings about unused variables */ (void) enable; @@ -482,7 +497,8 @@ class SecurityManager { * @retval BLE_ERROR_INVALID_STATE If the API is called without module initialization or * application registration. */ - virtual ble_error_t purgeAllBondingState(void) { + virtual ble_error_t purgeAllBondingState(void) + { return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ } @@ -498,7 +514,8 @@ class SecurityManager { * * @retval BLE_ERROR_NONE On success, else an error code indicating reason for failure */ - virtual ble_error_t generateWhitelistFromBondTable(Gap::Whitelist_t *whitelist) const { + virtual ble_error_t generateWhitelistFromBondTable(Gap::Whitelist_t *whitelist) const + { return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ } @@ -513,7 +530,8 @@ class SecurityManager { * @param[in] connectionHandle Handle to identify the connection. * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t requestPairing(ble::connection_handle_t connectionHandle) { + virtual ble_error_t requestPairing(ble::connection_handle_t connectionHandle) + { (void) connectionHandle; return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ } @@ -525,7 +543,8 @@ class SecurityManager { * @param[in] connectionHandle Handle to identify the connection. * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t acceptPairingRequest(ble::connection_handle_t connectionHandle) { + virtual ble_error_t acceptPairingRequest(ble::connection_handle_t connectionHandle) + { (void) connectionHandle; return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ } @@ -537,7 +556,8 @@ class SecurityManager { * @param[in] connectionHandle Handle to identify the connection. * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t cancelPairingRequest(ble::connection_handle_t connectionHandle) { + virtual ble_error_t cancelPairingRequest(ble::connection_handle_t connectionHandle) + { (void) connectionHandle; return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ } @@ -552,7 +572,8 @@ class SecurityManager { * or cancelPairingRequest if the user wishes to reject it. * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t setPairingRequestAuthorisation(bool required = true) { + virtual ble_error_t setPairingRequestAuthorisation(bool required = true) + { (void) required; return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ } @@ -569,7 +590,8 @@ class SecurityManager { * @param[out] allow If true legacy pairing will be used if either side doesn't support Secure Connections. * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t allowLegacyPairing(bool allow = true) { + virtual ble_error_t allowLegacyPairing(bool allow = true) + { (void) allow; return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ } @@ -580,7 +602,8 @@ class SecurityManager { * @param[out] enabled true if SC are supported * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t getSecureConnectionsSupport(bool *enabled) { + virtual ble_error_t getSecureConnectionsSupport(bool *enabled) + { (void) enabled; return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ } @@ -595,7 +618,8 @@ class SecurityManager { * @param[in] iocaps type of IO capabilities available on the local device * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t setIoCapability(SecurityIOCapabilities_t iocaps) { + virtual ble_error_t setIoCapability(SecurityIOCapabilities_t iocaps) + { (void) iocaps; return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ } @@ -607,7 +631,8 @@ class SecurityManager { * @param[in] passkey ASCII string of 6 digits * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t setDisplayPasskey(const Passkey_t passkey) { + virtual ble_error_t setDisplayPasskey(const Passkey_t passkey) + { (void) passkey; return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ } @@ -621,7 +646,8 @@ class SecurityManager { * * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t setLinkSecurity(ble::connection_handle_t connectionHandle, SecurityMode_t securityMode) { + virtual ble_error_t setLinkSecurity(ble::connection_handle_t connectionHandle, SecurityMode_t securityMode) + { /* Avoid compiler warnings about unused variables. */ (void)connectionHandle; (void)securityMode; @@ -638,7 +664,8 @@ class SecurityManager { * * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t setKeypressNotification(bool enabled = true) { + virtual ble_error_t setKeypressNotification(bool enabled = true) + { (void)enabled; return BLE_ERROR_NOT_IMPLEMENTED; } @@ -653,7 +680,8 @@ class SecurityManager { * during subsequent pairing. * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t enableSigning(ble::connection_handle_t connectionHandle, bool enabled = true) { + virtual ble_error_t enableSigning(ble::connection_handle_t connectionHandle, bool enabled = true) + { (void) enabled; return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ } @@ -665,7 +693,8 @@ class SecurityManager { * * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t setHintFutureRoleReversal(bool enable = true) { + virtual ble_error_t setHintFutureRoleReversal(bool enable = true) + { (void)enable; return BLE_ERROR_NOT_IMPLEMENTED; } @@ -681,7 +710,8 @@ class SecurityManager { * @param[out] encryption * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t getLinkEncryption(ble::connection_handle_t connectionHandle, ble::link_encryption_t *encryption) { + virtual ble_error_t getLinkEncryption(ble::connection_handle_t connectionHandle, ble::link_encryption_t *encryption) + { (void)connectionHandle; (void)encryption; return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ @@ -695,7 +725,8 @@ class SecurityManager { * @param[in] encryption encryption state requested * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t setLinkEncryption(ble::connection_handle_t connectionHandle, ble::link_encryption_t encryption) { + virtual ble_error_t setLinkEncryption(ble::connection_handle_t connectionHandle, ble::link_encryption_t encryption) + { (void)connectionHandle; (void)encryption; return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ @@ -709,7 +740,8 @@ class SecurityManager { * @param[in] maximumByteSize Largest allowed encryption key size in bytes. (no larger than 16) * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t setEncryptionKeyRequirements(uint8_t minimumByteSize, uint8_t maximumByteSize) { + virtual ble_error_t setEncryptionKeyRequirements(uint8_t minimumByteSize, uint8_t maximumByteSize) + { (void) minimumByteSize; (void) maximumByteSize; return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ @@ -726,7 +758,8 @@ class SecurityManager { * @param[in] connectionHandle Handle to identify the connection. * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t requestAuthentication(ble::connection_handle_t connectionHandle) { + virtual ble_error_t requestAuthentication(ble::connection_handle_t connectionHandle) + { (void) connectionHandle; return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ } @@ -745,7 +778,8 @@ class SecurityManager { * of exchange used by the OOB data itself provides MITM protection. * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t setOOBDataUsage(ble::connection_handle_t connectionHandle, bool useOOB, bool OOBProvidesMITM = true) { + virtual ble_error_t setOOBDataUsage(ble::connection_handle_t connectionHandle, bool useOOB, bool OOBProvidesMITM = true) + { /* Avoid compiler warnings about unused variables */ (void) connectionHandle; (void) useOOB; @@ -760,7 +794,8 @@ class SecurityManager { * @param[in] confirmation True value indicates the passkey displayed matches. * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t confirmationEntered(ble::connection_handle_t connectionHandle, bool confirmation) { + virtual ble_error_t confirmationEntered(ble::connection_handle_t connectionHandle, bool confirmation) + { (void) connectionHandle; (void) confirmation; return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ @@ -773,7 +808,8 @@ class SecurityManager { * @param[in] passkey ASCII string of digits entered by the user. * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t passkeyEntered(ble::connection_handle_t connectionHandle, Passkey_t passkey) { + virtual ble_error_t passkeyEntered(ble::connection_handle_t connectionHandle, Passkey_t passkey) + { (void) connectionHandle; (void) passkey; return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ @@ -787,7 +823,8 @@ class SecurityManager { * @param[in] keypress Type of keypress event. * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t sendKeypressNotification(ble::connection_handle_t connectionHandle, Keypress_t keypress) { + virtual ble_error_t sendKeypressNotification(ble::connection_handle_t connectionHandle, Keypress_t keypress) + { (void) connectionHandle; (void) keypress; return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ @@ -800,7 +837,8 @@ class SecurityManager { * @param[in] tk pointer to out of band data received containing the temporary key. * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t legacyPairingOobReceived(const ble::address_t *address, const ble::oob_tk_t *tk) { + virtual ble_error_t legacyPairingOobReceived(const ble::address_t *address, const ble::oob_tk_t *tk) + { (void) address; (void) tk; return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ @@ -815,7 +853,8 @@ class SecurityManager { * in secure connections pairing * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t oobReceived(const ble::address_t *address, const ble::oob_lesc_value_t *random, const ble::oob_confirm_t *confirm) { + virtual ble_error_t oobReceived(const ble::address_t *address, const ble::oob_lesc_value_t *random, const ble::oob_confirm_t *confirm) + { (void) address; (void) random; (void) confirm; @@ -837,7 +876,8 @@ class SecurityManager { * * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - virtual ble_error_t getSigningKey(ble::connection_handle_t connectionHandle, bool authenticated) { + virtual ble_error_t getSigningKey(ble::connection_handle_t connectionHandle, bool authenticated) + { (void)connectionHandle; (void)authenticated; return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ @@ -859,11 +899,13 @@ class SecurityManager { * * @note It is possible to unregister a callback using onShutdown().detach(callback) */ - void onShutdown(const SecurityManagerShutdownCallback_t& callback) { + void onShutdown(const SecurityManagerShutdownCallback_t &callback) + { shutdownCallChain.add(callback); } template - void onShutdown(T *objPtr, void (T::*memberPtr)(const SecurityManager *)) { + void onShutdown(T *objPtr, void (T::*memberPtr)(const SecurityManager *)) + { shutdownCallChain.add(objPtr, memberPtr); } @@ -874,7 +916,8 @@ class SecurityManager { * * @return The shutdown event callbacks chain */ - SecurityManagerShutdownCallbackChain_t& onShutdown() { + SecurityManagerShutdownCallbackChain_t &onShutdown() + { return shutdownCallChain; } @@ -884,7 +927,8 @@ class SecurityManager { * * @param[in] handler Event Handler interface implementation. */ - virtual void setSecurityManagerEventHandler(EventHandler* handler) { + virtual void setSecurityManagerEventHandler(EventHandler *handler) + { if (handler) { eventHandler = handler; } else { @@ -893,7 +937,8 @@ class SecurityManager { } protected: - SecurityManager() { + SecurityManager() + { eventHandler = &defaultEventHandler; } @@ -915,7 +960,8 @@ class SecurityManager { * @retval BLE_ERROR_INVALID_STATE If the API is called without module initialization or * application registration. */ - virtual ble_error_t getAddressesFromBondTable(Gap::Whitelist_t &addresses) const { + virtual ble_error_t getAddressesFromBondTable(Gap::Whitelist_t &addresses) const + { /* Avoid compiler warnings about unused variables */ (void) addresses; return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porters: override this API if security is supported. */ @@ -931,7 +977,8 @@ class SecurityManager { * * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason. */ - ble_error_t getLinkSecurity(ble::connection_handle_t connectionHandle, LinkSecurityStatus_t *securityStatus) { + ble_error_t getLinkSecurity(ble::connection_handle_t connectionHandle, LinkSecurityStatus_t *securityStatus) + { ble::link_encryption_t encryption(ble::link_encryption_t::NOT_ENCRYPTED); ble_error_t status = getLinkEncryption(connectionHandle, &encryption); /* legacy support limits the return values */ @@ -949,7 +996,8 @@ class SecurityManager { * * To indicate that a security procedure for the link has started. */ - virtual void onSecuritySetupInitiated(SecuritySetupInitiatedCallback_t callback) { + virtual void onSecuritySetupInitiated(SecuritySetupInitiatedCallback_t callback) + { defaultEventHandler.securitySetupInitiatedCallback = callback; } @@ -958,7 +1006,8 @@ class SecurityManager { * * To indicate that the security procedure for the link has completed. */ - virtual void onSecuritySetupCompleted(SecuritySetupCompletedCallback_t callback) { + virtual void onSecuritySetupCompleted(SecuritySetupCompletedCallback_t callback) + { defaultEventHandler.securitySetupCompletedCallback = callback; } @@ -970,7 +1019,8 @@ class SecurityManager { * when the link is secured; setup procedures will not occur (unless the * bonding information is either lost or deleted on either or both sides). */ - virtual void onLinkSecured(LinkSecuredCallback_t callback) { + virtual void onLinkSecured(LinkSecuredCallback_t callback) + { defaultEventHandler.linkSecuredCallback = callback; } @@ -979,7 +1029,8 @@ class SecurityManager { * * To indicate that device context is stored persistently. */ - virtual void onSecurityContextStored(HandleSpecificEvent_t callback) { + virtual void onSecurityContextStored(HandleSpecificEvent_t callback) + { defaultEventHandler.securityContextStoredCallback = callback; } @@ -987,24 +1038,28 @@ class SecurityManager { * * To set the callback for when the passkey needs to be displayed on a peripheral with DISPLAY capability. */ - virtual void onPasskeyDisplay(PasskeyDisplayCallback_t callback) { + virtual void onPasskeyDisplay(PasskeyDisplayCallback_t callback) + { defaultEventHandler.passkeyDisplayCallback = callback; } /* Entry points for the underlying stack to report events back to the user. */ public: /** @deprecated */ - void processSecuritySetupInitiatedEvent(ble::connection_handle_t connectionHandle, bool allowBonding, bool requireMITM, SecurityIOCapabilities_t iocaps) { + void processSecuritySetupInitiatedEvent(ble::connection_handle_t connectionHandle, bool allowBonding, bool requireMITM, SecurityIOCapabilities_t iocaps) + { if (defaultEventHandler.securitySetupInitiatedCallback) { defaultEventHandler.securitySetupInitiatedCallback(connectionHandle, allowBonding, requireMITM, iocaps); } } /** @deprecated */ - void processSecuritySetupCompletedEvent(ble::connection_handle_t connectionHandle, SecurityCompletionStatus_t status) { + void processSecuritySetupCompletedEvent(ble::connection_handle_t connectionHandle, SecurityCompletionStatus_t status) + { eventHandler->pairingResult(connectionHandle, status); } /** @deprecated */ - void processLinkSecuredEvent(ble::connection_handle_t connectionHandle, SecurityMode_t securityMode) { + void processLinkSecuredEvent(ble::connection_handle_t connectionHandle, SecurityMode_t securityMode) + { if (securityMode == SECURITY_MODE_ENCRYPTION_NO_MITM) { eventHandler->linkEncryptionResult(connectionHandle, ble::link_encryption_t::ENCRYPTED); } else { @@ -1012,13 +1067,15 @@ class SecurityManager { } } /** @deprecated */ - void processSecurityContextStoredEvent(ble::connection_handle_t connectionHandle) { + void processSecurityContextStoredEvent(ble::connection_handle_t connectionHandle) + { if (defaultEventHandler.securityContextStoredCallback) { defaultEventHandler.securityContextStoredCallback(connectionHandle); } } /** @deprecated */ - void processPasskeyDisplayEvent(ble::connection_handle_t connectionHandle, const Passkey_t passkey) { + void processPasskeyDisplayEvent(ble::connection_handle_t connectionHandle, const Passkey_t passkey) + { eventHandler->passkeyDisplay(connectionHandle, passkey); } @@ -1034,13 +1091,15 @@ class SecurityManager { securityContextStoredCallback(), passkeyDisplayCallback() { }; - virtual void pairingResult(ble::connection_handle_t connectionHandle, SecurityCompletionStatus_t result) { + virtual void pairingResult(ble::connection_handle_t connectionHandle, SecurityCompletionStatus_t result) + { if (securitySetupCompletedCallback) { securitySetupCompletedCallback(connectionHandle, result); } } - virtual void linkEncryptionResult(ble::connection_handle_t connectionHandle, ble::link_encryption_t result) { + virtual void linkEncryptionResult(ble::connection_handle_t connectionHandle, ble::link_encryption_t result) + { if (linkSecuredCallback) { SecurityManager::SecurityMode_t securityMode; if (result == ble::link_encryption_t::ENCRYPTED) { @@ -1054,7 +1113,8 @@ class SecurityManager { } }; - virtual void passkeyDisplay(ble::connection_handle_t connectionHandle, const SecurityManager::Passkey_t passkey) { + virtual void passkeyDisplay(ble::connection_handle_t connectionHandle, const SecurityManager::Passkey_t passkey) + { if (passkeyDisplayCallback) { passkeyDisplayCallback(connectionHandle, passkey); } @@ -1071,7 +1131,7 @@ class SecurityManager { SecurityManagerShutdownCallbackChain_t shutdownCallChain; protected: - EventHandler* eventHandler; + EventHandler *eventHandler; LegacyEventHandler defaultEventHandler; }; diff --git a/features/FEATURE_BLE/ble/ServiceDiscovery.h b/features/FEATURE_BLE/ble/ServiceDiscovery.h index c2e7512d1f1..c4143802cb0 100644 --- a/features/FEATURE_BLE/ble/ServiceDiscovery.h +++ b/features/FEATURE_BLE/ble/ServiceDiscovery.h @@ -55,7 +55,7 @@ class ServiceDiscovery { * the callback scope. */ typedef FunctionPointerWithContext - ServiceCallback_t; + ServiceCallback_t; /** * Characteristic discovered event handler. @@ -69,7 +69,7 @@ class ServiceDiscovery { * beyond the callback scope. */ typedef FunctionPointerWithContext - CharacteristicCallback_t; + CharacteristicCallback_t; /** * Service discovery ended event. @@ -168,7 +168,8 @@ class ServiceDiscovery { * * @return BLE_ERROR_NONE on success. */ - virtual ble_error_t reset(void) { + virtual ble_error_t reset(void) + { connHandle = 0; matchingServiceUUID = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN); serviceCallback = NULL; diff --git a/features/FEATURE_BLE/ble/UUID.h b/features/FEATURE_BLE/ble/UUID.h index 19acda27f57..33d813c4a86 100644 --- a/features/FEATURE_BLE/ble/UUID.h +++ b/features/FEATURE_BLE/ble/UUID.h @@ -144,7 +144,7 @@ class UUID { * @note Internally, the UUID is stored in the little endian order as a * 16-byte array. */ - UUID(const char* stringUUID) : + UUID(const char *stringUUID) : type(UUID_TYPE_LONG), baseUUID(), shortUUID(0) @@ -184,7 +184,8 @@ class UUID { setupLong(tempUUID, UUID::MSB); } else { const uint8_t sig[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, - 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB }; + 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB + }; setupLong(sig, UUID::MSB); } } @@ -195,7 +196,8 @@ class UUID { * @param[in] longUUID The 128-bit (16-byte) of the UUID value. * @param[in] order Bytes order of @p longUUID. */ - UUID(const LongUUIDBytes_t longUUID, ByteOrder_t order = UUID::MSB) : type(UUID_TYPE_LONG), baseUUID(), shortUUID(0) { + UUID(const LongUUIDBytes_t longUUID, ByteOrder_t order = UUID::MSB) : type(UUID_TYPE_LONG), baseUUID(), shortUUID(0) + { setupLong(longUUID, order); } @@ -218,7 +220,8 @@ class UUID { UUID(ShortUUIDBytes_t _shortUUID) : type(UUID_TYPE_SHORT), baseUUID(), - shortUUID(_shortUUID) { + shortUUID(_shortUUID) + { } /** @@ -243,7 +246,8 @@ class UUID { */ UUID(void) : type(UUID_TYPE_SHORT), - shortUUID(BLE_UUID_UNKNOWN) { + shortUUID(BLE_UUID_UNKNOWN) + { } /** @@ -288,7 +292,7 @@ class UUID { const uint8_t *getBaseUUID(void) const { if (type == UUID_TYPE_SHORT) { - return (const uint8_t*)&shortUUID; + return (const uint8_t *)&shortUUID; } else { return baseUUID; } @@ -315,8 +319,8 @@ class UUID { uint8_t getLen(void) const { return ((type == UUID_TYPE_SHORT) ? - sizeof(ShortUUIDBytes_t) : - LENGTH_OF_LONG_UUID); + sizeof(ShortUUIDBytes_t) : + LENGTH_OF_LONG_UUID); } /** @@ -329,12 +333,12 @@ class UUID { bool operator== (const UUID &other) const { if ((this->type == UUID_TYPE_SHORT) && (other.type == UUID_TYPE_SHORT) && - (this->shortUUID == other.shortUUID)) { + (this->shortUUID == other.shortUUID)) { return true; } if ((this->type == UUID_TYPE_LONG) && (other.type == UUID_TYPE_LONG) && - (memcmp(this->baseUUID, other.baseUUID, LENGTH_OF_LONG_UUID) == 0)) { + (memcmp(this->baseUUID, other.baseUUID, LENGTH_OF_LONG_UUID) == 0)) { return true; } diff --git a/features/FEATURE_BLE/ble/blecommon.h b/features/FEATURE_BLE/ble/blecommon.h index 971f10c6aac..a13f850ef06 100644 --- a/features/FEATURE_BLE/ble/blecommon.h +++ b/features/FEATURE_BLE/ble/blecommon.h @@ -87,7 +87,7 @@ enum { */ BLE_UUID_DESCRIPTOR_CHAR_AGGREGATE_FORMAT = 0x2905, -/* GATT specific UUIDs */ + /* GATT specific UUIDs */ /** * Generic Attribute Profile. */ @@ -98,7 +98,7 @@ enum { */ BLE_UUID_GATT_CHARACTERISTIC_SERVICE_CHANGED = 0x2A05, -/* GAP specific UUIDs */ + /* GAP specific UUIDs */ /** * Generic Access Profile. diff --git a/features/FEATURE_BLE/ble/deprecate.h b/features/FEATURE_BLE/ble/deprecate.h index e3b1edb7ee1..935d5e6e142 100644 --- a/features/FEATURE_BLE/ble/deprecate.h +++ b/features/FEATURE_BLE/ble/deprecate.h @@ -18,12 +18,12 @@ #define MBED_BLE_DEPRECATE_H__ #ifdef YOTTA_CFG_MBED_OS - #include "compiler-polyfill/attributes.h" +#include "compiler-polyfill/attributes.h" #else - /** - * Deprecated, use MBED_DEPRECATED instead. - */ - #define __deprecated_message(msg) +/** + * Deprecated, use MBED_DEPRECATED instead. + */ +#define __deprecated_message(msg) #endif #endif diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index e6b72b68661..25d563b188e 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -42,7 +42,7 @@ namespace generic { * @attention: Not part of the public interface of BLE API. */ class GenericGap : public ::Gap, - public pal::ConnectionEventMonitor { + public pal::ConnectionEventMonitor { public: /** @@ -306,7 +306,7 @@ class GenericGap : public ::Gap, bool initialize_whitelist() const; - pal::EventQueue& _event_queue; + pal::EventQueue &_event_queue; pal::Gap &_pal_gap; pal::GenericAccessService &_gap_service; BLEProtocol::AddressType_t _address_type; diff --git a/features/FEATURE_BLE/ble/generic/GenericGattClient.h b/features/FEATURE_BLE/ble/generic/GenericGattClient.h index f0a8462ff97..3c1bb787c5e 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGattClient.h +++ b/features/FEATURE_BLE/ble/generic/GenericGattClient.h @@ -36,7 +36,7 @@ class GenericGattClient : public GattClient { /** * Create a GenericGattClient from a pal::GattClient */ - GenericGattClient(pal::GattClient* pal_client); + GenericGattClient(pal::GattClient *pal_client); /** * @see GattClient::launchServiceDiscovery @@ -45,73 +45,73 @@ class GenericGattClient : public GattClient { Gap::Handle_t connection_handle, ServiceDiscovery::ServiceCallback_t service_callback, ServiceDiscovery::CharacteristicCallback_t characteristic_callback, - const UUID& matching_service_uuid, - const UUID& matching_characteristic_uuid + const UUID &matching_service_uuid, + const UUID &matching_characteristic_uuid ); - /** - * @see GattClient::isServiceDiscoveryActive - */ + /** + * @see GattClient::isServiceDiscoveryActive + */ virtual bool isServiceDiscoveryActive() const; - /** - * @see GattClient::terminateServiceDiscovery - */ + /** + * @see GattClient::terminateServiceDiscovery + */ virtual void terminateServiceDiscovery(); - /** - * @see GattClient::read - */ + /** + * @see GattClient::read + */ virtual ble_error_t read( Gap::Handle_t connection_handle, GattAttribute::Handle_t attribute_handle, uint16_t offset ) const; - /** - * @see GattClient::write - */ + /** + * @see GattClient::write + */ virtual ble_error_t write( GattClient::WriteOp_t cmd, Gap::Handle_t connection_handle, GattAttribute::Handle_t attribute_handle, size_t length, - const uint8_t* value + const uint8_t *value ) const; - /** - * @see GattClient::onServiceDiscoveryTermination - */ + /** + * @see GattClient::onServiceDiscoveryTermination + */ virtual void onServiceDiscoveryTermination( ServiceDiscovery::TerminationCallback_t callback ); - /** - * @see GattClient::discoverCharacteristicDescriptors - */ + /** + * @see GattClient::discoverCharacteristicDescriptors + */ virtual ble_error_t discoverCharacteristicDescriptors( - const DiscoveredCharacteristic& characteristic, - const CharacteristicDescriptorDiscovery::DiscoveryCallback_t& discoveryCallback, - const CharacteristicDescriptorDiscovery::TerminationCallback_t& terminationCallback + const DiscoveredCharacteristic &characteristic, + const CharacteristicDescriptorDiscovery::DiscoveryCallback_t &discoveryCallback, + const CharacteristicDescriptorDiscovery::TerminationCallback_t &terminationCallback ); - /** - * @see GattClient::isCharacteristicDescriptorDiscoveryActive - */ + /** + * @see GattClient::isCharacteristicDescriptorDiscoveryActive + */ virtual bool isCharacteristicDescriptorDiscoveryActive( - const DiscoveredCharacteristic& characteristic + const DiscoveredCharacteristic &characteristic ) const; - /** - * @see GattClient::terminateCharacteristicDescriptorDiscovery - */ + /** + * @see GattClient::terminateCharacteristicDescriptorDiscovery + */ virtual void terminateCharacteristicDescriptorDiscovery( - const DiscoveredCharacteristic& characteristic + const DiscoveredCharacteristic &characteristic ); - /** - * @see GattClient::reset - */ + /** + * @see GattClient::reset + */ virtual ble_error_t reset(void); private: @@ -121,22 +121,22 @@ class GenericGattClient : public GattClient { struct WriteControlBlock; struct DescriptorDiscoveryControlBlock; - ProcedureControlBlock* get_control_block(Gap::Handle_t connection); - const ProcedureControlBlock* get_control_block(Gap::Handle_t connection) const; - void insert_control_block(ProcedureControlBlock* cb) const; - void remove_control_block(ProcedureControlBlock* cb) const; + ProcedureControlBlock *get_control_block(Gap::Handle_t connection); + const ProcedureControlBlock *get_control_block(Gap::Handle_t connection) const; + void insert_control_block(ProcedureControlBlock *cb) const; + void remove_control_block(ProcedureControlBlock *cb) const; void on_termination(Gap::Handle_t connection_handle); - void on_server_message_received(connection_handle_t, const pal::AttServerMessage&); - void on_server_response(connection_handle_t, const pal::AttServerMessage&); - void on_server_event(connection_handle_t, const pal::AttServerMessage&); + void on_server_message_received(connection_handle_t, const pal::AttServerMessage &); + void on_server_response(connection_handle_t, const pal::AttServerMessage &); + void on_server_event(connection_handle_t, const pal::AttServerMessage &); void on_transaction_timeout(connection_handle_t); uint16_t get_mtu(Gap::Handle_t connection) const; - pal::GattClient* const _pal_client; + pal::GattClient *const _pal_client; ServiceDiscovery::TerminationCallback_t _termination_callback; - mutable ProcedureControlBlock* control_blocks; + mutable ProcedureControlBlock *control_blocks; bool _is_reseting; }; diff --git a/features/FEATURE_BLE/ble/generic/GenericSecurityManager.h b/features/FEATURE_BLE/ble/generic/GenericSecurityManager.h index ec9ae717b01..3c173314e3e 100644 --- a/features/FEATURE_BLE/ble/generic/GenericSecurityManager.h +++ b/features/FEATURE_BLE/ble/generic/GenericSecurityManager.h @@ -31,8 +31,8 @@ namespace generic { typedef SecurityManager::SecurityIOCapabilities_t SecurityIOCapabilities_t; class GenericSecurityManager : public SecurityManager, - public pal::SecurityManager::EventHandler, - public pal::ConnectionEventMonitor::EventHandler { + public pal::SecurityManager::EventHandler, + public pal::ConnectionEventMonitor::EventHandler { public: typedef ble::pal::SecurityDistributionFlags_t SecurityDistributionFlags_t; typedef ble::pal::SecurityEntryKeys_t SecurityEntryKeys_t; @@ -239,7 +239,8 @@ class GenericSecurityManager : public SecurityManager, _pairing_authorisation_required(false), _legacy_pairing_allowed(true), _master_sends_keys(false), - _public_keys_generated(false) { + _public_keys_generated(false) + { _pal.set_event_handler(this); } @@ -296,7 +297,7 @@ class GenericSecurityManager : public SecurityManager, */ void enable_encryption_cb( pal::SecurityDb::entry_handle_t entry, - const SecurityEntryKeys_t* entryKeys + const SecurityEntryKeys_t *entryKeys ); /** @@ -307,7 +308,7 @@ class GenericSecurityManager : public SecurityManager, */ void set_ltk_cb( pal::SecurityDb::entry_handle_t entry, - const SecurityEntryKeys_t* entryKeys + const SecurityEntryKeys_t *entryKeys ); /** @@ -411,7 +412,7 @@ class GenericSecurityManager : public SecurityManager, * @param[in] params information about the new connection. */ void connection_callback( - const Gap::ConnectionCallbackParams_t* params + const Gap::ConnectionCallbackParams_t *params ); /** @@ -420,23 +421,27 @@ class GenericSecurityManager : public SecurityManager, * @param[in] params handle and reason of the disconnection. */ void disconnection_callback( - const Gap::DisconnectionCallbackParams_t* params + const Gap::DisconnectionCallbackParams_t *params ); private: struct ControlBlock_t : public pal::SecurityDistributionFlags_t { ControlBlock_t(); - pal::KeyDistribution get_initiator_key_distribution() { + pal::KeyDistribution get_initiator_key_distribution() + { return pal::KeyDistribution(initiator_key_distribution); }; - pal::KeyDistribution get_responder_key_distribution() { + pal::KeyDistribution get_responder_key_distribution() + { return pal::KeyDistribution(responder_key_distribution); }; - void set_initiator_key_distribution(pal::KeyDistribution mask) { + void set_initiator_key_distribution(pal::KeyDistribution mask) + { initiator_key_distribution = mask.value(); }; - void set_responder_key_distribution(pal::KeyDistribution mask) { + void set_responder_key_distribution(pal::KeyDistribution mask) + { responder_key_distribution = mask.value(); }; @@ -446,25 +451,25 @@ class GenericSecurityManager : public SecurityManager, address_t local_address; /**< address used for connection, possibly different from identity */ private: - uint8_t initiator_key_distribution:4; - uint8_t responder_key_distribution:4; + uint8_t initiator_key_distribution: 4; + uint8_t responder_key_distribution: 4; public: - uint8_t connected:1; - uint8_t authenticated:1; /**< have we turned encryption on during this connection */ - uint8_t is_master:1; - - uint8_t encryption_requested:1; - uint8_t encryption_failed:1; - uint8_t encrypted:1; - uint8_t signing_requested:1; - uint8_t signing_override_default:1; - - uint8_t mitm_requested:1; - uint8_t mitm_performed:1; /**< keys exchange will have MITM protection */ - - uint8_t attempt_oob:1; - uint8_t oob_mitm_protection:1; - uint8_t oob_present:1; + uint8_t connected: 1; + uint8_t authenticated: 1; /**< have we turned encryption on during this connection */ + uint8_t is_master: 1; + + uint8_t encryption_requested: 1; + uint8_t encryption_failed: 1; + uint8_t encrypted: 1; + uint8_t signing_requested: 1; + uint8_t signing_override_default: 1; + + uint8_t mitm_requested: 1; + uint8_t mitm_performed: 1; /**< keys exchange will have MITM protection */ + + uint8_t attempt_oob: 1; + uint8_t oob_mitm_protection: 1; + uint8_t oob_present: 1; }; pal::SecurityManager &_pal; @@ -689,15 +694,15 @@ class GenericSecurityManager : public SecurityManager, /* list management */ - ControlBlock_t* acquire_control_block(connection_handle_t connection); + ControlBlock_t *acquire_control_block(connection_handle_t connection); - ControlBlock_t* get_control_block(connection_handle_t connection); + ControlBlock_t *get_control_block(connection_handle_t connection); - ControlBlock_t* get_control_block(const address_t &peer_address); + ControlBlock_t *get_control_block(const address_t &peer_address); - ControlBlock_t* get_control_block(pal::SecurityDb::entry_handle_t db_entry); + ControlBlock_t *get_control_block(pal::SecurityDb::entry_handle_t db_entry); - void release_control_block(ControlBlock_t* entry); + void release_control_block(ControlBlock_t *entry); }; diff --git a/features/FEATURE_BLE/ble/pal/AttClient.h b/features/FEATURE_BLE/ble/pal/AttClient.h index 56bd1a2f062..835b553558f 100644 --- a/features/FEATURE_BLE/ble/pal/AttClient.h +++ b/features/FEATURE_BLE/ble/pal/AttClient.h @@ -104,7 +104,7 @@ struct AttClient { */ virtual ble_error_t get_mtu_size( connection_handle_t connection_handle, - uint16_t& mtu_size + uint16_t &mtu_size ) = 0; /** @@ -178,7 +178,7 @@ struct AttClient { connection_handle_t connection_handle, attribute_handle_range_t discovery_range, uint16_t type, - const ArrayView& value + const ArrayView &value ) = 0; /** @@ -221,7 +221,7 @@ struct AttClient { virtual ble_error_t read_by_type_request( connection_handle_t connection_handle, attribute_handle_range_t read_range, - const UUID& type + const UUID &type ) = 0; /** @@ -349,7 +349,7 @@ struct AttClient { */ virtual ble_error_t read_multiple_request( connection_handle_t connection_handle, - const ArrayView& attribute_handles + const ArrayView &attribute_handles ) = 0; /** @@ -400,7 +400,7 @@ struct AttClient { virtual ble_error_t read_by_group_type_request( connection_handle_t connection_handle, attribute_handle_range_t read_range, - const UUID& group_type + const UUID &group_type ) = 0; /** @@ -453,7 +453,7 @@ struct AttClient { virtual ble_error_t write_request( connection_handle_t connection_handle, attribute_handle_t attribute_handle, - const ArrayView& value + const ArrayView &value ) = 0; /** @@ -473,7 +473,7 @@ struct AttClient { virtual ble_error_t write_command( connection_handle_t connection_handle, attribute_handle_t attribute_handle, - const ArrayView& value + const ArrayView &value ) = 0; /** @@ -498,7 +498,7 @@ struct AttClient { virtual ble_error_t signed_write_command( connection_handle_t connection_handle, attribute_handle_t attribute_handle, - const ArrayView& value + const ArrayView &value ) = 0; /** @@ -551,7 +551,7 @@ struct AttClient { connection_handle_t connection_handle, attribute_handle_t attribute_handle, uint16_t offset, - const ArrayView& value + const ArrayView &value ) = 0; /** @@ -605,8 +605,9 @@ struct AttClient { * can be obtained from its opcode. */ void when_server_message_received( - mbed::Callback cb - ) { + mbed::Callback cb + ) + { _server_message_cb = cb; } @@ -621,11 +622,12 @@ struct AttClient { * timeout. To send a new ATT message, the conenction should be * reestablished. */ - void when_transaction_timeout( - mbed::Callback cb - ) { - _transaction_timeout_cb = cb; - } + void when_transaction_timeout( + mbed::Callback cb + ) + { + _transaction_timeout_cb = cb; + } protected: AttClient() { } @@ -641,8 +643,9 @@ struct AttClient { */ void on_server_event( connection_handle_t connection_handle, - const AttServerMessage& server_message - ) { + const AttServerMessage &server_message + ) + { if (_server_message_cb) { _server_message_cb(connection_handle, server_message); } @@ -658,7 +661,8 @@ struct AttClient { */ void on_transaction_timeout( connection_handle_t connection_handle - ) { + ) + { if (_transaction_timeout_cb) { _transaction_timeout_cb(connection_handle); } @@ -668,7 +672,7 @@ struct AttClient { /** * Callback called when the client receive a message from the server. */ - mbed::Callback _server_message_cb; + mbed::Callback _server_message_cb; /** * Callback called when a transaction times out. @@ -676,8 +680,8 @@ struct AttClient { mbed::Callback _transaction_timeout_cb; // Disallow copy construction and copy assignment. - AttClient(const AttClient&); - AttClient& operator=(const AttClient&); + AttClient(const AttClient &); + AttClient &operator=(const AttClient &); }; diff --git a/features/FEATURE_BLE/ble/pal/AttClientToGattClientAdapter.h b/features/FEATURE_BLE/ble/pal/AttClientToGattClientAdapter.h index d99a55e4978..f07d18aecb2 100644 --- a/features/FEATURE_BLE/ble/pal/AttClientToGattClientAdapter.h +++ b/features/FEATURE_BLE/ble/pal/AttClientToGattClientAdapter.h @@ -41,8 +41,9 @@ class AttClientToGattClientAdapter : public GattClient { * Construct an instance of GattClient from an instance of AttClient. * @param client The client to adapt. */ - AttClientToGattClientAdapter(AttClient& client) : - GattClient(), _client(client) { + AttClientToGattClientAdapter(AttClient &client) : + GattClient(), _client(client) + { _client.when_server_message_received( mbed::callback(this, &AttClientToGattClientAdapter::on_server_event) ); @@ -56,7 +57,8 @@ class AttClientToGattClientAdapter : public GattClient { /** * @see ble::pal::GattClient::exchange_mtu */ - virtual ble_error_t exchange_mtu(connection_handle_t connection) { + virtual ble_error_t exchange_mtu(connection_handle_t connection) + { return _client.exchange_mtu_request(connection); } @@ -65,8 +67,9 @@ class AttClientToGattClientAdapter : public GattClient { */ virtual ble_error_t get_mtu_size( connection_handle_t connection_handle, - uint16_t& mtu_size - ) { + uint16_t &mtu_size + ) + { return _client.get_mtu_size(connection_handle, mtu_size); } @@ -76,12 +79,13 @@ class AttClientToGattClientAdapter : public GattClient { virtual ble_error_t discover_primary_service( connection_handle_t connection, attribute_handle_t discovery_range_begining - ) { + ) + { return _client.read_by_group_type_request( - connection, - attribute_handle_range(discovery_range_begining, END_ATTRIBUTE_HANDLE), - SERVICE_TYPE_UUID - ); + connection, + attribute_handle_range(discovery_range_begining, END_ATTRIBUTE_HANDLE), + SERVICE_TYPE_UUID + ); } /** @@ -90,17 +94,18 @@ class AttClientToGattClientAdapter : public GattClient { virtual ble_error_t discover_primary_service_by_service_uuid( connection_handle_t connection_handle, attribute_handle_t discovery_range_begining, - const UUID& uuid - ) { + const UUID &uuid + ) + { return _client.find_by_type_value_request( - connection_handle, - attribute_handle_range(discovery_range_begining, END_ATTRIBUTE_HANDLE), - SERVICE_TYPE_UUID, - ArrayView( - uuid.getBaseUUID(), - (uuid.shortOrLong() == UUID::UUID_TYPE_SHORT) ? 2 : UUID::LENGTH_OF_LONG_UUID - ) - ); + connection_handle, + attribute_handle_range(discovery_range_begining, END_ATTRIBUTE_HANDLE), + SERVICE_TYPE_UUID, + ArrayView( + uuid.getBaseUUID(), + (uuid.shortOrLong() == UUID::UUID_TYPE_SHORT) ? 2 : UUID::LENGTH_OF_LONG_UUID + ) + ); } /** @@ -109,12 +114,13 @@ class AttClientToGattClientAdapter : public GattClient { virtual ble_error_t find_included_service( connection_handle_t connection_handle, attribute_handle_range_t service_range - ) { + ) + { return _client.read_by_type_request( - connection_handle, - service_range, - INCLUDE_TYPE_UUID - ); + connection_handle, + service_range, + INCLUDE_TYPE_UUID + ); } /** @@ -123,12 +129,13 @@ class AttClientToGattClientAdapter : public GattClient { virtual ble_error_t discover_characteristics_of_a_service( connection_handle_t connection_handle, attribute_handle_range_t discovery_range - ) { + ) + { return _client.read_by_type_request( - connection_handle, - discovery_range, - CHARACTERISTIC_TYPE_UUID - ); + connection_handle, + discovery_range, + CHARACTERISTIC_TYPE_UUID + ); } /** @@ -137,11 +144,12 @@ class AttClientToGattClientAdapter : public GattClient { virtual ble_error_t discover_characteristics_descriptors( connection_handle_t connection_handle, attribute_handle_range_t descriptors_discovery_range - ) { + ) + { return _client.find_information_request( - connection_handle, - descriptors_discovery_range - ); + connection_handle, + descriptors_discovery_range + ); } /** @@ -150,11 +158,12 @@ class AttClientToGattClientAdapter : public GattClient { virtual ble_error_t read_attribute_value( connection_handle_t connection_handle, attribute_handle_t attribute_handle - ) { + ) + { return _client.read_request( - connection_handle, - attribute_handle - ); + connection_handle, + attribute_handle + ); } /** @@ -163,13 +172,14 @@ class AttClientToGattClientAdapter : public GattClient { virtual ble_error_t read_using_characteristic_uuid( connection_handle_t connection_handle, attribute_handle_range_t read_range, - const UUID& uuid - ) { + const UUID &uuid + ) + { return _client.read_by_type_request( - connection_handle, - read_range, - uuid - ); + connection_handle, + read_range, + uuid + ); } /** @@ -179,12 +189,13 @@ class AttClientToGattClientAdapter : public GattClient { connection_handle_t connection_handle, attribute_handle_t attribute_handle, uint16_t offset - ) { + ) + { return _client.read_blob_request( - connection_handle, - attribute_handle, - offset - ); + connection_handle, + attribute_handle, + offset + ); } /** @@ -192,12 +203,13 @@ class AttClientToGattClientAdapter : public GattClient { */ virtual ble_error_t read_multiple_characteristic_values( connection_handle_t connection_handle, - const ArrayView& characteristic_value_handles - ) { + const ArrayView &characteristic_value_handles + ) + { return _client.read_multiple_request( - connection_handle, - characteristic_value_handles - ); + connection_handle, + characteristic_value_handles + ); } /** @@ -206,13 +218,14 @@ class AttClientToGattClientAdapter : public GattClient { virtual ble_error_t write_without_response( connection_handle_t connection_handle, attribute_handle_t characteristic_value_handle, - const ArrayView& value - ) { + const ArrayView &value + ) + { return _client.write_command( - connection_handle, - characteristic_value_handle, - value - ); + connection_handle, + characteristic_value_handle, + value + ); } /** @@ -221,13 +234,14 @@ class AttClientToGattClientAdapter : public GattClient { virtual ble_error_t signed_write_without_response( connection_handle_t connection_handle, attribute_handle_t characteristic_value_handle, - const ArrayView& value - ) { + const ArrayView &value + ) + { return _client.signed_write_command( - connection_handle, - characteristic_value_handle, - value - ); + connection_handle, + characteristic_value_handle, + value + ); } /** @@ -236,13 +250,14 @@ class AttClientToGattClientAdapter : public GattClient { virtual ble_error_t write_attribute( connection_handle_t connection_handle, attribute_handle_t attribute_handle, - const ArrayView& value - ) { + const ArrayView &value + ) + { return _client.write_request( - connection_handle, - attribute_handle, - value - ); + connection_handle, + attribute_handle, + value + ); } /** @@ -251,15 +266,16 @@ class AttClientToGattClientAdapter : public GattClient { virtual ble_error_t queue_prepare_write( connection_handle_t connection_handle, attribute_handle_t characteristic_value_handle, - const ArrayView& value, + const ArrayView &value, uint16_t offset - ) { + ) + { return _client.prepare_write_request( - connection_handle, - characteristic_value_handle, - offset, - value - ); + connection_handle, + characteristic_value_handle, + offset, + value + ); } /** @@ -268,26 +284,29 @@ class AttClientToGattClientAdapter : public GattClient { virtual ble_error_t execute_write_queue( connection_handle_t connection_handle, bool execute - ) { + ) + { return _client.execute_write_request(connection_handle, execute); } /** * @see ble::pal::GattClient::initialize */ - virtual ble_error_t initialize() { + virtual ble_error_t initialize() + { return _client.initialize(); } /** * @see ble::pal::GattClient::terminate */ - virtual ble_error_t terminate() { + virtual ble_error_t terminate() + { return _client.initialize(); } private: - AttClient& _client; + AttClient &_client; }; } // namespace pal diff --git a/features/FEATURE_BLE/ble/pal/AttServerMessage.h b/features/FEATURE_BLE/ble/pal/AttServerMessage.h index 1862549673d..895183aac15 100644 --- a/features/FEATURE_BLE/ble/pal/AttServerMessage.h +++ b/features/FEATURE_BLE/ble/pal/AttServerMessage.h @@ -66,14 +66,16 @@ struct AttributeOpcode { /** * Equality comparison operator between two AttributeOpcode */ - friend bool operator==(AttributeOpcode lhs, AttributeOpcode rhs) { + friend bool operator==(AttributeOpcode lhs, AttributeOpcode rhs) + { return lhs._value == rhs._value; } /** * Non equality comparison operator between two AttributeOpcode */ - friend bool operator!=(AttributeOpcode lhs, AttributeOpcode rhs) { + friend bool operator!=(AttributeOpcode lhs, AttributeOpcode rhs) + { return lhs._value != rhs._value; } @@ -81,7 +83,8 @@ struct AttributeOpcode { * implicit cast to uint8_t. * Allows AttributeOpcode to be used in switch statements. */ - operator uint8_t() const { + operator uint8_t() const + { return _value; } @@ -132,7 +135,8 @@ struct AttErrorResponse : public AttServerMessage { uint8_t error_code_ ) : AttServerMessage(AttributeOpcode::ERROR_RESPONSE), request_opcode(request_opcode_), - handle_in_error(handle_in_error_), error_code(error_code_) { + handle_in_error(handle_in_error_), error_code(error_code_) + { } /** @@ -149,7 +153,8 @@ struct AttErrorResponse : public AttServerMessage { uint8_t error_code_ ) : AttServerMessage(AttributeOpcode::ERROR_RESPONSE), request_opcode(request_opcode_), - handle_in_error(0x0000), error_code(error_code_) { + handle_in_error(0x0000), error_code(error_code_) + { } /** @@ -283,7 +288,8 @@ struct AttExchangeMTUResponse : public AttServerMessage { */ AttExchangeMTUResponse(uint16_t server_rx_mtu_) : AttServerMessage(AttributeOpcode::EXCHANGE_MTU_RESPONSE), - server_rx_mtu(server_rx_mtu_) { + server_rx_mtu(server_rx_mtu_) + { } /** @@ -316,7 +322,8 @@ struct AttFindInformationResponse : public AttServerMessage { * Base constructor, setup the OpCode of the response. */ AttFindInformationResponse() : - AttServerMessage(AttributeOpcode::FIND_INFORMATION_RESPONSE) { + AttServerMessage(AttributeOpcode::FIND_INFORMATION_RESPONSE) + { } /** @@ -359,7 +366,8 @@ struct AttFindByTypeValueResponse : public AttServerMessage { * Base constructor, setup the OpCode of the response. */ AttFindByTypeValueResponse() : - AttServerMessage(AttributeOpcode::FIND_BY_VALUE_TYPE_RESPONSE) { + AttServerMessage(AttributeOpcode::FIND_BY_VALUE_TYPE_RESPONSE) + { } /** @@ -407,7 +415,8 @@ struct AttReadByTypeResponse : public AttServerMessage { * Base constructor, setup the OpCode of the response. */ AttReadByTypeResponse() : - AttServerMessage(AttributeOpcode::READ_BY_TYPE_RESPONSE) { + AttServerMessage(AttributeOpcode::READ_BY_TYPE_RESPONSE) + { } /** @@ -447,13 +456,15 @@ struct AttReadResponse : public AttServerMessage { * Construct a Read Response from an array of bytes. */ AttReadResponse(ArrayView data_) : - AttServerMessage(AttributeOpcode::READ_RESPONSE), _data(data_) { + AttServerMessage(AttributeOpcode::READ_RESPONSE), _data(data_) + { } /** * Return the number of octets presents in the response. */ - size_t size() const { + size_t size() const + { return _data.size(); } @@ -461,15 +472,17 @@ struct AttReadResponse : public AttServerMessage { * Return the octet at the specified index. * @note Out of range access is undefined. */ - uint8_t operator[](size_t index) const { + uint8_t operator[](size_t index) const + { return _data[index]; } /** * Return the pointer to the actual data */ - const uint8_t* data() const { - return _data.data(); + const uint8_t *data() const + { + return _data.data(); } private: @@ -496,13 +509,15 @@ struct AttReadBlobResponse : public AttServerMessage { * Construct a read blob response from the value responded. */ AttReadBlobResponse(ArrayView data_) : - AttServerMessage(AttributeOpcode::READ_BLOB_RESPONSE), _data(data_) { + AttServerMessage(AttributeOpcode::READ_BLOB_RESPONSE), _data(data_) + { } /** * Return the number of octets presents in the response value. */ - size_t size() const { + size_t size() const + { return _data.size(); } @@ -510,15 +525,17 @@ struct AttReadBlobResponse : public AttServerMessage { * Return the octet of the value read at the specified index. * @note Out of range access is undefined. */ - uint8_t operator[](size_t index) const { + uint8_t operator[](size_t index) const + { return _data[index]; } /** * Return the pointer to the actual data */ - const uint8_t* data() const { - return _data.data(); + const uint8_t *data() const + { + return _data.data(); } private: @@ -540,13 +557,15 @@ struct AttReadMultipleResponse : public AttServerMessage { * Construct a Resd Multiple Response from the set of value received. */ AttReadMultipleResponse(ArrayView data_) : - AttServerMessage(AttributeOpcode::READ_MULTIPLE_RESPONSE), _data(data_) { + AttServerMessage(AttributeOpcode::READ_MULTIPLE_RESPONSE), _data(data_) + { } /** * Return the number of octets presents in the response set of value. */ - size_t size() const { + size_t size() const + { return _data.size(); } @@ -554,7 +573,8 @@ struct AttReadMultipleResponse : public AttServerMessage { * Return the octet of the set of value read at the specified index. * @note Out of range access is undefined. */ - uint8_t operator[](size_t index) const { + uint8_t operator[](size_t index) const + { return _data[index]; } @@ -595,7 +615,8 @@ struct AttReadByGroupTypeResponse : public AttServerMessage { * Base constructor, setup the OpCode of the response. */ AttReadByGroupTypeResponse() : - AttServerMessage(AttributeOpcode::READ_BY_GROUP_TYPE_RESPONSE) { + AttServerMessage(AttributeOpcode::READ_BY_GROUP_TYPE_RESPONSE) + { } /** @@ -655,7 +676,8 @@ struct AttPrepareWriteResponse : public AttServerMessage { ) : AttServerMessage(AttributeOpcode::PREPARE_WRITE_RESPONSE), attribute_handle(handle_), offset(offset_), - partial_value(value_) { + partial_value(value_) + { } /** @@ -689,7 +711,8 @@ struct AttExecuteWriteResponse : public AttServerMessage { * Construct an execute write response object. */ AttExecuteWriteResponse() : - AttServerMessage(AttributeOpcode::EXECUTE_WRITE_RESPONSE) { + AttServerMessage(AttributeOpcode::EXECUTE_WRITE_RESPONSE) + { } }; @@ -715,7 +738,8 @@ struct AttHandleValueNotification : public AttServerMessage { ArrayView attribute_value ) : AttServerMessage(AttributeOpcode::HANDLE_VALUE_NOTIFICATION), attribute_handle(attribute_handle), - attribute_value(attribute_value) { + attribute_value(attribute_value) + { } /** @@ -750,7 +774,8 @@ struct AttHandleValueIndication : public AttServerMessage { AttHandleValueIndication( attribute_handle_t handle, ArrayView value ) : AttServerMessage(AttributeOpcode::HANDLE_VALUE_INDICATION), - attribute_handle(handle), attribute_value(value) { + attribute_handle(handle), attribute_value(value) + { } /** diff --git a/features/FEATURE_BLE/ble/pal/EventQueue.h b/features/FEATURE_BLE/ble/pal/EventQueue.h index ead56dd36ab..be8498eda7a 100644 --- a/features/FEATURE_BLE/ble/pal/EventQueue.h +++ b/features/FEATURE_BLE/ble/pal/EventQueue.h @@ -59,7 +59,7 @@ struct EventQueue { * the event queue shall be processed at the next invocation of * BLEInstanceBase::process */ - virtual bool post(const mbed::Callback& event) = 0; + virtual bool post(const mbed::Callback &event) = 0; }; } // namespace pal diff --git a/features/FEATURE_BLE/ble/pal/GapEvents.h b/features/FEATURE_BLE/ble/pal/GapEvents.h index a406d6cdccb..033f1fd86fd 100644 --- a/features/FEATURE_BLE/ble/pal/GapEvents.h +++ b/features/FEATURE_BLE/ble/pal/GapEvents.h @@ -76,8 +76,8 @@ struct GapEvent { GapEvent(GapEventType type) : type(type) { } // Disable copy construction and copy assignement operations. - GapEvent(const GapEvent&); - GapEvent& operator=(const GapEvent&); + GapEvent(const GapEvent &); + GapEvent &operator=(const GapEvent &); }; @@ -149,7 +149,7 @@ struct GapConnectionCompleteEvent : public GapEvent { connection_handle_t connection_handle, connection_role_t role, advertising_peer_address_type_t peer_address_type, - const address_t& peer_address, + const address_t &peer_address, uint16_t connection_interval, uint16_t connection_latency, uint16_t supervision_timeout @@ -162,7 +162,8 @@ struct GapConnectionCompleteEvent : public GapEvent { peer_address(peer_address), connection_interval(connection_interval), connection_latency(connection_latency), - supervision_timeout(supervision_timeout) { + supervision_timeout(supervision_timeout) + { } /* @@ -229,7 +230,7 @@ struct GapAdvertisingReportEvent : public GapEvent { struct advertising_t { received_advertising_type_t type; connection_peer_address_type_t address_type; - const address_t& address; + const address_t &address; ArrayView data; int8_t rssi; }; @@ -288,7 +289,8 @@ struct GapConnectionUpdateEvent : public GapEvent { connection_handle(connection_handle), connection_interval(connection_interval), connection_latency(connection_latency), - supervision_timeout(supervision_timeout) { + supervision_timeout(supervision_timeout) + { } /** @@ -357,7 +359,8 @@ struct GapRemoteConnectionParameterRequestEvent : public GapEvent { min_connection_interval(min_connection_interval), max_connection_interval(max_connection_interval), connection_latency(connection_latency), - supervision_timeout(supervision_timeout) { + supervision_timeout(supervision_timeout) + { } /** @@ -414,7 +417,8 @@ struct GapDisconnectionCompleteEvent : public GapEvent { ) : GapEvent(GapEventType::DISCONNECTION_COMPLETE), status(status), connection_handle(connection_handle), - reason(reason) { + reason(reason) + { } /** diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index 2dc6c0deff9..fbd915e8798 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -377,7 +377,7 @@ struct scanning_filter_policy_t : SafeEnum { */ FILTER_ADVERTISING = 0x01 - // EXTENDED ADVERTISING FILTER POLICY (accept private resolvable direct advertising) + // EXTENDED ADVERTISING FILTER POLICY (accept private resolvable direct advertising) }; /** @@ -419,7 +419,8 @@ struct advertising_data_t { * * @param input_value Reference to the array containing the advertising data */ - advertising_data_t(const uint8_t (&input_value)[31]) { + advertising_data_t(const uint8_t (&input_value)[31]) + { memcpy(value, input_value, sizeof(value)); } @@ -430,7 +431,8 @@ struct advertising_data_t { * * @param len Length of the buffer. */ - advertising_data_t(const uint8_t* input_value, size_t len) { + advertising_data_t(const uint8_t *input_value, size_t len) + { const size_t actual_len = std::min(len, sizeof(value)); memcpy(value, input_value, actual_len); memset(value + actual_len, 0x00, sizeof(value) - actual_len); @@ -440,8 +442,9 @@ struct advertising_data_t { * Equal operator between two advertising data. */ friend bool operator==( - const advertising_data_t& lhs, const advertising_data_t& rhs - ) { + const advertising_data_t &lhs, const advertising_data_t &rhs + ) + { return memcmp(lhs.value, rhs.value, sizeof(lhs.value)) == 0; } @@ -449,29 +452,33 @@ struct advertising_data_t { * Non equal operator between two advertising data. */ friend bool operator!=( - const advertising_data_t& lhs, const advertising_data_t& rhs - ) { + const advertising_data_t &lhs, const advertising_data_t &rhs + ) + { return !(lhs == rhs); } /** * Subscript operator used to access the content of the advertising data. */ - uint8_t operator[](uint8_t i) const { + uint8_t operator[](uint8_t i) const + { return value[i]; } /** * Return a pointer to the advertising data buffer. */ - const uint8_t* data() const { + const uint8_t *data() const + { return value; } /** * Return (fixed) size of advertising data. */ - uint8_t size() const { + uint8_t size() const + { return sizeof(value); } diff --git a/features/FEATURE_BLE/ble/pal/GenericAccessService.h b/features/FEATURE_BLE/ble/pal/GenericAccessService.h index 14c05e15337..ff2049322d2 100644 --- a/features/FEATURE_BLE/ble/pal/GenericAccessService.h +++ b/features/FEATURE_BLE/ble/pal/GenericAccessService.h @@ -56,7 +56,7 @@ struct GenericAccessService { * * @see Bluetooth 4.2 Vol 3 PartC: 12.1 - Device Name Characteristic */ - virtual ble_error_t get_device_name_length(uint8_t& length) = 0; + virtual ble_error_t get_device_name_length(uint8_t &length) = 0; /** * Get the current device name. @@ -71,7 +71,7 @@ struct GenericAccessService { * * @see Bluetooth 4.2 Vol 3 PartC: 12.1 - Device Name Characteristic */ - virtual ble_error_t get_device_name(ArrayView& array) = 0; + virtual ble_error_t get_device_name(ArrayView &array) = 0; /** * Set the value of the device name characteristic exposed by the GAP GATT @@ -85,7 +85,7 @@ struct GenericAccessService { * * @see Bluetooth 4.2 Vol 3 PartC: 12.1 - Device Name Characteristic */ - virtual ble_error_t set_device_name(const uint8_t* device_name) = 0; + virtual ble_error_t set_device_name(const uint8_t *device_name) = 0; /** * Acquire the appearance stored in the appearance characteristic of the GAP @@ -100,7 +100,7 @@ struct GenericAccessService { * @see Bluetooth 4.2 Vol 3 PartC: 12.2 - Appearance Characteristic */ virtual ble_error_t get_appearance( - GapAdvertisingData::Appearance& appearance + GapAdvertisingData::Appearance &appearance ) = 0; /** @@ -113,8 +113,8 @@ struct GenericAccessService { * * @see Bluetooth 4.2 Vol 3 PartC: 12.2 - Appearance Characteristic */ - virtual ble_error_t set_appearance( - GapAdvertisingData::Appearance appearance + virtual ble_error_t set_appearance( + GapAdvertisingData::Appearance appearance ) = 0; /** @@ -130,8 +130,8 @@ struct GenericAccessService { * @see Bluetooth 4.2 Vol 3 PartC: 12.3 - Peripheral Preferred Connection * Parameters Characteristic */ - virtual ble_error_t get_peripheral_prefered_connection_parameters( - ::Gap::ConnectionParams_t& parameters + virtual ble_error_t get_peripheral_prefered_connection_parameters( + ::Gap::ConnectionParams_t ¶meters ) = 0; /** @@ -148,12 +148,12 @@ struct GenericAccessService { * Parameters Characteristic */ virtual ble_error_t set_peripheral_prefered_connection_parameters( - const ::Gap::ConnectionParams_t& parameters - ) = 0; + const ::Gap::ConnectionParams_t ¶meters + ) = 0; private: - GenericAccessService(const GenericAccessService&); - GenericAccessService& operator=(const GenericAccessService&); + GenericAccessService(const GenericAccessService &); + GenericAccessService &operator=(const GenericAccessService &); }; } // namespace pal diff --git a/features/FEATURE_BLE/ble/pal/MemorySecurityDB.h b/features/FEATURE_BLE/ble/pal/MemorySecurityDB.h index bde58a186a1..b714229053c 100644 --- a/features/FEATURE_BLE/ble/pal/MemorySecurityDB.h +++ b/features/FEATURE_BLE/ble/pal/MemorySecurityDB.h @@ -42,19 +42,20 @@ class MemorySecurityDb : public SecurityDb { }; static const size_t MAX_ENTRIES = 5; - static entry_t* as_entry(entry_handle_t entry_handle) + static entry_t *as_entry(entry_handle_t entry_handle) { - return reinterpret_cast(entry_handle); + return reinterpret_cast(entry_handle); } public: MemorySecurityDb() { }; virtual ~MemorySecurityDb() { }; - virtual const SecurityDistributionFlags_t* get_distribution_flags( + virtual const SecurityDistributionFlags_t *get_distribution_flags( entry_handle_t entry_handle - ) { - entry_t* entry = as_entry(entry_handle); + ) + { + entry_t *entry = as_entry(entry_handle); if (!entry) { return NULL; } @@ -67,9 +68,10 @@ class MemorySecurityDb : public SecurityDb { */ virtual void set_distribution_flags( entry_handle_t entry_handle, - const SecurityDistributionFlags_t& flags - ) { - entry_t* entry = as_entry(entry_handle); + const SecurityDistributionFlags_t &flags + ) + { + entry_t *entry = as_entry(entry_handle); if (!entry) { return; } @@ -86,8 +88,9 @@ class MemorySecurityDb : public SecurityDb { entry_handle_t entry_handle, const ediv_t &ediv, const rand_t &rand - ) { - entry_t* entry = as_entry(entry_handle); + ) + { + entry_t *entry = as_entry(entry_handle); if (!entry) { return; } @@ -103,8 +106,9 @@ class MemorySecurityDb : public SecurityDb { virtual void get_entry_local_keys( SecurityEntryKeysDbCb_t cb, entry_handle_t entry_handle - ) { - entry_t* entry = as_entry(entry_handle); + ) + { + entry_t *entry = as_entry(entry_handle); if (!entry) { return; } @@ -122,7 +126,8 @@ class MemorySecurityDb : public SecurityDb { virtual void set_entry_local_ltk( entry_handle_t entry_handle, const ltk_t <k - ) { + ) + { entry_t *entry = as_entry(entry_handle); if (entry) { entry->state = ENTRY_WRITTEN; @@ -134,7 +139,8 @@ class MemorySecurityDb : public SecurityDb { entry_handle_t entry_handle, const ediv_t &ediv, const rand_t &rand - ) { + ) + { entry_t *entry = as_entry(entry_handle); if (entry) { entry->state = ENTRY_WRITTEN; @@ -149,7 +155,8 @@ class MemorySecurityDb : public SecurityDb { virtual void get_entry_peer_csrk( SecurityEntryCsrkDbCb_t cb, entry_handle_t entry_handle - ) { + ) + { csrk_t csrk; entry_t *entry = as_entry(entry_handle); if (entry) { @@ -161,7 +168,8 @@ class MemorySecurityDb : public SecurityDb { virtual void get_entry_peer_keys( SecurityEntryKeysDbCb_t cb, entry_handle_t entry_handle - ) { + ) + { SecurityEntryKeys_t *key = NULL; entry_t *entry = as_entry(entry_handle); if (entry) { @@ -175,7 +183,8 @@ class MemorySecurityDb : public SecurityDb { virtual void set_entry_peer_ltk( entry_handle_t entry_handle, const ltk_t <k - ) { + ) + { entry_t *entry = as_entry(entry_handle); if (entry) { entry->state = ENTRY_WRITTEN; @@ -187,7 +196,8 @@ class MemorySecurityDb : public SecurityDb { entry_handle_t entry_handle, const ediv_t &ediv, const rand_t &rand - ) { + ) + { entry_t *entry = as_entry(entry_handle); if (entry) { entry->state = ENTRY_WRITTEN; @@ -199,7 +209,8 @@ class MemorySecurityDb : public SecurityDb { virtual void set_entry_peer_irk( entry_handle_t entry_handle, const irk_t &irk - ) { + ) + { entry_t *entry = as_entry(entry_handle); if (entry) { entry->state = ENTRY_WRITTEN; @@ -211,7 +222,8 @@ class MemorySecurityDb : public SecurityDb { entry_handle_t entry_handle, bool address_is_public, const address_t &peer_address - ) { + ) + { entry_t *entry = as_entry(entry_handle); if (entry) { entry->state = ENTRY_WRITTEN; @@ -222,7 +234,8 @@ class MemorySecurityDb : public SecurityDb { virtual void set_entry_peer_csrk( entry_handle_t entry_handle, const csrk_t &csrk - ) { + ) + { entry_t *entry = as_entry(entry_handle); if (entry) { entry->state = ENTRY_WRITTEN; @@ -232,28 +245,33 @@ class MemorySecurityDb : public SecurityDb { /* local csrk */ - virtual const csrk_t* get_local_csrk() { + virtual const csrk_t *get_local_csrk() + { return &_local_csrk; } - virtual void set_local_csrk(const csrk_t &csrk) { + virtual void set_local_csrk(const csrk_t &csrk) + { _local_csrk = csrk; } /* public key */ - virtual const public_key_coord_t& get_public_key_x() { + virtual const public_key_coord_t &get_public_key_x() + { return _public_key_x; } - virtual const public_key_coord_t& get_public_key_y() { + virtual const public_key_coord_t &get_public_key_y() + { return _public_key_y; } virtual void set_public_key( const public_key_coord_t &public_key_x, const public_key_coord_t &public_key_y - ) { + ) + { _public_key_x = public_key_x; _public_key_y = public_key_y; } @@ -263,7 +281,8 @@ class MemorySecurityDb : public SecurityDb { virtual entry_handle_t open_entry( BLEProtocol::AddressType_t peer_address_type, const address_t &peer_address - ) { + ) + { const bool peer_address_public = (peer_address_type == BLEProtocol::AddressType::PUBLIC); @@ -271,7 +290,7 @@ class MemorySecurityDb : public SecurityDb { if (_entries[i].state == ENTRY_FREE) { continue; } else if (peer_address == _entries[i].peer_identity.identity_address - && _entries[i].flags.peer_address_is_public == peer_address_public) { + && _entries[i].flags.peer_address_is_public == peer_address_public) { return &_entries[i]; } } @@ -311,7 +330,8 @@ class MemorySecurityDb : public SecurityDb { } } - virtual void clear_entries() { + virtual void clear_entries() + { for (size_t i = 0; i < MAX_ENTRIES; i++) { _entries[i] = entry_t(); } @@ -319,12 +339,14 @@ class MemorySecurityDb : public SecurityDb { _local_csrk = csrk_t(); } - virtual void get_whitelist(WhitelistDbCb_t cb, ::Gap::Whitelist_t *whitelist) { + virtual void get_whitelist(WhitelistDbCb_t cb, ::Gap::Whitelist_t *whitelist) + { /*TODO: fill whitelist*/ cb(whitelist); } - virtual void generate_whitelist_from_bond_table(WhitelistDbCb_t cb, ::Gap::Whitelist_t *whitelist) { + virtual void generate_whitelist_from_bond_table(WhitelistDbCb_t cb, ::Gap::Whitelist_t *whitelist) + { for (size_t i = 0; i < MAX_ENTRIES && i < whitelist->capacity; i++) { if (_entries[i].flags.peer_address_is_public) { whitelist->addresses[i].type = BLEProtocol::AddressType::PUBLIC; diff --git a/features/FEATURE_BLE/ble/pal/PalGap.h b/features/FEATURE_BLE/ble/pal/PalGap.h index b365e5c23b0..8347151dd96 100644 --- a/features/FEATURE_BLE/ble/pal/PalGap.h +++ b/features/FEATURE_BLE/ble/pal/PalGap.h @@ -89,7 +89,7 @@ struct Gap { * @return BLE_ERROR_NONE if the request has been successfully sent or the * appropriate error otherwise. */ - virtual ble_error_t set_random_address(const address_t& address) = 0; + virtual ble_error_t set_random_address(const address_t &address) = 0; /** * Set the advertising parameters which will be used during the advertising @@ -154,7 +154,7 @@ struct Gap { advertising_type_t advertising_type, own_address_type_t own_address_type, advertising_peer_address_type_t peer_address_type, - const address_t& peer_address, + const address_t &peer_address, advertising_channel_map_t advertising_channel_map, advertising_filter_policy_t advertising_filter_policy ) = 0; @@ -178,7 +178,7 @@ struct Gap { */ virtual ble_error_t set_advertising_data( uint8_t advertising_data_length, - const advertising_data_t& advertising_data + const advertising_data_t &advertising_data ) = 0; /** @@ -200,7 +200,7 @@ struct Gap { */ virtual ble_error_t set_scan_response_data( uint8_t scan_response_data_length, - const advertising_data_t& scan_response_data + const advertising_data_t &scan_response_data ) = 0; /** @@ -382,7 +382,7 @@ struct Gap { uint16_t scan_window, initiator_policy_t initiator_policy, connection_peer_address_type_t peer_address_type, - const address_t& peer_address, + const address_t &peer_address, own_address_type_t own_address_type, uint16_t connection_interval_min, uint16_t connection_interval_max, @@ -656,7 +656,7 @@ struct Gap { * LE subsystem. * It accept a single parameter in input: The event received. */ - void when_gap_event_received(mbed::Callback cb) + void when_gap_event_received(mbed::Callback cb) { _gap_event_cb = cb; } @@ -672,7 +672,7 @@ struct Gap { * * @param gap_event The event to emit to higher layer. */ - void emit_gap_event(const GapEvent& gap_event) + void emit_gap_event(const GapEvent &gap_event) { if (_gap_event_cb) { _gap_event_cb(gap_event); @@ -683,11 +683,11 @@ struct Gap { /** * Callback called when an event is emitted by the LE subsystem. */ - mbed::Callback _gap_event_cb; + mbed::Callback _gap_event_cb; // Disallow copy construction and copy assignment. - Gap(const Gap&); - Gap& operator=(const Gap&); + Gap(const Gap &); + Gap &operator=(const Gap &); }; } // namespace pal diff --git a/features/FEATURE_BLE/ble/pal/PalGattClient.h b/features/FEATURE_BLE/ble/pal/PalGattClient.h index 2152c428f43..ca34d36d8b1 100644 --- a/features/FEATURE_BLE/ble/pal/PalGattClient.h +++ b/features/FEATURE_BLE/ble/pal/PalGattClient.h @@ -114,7 +114,7 @@ class GattClient { */ virtual ble_error_t get_mtu_size( connection_handle_t connection_handle, - uint16_t& mtu_size + uint16_t &mtu_size ) = 0; /** @@ -186,7 +186,7 @@ class GattClient { virtual ble_error_t discover_primary_service_by_service_uuid( connection_handle_t connection_handle, attribute_handle_t discovery_range_beginning, - const UUID& uuid + const UUID &uuid ) = 0; /** @@ -363,7 +363,7 @@ class GattClient { virtual ble_error_t read_using_characteristic_uuid( connection_handle_t connection_handle, attribute_handle_range_t read_range, - const UUID& uuid + const UUID &uuid ) = 0; /** @@ -420,7 +420,7 @@ class GattClient { */ virtual ble_error_t read_multiple_characteristic_values( connection_handle_t connection_handle, - const ArrayView& characteristic_value_handles + const ArrayView &characteristic_value_handles ) = 0; /** @@ -439,7 +439,7 @@ class GattClient { virtual ble_error_t write_without_response( connection_handle_t connection_handle, attribute_handle_t characteristic_value_handle, - const ArrayView& value + const ArrayView &value ) = 0; /** @@ -461,7 +461,7 @@ class GattClient { virtual ble_error_t signed_write_without_response( connection_handle_t connection_handle, attribute_handle_t characteristic_value_handle, - const ArrayView& value + const ArrayView &value ) = 0; /** @@ -487,7 +487,7 @@ class GattClient { virtual ble_error_t write_attribute( connection_handle_t connection_handle, attribute_handle_t attribute_handle, - const ArrayView& value + const ArrayView &value ) = 0; /** @@ -522,7 +522,7 @@ class GattClient { virtual ble_error_t queue_prepare_write( connection_handle_t connection_handle, attribute_handle_t characteristic_value_handle, - const ArrayView& value, + const ArrayView &value, uint16_t offset ) = 0; @@ -560,8 +560,9 @@ class GattClient { * can be obtained from its opcode. */ void when_server_message_received( - mbed::Callback cb - ) { + mbed::Callback cb + ) + { _server_message_cb = cb; } @@ -576,11 +577,12 @@ class GattClient { * timeout. To send a new ATT message, the conenction should be * reestablished. */ - void when_transaction_timeout( - mbed::Callback cb - ) { - _transaction_timeout_cb = cb; - } + void when_transaction_timeout( + mbed::Callback cb + ) + { + _transaction_timeout_cb = cb; + } protected: GattClient() { } @@ -596,8 +598,9 @@ class GattClient { */ void on_server_event( connection_handle_t connection_handle, - const AttServerMessage& server_message - ) { + const AttServerMessage &server_message + ) + { if (_server_message_cb) { _server_message_cb(connection_handle, server_message); } @@ -614,7 +617,8 @@ class GattClient { */ void on_transaction_timeout( connection_handle_t connection_handle - ) { + ) + { if (_transaction_timeout_cb) { _transaction_timeout_cb(connection_handle); } @@ -624,7 +628,7 @@ class GattClient { /** * Callback called when the client receive a message from the server. */ - mbed::Callback _server_message_cb; + mbed::Callback _server_message_cb; /** * Callback called when a transaction times out. @@ -632,8 +636,8 @@ class GattClient { mbed::Callback _transaction_timeout_cb; // Disallow copy construction and copy assignment. - GattClient(const GattClient&); - GattClient& operator=(const GattClient&); + GattClient(const GattClient &); + GattClient &operator=(const GattClient &); }; } // namespace pal diff --git a/features/FEATURE_BLE/ble/pal/PalSecurityManager.h b/features/FEATURE_BLE/ble/pal/PalSecurityManager.h index 3f51299f9b6..afa957fcd28 100644 --- a/features/FEATURE_BLE/ble/pal/PalSecurityManager.h +++ b/features/FEATURE_BLE/ble/pal/PalSecurityManager.h @@ -52,48 +52,57 @@ class KeyDistribution { KeyDistribution(bool encryption, bool identity, bool signing, - bool link) : _value(0) { + bool link) : _value(0) + { set_encryption(encryption); set_identity(identity); set_signing(signing); set_link(link); } - bool get_encryption() const { + bool get_encryption() const + { return _value & KEY_DISTRIBUTION_ENCRYPTION; } - bool get_identity() const { + bool get_identity() const + { return _value & KEY_DISTRIBUTION_IDENTITY; } - bool get_signing() const { + bool get_signing() const + { return _value & KEY_DISTRIBUTION_SIGNING; } - bool get_link() const { + bool get_link() const + { return _value & KEY_DISTRIBUTION_LINK; } - void set_encryption(bool enabled = true) { + void set_encryption(bool enabled = true) + { if (enabled) { _value |= KEY_DISTRIBUTION_ENCRYPTION; } else { _value &= ~KEY_DISTRIBUTION_ENCRYPTION; } } - void set_identity(bool enabled = true) { + void set_identity(bool enabled = true) + { if (enabled) { _value |= KEY_DISTRIBUTION_IDENTITY; } else { _value &= ~KEY_DISTRIBUTION_IDENTITY; } } - void set_signing(bool enabled = true) { + void set_signing(bool enabled = true) + { if (enabled) { _value |= KEY_DISTRIBUTION_SIGNING; } else { _value &= ~KEY_DISTRIBUTION_SIGNING; } } - void set_link(bool enabled = true) { + void set_link(bool enabled = true) + { if (enabled) { _value |= KEY_DISTRIBUTION_LINK; } else { @@ -101,21 +110,25 @@ class KeyDistribution { } } - operator uint8_t() { + operator uint8_t() + { return _value; } - KeyDistribution operator&(const KeyDistribution& other) const { + KeyDistribution operator&(const KeyDistribution &other) const + { KeyDistribution result(this->value() & other.value()); return result; } - KeyDistribution& operator&=(const KeyDistribution& other) { + KeyDistribution &operator&=(const KeyDistribution &other) + { this->_value = this->_value & other.value(); return *this; } - uint8_t value() const { + uint8_t value() const + { return _value; } @@ -141,48 +154,57 @@ class AuthenticationMask { AuthenticationMask(bool bondable, bool mitm, bool secure_connections, - bool keypress) : _value(0) { + bool keypress) : _value(0) + { set_bondable(bondable); set_mitm(mitm); set_secure_connections(secure_connections); set_keypress_notification(keypress); } - bool get_bondable() const { + bool get_bondable() const + { return _value & AUTHENTICATION_BONDABLE; } - bool get_mitm() const { + bool get_mitm() const + { return _value & AUTHENTICATION_MITM; } - bool get_secure_connections() const { + bool get_secure_connections() const + { return _value & AUTHENTICATION_SECURE_CONNECTIONS; } - bool get_keypress_notification() const { + bool get_keypress_notification() const + { return _value & AUTHENTICATION_KEYPRESS_NOTIFICATION; } - void set_bondable(bool enabled = true) { + void set_bondable(bool enabled = true) + { if (enabled) { _value |= AUTHENTICATION_BONDABLE; } else { _value &= ~AUTHENTICATION_BONDABLE; } } - void set_mitm(bool enabled = true) { + void set_mitm(bool enabled = true) + { if (enabled) { _value |= AUTHENTICATION_MITM; } else { _value &= ~AUTHENTICATION_MITM; } } - void set_secure_connections(bool enabled = true) { + void set_secure_connections(bool enabled = true) + { if (enabled) { _value |= AUTHENTICATION_SECURE_CONNECTIONS; } else { _value &= ~AUTHENTICATION_SECURE_CONNECTIONS; } } - void set_keypress_notification(bool enabled = true) { + void set_keypress_notification(bool enabled = true) + { if (enabled) { _value |= AUTHENTICATION_KEYPRESS_NOTIFICATION; } else { @@ -190,10 +212,12 @@ class AuthenticationMask { } } - operator uint8_t() { + operator uint8_t() + { return _value; } - uint8_t value() const { + uint8_t value() const + { return _value; } @@ -990,11 +1014,13 @@ class SecurityManager : private mbed::NonCopyable { */ void set_event_handler( EventHandler *event_handler - ) { + ) + { _pal_event_handler = event_handler; } - EventHandler* get_event_handler() { + EventHandler *get_event_handler() + { return _pal_event_handler; } diff --git a/features/FEATURE_BLE/ble/pal/SecurityDb.h b/features/FEATURE_BLE/ble/pal/SecurityDb.h index 39f4729953e..7085cb3a09d 100644 --- a/features/FEATURE_BLE/ble/pal/SecurityDb.h +++ b/features/FEATURE_BLE/ble/pal/SecurityDb.h @@ -40,7 +40,8 @@ struct SecurityDistributionFlags_t { csrk_mitm_protected(false), ltk_stored(false), ltk_mitm_protected(false), - secure_connections_paired(false) { + secure_connections_paired(false) + { } /** peer address */ @@ -49,20 +50,20 @@ struct SecurityDistributionFlags_t { /** encryption key size */ uint8_t encryption_key_size; /** true if peer address is public, false if it's static random */ - uint8_t peer_address_is_public:1; + uint8_t peer_address_is_public: 1; /** true if local address is public, false if it's static random */ - uint8_t local_address_is_public:1; + uint8_t local_address_is_public: 1; /** CSRK (Connection Signature Resolving Key) has been distributed and stored */ - uint8_t csrk_stored:1; + uint8_t csrk_stored: 1; /** CSRK that is stored has MITM protection */ - uint8_t csrk_mitm_protected:1; + uint8_t csrk_mitm_protected: 1; /** LTK (Long Term Key) has been distributed and stored */ - uint8_t ltk_stored:1; + uint8_t ltk_stored: 1; /** LTK that is stored has MITM protection */ - uint8_t ltk_mitm_protected:1; + uint8_t ltk_mitm_protected: 1; /** the current pairing was done using Secure Connections */ - uint8_t secure_connections_paired:1; + uint8_t secure_connections_paired: 1; }; /** Long Term Key and data used to identify it */ @@ -95,16 +96,16 @@ class SecurityDb { /** * Opaque type representing a handle to a database entry. */ - typedef void* entry_handle_t; + typedef void *entry_handle_t; /* callbacks for asynchronous data retrieval from the security db */ - typedef mbed::Callback - SecurityEntryKeysDbCb_t; - typedef mbed::Callback - SecurityEntryCsrkDbCb_t; - typedef mbed::Callback - WhitelistDbCb_t; + typedef mbed::Callback + SecurityEntryKeysDbCb_t; + typedef mbed::Callback + SecurityEntryCsrkDbCb_t; + typedef mbed::Callback + WhitelistDbCb_t; SecurityDb() { }; virtual ~SecurityDb() { }; @@ -116,7 +117,7 @@ class SecurityDb { * @return pointer to the flags or NULL if the entry do not have any * associated flags. */ - virtual const SecurityDistributionFlags_t* get_distribution_flags( + virtual const SecurityDistributionFlags_t *get_distribution_flags( entry_handle_t db_entry ) = 0; @@ -128,7 +129,7 @@ class SecurityDb { */ virtual void set_distribution_flags( entry_handle_t db_entry, - const SecurityDistributionFlags_t& flags + const SecurityDistributionFlags_t &flags ) = 0; /* local keys */ @@ -277,7 +278,7 @@ class SecurityDb { * * @return pointer to local CSRK */ - virtual const csrk_t* get_local_csrk() = 0; + virtual const csrk_t *get_local_csrk() = 0; /** * Update local signing key. @@ -293,14 +294,14 @@ class SecurityDb { * * @return ref to x component of public key */ - virtual const public_key_coord_t& get_public_key_x() = 0; + virtual const public_key_coord_t &get_public_key_x() = 0; /** * Return local public key. * * @return ref to y component of public key */ - virtual const public_key_coord_t& get_public_key_y() = 0; + virtual const public_key_coord_t &get_public_key_y() = 0; /** * Set local public key. diff --git a/features/FEATURE_BLE/ble/pal/SimpleAttServerMessage.h b/features/FEATURE_BLE/ble/pal/SimpleAttServerMessage.h index a0f3346dead..da3b74976f5 100644 --- a/features/FEATURE_BLE/ble/pal/SimpleAttServerMessage.h +++ b/features/FEATURE_BLE/ble/pal/SimpleAttServerMessage.h @@ -46,21 +46,24 @@ struct SimpleAttFindInformationResponse : public AttFindInformationResponse { Format format, ArrayView information_data ) : AttFindInformationResponse(), _format(format), _information_data(information_data), - _item_size(information_data_item_size()) { + _item_size(information_data_item_size()) + { } /** * @see ble::pal::AttFindInformationResponse::size */ - virtual size_t size() const { + virtual size_t size() const + { return _information_data.size() / _item_size; } /** * @see ble::pal::AttFindInformationResponse::operator[] */ - virtual information_data_t operator[](size_t index) const { - const uint8_t* item = &_information_data[index * _item_size]; + virtual information_data_t operator[](size_t index) const + { + const uint8_t *item = &_information_data[index * _item_size]; information_data_t result; memcpy(&result.handle, item, sizeof(result.handle)); @@ -77,7 +80,8 @@ struct SimpleAttFindInformationResponse : public AttFindInformationResponse { } private: - size_t information_data_item_size() const { + size_t information_data_item_size() const + { return sizeof(attribute_handle_t) + ((_format == FORMAT_16_BIT_UUID) ? 2 : 16); } @@ -98,22 +102,25 @@ struct SimpleAttFindByTypeValueResponse : public AttFindByTypeValueResponse { * @param handles raw array containing one or more Handle Informations. */ SimpleAttFindByTypeValueResponse(ArrayView handles) : - AttFindByTypeValueResponse(), _handles(handles) { + AttFindByTypeValueResponse(), _handles(handles) + { } /** * @see ble::pal::AttFindByTypeValueResponse::size */ - virtual std::size_t size() const { + virtual std::size_t size() const + { return _handles.size() / item_size; } /** * @see ble::pal::AttFindByTypeValueResponse::operator[] */ - virtual attribute_handle_range_t operator[](size_t index) const { + virtual attribute_handle_range_t operator[](size_t index) const + { attribute_handle_range_t result; - const uint8_t* item = &_handles[index * item_size]; + const uint8_t *item = &_handles[index * item_size]; memcpy(&result.begin, item, sizeof(result.begin)); memcpy(&result.end, item + sizeof(result.begin), sizeof(result.end)); return result; @@ -140,21 +147,24 @@ struct SimpleAttReadByTypeResponse : public AttReadByTypeResponse { SimpleAttReadByTypeResponse( uint8_t element_size, ArrayView attribute_data ) : AttReadByTypeResponse(), - _attribute_data(attribute_data), _element_size(element_size) { + _attribute_data(attribute_data), _element_size(element_size) + { } /** * @see ble::pal::AttReadByTypeResponse::size */ - virtual size_t size() const { + virtual size_t size() const + { return _attribute_data.size() / _element_size; } /** * @see ble::pal::AttReadByTypeResponse::operator[] */ - virtual attribute_data_t operator[](size_t index) const { - const uint8_t* item = &_attribute_data[index * _element_size]; + virtual attribute_data_t operator[](size_t index) const + { + const uint8_t *item = &_attribute_data[index * _element_size]; uint16_t handle; memcpy(&handle, item, sizeof(handle)); @@ -189,21 +199,24 @@ struct SimpleAttReadByGroupTypeResponse : public AttReadByGroupTypeResponse { SimpleAttReadByGroupTypeResponse( uint8_t element_size, ArrayView attribute_data ) : AttReadByGroupTypeResponse(), - _attribute_data(attribute_data), _element_size(element_size) { + _attribute_data(attribute_data), _element_size(element_size) + { } /** * @see ble::pal::AttReadByGroupTypeResponse::size */ - virtual size_t size() const { + virtual size_t size() const + { return _attribute_data.size() / _element_size; } /** * @see ble::pal::AttReadByGroupTypeResponse::operator[] */ - virtual attribute_data_t operator[](size_t index) const { - const uint8_t* item = &_attribute_data[index * _element_size]; + virtual attribute_data_t operator[](size_t index) const + { + const uint8_t *item = &_attribute_data[index * _element_size]; uint16_t begin; uint16_t end; diff --git a/features/FEATURE_BLE/ble/pal/SimpleEventQueue.h b/features/FEATURE_BLE/ble/pal/SimpleEventQueue.h index 84ccacfd485..0532175b3fd 100644 --- a/features/FEATURE_BLE/ble/pal/SimpleEventQueue.h +++ b/features/FEATURE_BLE/ble/pal/SimpleEventQueue.h @@ -51,7 +51,7 @@ struct SimpleEventQueue : EventQueue { * * @param ble_id Id of the BLE instance using that event queue. */ - void initialize(BLEInstanceBase* ble_base, BLE::InstanceID_t ble_id) + void initialize(BLEInstanceBase *ble_base, BLE::InstanceID_t ble_id) { _ble_base = ble_base; _ble_instance_id = ble_id; @@ -68,13 +68,13 @@ struct SimpleEventQueue : EventQueue { /** * @see ble::pal::post */ - virtual bool post(const mbed::Callback& event) + virtual bool post(const mbed::Callback &event) { if (_ble_base == NULL) { return false; } - EventNode* next = new (std::nothrow) EventNode(event); + EventNode *next = new (std::nothrow) EventNode(event); if (next == NULL) { return false; } @@ -82,7 +82,7 @@ struct SimpleEventQueue : EventQueue { if (_events == NULL) { _events = next; } else { - EventNode* previous = _events; + EventNode *previous = _events; while (previous->next) { previous = previous->next; } @@ -101,7 +101,7 @@ struct SimpleEventQueue : EventQueue { void clear() { while (_events) { - EventNode* next = _events->next; + EventNode *next = _events->next; delete _events; _events = next; } @@ -113,7 +113,7 @@ struct SimpleEventQueue : EventQueue { void process() { while (_events) { - EventNode* next = _events->next; + EventNode *next = _events->next; _events->event(); delete _events; _events = next; @@ -124,7 +124,7 @@ struct SimpleEventQueue : EventQueue { struct EventNode { EventNode(const event_t event) : event(event), next(NULL) { } event_t event; - EventNode* next; + EventNode *next; }; void signal_event() @@ -132,9 +132,9 @@ struct SimpleEventQueue : EventQueue { _ble_base->signalEventsToProcess(_ble_instance_id); } - BLEInstanceBase* _ble_base; + BLEInstanceBase *_ble_base; BLE::InstanceID_t _ble_instance_id; - EventNode* _events; + EventNode *_events; }; } // namespace pal diff --git a/features/FEATURE_BLE/ble/services/DFUService.h b/features/FEATURE_BLE/ble/services/DFUService.h index 1614a3cfd99..daa71cd5806 100644 --- a/features/FEATURE_BLE/ble/services/DFUService.h +++ b/features/FEATURE_BLE/ble/services/DFUService.h @@ -62,7 +62,8 @@ class DFUService { packet(DFUServicePacketCharacteristicUUID, packetBytes, SIZEOF_PACKET_BYTES, SIZEOF_PACKET_BYTES, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE), controlBytes(), - packetBytes() { + packetBytes() + { static bool serviceAdded = false; /* We only add the DFU service once. */ if (serviceAdded) { return; @@ -86,7 +87,8 @@ class DFUService { /** * @brief Get the handle for the value attribute of the control characteristic. */ - uint16_t getControlHandle(void) const { + uint16_t getControlHandle(void) const + { return controlPoint.getValueHandle(); } @@ -98,7 +100,8 @@ class DFUService { * @param[in] params * Information about the characteristic being updated. */ - virtual void onDataWritten(const GattWriteCallbackParams *params) { + virtual void onDataWritten(const GattWriteCallbackParams *params) + { if (params->handle == controlPoint.getValueHandle()) { /* At present, writing anything will do the trick - this needs to be improved. */ if (handoverCallback) { diff --git a/features/FEATURE_BLE/ble/services/DeviceInformationService.h b/features/FEATURE_BLE/ble/services/DeviceInformationService.h index a52ace1e35e..873c7fdaadc 100644 --- a/features/FEATURE_BLE/ble/services/DeviceInformationService.h +++ b/features/FEATURE_BLE/ble/services/DeviceInformationService.h @@ -95,9 +95,10 @@ class DeviceInformationService { &serialNumberStringCharacteristic, &hardwareRevisionStringCharacteristic, &firmwareRevisionStringCharacteristic, - &softwareRevisionStringCharacteristic}; + &softwareRevisionStringCharacteristic + }; GattService deviceInformationService(GattService::UUID_DEVICE_INFORMATION_SERVICE, charTable, - sizeof(charTable) / sizeof(GattCharacteristic *)); + sizeof(charTable) / sizeof(GattCharacteristic *)); ble.addService(deviceInformationService); serviceAdded = true; diff --git a/features/FEATURE_BLE/ble/services/EddystoneConfigService.h b/features/FEATURE_BLE/ble/services/EddystoneConfigService.h index f21bd13a500..44a4573ec9d 100644 --- a/features/FEATURE_BLE/ble/services/EddystoneConfigService.h +++ b/features/FEATURE_BLE/ble/services/EddystoneConfigService.h @@ -46,8 +46,7 @@ extern const uint8_t BEACON_EDDYSTONE[2]; * See https://github.com/google/eddystone * */ -class EddystoneConfigService -{ +class EddystoneConfigService { public: /** * @brief Transmission Power Modes for UriBeacon @@ -88,7 +87,7 @@ class EddystoneConfigService struct Params_t { // Config Data bool isConfigured; // Flag for configuration being complete: - // True = configured, False = not configured. Reset at instantiation, used for external callbacks. + // True = configured, False = not configured. Reset at instantiation, used for external callbacks. uint8_t lockedState; Lock_t lock; uint8_t flags; @@ -151,7 +150,8 @@ class EddystoneConfigService advPowerLevelsChar(UUID_ADV_POWER_LEVELS_CHAR, ¶ms.advPowerLevels), txPowerModeChar(UUID_TX_POWER_MODE_CHAR, ¶ms.txPowerMode), beaconPeriodChar(UUID_BEACON_PERIOD_CHAR, ¶ms.beaconPeriod), - resetChar(UUID_RESET_CHAR, &resetFlag) { + resetChar(UUID_RESET_CHAR, &resetFlag) + { // Set Eddystone as not configured yet. Used to exit config before timeout if GATT services are written to. params.isConfigured = false; @@ -185,7 +185,8 @@ class EddystoneConfigService * un-initialized, and default values should be used * instead. Otherwise, paramsIn overrides the defaults. */ - void start(bool resetToDefaultsFlag){ + void start(bool resetToDefaultsFlag) + { INFO("reset to defaults flag = %d", resetToDefaultsFlag); if (!resetToDefaultsFlag && (params.uriDataLength > URI_DATA_MAX)) { INFO("Reset to Defaults triggered"); @@ -205,7 +206,8 @@ class EddystoneConfigService /* * Check if Eddystone initialized successfully. */ - bool initSuccessfully(void) const { + bool initSuccessfully(void) const + { return initSucceeded; } @@ -216,7 +218,8 @@ class EddystoneConfigService * @param[in] advPeriodInMin How long between TLM frames being advertised, measured in minutes. * */ - void setDefaultTLMFrameData(uint8_t tlmVersionIn = 0, float advPeriodInSec = 60){ + void setDefaultTLMFrameData(uint8_t tlmVersionIn = 0, float advPeriodInSec = 60) + { DBG("Setting Default TLM Data, version = %d, advPeriodInMind= %f", tlmVersionIn, advPeriodInSec); defaultTlmVersion = tlmVersionIn; TlmBatteryVoltage = 0; @@ -234,7 +237,8 @@ class EddystoneConfigService * @param[in] advPeriod How long to advertise the URL, measured in number of ADV frames. * */ - void setDefaultURIFrameData(const char *uriIn, float advPeriod = 1){ + void setDefaultURIFrameData(const char *uriIn, float advPeriod = 1) + { DBG("Setting Default URI Data"); // Set URL Frame EddystoneService::encodeURL(uriIn, defaultUriData, defaultUriDataLength); // Encode URL to URL Formatting. @@ -242,7 +246,7 @@ class EddystoneConfigService return; } INFO("\t URI input = %s : %d", uriIn, defaultUriDataLength); - INFO("\t default URI = %s : %d ", defaultUriData, defaultUriDataLength ); + INFO("\t default URI = %s : %d ", defaultUriData, defaultUriDataLength); defaultUriAdvPeriod = advPeriod; urlIsSet = true; // Flag to add this to Eddystone service when config is done. } @@ -255,7 +259,8 @@ class EddystoneConfigService * @param[in] advPeriod How long to advertise the URL, measured in the number of ADV frames. * */ - void setDefaultUIDFrameData(UIDNamespaceID_t *namespaceID, UIDInstanceID_t *instanceID, float advPeriod = 10){ + void setDefaultUIDFrameData(UIDNamespaceID_t *namespaceID, UIDInstanceID_t *instanceID, float advPeriod = 10) + { //Set UID frame DBG("Setting default UID Data"); memcpy(defaultUidNamespaceID, namespaceID, UID_NAMESPACEID_SIZE); @@ -267,7 +272,8 @@ class EddystoneConfigService /* Start out by advertising the config service for a limited time after * startup, then switch to the normal non-connectible beacon functionality. */ - void setupEddystoneConfigAdvertisements() { + void setupEddystoneConfigAdvertisements() + { const char DEVICE_NAME[] = "eddystone Config"; ble.clearAdvertisingPayload(); @@ -298,7 +304,8 @@ class EddystoneConfigService * to load saved config params, or it can be called explicitly to reset the Eddystone beacon to hardcoded values on each reset. * */ - void setupEddystoneAdvertisements() { + void setupEddystoneAdvertisements() + { DBG("Switching Config -> adv"); // Save params to storage. extern void saveURIBeaconConfigParams(const Params_t *paramsP); /* forward declaration; necessary to avoid a circular dependency. */ @@ -329,7 +336,8 @@ class EddystoneConfigService * characteristics of this service. Attempts to do so are also applied to * the internal state of this service object. */ - void onDataWrittenCallback(const GattWriteCallbackParams *writeParams) { + void onDataWrittenCallback(const GattWriteCallbackParams *writeParams) + { uint16_t handle = writeParams->handle; if (handle == lockChar.getValueHandle()) { @@ -386,7 +394,8 @@ class EddystoneConfigService /* * Reset the default values. */ - void resetToDefaults(void) { + void resetToDefaults(void) + { INFO("Resetting to defaults"); // General. params.lockedState = false; @@ -420,7 +429,8 @@ class EddystoneConfigService * Internal helper function used to update the GATT database following any * change to the internal state of the service object. */ - void updateCharacteristicValues(void) { + void updateCharacteristicValues(void) + { ble.updateCharacteristicValue(lockedStateChar.getValueHandle(), ¶ms.lockedState, 1); ble.updateCharacteristicValue(uriDataChar.getValueHandle(), params.uriData, params.uriDataLength); ble.updateCharacteristicValue(flagsChar.getValueHandle(), ¶ms.flags, 1); @@ -432,7 +442,8 @@ class EddystoneConfigService } private: - void lockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { + void lockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) + { if (params.lockedState) { authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; } else if (authParams->len != sizeof(Lock_t)) { @@ -444,7 +455,8 @@ class EddystoneConfigService } } - void unlockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { + void unlockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) + { if ((!params.lockedState) && (authParams->len == sizeof(Lock_t))) { authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; } else if (authParams->len != sizeof(Lock_t)) { @@ -458,7 +470,8 @@ class EddystoneConfigService } } - void uriDataWriteAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { + void uriDataWriteAuthorizationCallback(GattWriteAuthCallbackParams *authParams) + { if (params.lockedState) { authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; } else if (authParams->offset != 0) { @@ -468,7 +481,8 @@ class EddystoneConfigService } } - void powerModeAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { + void powerModeAuthorizationCallback(GattWriteAuthCallbackParams *authParams) + { if (params.lockedState) { authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; } else if (authParams->len != sizeof(uint8_t)) { @@ -483,7 +497,8 @@ class EddystoneConfigService } template - void basicAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { + void basicAuthorizationCallback(GattWriteAuthCallbackParams *authParams) + { if (params.lockedState) { authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; } else if (authParams->len != sizeof(T)) { diff --git a/features/FEATURE_BLE/ble/services/EddystoneService.h b/features/FEATURE_BLE/ble/services/EddystoneService.h index c88a8a4791d..acfe7522b50 100644 --- a/features/FEATURE_BLE/ble/services/EddystoneService.h +++ b/features/FEATURE_BLE/ble/services/EddystoneService.h @@ -59,8 +59,7 @@ static const uint8_t BEACON_EDDYSTONE[] = {0xAA, 0xFE}; * See https://github.com/google/eddystone * */ -class EddystoneService -{ +class EddystoneService { public: enum FrameTypes { NONE, @@ -105,7 +104,8 @@ class EddystoneService UIDNamespaceID_t namespaceID, UIDInstanceID_t instanceID, float uidAdvPeriodIn, - uint16_t RFU = 0x0000) { + uint16_t RFU = 0x0000) + { if (0.0f == uidAdvPeriodIn) { uidIsSet = false; return; @@ -131,7 +131,8 @@ class EddystoneService * @param[in] maxSize number of bytes left in array, effectively how much empty space is available to write to * @return number of bytes used. negative number indicates error message. */ - unsigned constructUIDFrame(uint8_t *Data, uint8_t maxSize) { + unsigned constructUIDFrame(uint8_t *Data, uint8_t maxSize) + { unsigned index = 0; Data[index++] = FRAME_TYPE_UID; // 1B Type @@ -152,7 +153,7 @@ class EddystoneService DBG("'\r\n"); DBG("UID InstanceID = '0x"); - for (size_t x = 0; x< UID_INSTANCEID_SIZE; x++) { // 6B Instance ID + for (size_t x = 0; x < UID_INSTANCEID_SIZE; x++) { // 6B Instance ID Data[index++] = defaultUidInstanceID[x]; DBG("%x,", defaultUidInstanceID[x]); } @@ -173,7 +174,8 @@ class EddystoneService * @param[in] urlAdvPeriodIn How long to advertise the URL frame (measured in # of adv periods) * @return false on success, true on failure. */ - bool setURLFrameData(int8_t power, const char *urlIn, float urlAdvPeriodIn) { + bool setURLFrameData(int8_t power, const char *urlIn, float urlAdvPeriodIn) + { if (0.0f == urlAdvPeriodIn) { urlIsSet = false; return false; @@ -196,7 +198,8 @@ class EddystoneService * @param[in] urlAdvPeriodIn How long to advertise the URL frame (measured in # of adv periods) * @return false on success, true on failure. */ - bool setURLFrameEncodedData(int8_t power, const char *encodedUrlIn, uint8_t encodedUrlInLength, float urlAdvPeriodIn) { + bool setURLFrameEncodedData(int8_t power, const char *encodedUrlIn, uint8_t encodedUrlInLength, float urlAdvPeriodIn) + { if (0.0f == urlAdvPeriodIn) { urlIsSet = false; return false; @@ -218,7 +221,8 @@ class EddystoneService * @param[in] maxSize number of bytes left in array, effectively how much emtpy space is available to write to * @return number of bytes used. negative number indicates error message. */ - int constructURLFrame(uint8_t *Data, uint8_t maxSize) { + int constructURLFrame(uint8_t *Data, uint8_t maxSize) + { int index = 0; Data[index++] = FRAME_TYPE_URL; // 1B Type Data[index++] = defaultUrlPower; // 1B TX Power @@ -242,7 +246,8 @@ class EddystoneService uint16_t batteryVoltage = 0, uint16_t beaconTemp = 0x8000, uint32_t pduCount = 0, - uint32_t timeSinceBoot = 0) { + uint32_t timeSinceBoot = 0) + { if (0.0f == advPeriod) { tlmIsSet = false; return; @@ -262,7 +267,8 @@ class EddystoneService * @param[in] maxSize number of bytes left in array, effectively how much emtpy space is available to write to * @return number of bytes used. negative number indicates error message. */ - int constructTLMFrame(uint8_t *Data, uint8_t maxSize) { + int constructTLMFrame(uint8_t *Data, uint8_t maxSize) + { uint32_t now = timeSinceBootTimer.read_ms(); TlmTimeSinceBoot += (now - lastBootTimerRead) / 100; lastBootTimerRead = now; @@ -291,7 +297,8 @@ class EddystoneService * @param[in] voltagemv Voltage to update the TLM field battery voltage with (in mV) * @return nothing */ - void updateTlmBatteryVoltage(uint16_t voltagemv) { + void updateTlmBatteryVoltage(uint16_t voltagemv) + { TlmBatteryVoltage = voltagemv; } @@ -300,7 +307,8 @@ class EddystoneService * @param[in] temp Temperature of beacon (in 8.8fpn) * @return nothing */ - void updateTlmBeaconTemp(uint16_t temp) { + void updateTlmBeaconTemp(uint16_t temp) + { TlmBeaconTemp = temp; } @@ -309,7 +317,8 @@ class EddystoneService * @param[in] pduCount Number of Advertisiting frames sent since powerup * @return nothing */ - void updateTlmPduCount(uint32_t pduCount) { + void updateTlmPduCount(uint32_t pduCount) + { TlmPduCount = pduCount; } @@ -318,7 +327,8 @@ class EddystoneService * @param[in] timeSinceBoot Time since boot in 0.1s incriments * @return nothing */ - void updateTlmTimeSinceBoot(uint32_t timeSinceBoot) { + void updateTlmTimeSinceBoot(uint32_t timeSinceBoot) + { TlmTimeSinceBoot = timeSinceBoot; } @@ -326,7 +336,8 @@ class EddystoneService * Update advertising data * @return true on success, false on failure */ - bool updateAdvPacket(uint8_t serviceData[], unsigned serviceDataLen) { + bool updateAdvPacket(uint8_t serviceData[], unsigned serviceDataLen) + { // Fields from the Service DBG("Updating AdvFrame: %d", serviceDataLen); @@ -347,7 +358,8 @@ class EddystoneService * This function exists because of time constraints in the radioNotificationCallback, so it is effectively * broken up into two functions. */ - void swapOutFrames(FrameTypes frameType) { + void swapOutFrames(FrameTypes frameType) + { uint8_t serviceData[SERVICE_DATA_MAX]; unsigned serviceDataLen = 0; //hard code in the eddystone UUID @@ -399,7 +411,8 @@ class EddystoneService /* * Callback to swap in URL frame */ - void urlCallback(void) { + void urlCallback(void) + { DBG("urlCallback"); if (false == advLock) { advLock = true; @@ -418,7 +431,8 @@ class EddystoneService /* * Callback to swap in UID frame */ - void uidCallback(void) { + void uidCallback(void) + { DBG("uidCallback"); if (false == advLock) { advLock = true; @@ -437,7 +451,8 @@ class EddystoneService /* * Callback to swap in TLM frame */ - void tlmCallback(void) { + void tlmCallback(void) + { DBG("tlmCallback"); if (false == advLock) { // OK to broadcast @@ -454,7 +469,8 @@ class EddystoneService } } - void stopAdvCallback(void) { + void stopAdvCallback(void) + { if (overflow.empty()) { // if nothing left to transmit, stop ble.stopAdvertising(); @@ -472,7 +488,8 @@ class EddystoneService * Callback from onRadioNotification(), used to update the PDUCounter and process next state. */ #define EDDYSTONE_SWAPFRAME_DELAYMS 1 - void radioNotificationCallback(bool radioActive) { + void radioNotificationCallback(bool radioActive) + { // Update PDUCount TlmPduCount++; // True just before an frame is sent, false just after a frame is sent @@ -500,13 +517,15 @@ class EddystoneService advPeriodus(beaconPeriodus), txPower(txPowerIn), advLock(false), - frameIndex(NONE) { + frameIndex(NONE) + { } /* * @breif this function starts eddystone advertising based on configured frames. */ - void start(void) { + void start(void) + { // Initialize Frame transition, start with URL to pass eddystone validator app on first try if (urlIsSet) { frameIndex = url; @@ -581,7 +600,8 @@ class EddystoneService /* * Encode a human-readable URI into the binary format defined by URIBeacon spec (https://github.com/google/uribeacon/tree/master/specification). */ - static void encodeURL(const char *uriDataIn, UriData_t uriDataOut, uint8_t &sizeofURIDataOut) { + static void encodeURL(const char *uriDataIn, UriData_t uriDataOut, uint8_t &sizeofURIDataOut) + { DBG("Encode URL = %s", uriDataIn); const char *prefixes[] = { "http://www.", diff --git a/features/FEATURE_BLE/ble/services/EnvironmentalService.h b/features/FEATURE_BLE/ble/services/EnvironmentalService.h index c081245bebf..e25a55f91ce 100644 --- a/features/FEATURE_BLE/ble/services/EnvironmentalService.h +++ b/features/FEATURE_BLE/ble/services/EnvironmentalService.h @@ -37,7 +37,7 @@ class EnvironmentalService { * @brief EnvironmentalService constructor. * @param _ble Reference to BLE device. */ - EnvironmentalService(BLE& _ble) : + EnvironmentalService(BLE &_ble) : ble(_ble), temperatureCharacteristic(GattCharacteristic::UUID_TEMPERATURE_CHAR, &temperature), humidityCharacteristic(GattCharacteristic::UUID_HUMIDITY_CHAR, &humidity), @@ -50,7 +50,8 @@ class EnvironmentalService { GattCharacteristic *charTable[] = { &humidityCharacteristic, &pressureCharacteristic, - &temperatureCharacteristic }; + &temperatureCharacteristic + }; GattService environmentalService(GattService::UUID_ENVIRONMENTAL_SERVICE, charTable, sizeof(charTable) / sizeof(GattCharacteristic *)); @@ -64,7 +65,7 @@ class EnvironmentalService { */ void updateHumidity(HumidityType_t newHumidityVal) { - humidity = (HumidityType_t) (newHumidityVal * 100); + humidity = (HumidityType_t)(newHumidityVal * 100); ble.gattServer().write(humidityCharacteristic.getValueHandle(), (uint8_t *) &humidity, sizeof(HumidityType_t)); } @@ -74,7 +75,7 @@ class EnvironmentalService { */ void updatePressure(PressureType_t newPressureVal) { - pressure = (PressureType_t) (newPressureVal * 10); + pressure = (PressureType_t)(newPressureVal * 10); ble.gattServer().write(pressureCharacteristic.getValueHandle(), (uint8_t *) &pressure, sizeof(PressureType_t)); } @@ -84,12 +85,12 @@ class EnvironmentalService { */ void updateTemperature(float newTemperatureVal) { - temperature = (TemperatureType_t) (newTemperatureVal * 100); + temperature = (TemperatureType_t)(newTemperatureVal * 100); ble.gattServer().write(temperatureCharacteristic.getValueHandle(), (uint8_t *) &temperature, sizeof(TemperatureType_t)); } private: - BLE& ble; + BLE &ble; TemperatureType_t temperature; HumidityType_t humidity; diff --git a/features/FEATURE_BLE/ble/services/HealthThermometerService.h b/features/FEATURE_BLE/ble/services/HealthThermometerService.h index af06b59f5d9..08b5d21f299 100644 --- a/features/FEATURE_BLE/ble/services/HealthThermometerService.h +++ b/features/FEATURE_BLE/ble/services/HealthThermometerService.h @@ -54,7 +54,8 @@ class HealthThermometerService { ble(_ble), valueBytes(initialTemp), tempMeasurement(GattCharacteristic::UUID_TEMPERATURE_MEASUREMENT_CHAR, (TemperatureValueBytes *)valueBytes.getPointer(), GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY), - tempLocation(GattCharacteristic::UUID_TEMPERATURE_TYPE_CHAR, &_location) { + tempLocation(GattCharacteristic::UUID_TEMPERATURE_TYPE_CHAR, &_location) + { GattCharacteristic *hrmChars[] = {&tempMeasurement, &tempLocation, }; GattService hrmService(GattService::UUID_HEALTH_THERMOMETER_SERVICE, hrmChars, sizeof(hrmChars) / sizeof(GattCharacteristic *)); @@ -69,7 +70,8 @@ class HealthThermometerService { * Floating point value of the temperature. * */ - void updateTemperature(float temperature) { + void updateTemperature(float temperature) + { if (ble.getGapState().connected) { valueBytes.updateTemperature(temperature); ble.gattServer().write(tempMeasurement.getValueHandle(), valueBytes.getPointer(), sizeof(TemperatureValueBytes)); @@ -81,7 +83,8 @@ class HealthThermometerService { * @param loc * New location value. */ - void updateLocation(SensorLocation_t loc) { + void updateLocation(SensorLocation_t loc) + { ble.gattServer().write(tempLocation.getValueHandle(), reinterpret_cast(&loc), sizeof(uint8_t)); } @@ -99,41 +102,46 @@ class HealthThermometerService { static const uint8_t TEMPERATURE_UNITS_CELSIUS = 0; static const uint8_t TEMPERATURE_UNITS_FAHRENHEIT = 1; - TemperatureValueBytes(float initialTemperature) : bytes() { + TemperatureValueBytes(float initialTemperature) : bytes() + { /* Assumption: temperature values are expressed in celsius */ - bytes[OFFSET_OF_FLAGS] = (TEMPERATURE_UNITS_CELSIUS << TEMPERATURE_UNITS_FLAG_POS) | - (false << TIMESTAMP_FLAG_POS) | - (false << TEMPERATURE_TYPE_FLAG_POS); + bytes[OFFSET_OF_FLAGS] = (TEMPERATURE_UNITS_CELSIUS << TEMPERATURE_UNITS_FLAG_POS) | + (false << TIMESTAMP_FLAG_POS) | + (false << TEMPERATURE_TYPE_FLAG_POS); updateTemperature(initialTemperature); } - void updateTemperature(float temp) { + void updateTemperature(float temp) + { uint32_t temp_ieee11073 = quick_ieee11073_from_float(temp); memcpy(&bytes[OFFSET_OF_VALUE], &temp_ieee11073, sizeof(float)); } - uint8_t *getPointer(void) { + uint8_t *getPointer(void) + { return bytes; } - const uint8_t *getPointer(void) const { + const uint8_t *getPointer(void) const + { return bytes; } -private: + private: /** * @brief A very quick conversion between a float temperature and 11073-20601 FLOAT-Type. * @param temperature The temperature as a float. * @return The temperature in 11073-20601 FLOAT-Type format. */ - uint32_t quick_ieee11073_from_float(float temperature) { + uint32_t quick_ieee11073_from_float(float temperature) + { uint8_t exponent = 0xFE; //Exponent is -2 uint32_t mantissa = (uint32_t)(temperature * 100); return (((uint32_t)exponent) << 24) | mantissa; } -private: + private: /* First byte: 8-bit flags. Second field is a float holding the temperature value. */ /* See https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.temperature_measurement.xml */ uint8_t bytes[SIZEOF_VALUE_BYTES]; diff --git a/features/FEATURE_BLE/ble/services/HeartRateService.h b/features/FEATURE_BLE/ble/services/HeartRateService.h index e8e239361cd..0f97fa87e64 100644 --- a/features/FEATURE_BLE/ble/services/HeartRateService.h +++ b/features/FEATURE_BLE/ble/services/HeartRateService.h @@ -123,7 +123,7 @@ class HeartRateService { ), hrmLocation( GattCharacteristic::UUID_BODY_SENSOR_LOCATION_CHAR, - reinterpret_cast(&location) + reinterpret_cast(&location) ) { setupService(); @@ -142,7 +142,8 @@ class HeartRateService { * @attention This function must be called in the execution context of the * BLE stack. */ - void updateHeartRate(uint16_t hrmCounter) { + void updateHeartRate(uint16_t hrmCounter) + { valueBytes.updateHeartRate(hrmCounter); ble.gattServer().write( hrmRate.getValueHandle(), @@ -155,7 +156,8 @@ class HeartRateService { /** * Construct and add to the GattServer the heart rate service. */ - void setupService(void) { + void setupService(void) + { GattCharacteristic *charTable[] = { &hrmRate, &hrmLocation @@ -163,7 +165,7 @@ class HeartRateService { GattService hrmService( GattService::UUID_HEART_RATE_SERVICE, charTable, - sizeof(charTable) / sizeof(GattCharacteristic*) + sizeof(charTable) / sizeof(GattCharacteristic *) ); ble.gattServer().addService(hrmService); diff --git a/features/FEATURE_BLE/ble/services/LinkLossService.h b/features/FEATURE_BLE/ble/services/LinkLossService.h index 9bfed115e5c..96a35228373 100644 --- a/features/FEATURE_BLE/ble/services/LinkLossService.h +++ b/features/FEATURE_BLE/ble/services/LinkLossService.h @@ -45,7 +45,8 @@ class LinkLossService { ble(bleIn), alertLevel(levelIn), callback(callbackIn), - alertLevelChar(GattCharacteristic::UUID_ALERT_LEVEL_CHAR, reinterpret_cast(&alertLevel)) { + alertLevelChar(GattCharacteristic::UUID_ALERT_LEVEL_CHAR, reinterpret_cast(&alertLevel)) + { static bool serviceAdded = false; /* We should only ever add one LinkLoss service. */ if (serviceAdded) { return; @@ -64,14 +65,16 @@ class LinkLossService { /** * Update the callback. */ - void setCallback(callback_t newCallback) { + void setCallback(callback_t newCallback) + { callback = newCallback; } /** * Update alertness level. */ - void setAlertLevel(AlertLevel_t newLevel) { + void setAlertLevel(AlertLevel_t newLevel) + { alertLevel = newLevel; } @@ -82,13 +85,15 @@ class LinkLossService { * @param[in] params * Information about the characteristic being updated. */ - virtual void onDataWritten(const GattWriteCallbackParams *params) { + virtual void onDataWritten(const GattWriteCallbackParams *params) + { if (params->handle == alertLevelChar.getValueHandle()) { alertLevel = *reinterpret_cast(params->data); } } - void onDisconnectionFilter(const Gap::DisconnectionCallbackParams_t *params) { + void onDisconnectionFilter(const Gap::DisconnectionCallbackParams_t *params) + { if (alertLevel != NO_ALERT) { callback(alertLevel); } diff --git a/features/FEATURE_BLE/ble/services/UARTService.h b/features/FEATURE_BLE/ble/services/UARTService.h index 43da23c6f99..da082763d2d 100644 --- a/features/FEATURE_BLE/ble/services/UARTService.h +++ b/features/FEATURE_BLE/ble/services/UARTService.h @@ -63,7 +63,8 @@ class UARTService { receiveBufferIndex(0), txCharacteristic(UARTServiceTXCharacteristicUUID, receiveBuffer, 1, BLE_UART_SERVICE_MAX_DATA_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE), - rxCharacteristic(UARTServiceRXCharacteristicUUID, sendBuffer, 1, BLE_UART_SERVICE_MAX_DATA_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY) { + rxCharacteristic(UARTServiceRXCharacteristicUUID, sendBuffer, 1, BLE_UART_SERVICE_MAX_DATA_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY) + { GattCharacteristic *charTable[] = {&txCharacteristic, &rxCharacteristic}; GattService uartService(UARTServiceUUID, charTable, sizeof(charTable) / sizeof(GattCharacteristic *)); @@ -74,14 +75,16 @@ class UARTService { /** * Note: TX and RX characteristics are to be interpreted from the viewpoint of the GATT client using this service. */ - uint16_t getTXCharacteristicHandle() { + uint16_t getTXCharacteristicHandle() + { return txCharacteristic.getValueAttribute().getHandle(); } /** * Note: TX and RX characteristics are to be interpreted from the viewpoint of the GATT client using this service. */ - uint16_t getRXCharacteristicHandle() { + uint16_t getRXCharacteristicHandle() + { return rxCharacteristic.getValueAttribute().getHandle(); } @@ -102,7 +105,8 @@ class UARTService { * @param length Number of characters to be appended. * @return Number of characters appended to the rxCharacteristic. */ - size_t write(const void *_buffer, size_t length) { + size_t write(const void *_buffer, size_t length) + { size_t origLength = length; const uint8_t *buffer = static_cast(_buffer); @@ -120,8 +124,8 @@ class UARTService { /* Have we collected enough? */ if ((sendBufferIndex == BLE_UART_SERVICE_MAX_DATA_LEN) || - // (sendBuffer[sendBufferIndex - 1] == '\r') || - (sendBuffer[sendBufferIndex - 1] == '\n')) { + // (sendBuffer[sendBufferIndex - 1] == '\r') || + (sendBuffer[sendBufferIndex - 1] == '\n')) { ble.gattServer().write(getRXCharacteristicHandle(), static_cast(sendBuffer), sendBufferIndex); sendBufferIndex = 0; } @@ -136,7 +140,8 @@ class UARTService { * @param str The received string. * @return Number of characters appended to the rxCharacteristic. */ - size_t writeString(const char *str) { + size_t writeString(const char *str) + { return write(str, strlen(str)); } @@ -144,7 +149,8 @@ class UARTService { * Flush sendBuffer, i.e., forcefully write its contents to the UART RX * characteristic even if the buffer is not full. */ - void flush() { + void flush() + { if (ble.getGapState().connected) { if (sendBufferIndex != 0) { ble.gattServer().write(getRXCharacteristicHandle(), static_cast(sendBuffer), sendBufferIndex); @@ -160,7 +166,8 @@ class UARTService { * @return * The character written as an unsigned char cast to an int or EOF on error. */ - int _putc(int c) { + int _putc(int c) + { return (write(&c, 1) == 1) ? 1 : EOF; } @@ -169,7 +176,8 @@ class UARTService { * @return * The character read. */ - int _getc() { + int _getc() + { if (receiveBufferIndex == numBytesReceived) { return EOF; } @@ -184,7 +192,8 @@ class UARTService { * function from the global onDataWritten() callback handler; if that's * not used, this method can be used as a callback directly. */ - void onDataWritten(const GattWriteCallbackParams *params) { + void onDataWritten(const GattWriteCallbackParams *params) + { if (params->handle == getTXCharacteristicHandle()) { uint16_t bytesRead = params->len; if (bytesRead <= BLE_UART_SERVICE_MAX_DATA_LEN) { diff --git a/features/FEATURE_BLE/ble/services/URIBeaconConfigService.h b/features/FEATURE_BLE/ble/services/URIBeaconConfigService.h index 9eb95bd40c2..81fff56eaa9 100644 --- a/features/FEATURE_BLE/ble/services/URIBeaconConfigService.h +++ b/features/FEATURE_BLE/ble/services/URIBeaconConfigService.h @@ -45,7 +45,7 @@ extern const uint8_t BEACON_UUID[sizeof(UUID::ShortUUIDBytes_t)]; * */ class URIBeaconConfigService { - public: +public: /** * @brief Transmission power modes for UriBeacon. */ @@ -111,7 +111,8 @@ class URIBeaconConfigService { advPowerLevelsChar(UUID_ADV_POWER_LEVELS_CHAR, ¶ms.advPowerLevels), txPowerModeChar(UUID_TX_POWER_MODE_CHAR, ¶ms.txPowerMode), beaconPeriodChar(UUID_BEACON_PERIOD_CHAR, ¶ms.beaconPeriod), - resetChar(UUID_RESET_CHAR, &resetFlag) { + resetChar(UUID_RESET_CHAR, &resetFlag) + { encodeURI(defaultURIDataIn, defaultUriData, defaultUriDataLength); if (defaultUriDataLength > URI_DATA_MAX) { @@ -153,7 +154,8 @@ class URIBeaconConfigService { initSucceeded = true; } - bool configuredSuccessfully(void) const { + bool configuredSuccessfully(void) const + { return initSucceeded; } @@ -223,9 +225,10 @@ class URIBeaconConfigService { ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::SERVICE_DATA, serviceData, serviceDataLen); } - private: +private: // True if the lock bits are non-zero. - bool isLocked() { + bool isLocked() + { Lock_t testLock; memset(testLock, 0, sizeof(Lock_t)); return memcmp(params.lock, testLock, sizeof(Lock_t)); @@ -236,7 +239,8 @@ class URIBeaconConfigService { * characteristics of this service. These attempts are also applied to * the internal state of this service object. */ - void onDataWrittenCallback(const GattWriteCallbackParams *writeParams) { + void onDataWrittenCallback(const GattWriteCallbackParams *writeParams) + { uint16_t handle = writeParams->handle; if (handle == lockChar.getValueHandle()) { @@ -282,7 +286,8 @@ class URIBeaconConfigService { /* * Reset the default values. */ - void resetToDefaults(void) { + void resetToDefaults(void) + { lockedState = false; memset(params.lock, 0, sizeof(Lock_t)); memcpy(params.uriData, defaultUriData, URI_DATA_MAX); @@ -298,19 +303,21 @@ class URIBeaconConfigService { * Internal helper function used to update the GATT database following any * change to the internal state of the service object. */ - void updateCharacteristicValues(void) { + void updateCharacteristicValues(void) + { ble.gattServer().write(lockedStateChar.getValueHandle(), &lockedState, 1); ble.gattServer().write(uriDataChar.getValueHandle(), params.uriData, params.uriDataLength); ble.gattServer().write(flagsChar.getValueHandle(), ¶ms.flags, 1); ble.gattServer().write(beaconPeriodChar.getValueHandle(), - reinterpret_cast(¶ms.beaconPeriod), sizeof(uint16_t)); + reinterpret_cast(¶ms.beaconPeriod), sizeof(uint16_t)); ble.gattServer().write(txPowerModeChar.getValueHandle(), ¶ms.txPowerMode, 1); ble.gattServer().write(advPowerLevelsChar.getValueHandle(), - reinterpret_cast(params.advPowerLevels), sizeof(PowerLevels_t)); + reinterpret_cast(params.advPowerLevels), sizeof(PowerLevels_t)); } protected: - void lockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { + void lockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) + { if (lockedState) { authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; } else if (authParams->len != sizeof(Lock_t)) { @@ -323,7 +330,8 @@ class URIBeaconConfigService { } - void unlockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { + void unlockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) + { if (!lockedState) { authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; } else if (authParams->len != sizeof(Lock_t)) { @@ -337,7 +345,8 @@ class URIBeaconConfigService { } } - void uriDataWriteAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { + void uriDataWriteAuthorizationCallback(GattWriteAuthCallbackParams *authParams) + { if (lockedState) { authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; } else if (authParams->offset != 0) { @@ -347,7 +356,8 @@ class URIBeaconConfigService { } } - void powerModeAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { + void powerModeAuthorizationCallback(GattWriteAuthCallbackParams *authParams) + { if (lockedState) { authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; } else if (authParams->len != sizeof(uint8_t)) { @@ -362,7 +372,8 @@ class URIBeaconConfigService { } template - void basicAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { + void basicAuthorizationCallback(GattWriteAuthCallbackParams *authParams) + { if (lockedState) { authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; } else if (authParams->len != sizeof(T)) { @@ -400,7 +411,8 @@ class URIBeaconConfigService { /* * Encode a human-readable URI into the binary format defined by the UriBeacon spec (https://github.com/google/uribeacon/tree/master/specification). */ - static void encodeURI(const char *uriDataIn, UriData_t uriDataOut, size_t &sizeofURIDataOut) { + static void encodeURI(const char *uriDataIn, UriData_t uriDataOut, size_t &sizeofURIDataOut) + { const char *prefixes[] = { "http://www.", "https://www.", diff --git a/features/FEATURE_BLE/ble/services/iBeacon.h b/features/FEATURE_BLE/ble/services/iBeacon.h index f75e460381e..06fc67882bb 100644 --- a/features/FEATURE_BLE/ble/services/iBeacon.h +++ b/features/FEATURE_BLE/ble/services/iBeacon.h @@ -82,8 +82,7 @@ * * @note More information at https://developer.apple.com/ibeacon/Getting-Started-with-iBeacon.pdf */ -class iBeacon -{ +class iBeacon { public: /** * Data buffer of a location UUID. @@ -170,8 +169,7 @@ class iBeacon len(0x15), majorNumber(__REV16(majNum)), minorNumber(__REV16(minNum)), - txPower(transmitPower) - { + txPower(transmitPower) { memcpy(proximityUUID, uuid, sizeof(LocationUUID_t)); } }; diff --git a/features/FEATURE_BLE/source/BLE.cpp b/features/FEATURE_BLE/source/BLE.cpp index 9eba68f96e2..a8960c74d3c 100644 --- a/features/FEATURE_BLE/source/BLE.cpp +++ b/features/FEATURE_BLE/source/BLE.cpp @@ -31,7 +31,7 @@ #include #endif -static const char* error_strings[] = { +static const char *error_strings[] = { "BLE_ERROR_NONE: No error", "BLE_ERROR_BUFFER_OVERFLOW: The requested action would cause a buffer overflow and has been aborted", "BLE_ERROR_NOT_IMPLEMENTED: Requested a feature that isn't yet implement or isn't supported by the target HW", @@ -47,7 +47,7 @@ static const char* error_strings[] = { "BLE_ERROR_INTERNAL_STACK_FAILURE: The platform-specific stack failed" }; -const char* BLE::errorToString(ble_error_t error) +const char *BLE::errorToString(ble_error_t error) { if (error > BLE_ERROR_INTERNAL_STACK_FAILURE) { return "Illegal error code"; @@ -56,7 +56,7 @@ const char* BLE::errorToString(ble_error_t error) } ble_error_t -BLE::initImplementation(FunctionPointerWithContext callback) +BLE::initImplementation(FunctionPointerWithContext callback) { ble_error_t err = transport->init(instanceID, callback); if (err != BLE_ERROR_NONE) { @@ -118,7 +118,8 @@ BLE::initImplementation(FunctionPointerWithContextble, &BLE::processEvents); } #else @@ -225,7 +227,7 @@ Gap &BLE::gap() return transport->getGap(); } -const GattServer& BLE::gattServer() const +const GattServer &BLE::gattServer() const { if (!transport) { error("bad handle to underlying transport"); @@ -234,7 +236,7 @@ const GattServer& BLE::gattServer() const return transport->getGattServer(); } -GattServer& BLE::gattServer() +GattServer &BLE::gattServer() { if (!transport) { error("bad handle to underlying transport"); @@ -243,7 +245,7 @@ GattServer& BLE::gattServer() return transport->getGattServer(); } -const GattClient& BLE::gattClient() const +const GattClient &BLE::gattClient() const { if (!transport) { error("bad handle to underlying transport"); @@ -252,7 +254,7 @@ const GattClient& BLE::gattClient() const return transport->getGattClient(); } -GattClient& BLE::gattClient() +GattClient &BLE::gattClient() { if (!transport) { error("bad handle to underlying transport"); @@ -261,7 +263,7 @@ GattClient& BLE::gattClient() return transport->getGattClient(); } -const SecurityManager& BLE::securityManager() const +const SecurityManager &BLE::securityManager() const { if (!transport) { error("bad handle to underlying transport"); @@ -270,7 +272,7 @@ const SecurityManager& BLE::securityManager() const return transport->getSecurityManager(); } -SecurityManager& BLE::securityManager() +SecurityManager &BLE::securityManager() { if (!transport) { error("bad handle to underlying transport"); @@ -303,7 +305,7 @@ void BLE::processEvents() transport->processEvents(); } -void BLE::onEventsToProcess(const BLE::OnEventsToProcessCallback_t& callback) +void BLE::onEventsToProcess(const BLE::OnEventsToProcessCallback_t &callback) { whenEventsToProcess = callback; diff --git a/features/FEATURE_BLE/source/DiscoveredCharacteristic.cpp b/features/FEATURE_BLE/source/DiscoveredCharacteristic.cpp index e2a68499a0b..5d52bfafd7a 100644 --- a/features/FEATURE_BLE/source/DiscoveredCharacteristic.cpp +++ b/features/FEATURE_BLE/source/DiscoveredCharacteristic.cpp @@ -32,26 +32,29 @@ DiscoveredCharacteristic::read(uint16_t offset) const } struct OneShotReadCallback { - static void launch(GattClient* client, Gap::Handle_t connHandle, - GattAttribute::Handle_t handle, const GattClient::ReadCallback_t& cb) { - OneShotReadCallback* oneShot = new OneShotReadCallback(client, connHandle, handle, cb); + static void launch(GattClient *client, Gap::Handle_t connHandle, + GattAttribute::Handle_t handle, const GattClient::ReadCallback_t &cb) + { + OneShotReadCallback *oneShot = new OneShotReadCallback(client, connHandle, handle, cb); oneShot->attach(); // delete will be made when this callback is called } private: - OneShotReadCallback(GattClient* client, Gap::Handle_t connHandle, - GattAttribute::Handle_t handle, const GattClient::ReadCallback_t& cb) : + OneShotReadCallback(GattClient *client, Gap::Handle_t connHandle, + GattAttribute::Handle_t handle, const GattClient::ReadCallback_t &cb) : _client(client), _connHandle(connHandle), _handle(handle), _callback(cb) { } - void attach() { + void attach() + { _client->onDataRead(makeFunctionPointer(this, &OneShotReadCallback::call)); } - void call(const GattReadCallbackParams* params) { + void call(const GattReadCallbackParams *params) + { // verifiy that it is the right characteristic on the right connection if (params->connHandle == _connHandle && params->handle == _handle) { _callback(params); @@ -60,13 +63,14 @@ struct OneShotReadCallback { } } - GattClient* _client; + GattClient *_client; Gap::Handle_t _connHandle; GattAttribute::Handle_t _handle; GattClient::ReadCallback_t _callback; }; -ble_error_t DiscoveredCharacteristic::read(uint16_t offset, const GattClient::ReadCallback_t& onRead) const { +ble_error_t DiscoveredCharacteristic::read(uint16_t offset, const GattClient::ReadCallback_t &onRead) const +{ ble_error_t error = read(offset); if (error) { return error; @@ -106,26 +110,29 @@ DiscoveredCharacteristic::writeWoResponse(uint16_t length, const uint8_t *value) } struct OneShotWriteCallback { - static void launch(GattClient* client, Gap::Handle_t connHandle, - GattAttribute::Handle_t handle, const GattClient::WriteCallback_t& cb) { - OneShotWriteCallback* oneShot = new OneShotWriteCallback(client, connHandle, handle, cb); + static void launch(GattClient *client, Gap::Handle_t connHandle, + GattAttribute::Handle_t handle, const GattClient::WriteCallback_t &cb) + { + OneShotWriteCallback *oneShot = new OneShotWriteCallback(client, connHandle, handle, cb); oneShot->attach(); // delete will be made when this callback is called } private: - OneShotWriteCallback(GattClient* client, Gap::Handle_t connHandle, - GattAttribute::Handle_t handle, const GattClient::WriteCallback_t& cb) : + OneShotWriteCallback(GattClient *client, Gap::Handle_t connHandle, + GattAttribute::Handle_t handle, const GattClient::WriteCallback_t &cb) : _client(client), _connHandle(connHandle), _handle(handle), _callback(cb) { } - void attach() { + void attach() + { _client->onDataWritten(makeFunctionPointer(this, &OneShotWriteCallback::call)); } - void call(const GattWriteCallbackParams* params) { + void call(const GattWriteCallbackParams *params) + { // verifiy that it is the right characteristic on the right connection if (params->connHandle == _connHandle && params->handle == _handle) { _callback(params); @@ -134,13 +141,14 @@ struct OneShotWriteCallback { } } - GattClient* _client; + GattClient *_client; Gap::Handle_t _connHandle; GattAttribute::Handle_t _handle; GattClient::WriteCallback_t _callback; }; -ble_error_t DiscoveredCharacteristic::write(uint16_t length, const uint8_t *value, const GattClient::WriteCallback_t& onRead) const { +ble_error_t DiscoveredCharacteristic::write(uint16_t length, const uint8_t *value, const GattClient::WriteCallback_t &onRead) const +{ ble_error_t error = write(length, value); if (error) { return error; @@ -152,16 +160,17 @@ ble_error_t DiscoveredCharacteristic::write(uint16_t length, const uint8_t *valu } ble_error_t DiscoveredCharacteristic::discoverDescriptors( - const CharacteristicDescriptorDiscovery::DiscoveryCallback_t& onCharacteristicDiscovered, - const CharacteristicDescriptorDiscovery::TerminationCallback_t& onTermination) const { + const CharacteristicDescriptorDiscovery::DiscoveryCallback_t &onCharacteristicDiscovered, + const CharacteristicDescriptorDiscovery::TerminationCallback_t &onTermination) const +{ - if(!gattc) { + if (!gattc) { return BLE_ERROR_INVALID_STATE; } ble_error_t err = gattc->discoverCharacteristicDescriptors( - *this, onCharacteristicDiscovered, onTermination - ); + *this, onCharacteristicDiscovered, onTermination + ); return err; } diff --git a/features/FEATURE_BLE/source/GapScanningParams.cpp b/features/FEATURE_BLE/source/GapScanningParams.cpp index 1d9f1cb26f2..4770421c86c 100644 --- a/features/FEATURE_BLE/source/GapScanningParams.cpp +++ b/features/FEATURE_BLE/source/GapScanningParams.cpp @@ -21,7 +21,8 @@ GapScanningParams::GapScanningParams(uint16_t interval, uint16_t window, uint16_ _interval(MSEC_TO_SCAN_DURATION_UNITS(interval)), _window(MSEC_TO_SCAN_DURATION_UNITS(window)), _timeout(timeout), - _activeScanning(activeScanning) { + _activeScanning(activeScanning) +{ /* stay within limits */ if (_interval < SCAN_INTERVAL_MIN) { _interval = SCAN_INTERVAL_MIN; diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 877564bb230..da20084bef9 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -57,7 +57,8 @@ static const GapScanningParams default_scan_params; * Return true if value is included in the range [lower_bound : higher_bound] */ template -static bool is_in_range(T value, T lower_bound, T higher_bound) { +static bool is_in_range(T value, T lower_bound, T higher_bound) +{ if (value < lower_bound || value > higher_bound) { return false; } @@ -67,7 +68,7 @@ static bool is_in_range(T value, T lower_bound, T higher_bound) { /* * Return true if the scan parameters are valid or false otherwise. */ -static bool is_scan_params_valid(const GapScanningParams* params) +static bool is_scan_params_valid(const GapScanningParams *params) { if (params == NULL) { return false; @@ -87,7 +88,7 @@ static bool is_scan_params_valid(const GapScanningParams* params) /* * Return true if the connection parameters are valid or false otherwise. */ -static bool is_connection_params_valid(const Gap::ConnectionParams_t* params) +static bool is_connection_params_valid(const Gap::ConnectionParams_t *params) { if (params == NULL) { return false; @@ -130,7 +131,7 @@ static bool is_connection_params_valid(const Gap::ConnectionParams_t* params) * timeout to be equal to 0xFFFF. When it is the case that value can be * interpreted as "non specific". */ -static bool is_preferred_connection_params_valid(const Gap::ConnectionParams_t* params) +static bool is_preferred_connection_params_valid(const Gap::ConnectionParams_t *params) { if (params == NULL) { return false; @@ -141,12 +142,12 @@ static bool is_preferred_connection_params_valid(const Gap::ConnectionParams_t* } if ((is_in_range(params->maxConnectionInterval, connection_interval_min, connection_interval_max) == false) && - (params->maxConnectionInterval != 0xFFFF)) { + (params->maxConnectionInterval != 0xFFFF)) { return false; } if ((is_in_range(params->minConnectionInterval, connection_interval_min, params->maxConnectionInterval) == false) && - (params->minConnectionInterval != 0xFFFF)) { + (params->minConnectionInterval != 0xFFFF)) { return false; } @@ -177,7 +178,7 @@ static bool is_preferred_connection_params_valid(const Gap::ConnectionParams_t* /** * Check if random bytes of an address are valid. */ -static bool is_prand_valid(const uint8_t* bytes, size_t len) +static bool is_prand_valid(const uint8_t *bytes, size_t len) { // at least one bit of the random part of the static address shall be // equal to 0 and at least one bit of the random part of the static @@ -241,7 +242,8 @@ static bool is_random_static_address(const BLEProtocol::AddressBytes_t address) */ static bool is_random_private_non_resolvable_address( const BLEProtocol::AddressBytes_t address -) { +) +{ // top two msb bits shall be equal to 0. if ((address[5] >> 6) != 0x00) { return false; @@ -255,7 +257,8 @@ static bool is_random_private_non_resolvable_address( */ static bool is_random_private_resolvable_address( const BLEProtocol::AddressBytes_t address -) { +) +{ // top two msb bits shall be equal to 01. if ((address[5] >> 6) != 0x01) { return false; @@ -270,8 +273,8 @@ static bool is_random_private_resolvable_address( static bool is_random_address(const BLEProtocol::AddressBytes_t address) { return is_random_private_resolvable_address(address) || - is_random_private_non_resolvable_address(address) || - is_random_static_address(address); + is_random_private_non_resolvable_address(address) || + is_random_static_address(address); } /* @@ -306,14 +309,14 @@ static bool is_disconnection_reason_valid(Gap::DisconnectionReason_t reason) /* * Return true if the whitelist in input is valid or false otherwise. */ -static bool is_whitelist_valid(const Gap::Whitelist_t& whitelist) +static bool is_whitelist_valid(const Gap::Whitelist_t &whitelist) { if (whitelist.size > whitelist.capacity) { return false; } for (size_t i = 0; i < whitelist.size; ++i) { - const BLEProtocol::Address_t& address = whitelist.addresses[i]; + const BLEProtocol::Address_t &address = whitelist.addresses[i]; if (address.type > BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE) { return false; } @@ -331,10 +334,11 @@ static bool is_whitelist_valid(const Gap::Whitelist_t& whitelist) * Return true if device is present in the whitelist. */ static bool is_in_whitelist( - const BLEProtocol::Address_t& device, const Gap::Whitelist_t& whitelist -) { + const BLEProtocol::Address_t &device, const Gap::Whitelist_t &whitelist +) +{ for (size_t i = 0; i < whitelist.size; ++i) { - const BLEProtocol::Address_t& potential_device = whitelist.addresses[i]; + const BLEProtocol::Address_t &potential_device = whitelist.addresses[i]; if (potential_device.type != device.type) { continue; @@ -352,16 +356,17 @@ static bool is_in_whitelist( */ static pal::whitelist_address_type_t to_device_address_type( BLEProtocol::AddressType_t address_type -) { - return (address_type == BLEProtocol::AddressType::PUBLIC) ? - pal::whitelist_address_type_t::PUBLIC_DEVICE_ADDRESS : - pal::whitelist_address_type_t::RANDOM_DEVICE_ADDRESS; +) +{ + return (address_type == BLEProtocol::AddressType::PUBLIC) ? + pal::whitelist_address_type_t::PUBLIC_DEVICE_ADDRESS : + pal::whitelist_address_type_t::RANDOM_DEVICE_ADDRESS; } /* * Return true if the advertising parameters are valid. */ -static bool is_advertising_params_valid(const GapAdvertisingParams& params) +static bool is_advertising_params_valid(const GapAdvertisingParams ¶ms) { if (is_in_range(params.getIntervalInADVUnits(), advertising_interval_min, advertising_interval_max) == false) { return false; @@ -377,9 +382,9 @@ static bool is_advertising_params_valid(const GapAdvertisingParams& params) } // end of anonymous namespace GenericGap::GenericGap( - pal::EventQueue& event_queue, - pal::Gap& pal_gap, - pal::GenericAccessService& generic_access_service + pal::EventQueue &event_queue, + pal::Gap &pal_gap, + pal::GenericAccessService &generic_access_service ) : _event_queue(event_queue), _pal_gap(pal_gap), _gap_service(generic_access_service), @@ -404,7 +409,8 @@ GenericGap::~GenericGap() ble_error_t GenericGap::setAddress( BLEProtocol::AddressType_t type, const BLEProtocol::AddressBytes_t address -) { +) +{ switch (type) { case BLEProtocol::AddressType::PUBLIC: // The public address cannot be set, just set the type to public @@ -412,21 +418,21 @@ ble_error_t GenericGap::setAddress( return BLE_ERROR_NONE; case BLEProtocol::AddressType::RANDOM_STATIC: { - if (is_random_static_address(address) == false) { - return BLE_ERROR_INVALID_PARAM; - } + if (is_random_static_address(address) == false) { + return BLE_ERROR_INVALID_PARAM; + } - ble_error_t err = _pal_gap.set_random_address( - ble::address_t(address) - ); - if (err) { - return err; - } + ble_error_t err = _pal_gap.set_random_address( + ble::address_t(address) + ); + if (err) { + return err; + } - _address_type = type; - _address = ble::address_t(address); - return BLE_ERROR_NONE; - } + _address_type = type; + _address = ble::address_t(address); + return BLE_ERROR_NONE; + } case BLEProtocol::AddressType::RANDOM_PRIVATE_RESOLVABLE: // TODO: Fix with the privacy/security rework @@ -445,7 +451,8 @@ ble_error_t GenericGap::setAddress( ble_error_t GenericGap::getAddress( BLEProtocol::AddressType_t *type, BLEProtocol::AddressBytes_t address -) { +) +{ *type = _address_type; ble::address_t address_value; if (_address_type == BLEProtocol::AddressType::PUBLIC) { @@ -498,9 +505,10 @@ ble_error_t GenericGap::stopScan() ble_error_t GenericGap::connect( const BLEProtocol::AddressBytes_t peerAddr, BLEProtocol::AddressType_t peerAddrType, - const ConnectionParams_t* connectionParams, - const GapScanningParams* scanParams -) { + const ConnectionParams_t *connectionParams, + const GapScanningParams *scanParams +) +{ if (connectionParams == NULL) { connectionParams = &default_connection_params; } @@ -523,19 +531,19 @@ ble_error_t GenericGap::connect( stopScan(); return _pal_gap.create_connection( - scanParams->getInterval(), - scanParams->getWindow(), - _initiator_policy_mode, - (pal::connection_peer_address_type_t::type) peerAddrType, - ble::address_t(peerAddr), - (pal::own_address_type_t::type) _address_type, - connectionParams->minConnectionInterval, - connectionParams->maxConnectionInterval, - connectionParams->slaveLatency, - connectionParams->connectionSupervisionTimeout, - /* minimum_connection_event_length */ 0, - /* maximum_connection_event_length */ 0 - ); + scanParams->getInterval(), + scanParams->getWindow(), + _initiator_policy_mode, + (pal::connection_peer_address_type_t::type) peerAddrType, + ble::address_t(peerAddr), + (pal::own_address_type_t::type) _address_type, + connectionParams->minConnectionInterval, + connectionParams->maxConnectionInterval, + connectionParams->slaveLatency, + connectionParams->connectionSupervisionTimeout, + /* minimum_connection_event_length */ 0, + /* maximum_connection_event_length */ 0 + ); } ble_error_t GenericGap::disconnect(Handle_t connectionHandle, DisconnectionReason_t reason) @@ -544,9 +552,9 @@ ble_error_t GenericGap::disconnect(Handle_t connectionHandle, DisconnectionReaso return BLE_ERROR_INVALID_PARAM; } return _pal_gap.disconnect( - connectionHandle, - (pal::disconnection_reason_t::type) reason - ); + connectionHandle, + (pal::disconnection_reason_t::type) reason + ); } ble_error_t GenericGap::updateConnectionParams(Handle_t handle, const ConnectionParams_t *params) @@ -556,14 +564,14 @@ ble_error_t GenericGap::updateConnectionParams(Handle_t handle, const Connection } return _pal_gap.connection_parameters_update( - handle, - params->minConnectionInterval, - params->maxConnectionInterval, - params->slaveLatency, - params->connectionSupervisionTimeout, - /* minimum_connection_event_length */ 0, - /* maximum_connection_event_length */ 0 - ); + handle, + params->minConnectionInterval, + params->maxConnectionInterval, + params->slaveLatency, + params->connectionSupervisionTimeout, + /* minimum_connection_event_length */ 0, + /* maximum_connection_event_length */ 0 + ); } ble_error_t GenericGap::getPreferredConnectionParams(ConnectionParams_t *params) @@ -573,19 +581,19 @@ ble_error_t GenericGap::getPreferredConnectionParams(ConnectionParams_t *params) } return _gap_service.get_peripheral_prefered_connection_parameters( - *params - ); + *params + ); } ble_error_t GenericGap::setPreferredConnectionParams(const ConnectionParams_t *params) { - if(is_preferred_connection_params_valid(params) == false) { + if (is_preferred_connection_params_valid(params) == false) { return BLE_ERROR_PARAM_OUT_OF_RANGE; } return _gap_service.set_peripheral_prefered_connection_parameters( - *params - ); + *params + ); } ble_error_t GenericGap::setDeviceName(const uint8_t *deviceName) @@ -652,7 +660,7 @@ uint8_t GenericGap::getMaxWhitelistSize(void) const ble_error_t GenericGap::getWhitelist(Whitelist_t &whitelist) const { - if(initialize_whitelist() == false) { + if (initialize_whitelist() == false) { return BLE_ERROR_INVALID_STATE; } @@ -674,7 +682,7 @@ ble_error_t GenericGap::setWhitelist(const Whitelist_t &whitelist) return BLE_ERROR_INVALID_PARAM; } - if(initialize_whitelist() == false) { + if (initialize_whitelist() == false) { return BLE_ERROR_INVALID_STATE; } @@ -684,18 +692,18 @@ ble_error_t GenericGap::setWhitelist(const Whitelist_t &whitelist) // first evict devices not in the existing whitelist for (size_t i = 0; i < _whitelist.size; ++i) { - const BLEProtocol::Address_t& device = _whitelist.addresses[i]; + const BLEProtocol::Address_t &device = _whitelist.addresses[i]; if (is_in_whitelist(device, whitelist) == false) { ble_error_t err = _pal_gap.remove_device_from_whitelist( - to_device_address_type(device.type), - device.address - ); + to_device_address_type(device.type), + device.address + ); // try to restore the whitelist to its initial state if (err) { for (size_t j = 0; j < i; ++j) { - const BLEProtocol::Address_t& device = _whitelist.addresses[j]; + const BLEProtocol::Address_t &device = _whitelist.addresses[j]; if (is_in_whitelist(device, whitelist) == false) { _pal_gap.add_device_to_whitelist( @@ -711,19 +719,19 @@ ble_error_t GenericGap::setWhitelist(const Whitelist_t &whitelist) // second add devices which were not in the initial whitelist for (size_t i = 0; i < whitelist.size; ++i) { - const BLEProtocol::Address_t& device = whitelist.addresses[i]; + const BLEProtocol::Address_t &device = whitelist.addresses[i]; if (is_in_whitelist(device, _whitelist) == false) { ble_error_t err = _pal_gap.add_device_to_whitelist( - to_device_address_type(device.type), - device.address - ); + to_device_address_type(device.type), + device.address + ); // try to restore the whitelist to its initial state if (err) { // first remove the devices added for (size_t j = 0; j < i; ++j) { - const BLEProtocol::Address_t& device = whitelist.addresses[j]; + const BLEProtocol::Address_t &device = whitelist.addresses[j]; if (is_in_whitelist(device, _whitelist) == false) { _pal_gap.remove_device_from_whitelist( @@ -735,7 +743,7 @@ ble_error_t GenericGap::setWhitelist(const Whitelist_t &whitelist) // second add the devices of the initial list evicted for (size_t i = 0; i < _whitelist.size; ++i) { - const BLEProtocol::Address_t& device = _whitelist.addresses[i]; + const BLEProtocol::Address_t &device = _whitelist.addresses[i]; if (is_in_whitelist(device, whitelist) == false) { _pal_gap.add_device_to_whitelist( @@ -812,17 +820,17 @@ ble_error_t GenericGap::startRadioScan(const GapScanningParams &scanningParams) } if (_scanning_filter_policy == pal::scanning_filter_policy_t::FILTER_ADVERTISING && - _whitelist.size == 0) { + _whitelist.size == 0) { return BLE_ERROR_INVALID_STATE; } ble_error_t err = _pal_gap.set_scan_parameters( - scanningParams.getActiveScanning(), - scanningParams.getInterval(), - scanningParams.getWindow(), - get_own_address_type(), - _scanning_filter_policy - ); + scanningParams.getActiveScanning(), + scanningParams.getInterval(), + scanningParams.getWindow(), + get_own_address_type(), + _scanning_filter_policy + ); if (err) { return err; @@ -854,20 +862,20 @@ ble_error_t GenericGap::initRadioNotification(void) ble_error_t GenericGap::setAdvertisingData(const GapAdvertisingData &advData, const GapAdvertisingData &scanResponse) { ble_error_t err = _pal_gap.set_advertising_data( - advData.getPayloadLen(), - pal::advertising_data_t(advData.getPayload(), advData.getPayloadLen()) - ); + advData.getPayloadLen(), + pal::advertising_data_t(advData.getPayload(), advData.getPayloadLen()) + ); if (err) { return err; } return _pal_gap.set_scan_response_data( - scanResponse.getPayloadLen(), - pal::advertising_data_t(scanResponse.getPayload(), scanResponse.getPayloadLen()) - ); + scanResponse.getPayloadLen(), + pal::advertising_data_t(scanResponse.getPayload(), scanResponse.getPayloadLen()) + ); } -ble_error_t GenericGap::startAdvertising(const GapAdvertisingParams& params) +ble_error_t GenericGap::startAdvertising(const GapAdvertisingParams ¶ms) { if (is_advertising_params_valid(params) == false) { return BLE_ERROR_INVALID_PARAM; @@ -880,15 +888,15 @@ ble_error_t GenericGap::startAdvertising(const GapAdvertisingParams& params) // for now but not against specification: "The Advertising_Interval_Min // shall be less than or equal to the Advertising_Interval_Max" ble_error_t err = _pal_gap.set_advertising_parameters( - /* advertising_interval_min */ params.getIntervalInADVUnits(), - /* advertising_interval_max */ params.getIntervalInADVUnits(), - (pal::advertising_type_t::type) params.getAdvertisingType(), - get_own_address_type(), - pal::advertising_peer_address_type_t::PUBLIC_ADDRESS, - ble::address_t(), - pal::advertising_channel_map_t::ALL_ADVERTISING_CHANNELS, - _advertising_filter_policy - ); + /* advertising_interval_min */ params.getIntervalInADVUnits(), + /* advertising_interval_max */ params.getIntervalInADVUnits(), + (pal::advertising_type_t::type) params.getAdvertisingType(), + get_own_address_type(), + pal::advertising_peer_address_type_t::PUBLIC_ADDRESS, + ble::address_t(), + pal::advertising_channel_map_t::ALL_ADVERTISING_CHANNELS, + _advertising_filter_policy + ); if (err) { return err; @@ -930,7 +938,8 @@ void GenericGap::processConnectionEvent( BLEProtocol::AddressType_t ownAddrType, const BLEProtocol::AddressBytes_t ownAddr, const ConnectionParams_t *connectionParams -) { +) +{ if (_connection_event_handler) { _connection_event_handler->on_connected( handle, @@ -951,13 +960,14 @@ void GenericGap::processConnectionEvent( ownAddrType, ownAddr, connectionParams - ); + ); } void GenericGap::processDisconnectionEvent( Handle_t handle, DisconnectionReason_t reason -) { +) +{ if (_connection_event_handler) { _connection_event_handler->on_disconnected( handle, @@ -999,31 +1009,31 @@ void GenericGap::process_advertising_timeout() processTimeoutEvent(Gap::TIMEOUT_SRC_ADVERTISING); } -void GenericGap::on_gap_event_received(const pal::GapEvent& e) +void GenericGap::on_gap_event_received(const pal::GapEvent &e) { switch (e.type.value()) { case pal::GapEventType::ADVERTISING_REPORT: - on_advertising_report(static_cast(e)); + on_advertising_report(static_cast(e)); break; case pal::GapEventType::CONNECTION_COMPLETE: - on_connection_complete(static_cast(e)); + on_connection_complete(static_cast(e)); break; case pal::GapEventType::CONNECTION_UPDATE: - on_connection_update(static_cast(e)); + on_connection_update(static_cast(e)); break; case pal::GapEventType::DISCONNECTION_COMPLETE: - on_disconnection_complete(static_cast(e)); + on_disconnection_complete(static_cast(e)); break; case pal::GapEventType::REMOTE_CONNECTION_PARAMETER_REQUEST: - on_connection_parameter_request(static_cast(e)); + on_connection_parameter_request(static_cast(e)); break; case pal::GapEventType::UNEXPECTED_ERROR: - on_unexpected_error(static_cast(e)); + on_unexpected_error(static_cast(e)); break; default: @@ -1031,7 +1041,7 @@ void GenericGap::on_gap_event_received(const pal::GapEvent& e) } } -void GenericGap::on_advertising_report(const pal::GapAdvertisingReportEvent& e) +void GenericGap::on_advertising_report(const pal::GapAdvertisingReportEvent &e) { for (size_t i = 0; i < e.size(); ++i) { pal::GapAdvertisingReportEvent::advertising_t advertising = e[i]; @@ -1048,7 +1058,7 @@ void GenericGap::on_advertising_report(const pal::GapAdvertisingReportEvent& e) } } -void GenericGap::on_connection_complete(const pal::GapConnectionCompleteEvent& e) +void GenericGap::on_connection_complete(const pal::GapConnectionCompleteEvent &e) { // TODO: deprecate ownAddrType and ownAddr, those are not specified // from the Bluetooth perspective @@ -1091,7 +1101,7 @@ void GenericGap::on_connection_complete(const pal::GapConnectionCompleteEvent& e } } -void GenericGap::on_disconnection_complete(const pal::GapDisconnectionCompleteEvent& e) +void GenericGap::on_disconnection_complete(const pal::GapDisconnectionCompleteEvent &e) { if (e.status == pal::hci_error_code_t::SUCCESS) { processDisconnectionEvent( @@ -1103,7 +1113,7 @@ void GenericGap::on_disconnection_complete(const pal::GapDisconnectionCompleteEv } } -void GenericGap::on_connection_parameter_request(const pal::GapRemoteConnectionParameterRequestEvent& e) +void GenericGap::on_connection_parameter_request(const pal::GapRemoteConnectionParameterRequestEvent &e) { // intern behavior, accept all new parameter requests // TODO: expose an API so user code can accept or reject such request @@ -1118,13 +1128,13 @@ void GenericGap::on_connection_parameter_request(const pal::GapRemoteConnectionP ); } -void GenericGap::on_connection_update(const pal::GapConnectionUpdateEvent& e) +void GenericGap::on_connection_update(const pal::GapConnectionUpdateEvent &e) { // TODO: add feature in interface to notify the user that the connection // has been updated. } -void GenericGap::on_unexpected_error(const pal::GapUnexpectedErrorEvent& e) +void GenericGap::on_unexpected_error(const pal::GapUnexpectedErrorEvent &e) { // TODO: add feature in interface to notify the user that the connection // has been updated. diff --git a/features/FEATURE_BLE/source/generic/GenericGattClient.cpp b/features/FEATURE_BLE/source/generic/GenericGattClient.cpp index 97c6d57fc0f..3dcebbf233c 100644 --- a/features/FEATURE_BLE/source/generic/GenericGattClient.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGattClient.cpp @@ -45,10 +45,10 @@ namespace generic { * Type of procedures which can be launched by the client. */ enum procedure_type_t { - COMPLETE_DISCOVERY_PROCEDURE, - READ_PROCEDURE, - WRITE_PROCEDURE, - DESCRIPTOR_DISCOVERY_PROCEDURE + COMPLETE_DISCOVERY_PROCEDURE, + READ_PROCEDURE, + WRITE_PROCEDURE, + DESCRIPTOR_DISCOVERY_PROCEDURE }; @@ -56,32 +56,32 @@ enum procedure_type_t { * Base class for a procedure control block */ struct GenericGattClient::ProcedureControlBlock { - /* - * Base constructor for procedure control block. - */ - ProcedureControlBlock(procedure_type_t type, Gap::Handle_t handle) : - type(type), connection_handle(handle), next(NULL) { } - - virtual ~ProcedureControlBlock() { } - - /* - * Entry point of the control block stack machine. - */ - virtual void handle(GenericGattClient* client, const AttServerMessage& message) = 0; - - /* - * Function call in case of timeout - */ - virtual void handle_timeout_error(GenericGattClient* client) = 0; - - /** - * Function called when the procedure is aborted - */ - virtual void abort(GenericGattClient *client) = 0; - - procedure_type_t type; - Gap::Handle_t connection_handle; - ProcedureControlBlock* next; + /* + * Base constructor for procedure control block. + */ + ProcedureControlBlock(procedure_type_t type, Gap::Handle_t handle) : + type(type), connection_handle(handle), next(NULL) { } + + virtual ~ProcedureControlBlock() { } + + /* + * Entry point of the control block stack machine. + */ + virtual void handle(GenericGattClient *client, const AttServerMessage &message) = 0; + + /* + * Function call in case of timeout + */ + virtual void handle_timeout_error(GenericGattClient *client) = 0; + + /** + * Function called when the procedure is aborted + */ + virtual void abort(GenericGattClient *client) = 0; + + procedure_type_t type; + Gap::Handle_t connection_handle; + ProcedureControlBlock *next; }; @@ -89,1301 +89,1378 @@ struct GenericGattClient::ProcedureControlBlock { * Procedure control block for the discovery process. */ struct GenericGattClient::DiscoveryControlBlock : public ProcedureControlBlock { - DiscoveryControlBlock( - Gap::Handle_t handle, - ServiceDiscovery::ServiceCallback_t service_callback, - ServiceDiscovery::CharacteristicCallback_t characteristic_callback, - UUID matching_service_uuid, - UUID matching_characteristic_uuid - ) : ProcedureControlBlock(COMPLETE_DISCOVERY_PROCEDURE, handle), - service_callback(service_callback), - characteristic_callback(characteristic_callback), - matching_service_uuid(matching_service_uuid), - matching_characteristic_uuid(matching_characteristic_uuid), - services_discovered(NULL), - done(false) { - } - - virtual ~DiscoveryControlBlock() { - while(services_discovered) { - service_t* tmp = services_discovered->next; - delete services_discovered; - services_discovered = tmp; - } - } - - virtual void handle_timeout_error(GenericGattClient* client) { - terminate(client); - } - - virtual void abort(GenericGattClient *client) { - terminate(client); - } - - virtual void handle(GenericGattClient* client, const AttServerMessage& message) { - // if end of discovery has been requested, ends it immediately - if (done) { - terminate(client); - return; - } - - switch(message.opcode) { - case AttributeOpcode::READ_BY_GROUP_TYPE_RESPONSE: - handle_service_discovered( - client, static_cast(message) - ); - break; - case AttributeOpcode::FIND_BY_VALUE_TYPE_RESPONSE: - handle_service_discovered( - client, static_cast(message) - ); - break; - case AttributeOpcode::READ_BY_TYPE_RESPONSE: - handle_characteristic_discovered( - client, static_cast(message) - ); - break; - case AttributeOpcode::ERROR_RESPONSE: { - const AttErrorResponse& error = static_cast(message); - if (error.error_code != AttErrorResponse::ATTRIBUTE_NOT_FOUND) { - terminate(client); - } - - switch (error.request_opcode) { - case AttributeOpcode::READ_BY_GROUP_TYPE_REQUEST: - case AttributeOpcode::FIND_BY_TYPE_VALUE_REQUEST: - start_characteristic_discovery(client); - break; - case AttributeOpcode::READ_BY_TYPE_REQUEST: - handle_all_characteristics_discovered(client); - break; - default: - // error - break; - } - } break; - default: - // error - break; - } - } - - template - void handle_service_discovered(GenericGattClient* client, const Response& response) { - if (!response.size()) { - terminate(client); - return; - } - - uint16_t end_handle = 0x0000; - for (size_t i = 0; i < response.size(); ++i) { - uint16_t start_handle = get_start_handle(response[i]); - end_handle = get_end_handle(response[i]); - UUID uuid = get_uuid(response[i]); - - if (!characteristic_callback) { - DiscoveredService discovered_service; - discovered_service.setup(uuid, start_handle, end_handle); - service_callback(&discovered_service); - } else { - service_t* discovered_service = new (std::nothrow) service_t( - start_handle, end_handle, uuid - ); - - if (discovered_service == NULL) { - terminate(client); - return; - } - - insert_service(discovered_service); - } - } - - if (end_handle == 0xFFFF) { - start_characteristic_discovery(client); - } else { - ble_error_t err = client->_pal_client->discover_primary_service( - connection_handle, end_handle + 1 - ); - - if (err) { - terminate(client); - } - } - } - - void start_characteristic_discovery(GenericGattClient* client) { - if (!services_discovered) { - terminate(client); - return; - } - - if (!characteristic_callback) { - terminate(client); - return; - } - - if (service_callback) { - DiscoveredService discovered_service; - discovered_service.setup( - services_discovered->uuid, - services_discovered->begin, - services_discovered->end - ); - service_callback(&discovered_service); - } - - last_characteristic = characteristic_t(); - client->_pal_client->discover_characteristics_of_a_service( - connection_handle, - attribute_handle_range( - services_discovered->begin, - services_discovered->end - ) - ); - } - - void handle_characteristic_discovered(GenericGattClient* client, const AttReadByTypeResponse& response) { - for (size_t i = 0; i < response.size(); ++i) { - if (last_characteristic.is_valid() == false) { - last_characteristic.set_last_handle(response[i].handle - 1); - if (matching_characteristic_uuid == UUID() - || last_characteristic.getUUID() == matching_characteristic_uuid) { - characteristic_callback(&last_characteristic); - } - } - - last_characteristic = characteristic_t( - client, connection_handle, response[i].handle, response[i].value - ); - } - - // check if all the characteristics of the service has been discovered - if (last_characteristic.getValueHandle() == services_discovered->end) { - handle_all_characteristics_discovered(client); - } else { - ble_error_t err = client->_pal_client->discover_characteristics_of_a_service( - connection_handle, - attribute_handle_range( - last_characteristic.getValueHandle() + 1, - services_discovered->end - ) - ); - - if (err) { - terminate(client); - } - } - } - - void handle_all_characteristics_discovered(GenericGattClient* client) { - if (last_characteristic.is_valid() == false) { - if (matching_characteristic_uuid == UUID() - || matching_characteristic_uuid == last_characteristic.getUUID()) { - last_characteristic.set_last_handle(services_discovered->end); - characteristic_callback(&last_characteristic); - } - } - - service_t* old = services_discovered; - services_discovered = services_discovered->next; - delete old; - - if (!services_discovered) { - terminate(client); - } else { - start_characteristic_discovery(client); - } - } - - void terminate(GenericGattClient* client) { - // unknown error, terminate the procedure immediately - client->remove_control_block(this); - Gap::Handle_t handle = connection_handle; - delete this; - client->on_termination(handle); - } - - uint16_t get_start_handle(const AttReadByGroupTypeResponse::attribute_data_t& data) { - return data.group_range.begin; - } - - uint16_t get_start_handle(const attribute_handle_range_t& range) { - return range.begin; - } - - uint16_t get_end_handle(const AttReadByGroupTypeResponse::attribute_data_t& data) { - return data.group_range.end; - } - - uint16_t get_end_handle(const attribute_handle_range_t& range) { - return range.end; - } - - UUID get_uuid(const AttReadByGroupTypeResponse::attribute_data_t& data) { - if (data.value.size() == 2) { - return UUID(data.value[0] | data.value[1] << 8); - } else { - return UUID(data.value.data(), UUID::LSB); - } - } - - UUID get_uuid(const attribute_handle_range_t& range) { - return matching_service_uuid; - } - - struct service_t { - service_t(uint16_t begin, uint16_t end, const UUID& uuid) : - begin(begin), end(end), uuid(uuid), next(NULL) { } - uint16_t begin; - uint16_t end; - UUID uuid; - service_t* next; - }; - - struct characteristic_t : DiscoveredCharacteristic { - characteristic_t() : DiscoveredCharacteristic() { - lastHandle = 0x0001; - } - - characteristic_t( - GattClient* client, - Gap::Handle_t connection_handle, - uint16_t decl_handle, - const ArrayView value - ) : DiscoveredCharacteristic() { - gattc = client; - uuid = get_uuid(value); - props = get_properties(value); - declHandle = decl_handle; - valueHandle = get_value_handle(value); - lastHandle = 0x0000; - connHandle = connection_handle; - } - - static UUID get_uuid(const ArrayView& value) { - if (value.size() == 5) { - return UUID(value[3] | (value[4] << 8)); - } else { - return UUID(value.data() + 3, UUID::LSB); - } - } - - static DiscoveredCharacteristic::Properties_t get_properties(const ArrayView& value) { - uint8_t raw_properties = value[0]; - DiscoveredCharacteristic::Properties_t result; - result._broadcast = (raw_properties & (1 << 0)) ? true : false; - result._read = (raw_properties & (1 << 1)) ? true : false; - result._writeWoResp = (raw_properties & (1 << 2)) ? true : false; - result._write = (raw_properties & (1 << 3)) ? true : false; - result._notify = (raw_properties & (1 << 4)) ? true : false; - result._indicate = (raw_properties & (1 << 5)) ? true : false; - result._authSignedWrite = (raw_properties & (1 << 6)) ? true : false; - return result; - } - - static uint16_t get_value_handle(const ArrayView& value) { - return value[1] | (value[2] << 8); - } - - void set_last_handle(uint16_t last_handle) { - lastHandle = last_handle; - } - - bool is_valid() const { - return lastHandle != 0x0000; - } - }; - - void insert_service(service_t* service) { - if (services_discovered == NULL) { - services_discovered = service; - return; - } - - service_t* current = services_discovered; - while (current->next) { - current = current->next; - } - current->next = service; - } - - ServiceDiscovery::ServiceCallback_t service_callback; - ServiceDiscovery::CharacteristicCallback_t characteristic_callback; - UUID matching_service_uuid; - UUID matching_characteristic_uuid; - service_t* services_discovered; - characteristic_t last_characteristic; - bool done; + DiscoveryControlBlock( + Gap::Handle_t handle, + ServiceDiscovery::ServiceCallback_t service_callback, + ServiceDiscovery::CharacteristicCallback_t characteristic_callback, + UUID matching_service_uuid, + UUID matching_characteristic_uuid + ) : ProcedureControlBlock(COMPLETE_DISCOVERY_PROCEDURE, handle), + service_callback(service_callback), + characteristic_callback(characteristic_callback), + matching_service_uuid(matching_service_uuid), + matching_characteristic_uuid(matching_characteristic_uuid), + services_discovered(NULL), + done(false) + { + } + + virtual ~DiscoveryControlBlock() + { + while (services_discovered) { + service_t *tmp = services_discovered->next; + delete services_discovered; + services_discovered = tmp; + } + } + + virtual void handle_timeout_error(GenericGattClient *client) + { + terminate(client); + } + + virtual void abort(GenericGattClient *client) + { + terminate(client); + } + + virtual void handle(GenericGattClient *client, const AttServerMessage &message) + { + // if end of discovery has been requested, ends it immediately + if (done) { + terminate(client); + return; + } + + switch (message.opcode) { + case AttributeOpcode::READ_BY_GROUP_TYPE_RESPONSE: + handle_service_discovered( + client, static_cast(message) + ); + break; + case AttributeOpcode::FIND_BY_VALUE_TYPE_RESPONSE: + handle_service_discovered( + client, static_cast(message) + ); + break; + case AttributeOpcode::READ_BY_TYPE_RESPONSE: + handle_characteristic_discovered( + client, static_cast(message) + ); + break; + case AttributeOpcode::ERROR_RESPONSE: { + const AttErrorResponse &error = static_cast(message); + if (error.error_code != AttErrorResponse::ATTRIBUTE_NOT_FOUND) { + terminate(client); + } + + switch (error.request_opcode) { + case AttributeOpcode::READ_BY_GROUP_TYPE_REQUEST: + case AttributeOpcode::FIND_BY_TYPE_VALUE_REQUEST: + start_characteristic_discovery(client); + break; + case AttributeOpcode::READ_BY_TYPE_REQUEST: + handle_all_characteristics_discovered(client); + break; + default: + // error + break; + } + } + break; + default: + // error + break; + } + } + + template + void handle_service_discovered(GenericGattClient *client, const Response &response) + { + if (!response.size()) { + terminate(client); + return; + } + + uint16_t end_handle = 0x0000; + for (size_t i = 0; i < response.size(); ++i) { + uint16_t start_handle = get_start_handle(response[i]); + end_handle = get_end_handle(response[i]); + UUID uuid = get_uuid(response[i]); + + if (!characteristic_callback) { + DiscoveredService discovered_service; + discovered_service.setup(uuid, start_handle, end_handle); + service_callback(&discovered_service); + } else { + service_t *discovered_service = new (std::nothrow) service_t( + start_handle, end_handle, uuid + ); + + if (discovered_service == NULL) { + terminate(client); + return; + } + + insert_service(discovered_service); + } + } + + if (end_handle == 0xFFFF) { + start_characteristic_discovery(client); + } else { + ble_error_t err = client->_pal_client->discover_primary_service( + connection_handle, end_handle + 1 + ); + + if (err) { + terminate(client); + } + } + } + + void start_characteristic_discovery(GenericGattClient *client) + { + if (!services_discovered) { + terminate(client); + return; + } + + if (!characteristic_callback) { + terminate(client); + return; + } + + if (service_callback) { + DiscoveredService discovered_service; + discovered_service.setup( + services_discovered->uuid, + services_discovered->begin, + services_discovered->end + ); + service_callback(&discovered_service); + } + + last_characteristic = characteristic_t(); + client->_pal_client->discover_characteristics_of_a_service( + connection_handle, + attribute_handle_range( + services_discovered->begin, + services_discovered->end + ) + ); + } + + void handle_characteristic_discovered(GenericGattClient *client, const AttReadByTypeResponse &response) + { + for (size_t i = 0; i < response.size(); ++i) { + if (last_characteristic.is_valid() == false) { + last_characteristic.set_last_handle(response[i].handle - 1); + if (matching_characteristic_uuid == UUID() + || last_characteristic.getUUID() == matching_characteristic_uuid) { + characteristic_callback(&last_characteristic); + } + } + + last_characteristic = characteristic_t( + client, connection_handle, response[i].handle, response[i].value + ); + } + + // check if all the characteristics of the service has been discovered + if (last_characteristic.getValueHandle() == services_discovered->end) { + handle_all_characteristics_discovered(client); + } else { + ble_error_t err = client->_pal_client->discover_characteristics_of_a_service( + connection_handle, + attribute_handle_range( + last_characteristic.getValueHandle() + 1, + services_discovered->end + ) + ); + + if (err) { + terminate(client); + } + } + } + + void handle_all_characteristics_discovered(GenericGattClient *client) + { + if (last_characteristic.is_valid() == false) { + if (matching_characteristic_uuid == UUID() + || matching_characteristic_uuid == last_characteristic.getUUID()) { + last_characteristic.set_last_handle(services_discovered->end); + characteristic_callback(&last_characteristic); + } + } + + service_t *old = services_discovered; + services_discovered = services_discovered->next; + delete old; + + if (!services_discovered) { + terminate(client); + } else { + start_characteristic_discovery(client); + } + } + + void terminate(GenericGattClient *client) + { + // unknown error, terminate the procedure immediately + client->remove_control_block(this); + Gap::Handle_t handle = connection_handle; + delete this; + client->on_termination(handle); + } + + uint16_t get_start_handle(const AttReadByGroupTypeResponse::attribute_data_t &data) + { + return data.group_range.begin; + } + + uint16_t get_start_handle(const attribute_handle_range_t &range) + { + return range.begin; + } + + uint16_t get_end_handle(const AttReadByGroupTypeResponse::attribute_data_t &data) + { + return data.group_range.end; + } + + uint16_t get_end_handle(const attribute_handle_range_t &range) + { + return range.end; + } + + UUID get_uuid(const AttReadByGroupTypeResponse::attribute_data_t &data) + { + if (data.value.size() == 2) { + return UUID(data.value[0] | data.value[1] << 8); + } else { + return UUID(data.value.data(), UUID::LSB); + } + } + + UUID get_uuid(const attribute_handle_range_t &range) + { + return matching_service_uuid; + } + + struct service_t { + service_t(uint16_t begin, uint16_t end, const UUID &uuid) : + begin(begin), end(end), uuid(uuid), next(NULL) { } + uint16_t begin; + uint16_t end; + UUID uuid; + service_t *next; + }; + + struct characteristic_t : DiscoveredCharacteristic { + characteristic_t() : DiscoveredCharacteristic() + { + lastHandle = 0x0001; + } + + characteristic_t( + GattClient *client, + Gap::Handle_t connection_handle, + uint16_t decl_handle, + const ArrayView value + ) : DiscoveredCharacteristic() + { + gattc = client; + uuid = get_uuid(value); + props = get_properties(value); + declHandle = decl_handle; + valueHandle = get_value_handle(value); + lastHandle = 0x0000; + connHandle = connection_handle; + } + + static UUID get_uuid(const ArrayView &value) + { + if (value.size() == 5) { + return UUID(value[3] | (value[4] << 8)); + } else { + return UUID(value.data() + 3, UUID::LSB); + } + } + + static DiscoveredCharacteristic::Properties_t get_properties(const ArrayView &value) + { + uint8_t raw_properties = value[0]; + DiscoveredCharacteristic::Properties_t result; + result._broadcast = (raw_properties & (1 << 0)) ? true : false; + result._read = (raw_properties & (1 << 1)) ? true : false; + result._writeWoResp = (raw_properties & (1 << 2)) ? true : false; + result._write = (raw_properties & (1 << 3)) ? true : false; + result._notify = (raw_properties & (1 << 4)) ? true : false; + result._indicate = (raw_properties & (1 << 5)) ? true : false; + result._authSignedWrite = (raw_properties & (1 << 6)) ? true : false; + return result; + } + + static uint16_t get_value_handle(const ArrayView &value) + { + return value[1] | (value[2] << 8); + } + + void set_last_handle(uint16_t last_handle) + { + lastHandle = last_handle; + } + + bool is_valid() const + { + return lastHandle != 0x0000; + } + }; + + void insert_service(service_t *service) + { + if (services_discovered == NULL) { + services_discovered = service; + return; + } + + service_t *current = services_discovered; + while (current->next) { + current = current->next; + } + current->next = service; + } + + ServiceDiscovery::ServiceCallback_t service_callback; + ServiceDiscovery::CharacteristicCallback_t characteristic_callback; + UUID matching_service_uuid; + UUID matching_characteristic_uuid; + service_t *services_discovered; + characteristic_t last_characteristic; + bool done; }; struct GenericGattClient::ReadControlBlock : public ProcedureControlBlock { - ReadControlBlock( - Gap::Handle_t connection_handle, uint16_t attribute_handle, uint16_t offset - ) : ProcedureControlBlock(READ_PROCEDURE, connection_handle), - attribute_handle(attribute_handle), - offset(offset), current_offset(offset), data(NULL) { - } - - virtual ~ReadControlBlock() { - if (data != NULL) { - free(data); - } - } - - virtual void handle_timeout_error(GenericGattClient* client) { - GattReadCallbackParams response = { - connection_handle, - attribute_handle, - offset, - 0, // size of 0 - NULL, // no data - BLE_ERROR_UNSPECIFIED, - - }; - terminate(client, response); - } - - virtual void abort(GenericGattClient *client) { - GattReadCallbackParams response = { - connection_handle, - attribute_handle, - offset, - 0, // size of 0 - NULL, // no data - BLE_ERROR_INVALID_STATE, - - }; - terminate(client, response); - } - - void terminate(GenericGattClient* client, const GattReadCallbackParams& response) { - client->remove_control_block(this); - client->processReadResponse(&response); - delete this; - } - - virtual void handle(GenericGattClient* client, const AttServerMessage& message) { - switch(message.opcode) { - case AttributeOpcode::ERROR_RESPONSE: - handle_error(client, static_cast(message)); - break; - - case AttributeOpcode::READ_RESPONSE: - handle_read_response(client, static_cast(message)); - break; - - case AttributeOpcode::READ_BLOB_RESPONSE: - handle_read_response(client, static_cast(message)); - break; - - default: { - // should not happen, terminate the procedure and notify client with an error - // in such case - GattReadCallbackParams response = { - connection_handle, - attribute_handle, - AttErrorResponse::UNLIKELY_ERROR, - 0, // size of 0 - NULL, // no data - BLE_ERROR_UNSPECIFIED, - - }; - terminate(client, response); - } break; - } - } - - template - void handle_read_response(GenericGattClient* client, const ResponseType& read_response) { - uint16_t mtu_size = client->get_mtu(connection_handle); - - // end of responses ? - if ((uint16_t) read_response.size() < (mtu_size - 1)) { - GattReadCallbackParams response = { - connection_handle, - attribute_handle, - offset, - 0, // size of 0 - NULL, // no data - BLE_ERROR_NONE, - }; - - // is it the first response, or is there any other response already - // in the object ? - if (data == NULL) { - response.len = (uint16_t) read_response.size(); - response.data = read_response.data(); - } else { - // copy the data in the existing buffer - memcpy(data + (current_offset - offset), read_response.data(), read_response.size()); - response.len = (current_offset + read_response.size()) - offset; - response.data = data; - } - terminate(client, response); - } else { - // allocation which will contain the response data plus the next one. - data = (uint8_t*) realloc(data, (current_offset - offset) + ((mtu_size - 1) * 2)); - if (data == NULL) { - GattReadCallbackParams response = { - connection_handle, - attribute_handle, - offset, - AttErrorResponse::INSUFFICIENT_RESOURCES, - NULL, - BLE_ERROR_NO_MEM, - }; - terminate(client, response); - return; - } - - memcpy(data + (current_offset - offset), read_response.data(), read_response.size()); - current_offset = current_offset + read_response.size(); - ble_error_t err = client->_pal_client->read_attribute_blob( - connection_handle, - attribute_handle, - current_offset - ); - - if (err) { - GattReadCallbackParams response = { - connection_handle, - attribute_handle, - AttErrorResponse::UNLIKELY_ERROR, - 0, // size of 0 - NULL, // no data - BLE_ERROR_UNSPECIFIED, - - }; - terminate(client, response); - } - } - } - - void handle_error(GenericGattClient* client, const AttErrorResponse& error) { - ble_error_t status = BLE_ERROR_UNSPECIFIED; - - switch (error.error_code) { - case AttErrorResponse::INVALID_HANDLE: - status = BLE_ERROR_INVALID_PARAM; - break; - case AttErrorResponse::INSUFFICIENT_AUTHORIZATION: - status = BLE_ERROR_INVALID_STATE; - break; - case AttErrorResponse::INSUFFICIENT_AUTHENTICATION: - status = BLE_ERROR_INVALID_STATE; - break; - case AttErrorResponse::INSUFFICIENT_ENCRYPTION_KEY_SIZE: - status = BLE_ERROR_INVALID_STATE; - break; - case AttErrorResponse::INSUFFICIENT_ENCRYPTION: - status = BLE_ERROR_INVALID_STATE; - break; - case AttErrorResponse::READ_NOT_PERMITTED: - status = BLE_ERROR_OPERATION_NOT_PERMITTED; - break; - case AttErrorResponse::INVALID_OFFSET: - status = BLE_ERROR_PARAM_OUT_OF_RANGE; - break; - case AttErrorResponse::ATTRIBUTE_NOT_LONG: - status = BLE_ERROR_PARAM_OUT_OF_RANGE; - break; - default: - status = BLE_ERROR_UNSPECIFIED; - break; - } - - GattReadCallbackParams response = { - connection_handle, - attribute_handle, - offset, - error.error_code, - /* data */ NULL, - status - }; - - terminate(client, response); - } - - uint16_t attribute_handle; - uint16_t offset; - uint16_t current_offset; - uint8_t* data; + ReadControlBlock( + Gap::Handle_t connection_handle, uint16_t attribute_handle, uint16_t offset + ) : ProcedureControlBlock(READ_PROCEDURE, connection_handle), + attribute_handle(attribute_handle), + offset(offset), current_offset(offset), data(NULL) + { + } + + virtual ~ReadControlBlock() + { + if (data != NULL) { + free(data); + } + } + + virtual void handle_timeout_error(GenericGattClient *client) + { + GattReadCallbackParams response = { + connection_handle, + attribute_handle, + offset, + 0, // size of 0 + NULL, // no data + BLE_ERROR_UNSPECIFIED, + + }; + terminate(client, response); + } + + virtual void abort(GenericGattClient *client) + { + GattReadCallbackParams response = { + connection_handle, + attribute_handle, + offset, + 0, // size of 0 + NULL, // no data + BLE_ERROR_INVALID_STATE, + + }; + terminate(client, response); + } + + void terminate(GenericGattClient *client, const GattReadCallbackParams &response) + { + client->remove_control_block(this); + client->processReadResponse(&response); + delete this; + } + + virtual void handle(GenericGattClient *client, const AttServerMessage &message) + { + switch (message.opcode) { + case AttributeOpcode::ERROR_RESPONSE: + handle_error(client, static_cast(message)); + break; + + case AttributeOpcode::READ_RESPONSE: + handle_read_response(client, static_cast(message)); + break; + + case AttributeOpcode::READ_BLOB_RESPONSE: + handle_read_response(client, static_cast(message)); + break; + + default: { + // should not happen, terminate the procedure and notify client with an error + // in such case + GattReadCallbackParams response = { + connection_handle, + attribute_handle, + AttErrorResponse::UNLIKELY_ERROR, + 0, // size of 0 + NULL, // no data + BLE_ERROR_UNSPECIFIED, + + }; + terminate(client, response); + } + break; + } + } + + template + void handle_read_response(GenericGattClient *client, const ResponseType &read_response) + { + uint16_t mtu_size = client->get_mtu(connection_handle); + + // end of responses ? + if ((uint16_t) read_response.size() < (mtu_size - 1)) { + GattReadCallbackParams response = { + connection_handle, + attribute_handle, + offset, + 0, // size of 0 + NULL, // no data + BLE_ERROR_NONE, + }; + + // is it the first response, or is there any other response already + // in the object ? + if (data == NULL) { + response.len = (uint16_t) read_response.size(); + response.data = read_response.data(); + } else { + // copy the data in the existing buffer + memcpy(data + (current_offset - offset), read_response.data(), read_response.size()); + response.len = (current_offset + read_response.size()) - offset; + response.data = data; + } + terminate(client, response); + } else { + // allocation which will contain the response data plus the next one. + data = (uint8_t *) realloc(data, (current_offset - offset) + ((mtu_size - 1) * 2)); + if (data == NULL) { + GattReadCallbackParams response = { + connection_handle, + attribute_handle, + offset, + AttErrorResponse::INSUFFICIENT_RESOURCES, + NULL, + BLE_ERROR_NO_MEM, + }; + terminate(client, response); + return; + } + + memcpy(data + (current_offset - offset), read_response.data(), read_response.size()); + current_offset = current_offset + read_response.size(); + ble_error_t err = client->_pal_client->read_attribute_blob( + connection_handle, + attribute_handle, + current_offset + ); + + if (err) { + GattReadCallbackParams response = { + connection_handle, + attribute_handle, + AttErrorResponse::UNLIKELY_ERROR, + 0, // size of 0 + NULL, // no data + BLE_ERROR_UNSPECIFIED, + + }; + terminate(client, response); + } + } + } + + void handle_error(GenericGattClient *client, const AttErrorResponse &error) + { + ble_error_t status = BLE_ERROR_UNSPECIFIED; + + switch (error.error_code) { + case AttErrorResponse::INVALID_HANDLE: + status = BLE_ERROR_INVALID_PARAM; + break; + case AttErrorResponse::INSUFFICIENT_AUTHORIZATION: + status = BLE_ERROR_INVALID_STATE; + break; + case AttErrorResponse::INSUFFICIENT_AUTHENTICATION: + status = BLE_ERROR_INVALID_STATE; + break; + case AttErrorResponse::INSUFFICIENT_ENCRYPTION_KEY_SIZE: + status = BLE_ERROR_INVALID_STATE; + break; + case AttErrorResponse::INSUFFICIENT_ENCRYPTION: + status = BLE_ERROR_INVALID_STATE; + break; + case AttErrorResponse::READ_NOT_PERMITTED: + status = BLE_ERROR_OPERATION_NOT_PERMITTED; + break; + case AttErrorResponse::INVALID_OFFSET: + status = BLE_ERROR_PARAM_OUT_OF_RANGE; + break; + case AttErrorResponse::ATTRIBUTE_NOT_LONG: + status = BLE_ERROR_PARAM_OUT_OF_RANGE; + break; + default: + status = BLE_ERROR_UNSPECIFIED; + break; + } + + GattReadCallbackParams response = { + connection_handle, + attribute_handle, + offset, + error.error_code, + /* data */ NULL, + status + }; + + terminate(client, response); + } + + uint16_t attribute_handle; + uint16_t offset; + uint16_t current_offset; + uint8_t *data; }; /* * Control block for the write process */ struct GenericGattClient::WriteControlBlock : public ProcedureControlBlock { - WriteControlBlock( - Gap::Handle_t connection_handle, uint16_t attribute_handle, - uint8_t* data, uint16_t len - ) : ProcedureControlBlock(WRITE_PROCEDURE, connection_handle), - attribute_handle(attribute_handle), len(len), offset(0), data(data), - prepare_success(false), status(BLE_ERROR_UNSPECIFIED), error_code(0xFF) { - } - - virtual ~WriteControlBlock() { - free(data); - } - - virtual void handle_timeout_error(GenericGattClient* client) { - GattWriteCallbackParams response = { - connection_handle, - attribute_handle, - GattWriteCallbackParams::OP_WRITE_REQ, - BLE_ERROR_UNSPECIFIED, - 0x00 - }; - terminate(client, response); - } - - virtual void abort(GenericGattClient *client) { - GattWriteCallbackParams response = { - connection_handle, - attribute_handle, - GattWriteCallbackParams::OP_WRITE_REQ, - BLE_ERROR_INVALID_STATE, - 0x00 - }; - terminate(client, response); - } - - void terminate(GenericGattClient* client, const GattWriteCallbackParams& response) { - client->remove_control_block(this); - client->processWriteResponse(&response); - delete this; - } - - virtual void handle(GenericGattClient* client, const AttServerMessage& message) { - switch(message.opcode) { - case AttributeOpcode::ERROR_RESPONSE: - handle_error(client, static_cast(message)); - break; - - case AttributeOpcode::WRITE_RESPONSE: - handle_write_response(client, static_cast(message)); - break; - - case AttributeOpcode::PREPARE_WRITE_RESPONSE: - handle_prepare_write_response(client, static_cast(message)); - break; - - case AttributeOpcode::EXECUTE_WRITE_RESPONSE: - handle_execute_write_response(client, static_cast(message)); - break; - - default: { - GattWriteCallbackParams response = { - connection_handle, - attribute_handle, - GattWriteCallbackParams::OP_WRITE_REQ, - BLE_ERROR_UNSPECIFIED, - AttErrorResponse::UNLIKELY_ERROR - }; - - terminate(client, response); - } break; - } - } - - void handle_write_response(GenericGattClient* client, const AttWriteResponse& write_response) { - GattWriteCallbackParams response = { - connection_handle, attribute_handle, - GattWriteCallbackParams::OP_WRITE_REQ, - BLE_ERROR_NONE, 0x00 - }; - - terminate(client, response); - } - - void handle_prepare_write_response(GenericGattClient* client, const AttPrepareWriteResponse& write_response) { - ble_error_t err = BLE_ERROR_UNSPECIFIED; - - uint16_t mtu_size = client->get_mtu(connection_handle); - offset = write_response.offset + write_response.partial_value.size(); - if (offset < len) { - err = client->_pal_client->queue_prepare_write( - connection_handle, attribute_handle, - make_const_ArrayView( - data + offset, - std::min((len - offset), (mtu_size - 5)) - ), - offset - ); - } else { - err = client->_pal_client->execute_write_queue( - connection_handle, true - ); - } - - if (err) { - clear_prepare_queue(client, err, AttErrorResponse::UNLIKELY_ERROR); - } - } - - void handle_execute_write_response(GenericGattClient* client, const AttExecuteWriteResponse& execute_response) { - if (prepare_success) { - status = BLE_ERROR_NONE; - error_code = 0x00; - } - - GattWriteCallbackParams response = { - connection_handle, - attribute_handle, - GattWriteCallbackParams::OP_WRITE_REQ, - status, - error_code - }; - - terminate(client, response); - } - - void clear_prepare_queue(GenericGattClient* client, ble_error_t s, uint8_t e) { - prepare_success = false; - status = s; - error_code = e; - ble_error_t err = client->_pal_client->execute_write_queue( - connection_handle, false - ); - - if (err) { - GattWriteCallbackParams response = { - connection_handle, - attribute_handle, - GattWriteCallbackParams::OP_WRITE_REQ, - err, - AttErrorResponse::UNLIKELY_ERROR - }; - - terminate(client, response); - } - } - - void handle_error(GenericGattClient* client, const AttErrorResponse& error) { - ble_error_t status = BLE_ERROR_UNSPECIFIED; - - switch (error.error_code) { - case AttErrorResponse::INVALID_HANDLE: - status = BLE_ERROR_INVALID_PARAM; - break; - case AttErrorResponse::INVALID_ATTRIBUTE_VALUE_LENGTH: - status = BLE_ERROR_INVALID_PARAM; - break; - case AttErrorResponse::INSUFFICIENT_AUTHORIZATION: - status = BLE_ERROR_INVALID_STATE; - break; - case AttErrorResponse::INSUFFICIENT_AUTHENTICATION: - status = BLE_ERROR_INVALID_STATE; - break; - case AttErrorResponse::INSUFFICIENT_ENCRYPTION_KEY_SIZE: - status = BLE_ERROR_INVALID_STATE; - break; - case AttErrorResponse::INSUFFICIENT_ENCRYPTION: - status = BLE_ERROR_INVALID_STATE; - break; - case AttErrorResponse::WRITE_NOT_PERMITTED: - status = BLE_ERROR_OPERATION_NOT_PERMITTED; - break; - default: - status = BLE_ERROR_UNSPECIFIED; - break; - } - - if (error.request_opcode == AttributeOpcode(AttributeOpcode::PREPARE_WRITE_REQUEST)) { - clear_prepare_queue(client, status, error.error_code); - } else { - GattWriteCallbackParams response = { - connection_handle, - attribute_handle, - GattWriteCallbackParams::OP_WRITE_REQ, - status, - error.error_code - }; - - terminate(client, response); - } - } - - uint16_t attribute_handle; - uint16_t len; - uint16_t offset; - uint8_t* data; - bool prepare_success; - ble_error_t status; - uint8_t error_code; + WriteControlBlock( + Gap::Handle_t connection_handle, uint16_t attribute_handle, + uint8_t *data, uint16_t len + ) : ProcedureControlBlock(WRITE_PROCEDURE, connection_handle), + attribute_handle(attribute_handle), len(len), offset(0), data(data), + prepare_success(false), status(BLE_ERROR_UNSPECIFIED), error_code(0xFF) + { + } + + virtual ~WriteControlBlock() + { + free(data); + } + + virtual void handle_timeout_error(GenericGattClient *client) + { + GattWriteCallbackParams response = { + connection_handle, + attribute_handle, + GattWriteCallbackParams::OP_WRITE_REQ, + BLE_ERROR_UNSPECIFIED, + 0x00 + }; + terminate(client, response); + } + + virtual void abort(GenericGattClient *client) + { + GattWriteCallbackParams response = { + connection_handle, + attribute_handle, + GattWriteCallbackParams::OP_WRITE_REQ, + BLE_ERROR_INVALID_STATE, + 0x00 + }; + terminate(client, response); + } + + void terminate(GenericGattClient *client, const GattWriteCallbackParams &response) + { + client->remove_control_block(this); + client->processWriteResponse(&response); + delete this; + } + + virtual void handle(GenericGattClient *client, const AttServerMessage &message) + { + switch (message.opcode) { + case AttributeOpcode::ERROR_RESPONSE: + handle_error(client, static_cast(message)); + break; + + case AttributeOpcode::WRITE_RESPONSE: + handle_write_response(client, static_cast(message)); + break; + + case AttributeOpcode::PREPARE_WRITE_RESPONSE: + handle_prepare_write_response(client, static_cast(message)); + break; + + case AttributeOpcode::EXECUTE_WRITE_RESPONSE: + handle_execute_write_response(client, static_cast(message)); + break; + + default: { + GattWriteCallbackParams response = { + connection_handle, + attribute_handle, + GattWriteCallbackParams::OP_WRITE_REQ, + BLE_ERROR_UNSPECIFIED, + AttErrorResponse::UNLIKELY_ERROR + }; + + terminate(client, response); + } + break; + } + } + + void handle_write_response(GenericGattClient *client, const AttWriteResponse &write_response) + { + GattWriteCallbackParams response = { + connection_handle, attribute_handle, + GattWriteCallbackParams::OP_WRITE_REQ, + BLE_ERROR_NONE, 0x00 + }; + + terminate(client, response); + } + + void handle_prepare_write_response(GenericGattClient *client, const AttPrepareWriteResponse &write_response) + { + ble_error_t err = BLE_ERROR_UNSPECIFIED; + + uint16_t mtu_size = client->get_mtu(connection_handle); + offset = write_response.offset + write_response.partial_value.size(); + if (offset < len) { + err = client->_pal_client->queue_prepare_write( + connection_handle, attribute_handle, + make_const_ArrayView( + data + offset, + std::min((len - offset), (mtu_size - 5)) + ), + offset + ); + } else { + err = client->_pal_client->execute_write_queue( + connection_handle, true + ); + } + + if (err) { + clear_prepare_queue(client, err, AttErrorResponse::UNLIKELY_ERROR); + } + } + + void handle_execute_write_response(GenericGattClient *client, const AttExecuteWriteResponse &execute_response) + { + if (prepare_success) { + status = BLE_ERROR_NONE; + error_code = 0x00; + } + + GattWriteCallbackParams response = { + connection_handle, + attribute_handle, + GattWriteCallbackParams::OP_WRITE_REQ, + status, + error_code + }; + + terminate(client, response); + } + + void clear_prepare_queue(GenericGattClient *client, ble_error_t s, uint8_t e) + { + prepare_success = false; + status = s; + error_code = e; + ble_error_t err = client->_pal_client->execute_write_queue( + connection_handle, false + ); + + if (err) { + GattWriteCallbackParams response = { + connection_handle, + attribute_handle, + GattWriteCallbackParams::OP_WRITE_REQ, + err, + AttErrorResponse::UNLIKELY_ERROR + }; + + terminate(client, response); + } + } + + void handle_error(GenericGattClient *client, const AttErrorResponse &error) + { + ble_error_t status = BLE_ERROR_UNSPECIFIED; + + switch (error.error_code) { + case AttErrorResponse::INVALID_HANDLE: + status = BLE_ERROR_INVALID_PARAM; + break; + case AttErrorResponse::INVALID_ATTRIBUTE_VALUE_LENGTH: + status = BLE_ERROR_INVALID_PARAM; + break; + case AttErrorResponse::INSUFFICIENT_AUTHORIZATION: + status = BLE_ERROR_INVALID_STATE; + break; + case AttErrorResponse::INSUFFICIENT_AUTHENTICATION: + status = BLE_ERROR_INVALID_STATE; + break; + case AttErrorResponse::INSUFFICIENT_ENCRYPTION_KEY_SIZE: + status = BLE_ERROR_INVALID_STATE; + break; + case AttErrorResponse::INSUFFICIENT_ENCRYPTION: + status = BLE_ERROR_INVALID_STATE; + break; + case AttErrorResponse::WRITE_NOT_PERMITTED: + status = BLE_ERROR_OPERATION_NOT_PERMITTED; + break; + default: + status = BLE_ERROR_UNSPECIFIED; + break; + } + + if (error.request_opcode == AttributeOpcode(AttributeOpcode::PREPARE_WRITE_REQUEST)) { + clear_prepare_queue(client, status, error.error_code); + } else { + GattWriteCallbackParams response = { + connection_handle, + attribute_handle, + GattWriteCallbackParams::OP_WRITE_REQ, + status, + error.error_code + }; + + terminate(client, response); + } + } + + uint16_t attribute_handle; + uint16_t len; + uint16_t offset; + uint8_t *data; + bool prepare_success; + ble_error_t status; + uint8_t error_code; }; /* * Control block for the descriptor discovery process */ struct GenericGattClient::DescriptorDiscoveryControlBlock : public ProcedureControlBlock { - DescriptorDiscoveryControlBlock( - const DiscoveredCharacteristic& characteristic, - const CharacteristicDescriptorDiscovery::DiscoveryCallback_t& discoveryCallback, - const CharacteristicDescriptorDiscovery::TerminationCallback_t& terminationCallback - ) : ProcedureControlBlock(DESCRIPTOR_DISCOVERY_PROCEDURE, characteristic.getConnectionHandle()), - characteristic(characteristic), - discovery_cb(discoveryCallback), - termination_cb(terminationCallback), - next_handle(characteristic.getValueHandle() + 1), - done(false) { - } - - virtual ~DescriptorDiscoveryControlBlock() { } - - ble_error_t start(GenericGattClient* client) { - return client->_pal_client->discover_characteristics_descriptors( - connection_handle, - attribute_handle_range( - next_handle, - characteristic.getLastHandle() - ) - ); - } - - virtual void handle_timeout_error(GenericGattClient* client) { - terminate(client, BLE_ERROR_UNSPECIFIED); - } - - virtual void abort(GenericGattClient *client) { - terminate(client, BLE_ERROR_INVALID_STATE); - } - - virtual void handle(GenericGattClient* client, const AttServerMessage& message) { - if (done) { - terminate(client, BLE_ERROR_NONE); - return; - } - - switch(message.opcode) { - case AttributeOpcode::ERROR_RESPONSE: - handle_error(client, static_cast(message)); - return; - - case AttributeOpcode::FIND_INFORMATION_RESPONSE: - handle_response(client, static_cast(message)); - return; - - default: - break; - } - } - - void handle_error(GenericGattClient* client, const AttErrorResponse& error) { - if (error.error_code == AttErrorResponse::ATTRIBUTE_NOT_FOUND) { - terminate(client, BLE_ERROR_NONE); - } else { - terminate(client, BLE_ERROR_UNSPECIFIED, error.error_code); - } - } - - void handle_response(GenericGattClient* client, const AttFindInformationResponse& response) { - for (size_t i = 0; i < response.size(); ++i) { - DiscoveredCharacteristicDescriptor descriptor( - client, connection_handle, response[i].handle, response[i].uuid - ); - CharacteristicDescriptorDiscovery::DiscoveryCallbackParams_t params = { - characteristic, - descriptor - }; - discovery_cb(¶ms); - if (done) { - terminate(client, BLE_ERROR_NONE); - return; - } - - if (response[i].handle == characteristic.getLastHandle()) { - terminate(client, BLE_ERROR_NONE); - return; - } - next_handle = response[i].handle + 1; - } - - ble_error_t err = start(client); - if (err) { - terminate(client, err, AttErrorResponse::UNLIKELY_ERROR); - } - } - - void terminate(GenericGattClient* client, ble_error_t status, uint8_t error_code = 0x00) { - client->remove_control_block(this); - CharacteristicDescriptorDiscovery::TerminationCallbackParams_t params = { - characteristic, - status, - error_code - }; - termination_cb(¶ms); - delete this; - } - - DiscoveredCharacteristic characteristic; - CharacteristicDescriptorDiscovery::DiscoveryCallback_t discovery_cb; - CharacteristicDescriptorDiscovery::TerminationCallback_t termination_cb; - uint16_t next_handle; - bool done; + DescriptorDiscoveryControlBlock( + const DiscoveredCharacteristic &characteristic, + const CharacteristicDescriptorDiscovery::DiscoveryCallback_t &discoveryCallback, + const CharacteristicDescriptorDiscovery::TerminationCallback_t &terminationCallback + ) : ProcedureControlBlock(DESCRIPTOR_DISCOVERY_PROCEDURE, characteristic.getConnectionHandle()), + characteristic(characteristic), + discovery_cb(discoveryCallback), + termination_cb(terminationCallback), + next_handle(characteristic.getValueHandle() + 1), + done(false) + { + } + + virtual ~DescriptorDiscoveryControlBlock() { } + + ble_error_t start(GenericGattClient *client) + { + return client->_pal_client->discover_characteristics_descriptors( + connection_handle, + attribute_handle_range( + next_handle, + characteristic.getLastHandle() + ) + ); + } + + virtual void handle_timeout_error(GenericGattClient *client) + { + terminate(client, BLE_ERROR_UNSPECIFIED); + } + + virtual void abort(GenericGattClient *client) + { + terminate(client, BLE_ERROR_INVALID_STATE); + } + + virtual void handle(GenericGattClient *client, const AttServerMessage &message) + { + if (done) { + terminate(client, BLE_ERROR_NONE); + return; + } + + switch (message.opcode) { + case AttributeOpcode::ERROR_RESPONSE: + handle_error(client, static_cast(message)); + return; + + case AttributeOpcode::FIND_INFORMATION_RESPONSE: + handle_response(client, static_cast(message)); + return; + + default: + break; + } + } + + void handle_error(GenericGattClient *client, const AttErrorResponse &error) + { + if (error.error_code == AttErrorResponse::ATTRIBUTE_NOT_FOUND) { + terminate(client, BLE_ERROR_NONE); + } else { + terminate(client, BLE_ERROR_UNSPECIFIED, error.error_code); + } + } + + void handle_response(GenericGattClient *client, const AttFindInformationResponse &response) + { + for (size_t i = 0; i < response.size(); ++i) { + DiscoveredCharacteristicDescriptor descriptor( + client, connection_handle, response[i].handle, response[i].uuid + ); + CharacteristicDescriptorDiscovery::DiscoveryCallbackParams_t params = { + characteristic, + descriptor + }; + discovery_cb(¶ms); + if (done) { + terminate(client, BLE_ERROR_NONE); + return; + } + + if (response[i].handle == characteristic.getLastHandle()) { + terminate(client, BLE_ERROR_NONE); + return; + } + next_handle = response[i].handle + 1; + } + + ble_error_t err = start(client); + if (err) { + terminate(client, err, AttErrorResponse::UNLIKELY_ERROR); + } + } + + void terminate(GenericGattClient *client, ble_error_t status, uint8_t error_code = 0x00) + { + client->remove_control_block(this); + CharacteristicDescriptorDiscovery::TerminationCallbackParams_t params = { + characteristic, + status, + error_code + }; + termination_cb(¶ms); + delete this; + } + + DiscoveredCharacteristic characteristic; + CharacteristicDescriptorDiscovery::DiscoveryCallback_t discovery_cb; + CharacteristicDescriptorDiscovery::TerminationCallback_t termination_cb; + uint16_t next_handle; + bool done; }; -GenericGattClient::GenericGattClient(pal::GattClient* pal_client) : - _pal_client(pal_client), - _termination_callback(), - control_blocks(NULL), - _is_reseting(false) { - _pal_client->when_server_message_received( - mbed::callback(this, &GenericGattClient::on_server_message_received) - ); - _pal_client->when_transaction_timeout( - mbed::callback(this, &GenericGattClient::on_transaction_timeout) - ); +GenericGattClient::GenericGattClient(pal::GattClient *pal_client) : + _pal_client(pal_client), + _termination_callback(), + control_blocks(NULL), + _is_reseting(false) +{ + _pal_client->when_server_message_received( + mbed::callback(this, &GenericGattClient::on_server_message_received) + ); + _pal_client->when_transaction_timeout( + mbed::callback(this, &GenericGattClient::on_transaction_timeout) + ); } ble_error_t GenericGattClient::launchServiceDiscovery( - Gap::Handle_t connection_handle, - ServiceDiscovery::ServiceCallback_t service_callback, - ServiceDiscovery::CharacteristicCallback_t characteristic_callback, - const UUID& matching_service_uuid, - const UUID& matching_characteristic_uuid -) { - // verify that there is no other procedures going on this connection - if (_is_reseting || get_control_block(connection_handle)) { - return BLE_ERROR_INVALID_STATE; - } - - // terminate and return if there is no callback to call - if (!service_callback && !characteristic_callback) { - on_termination(connection_handle); - return BLE_ERROR_NONE; - } - - DiscoveryControlBlock* discovery_pcb = new(std::nothrow) DiscoveryControlBlock( - connection_handle, - service_callback, - characteristic_callback, - matching_service_uuid, - matching_characteristic_uuid - ); - - if (discovery_pcb == NULL) { - return BLE_ERROR_NO_MEM; - } - - // note: control block inserted prior the request because they are part of - // of the transaction and the callback can be call synchronously - insert_control_block(discovery_pcb); - - // launch the request - ble_error_t err = BLE_ERROR_UNSPECIFIED; - if (matching_service_uuid == UUID()) { - err = _pal_client->discover_primary_service( - connection_handle, - 0x0001 - ); - } else { - err = _pal_client->discover_primary_service_by_service_uuid( - connection_handle, - 0x0001, - matching_service_uuid - ); - } - - if (err) { - remove_control_block(discovery_pcb); - delete discovery_pcb; - } - - return err; + Gap::Handle_t connection_handle, + ServiceDiscovery::ServiceCallback_t service_callback, + ServiceDiscovery::CharacteristicCallback_t characteristic_callback, + const UUID &matching_service_uuid, + const UUID &matching_characteristic_uuid +) +{ + // verify that there is no other procedures going on this connection + if (_is_reseting || get_control_block(connection_handle)) { + return BLE_ERROR_INVALID_STATE; + } + + // terminate and return if there is no callback to call + if (!service_callback && !characteristic_callback) { + on_termination(connection_handle); + return BLE_ERROR_NONE; + } + + DiscoveryControlBlock *discovery_pcb = new (std::nothrow) DiscoveryControlBlock( + connection_handle, + service_callback, + characteristic_callback, + matching_service_uuid, + matching_characteristic_uuid + ); + + if (discovery_pcb == NULL) { + return BLE_ERROR_NO_MEM; + } + + // note: control block inserted prior the request because they are part of + // of the transaction and the callback can be call synchronously + insert_control_block(discovery_pcb); + + // launch the request + ble_error_t err = BLE_ERROR_UNSPECIFIED; + if (matching_service_uuid == UUID()) { + err = _pal_client->discover_primary_service( + connection_handle, + 0x0001 + ); + } else { + err = _pal_client->discover_primary_service_by_service_uuid( + connection_handle, + 0x0001, + matching_service_uuid + ); + } + + if (err) { + remove_control_block(discovery_pcb); + delete discovery_pcb; + } + + return err; } -bool GenericGattClient::isServiceDiscoveryActive() const { - ProcedureControlBlock* pcb = control_blocks; +bool GenericGattClient::isServiceDiscoveryActive() const +{ + ProcedureControlBlock *pcb = control_blocks; - while (pcb) { - if (pcb->type == COMPLETE_DISCOVERY_PROCEDURE) { - return true; - } - pcb = pcb->next; - } + while (pcb) { + if (pcb->type == COMPLETE_DISCOVERY_PROCEDURE) { + return true; + } + pcb = pcb->next; + } - return false; + return false; } void GenericGattClient::terminateServiceDiscovery() { - ProcedureControlBlock* pcb = control_blocks; - while (pcb) { - if (pcb->type == COMPLETE_DISCOVERY_PROCEDURE) { - static_cast(pcb)->done = true; - } - pcb = pcb->next; - } + ProcedureControlBlock *pcb = control_blocks; + while (pcb) { + if (pcb->type == COMPLETE_DISCOVERY_PROCEDURE) { + static_cast(pcb)->done = true; + } + pcb = pcb->next; + } } ble_error_t GenericGattClient::read( - Gap::Handle_t connection_handle, - GattAttribute::Handle_t attribute_handle, - uint16_t offset) const + Gap::Handle_t connection_handle, + GattAttribute::Handle_t attribute_handle, + uint16_t offset) const { - // verify that there is no other procedures going on this connection - if (_is_reseting || get_control_block(connection_handle)) { - return BLE_ERROR_INVALID_STATE; - } - - ReadControlBlock* read_pcb = new(std::nothrow) ReadControlBlock( - connection_handle, - attribute_handle, - offset - ); - - if (read_pcb == NULL) { - return BLE_ERROR_NO_MEM; - } - - insert_control_block(read_pcb); - - ble_error_t err = BLE_ERROR_NONE; - - if (offset == 0) { - err = _pal_client->read_attribute_value( - connection_handle, attribute_handle - ); - } else { - err = _pal_client->read_attribute_blob( - connection_handle, attribute_handle, offset - ); - } - - if (err) { - remove_control_block(read_pcb); - delete read_pcb; - } - - return err; + // verify that there is no other procedures going on this connection + if (_is_reseting || get_control_block(connection_handle)) { + return BLE_ERROR_INVALID_STATE; + } + + ReadControlBlock *read_pcb = new (std::nothrow) ReadControlBlock( + connection_handle, + attribute_handle, + offset + ); + + if (read_pcb == NULL) { + return BLE_ERROR_NO_MEM; + } + + insert_control_block(read_pcb); + + ble_error_t err = BLE_ERROR_NONE; + + if (offset == 0) { + err = _pal_client->read_attribute_value( + connection_handle, attribute_handle + ); + } else { + err = _pal_client->read_attribute_blob( + connection_handle, attribute_handle, offset + ); + } + + if (err) { + remove_control_block(read_pcb); + delete read_pcb; + } + + return err; } ble_error_t GenericGattClient::write( - GattClient::WriteOp_t cmd, - Gap::Handle_t connection_handle, - GattAttribute::Handle_t attribute_handle, - size_t length, - const uint8_t* value -) const { - // verify that there is no other procedures going on this connection - if (_is_reseting || get_control_block(connection_handle)) { - return BLE_ERROR_INVALID_STATE; - } - - uint16_t mtu = get_mtu(connection_handle); - - if (cmd == GattClient::GATT_OP_WRITE_CMD) { - if (length > (uint16_t)(mtu - 3)) { - return BLE_ERROR_PARAM_OUT_OF_RANGE; - } - return _pal_client->write_without_response( - connection_handle, - attribute_handle, - make_const_ArrayView(value, length) - ); - } else { - uint8_t* data = NULL; - - if (length > (uint16_t)(mtu - 3)) { - data = (uint8_t*) malloc(length); - if (data == NULL) { - return BLE_ERROR_NO_MEM; - } - memcpy(data, value, length); - } - - WriteControlBlock* write_pcb = new(std::nothrow) WriteControlBlock( - connection_handle, - attribute_handle, - data, - length - ); - - if (write_pcb == NULL) { - free(data); - return BLE_ERROR_NO_MEM; - } - - insert_control_block(write_pcb); - - ble_error_t err = BLE_ERROR_UNSPECIFIED; - if (data) { - err = _pal_client->queue_prepare_write( - connection_handle, - attribute_handle, - make_const_ArrayView(value, mtu - 5), - /* offset */ 0 - ); - } else { - err = _pal_client->write_attribute( - connection_handle, - attribute_handle, - make_const_ArrayView(value, length) - ); - } - - if (err) { - remove_control_block(write_pcb); - delete write_pcb; - } - - return err; - } - - return BLE_ERROR_NOT_IMPLEMENTED; + GattClient::WriteOp_t cmd, + Gap::Handle_t connection_handle, + GattAttribute::Handle_t attribute_handle, + size_t length, + const uint8_t *value +) const +{ + // verify that there is no other procedures going on this connection + if (_is_reseting || get_control_block(connection_handle)) { + return BLE_ERROR_INVALID_STATE; + } + + uint16_t mtu = get_mtu(connection_handle); + + if (cmd == GattClient::GATT_OP_WRITE_CMD) { + if (length > (uint16_t)(mtu - 3)) { + return BLE_ERROR_PARAM_OUT_OF_RANGE; + } + return _pal_client->write_without_response( + connection_handle, + attribute_handle, + make_const_ArrayView(value, length) + ); + } else { + uint8_t *data = NULL; + + if (length > (uint16_t)(mtu - 3)) { + data = (uint8_t *) malloc(length); + if (data == NULL) { + return BLE_ERROR_NO_MEM; + } + memcpy(data, value, length); + } + + WriteControlBlock *write_pcb = new (std::nothrow) WriteControlBlock( + connection_handle, + attribute_handle, + data, + length + ); + + if (write_pcb == NULL) { + free(data); + return BLE_ERROR_NO_MEM; + } + + insert_control_block(write_pcb); + + ble_error_t err = BLE_ERROR_UNSPECIFIED; + if (data) { + err = _pal_client->queue_prepare_write( + connection_handle, + attribute_handle, + make_const_ArrayView(value, mtu - 5), + /* offset */ 0 + ); + } else { + err = _pal_client->write_attribute( + connection_handle, + attribute_handle, + make_const_ArrayView(value, length) + ); + } + + if (err) { + remove_control_block(write_pcb); + delete write_pcb; + } + + return err; + } + + return BLE_ERROR_NOT_IMPLEMENTED; } void GenericGattClient::onServiceDiscoveryTermination( - ServiceDiscovery::TerminationCallback_t callback -) { - _termination_callback = callback; + ServiceDiscovery::TerminationCallback_t callback +) +{ + _termination_callback = callback; } ble_error_t GenericGattClient::discoverCharacteristicDescriptors( - const DiscoveredCharacteristic& characteristic, - const CharacteristicDescriptorDiscovery::DiscoveryCallback_t& discoveryCallback, - const CharacteristicDescriptorDiscovery::TerminationCallback_t& terminationCallback -) { - // verify that there is no other procedures going on this connection - if (_is_reseting || get_control_block(characteristic.getConnectionHandle())) { - return BLE_ERROR_INVALID_STATE; - } - - if (characteristic.getValueHandle() == characteristic.getLastHandle()) { - CharacteristicDescriptorDiscovery::TerminationCallbackParams_t params = { - characteristic, - BLE_ERROR_NONE, - /* error code */ 0x00 - }; - - terminationCallback(¶ms); - return BLE_ERROR_NONE; - } - - DescriptorDiscoveryControlBlock* discovery_pcb = - new(std::nothrow) DescriptorDiscoveryControlBlock( - characteristic, - discoveryCallback, - terminationCallback - ); - - if (discovery_pcb == NULL) { - return BLE_ERROR_NO_MEM; - } - - insert_control_block(discovery_pcb); - - ble_error_t err = discovery_pcb->start(this); - - if (err) { - remove_control_block(discovery_pcb); - delete discovery_pcb; - } - - return err; + const DiscoveredCharacteristic &characteristic, + const CharacteristicDescriptorDiscovery::DiscoveryCallback_t &discoveryCallback, + const CharacteristicDescriptorDiscovery::TerminationCallback_t &terminationCallback +) +{ + // verify that there is no other procedures going on this connection + if (_is_reseting || get_control_block(characteristic.getConnectionHandle())) { + return BLE_ERROR_INVALID_STATE; + } + + if (characteristic.getValueHandle() == characteristic.getLastHandle()) { + CharacteristicDescriptorDiscovery::TerminationCallbackParams_t params = { + characteristic, + BLE_ERROR_NONE, + /* error code */ 0x00 + }; + + terminationCallback(¶ms); + return BLE_ERROR_NONE; + } + + DescriptorDiscoveryControlBlock *discovery_pcb = + new (std::nothrow) DescriptorDiscoveryControlBlock( + characteristic, + discoveryCallback, + terminationCallback + ); + + if (discovery_pcb == NULL) { + return BLE_ERROR_NO_MEM; + } + + insert_control_block(discovery_pcb); + + ble_error_t err = discovery_pcb->start(this); + + if (err) { + remove_control_block(discovery_pcb); + delete discovery_pcb; + } + + return err; } bool GenericGattClient::isCharacteristicDescriptorDiscoveryActive( - const DiscoveredCharacteristic& characteristic -) const { - ProcedureControlBlock* pcb = control_blocks; - - while (pcb) { - if (pcb->type == DESCRIPTOR_DISCOVERY_PROCEDURE && - static_cast(pcb)->characteristic == characteristic) { - return true; - } - pcb = pcb->next; - } - - return false; + const DiscoveredCharacteristic &characteristic +) const +{ + ProcedureControlBlock *pcb = control_blocks; + + while (pcb) { + if (pcb->type == DESCRIPTOR_DISCOVERY_PROCEDURE && + static_cast(pcb)->characteristic == characteristic) { + return true; + } + pcb = pcb->next; + } + + return false; } void GenericGattClient::terminateCharacteristicDescriptorDiscovery( - const DiscoveredCharacteristic& characteristic -) { - ProcedureControlBlock* pcb = control_blocks; - - while (pcb) { - if (pcb->type == DESCRIPTOR_DISCOVERY_PROCEDURE) { - DescriptorDiscoveryControlBlock* dpcb = - static_cast(pcb); - if (dpcb->characteristic == characteristic) { - dpcb->done = true; - return; - } - } - - pcb = pcb->next; - } + const DiscoveredCharacteristic &characteristic +) +{ + ProcedureControlBlock *pcb = control_blocks; + + while (pcb) { + if (pcb->type == DESCRIPTOR_DISCOVERY_PROCEDURE) { + DescriptorDiscoveryControlBlock *dpcb = + static_cast(pcb); + if (dpcb->characteristic == characteristic) { + dpcb->done = true; + return; + } + } + + pcb = pcb->next; + } } -ble_error_t GenericGattClient::reset(void) { +ble_error_t GenericGattClient::reset(void) +{ - // _is_reseting prevent executions of new procedure while the instance resets. - // otherwise new procedures can be launched from callbacks generated by the - // reset. - _is_reseting = true; - while (control_blocks) { - control_blocks->abort(this); - } - _is_reseting = false; + // _is_reseting prevent executions of new procedure while the instance resets. + // otherwise new procedures can be launched from callbacks generated by the + // reset. + _is_reseting = true; + while (control_blocks) { + control_blocks->abort(this); + } + _is_reseting = false; - return BLE_ERROR_NONE; + return BLE_ERROR_NONE; } -void GenericGattClient::on_termination(Gap::Handle_t connection_handle) { - if (_termination_callback) { - _termination_callback(connection_handle); - } +void GenericGattClient::on_termination(Gap::Handle_t connection_handle) +{ + if (_termination_callback) { + _termination_callback(connection_handle); + } } void GenericGattClient::on_server_message_received( - connection_handle_t connection_handle, - const AttServerMessage& message -) { - switch(message.opcode) { - case AttributeOpcode::ERROR_RESPONSE: - case AttributeOpcode::EXCHANGE_MTU_RESPONSE: - case AttributeOpcode::FIND_INFORMATION_RESPONSE: - case AttributeOpcode::FIND_BY_VALUE_TYPE_RESPONSE: - case AttributeOpcode::READ_BY_TYPE_RESPONSE: - case AttributeOpcode::READ_RESPONSE: - case AttributeOpcode::READ_BLOB_RESPONSE: - case AttributeOpcode::READ_MULTIPLE_RESPONSE: - case AttributeOpcode::READ_BY_GROUP_TYPE_RESPONSE: - case AttributeOpcode::WRITE_RESPONSE: - case AttributeOpcode::PREPARE_WRITE_RESPONSE: - case AttributeOpcode::EXECUTE_WRITE_RESPONSE: { - on_server_response(connection_handle, message); - } break; - - case AttributeOpcode::HANDLE_VALUE_INDICATION: - case AttributeOpcode::HANDLE_VALUE_NOTIFICATION: { - on_server_event(connection_handle, message); - } break; - - default: - // invalid message receive - return; - } + connection_handle_t connection_handle, + const AttServerMessage &message +) +{ + switch (message.opcode) { + case AttributeOpcode::ERROR_RESPONSE: + case AttributeOpcode::EXCHANGE_MTU_RESPONSE: + case AttributeOpcode::FIND_INFORMATION_RESPONSE: + case AttributeOpcode::FIND_BY_VALUE_TYPE_RESPONSE: + case AttributeOpcode::READ_BY_TYPE_RESPONSE: + case AttributeOpcode::READ_RESPONSE: + case AttributeOpcode::READ_BLOB_RESPONSE: + case AttributeOpcode::READ_MULTIPLE_RESPONSE: + case AttributeOpcode::READ_BY_GROUP_TYPE_RESPONSE: + case AttributeOpcode::WRITE_RESPONSE: + case AttributeOpcode::PREPARE_WRITE_RESPONSE: + case AttributeOpcode::EXECUTE_WRITE_RESPONSE: { + on_server_response(connection_handle, message); + } + break; + + case AttributeOpcode::HANDLE_VALUE_INDICATION: + case AttributeOpcode::HANDLE_VALUE_NOTIFICATION: { + on_server_event(connection_handle, message); + } + break; + + default: + // invalid message receive + return; + } } void GenericGattClient::on_server_response( - connection_handle_t connection, - const AttServerMessage& message -) { - ProcedureControlBlock* pcb = get_control_block(connection); - if (pcb == NULL) { - return; - } - - pcb->handle(this, message); + connection_handle_t connection, + const AttServerMessage &message +) +{ + ProcedureControlBlock *pcb = get_control_block(connection); + if (pcb == NULL) { + return; + } + + pcb->handle(this, message); } -void GenericGattClient::on_server_event(connection_handle_t connection, const AttServerMessage& message) { - GattHVXCallbackParams callbacks_params = { - (Gap::Handle_t) connection, 0 - }; - - switch (message.opcode) { - case AttributeOpcode::HANDLE_VALUE_NOTIFICATION: { - const AttHandleValueNotification& notification = - static_cast(message); - callbacks_params.handle = notification.attribute_handle; - callbacks_params.type = BLE_HVX_NOTIFICATION; - callbacks_params.len = notification.attribute_value.size(); - callbacks_params.data = notification.attribute_value.data(); - } break; - - case AttributeOpcode::HANDLE_VALUE_INDICATION: { - const AttHandleValueIndication& indication = - static_cast(message); - callbacks_params.handle = indication.attribute_handle; - callbacks_params.type = BLE_HVX_INDICATION; - callbacks_params.len = indication.attribute_value.size(); - callbacks_params.data = indication.attribute_value.data(); - } break; - - default: - return; - } - - processHVXEvent(&callbacks_params); +void GenericGattClient::on_server_event(connection_handle_t connection, const AttServerMessage &message) +{ + GattHVXCallbackParams callbacks_params = { + (Gap::Handle_t) connection, 0 + }; + + switch (message.opcode) { + case AttributeOpcode::HANDLE_VALUE_NOTIFICATION: { + const AttHandleValueNotification ¬ification = + static_cast(message); + callbacks_params.handle = notification.attribute_handle; + callbacks_params.type = BLE_HVX_NOTIFICATION; + callbacks_params.len = notification.attribute_value.size(); + callbacks_params.data = notification.attribute_value.data(); + } + break; + + case AttributeOpcode::HANDLE_VALUE_INDICATION: { + const AttHandleValueIndication &indication = + static_cast(message); + callbacks_params.handle = indication.attribute_handle; + callbacks_params.type = BLE_HVX_INDICATION; + callbacks_params.len = indication.attribute_value.size(); + callbacks_params.data = indication.attribute_value.data(); + } + break; + + default: + return; + } + + processHVXEvent(&callbacks_params); } -void GenericGattClient::on_transaction_timeout(connection_handle_t connection) { - ProcedureControlBlock* pcb = get_control_block(connection); - if (pcb == NULL) { - return; - } +void GenericGattClient::on_transaction_timeout(connection_handle_t connection) +{ + ProcedureControlBlock *pcb = get_control_block(connection); + if (pcb == NULL) { + return; + } - pcb->handle_timeout_error(this); + pcb->handle_timeout_error(this); } -GenericGattClient::ProcedureControlBlock* GenericGattClient::get_control_block(Gap::Handle_t connection) { - ProcedureControlBlock* it = control_blocks; - while (it && it->connection_handle != connection) { - it = it->next; - } - return it; +GenericGattClient::ProcedureControlBlock *GenericGattClient::get_control_block(Gap::Handle_t connection) +{ + ProcedureControlBlock *it = control_blocks; + while (it && it->connection_handle != connection) { + it = it->next; + } + return it; } -const GenericGattClient::ProcedureControlBlock* GenericGattClient::get_control_block(Gap::Handle_t connection) const { - ProcedureControlBlock* it = control_blocks; - while (it && it->connection_handle != connection) { - it = it->next; - } - return it; +const GenericGattClient::ProcedureControlBlock *GenericGattClient::get_control_block(Gap::Handle_t connection) const +{ + ProcedureControlBlock *it = control_blocks; + while (it && it->connection_handle != connection) { + it = it->next; + } + return it; } -void GenericGattClient::insert_control_block(ProcedureControlBlock* cb) const { - if (control_blocks == NULL) { - control_blocks = cb; - return; - } - - ProcedureControlBlock* current = control_blocks; - while (current->next) { - current = current->next; - } - current->next = cb; +void GenericGattClient::insert_control_block(ProcedureControlBlock *cb) const +{ + if (control_blocks == NULL) { + control_blocks = cb; + return; + } + + ProcedureControlBlock *current = control_blocks; + while (current->next) { + current = current->next; + } + current->next = cb; } -void GenericGattClient::remove_control_block(ProcedureControlBlock* cb) const { - if (control_blocks == NULL) { - return; - } - - if (cb == control_blocks) { - control_blocks = control_blocks->next; - return; - } - - ProcedureControlBlock* current = control_blocks; - while (current->next && current->next != cb) { - current = current->next; - } - - if (current->next == NULL) { - return; - } - - current->next = cb->next; - cb->next = NULL; +void GenericGattClient::remove_control_block(ProcedureControlBlock *cb) const +{ + if (control_blocks == NULL) { + return; + } + + if (cb == control_blocks) { + control_blocks = control_blocks->next; + return; + } + + ProcedureControlBlock *current = control_blocks; + while (current->next && current->next != cb) { + current = current->next; + } + + if (current->next == NULL) { + return; + } + + current->next = cb->next; + cb->next = NULL; } -uint16_t GenericGattClient::get_mtu(Gap::Handle_t connection) const { - uint16_t result = 23; - if(_pal_client->get_mtu_size((connection_handle_t) connection, result) != BLE_ERROR_NONE) { - result = 23; - } - return result; +uint16_t GenericGattClient::get_mtu(Gap::Handle_t connection) const +{ + uint16_t result = 23; + if (_pal_client->get_mtu_size((connection_handle_t) connection, result) != BLE_ERROR_NONE) { + result = 23; + } + return result; } } // namespace pal diff --git a/features/FEATURE_BLE/source/generic/GenericSecurityManager.cpp b/features/FEATURE_BLE/source/generic/GenericSecurityManager.cpp index 1568f11fb2b..f47e07432f8 100644 --- a/features/FEATURE_BLE/source/generic/GenericSecurityManager.cpp +++ b/features/FEATURE_BLE/source/generic/GenericSecurityManager.cpp @@ -41,7 +41,8 @@ ble_error_t GenericSecurityManager::init( SecurityIOCapabilities_t iocaps, const Passkey_t passkey, bool signing -) { +) +{ _db.restore(); _pal.set_io_capability((io_capability_t::type) iocaps); @@ -76,7 +77,8 @@ ble_error_t GenericSecurityManager::init( return BLE_ERROR_NONE; } -ble_error_t GenericSecurityManager::reset(void) { +ble_error_t GenericSecurityManager::reset(void) +{ _db.sync(); _public_keys_generated = false; SecurityManager::reset(); @@ -84,7 +86,8 @@ ble_error_t GenericSecurityManager::reset(void) { return BLE_ERROR_NONE; } -ble_error_t GenericSecurityManager::preserveBondingStateOnReset(bool enabled) { +ble_error_t GenericSecurityManager::preserveBondingStateOnReset(bool enabled) +{ _db.set_restore(enabled); return BLE_ERROR_NONE; } @@ -93,12 +96,14 @@ ble_error_t GenericSecurityManager::preserveBondingStateOnReset(bool enabled) { // List management // -ble_error_t GenericSecurityManager::purgeAllBondingState(void) { +ble_error_t GenericSecurityManager::purgeAllBondingState(void) +{ _db.clear_entries(); return BLE_ERROR_NONE; } -ble_error_t GenericSecurityManager::generateWhitelistFromBondTable(Gap::Whitelist_t *whitelist) const { +ble_error_t GenericSecurityManager::generateWhitelistFromBondTable(Gap::Whitelist_t *whitelist) const +{ if (eventHandler) { _db.generate_whitelist_from_bond_table( mbed::callback(eventHandler, &::SecurityManager::EventHandler::whitelistFromBondTable), @@ -112,7 +117,8 @@ ble_error_t GenericSecurityManager::generateWhitelistFromBondTable(Gap::Whitelis // Pairing // -ble_error_t GenericSecurityManager::requestPairing(connection_handle_t connection) { +ble_error_t GenericSecurityManager::requestPairing(connection_handle_t connection) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return BLE_ERROR_INVALID_PARAM; @@ -157,15 +163,16 @@ ble_error_t GenericSecurityManager::requestPairing(connection_handle_t connectio } return _pal.send_pairing_request( - connection, - cb->oob_present, - link_authentication, - initiator_distribution, - responder_distribution - ); + connection, + cb->oob_present, + link_authentication, + initiator_distribution, + responder_distribution + ); } -ble_error_t GenericSecurityManager::acceptPairingRequest(connection_handle_t connection) { +ble_error_t GenericSecurityManager::acceptPairingRequest(connection_handle_t connection) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return BLE_ERROR_INVALID_PARAM; @@ -205,19 +212,21 @@ ble_error_t GenericSecurityManager::acceptPairingRequest(connection_handle_t con } return _pal.send_pairing_response( - connection, - cb->oob_present, - link_authentication, - initiator_distribution, - responder_distribution - ); + connection, + cb->oob_present, + link_authentication, + initiator_distribution, + responder_distribution + ); } -ble_error_t GenericSecurityManager::cancelPairingRequest(connection_handle_t connection) { +ble_error_t GenericSecurityManager::cancelPairingRequest(connection_handle_t connection) +{ return _pal.cancel_pairing(connection, pairing_failure_t::UNSPECIFIED_REASON); } -ble_error_t GenericSecurityManager::setPairingRequestAuthorisation(bool required) { +ble_error_t GenericSecurityManager::setPairingRequestAuthorisation(bool required) +{ _pairing_authorisation_required = required; return BLE_ERROR_NONE; } @@ -226,12 +235,14 @@ ble_error_t GenericSecurityManager::setPairingRequestAuthorisation(bool required // Feature support // -ble_error_t GenericSecurityManager::allowLegacyPairing(bool allow) { +ble_error_t GenericSecurityManager::allowLegacyPairing(bool allow) +{ _legacy_pairing_allowed = allow; return BLE_ERROR_NONE; } -ble_error_t GenericSecurityManager::getSecureConnectionsSupport(bool *enabled) { +ble_error_t GenericSecurityManager::getSecureConnectionsSupport(bool *enabled) +{ return _pal.get_secure_connections_support(*enabled); } @@ -239,25 +250,29 @@ ble_error_t GenericSecurityManager::getSecureConnectionsSupport(bool *enabled) { // Security settings // -ble_error_t GenericSecurityManager::setIoCapability(SecurityIOCapabilities_t iocaps) { +ble_error_t GenericSecurityManager::setIoCapability(SecurityIOCapabilities_t iocaps) +{ return _pal.set_io_capability((io_capability_t::type) iocaps); } -ble_error_t GenericSecurityManager::setDisplayPasskey(const Passkey_t passkey) { +ble_error_t GenericSecurityManager::setDisplayPasskey(const Passkey_t passkey) +{ return _pal.set_display_passkey(PasskeyAscii::to_num(passkey)); } ble_error_t GenericSecurityManager::setAuthenticationTimeout( connection_handle_t connection, uint32_t timeout_in_ms -) { +) +{ return _pal.set_authentication_timeout(connection, timeout_in_ms / 10); } ble_error_t GenericSecurityManager::getAuthenticationTimeout( connection_handle_t connection, uint32_t *timeout_in_ms -) { +) +{ uint16_t timeout_in_10ms; ble_error_t status = _pal.get_authentication_timeout(connection, timeout_in_10ms); *timeout_in_ms = 10 * timeout_in_10ms; @@ -267,7 +282,8 @@ ble_error_t GenericSecurityManager::getAuthenticationTimeout( ble_error_t GenericSecurityManager::setLinkSecurity( connection_handle_t connection, SecurityMode_t securityMode -) { +) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return BLE_ERROR_INVALID_PARAM; @@ -298,7 +314,8 @@ ble_error_t GenericSecurityManager::setLinkSecurity( } } -ble_error_t GenericSecurityManager::setKeypressNotification(bool enabled) { +ble_error_t GenericSecurityManager::setKeypressNotification(bool enabled) +{ _default_authentication.set_keypress_notification(enabled); return BLE_ERROR_NONE; } @@ -306,7 +323,8 @@ ble_error_t GenericSecurityManager::setKeypressNotification(bool enabled) { ble_error_t GenericSecurityManager::enableSigning( connection_handle_t connection, bool enabled -) { +) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return BLE_ERROR_INVALID_PARAM; @@ -330,7 +348,8 @@ ble_error_t GenericSecurityManager::enableSigning( return BLE_ERROR_NONE; } -ble_error_t GenericSecurityManager::setHintFutureRoleReversal(bool enable) { +ble_error_t GenericSecurityManager::setHintFutureRoleReversal(bool enable) +{ _master_sends_keys = enable; return BLE_ERROR_NONE; } @@ -342,7 +361,8 @@ ble_error_t GenericSecurityManager::setHintFutureRoleReversal(bool enable) { ble_error_t GenericSecurityManager::getLinkEncryption( connection_handle_t connection, link_encryption_t *encryption -) { +) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { @@ -367,7 +387,8 @@ ble_error_t GenericSecurityManager::getLinkEncryption( ble_error_t GenericSecurityManager::setLinkEncryption( connection_handle_t connection, link_encryption_t encryption -) { +) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return BLE_ERROR_INVALID_PARAM; @@ -418,7 +439,8 @@ ble_error_t GenericSecurityManager::setLinkEncryption( ble_error_t GenericSecurityManager::getEncryptionKeySize( connection_handle_t connection, uint8_t *size -) { +) +{ ControlBlock_t *cb = get_control_block(connection); if (cb) { *size = cb->encryption_key_size; @@ -431,7 +453,8 @@ ble_error_t GenericSecurityManager::getEncryptionKeySize( ble_error_t GenericSecurityManager::setEncryptionKeyRequirements( uint8_t minimumByteSize, uint8_t maximumByteSize -) { +) +{ return _pal.set_encryption_key_requirements(minimumByteSize, maximumByteSize); } @@ -439,7 +462,8 @@ ble_error_t GenericSecurityManager::setEncryptionKeyRequirements( // Keys // -ble_error_t GenericSecurityManager::getSigningKey(connection_handle_t connection, bool authenticated) { +ble_error_t GenericSecurityManager::getSigningKey(connection_handle_t connection, bool authenticated) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return BLE_ERROR_INVALID_PARAM; @@ -471,15 +495,17 @@ ble_error_t GenericSecurityManager::getSigningKey(connection_handle_t connection // Privacy // -ble_error_t GenericSecurityManager::setPrivateAddressTimeout(uint16_t timeout_in_seconds) { - return _pal.set_private_address_timeout(timeout_in_seconds); +ble_error_t GenericSecurityManager::setPrivateAddressTimeout(uint16_t timeout_in_seconds) +{ + return _pal.set_private_address_timeout(timeout_in_seconds); } //////////////////////////////////////////////////////////////////////////// // Authentication // -ble_error_t GenericSecurityManager::requestAuthentication(connection_handle_t connection) { +ble_error_t GenericSecurityManager::requestAuthentication(connection_handle_t connection) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return BLE_ERROR_INVALID_PARAM; @@ -510,7 +536,8 @@ ble_error_t GenericSecurityManager::setOOBDataUsage( connection_handle_t connection, bool useOOB, bool OOBProvidesMITM -) { +) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return BLE_ERROR_INVALID_PARAM; @@ -531,31 +558,35 @@ ble_error_t GenericSecurityManager::setOOBDataUsage( ble_error_t GenericSecurityManager::confirmationEntered( connection_handle_t connection, bool confirmation -) { +) +{ return _pal.confirmation_entered(connection, confirmation); } ble_error_t GenericSecurityManager::passkeyEntered( connection_handle_t connection, Passkey_t passkey -) { +) +{ return _pal.passkey_request_reply( - connection, - PasskeyAscii::to_num(passkey) - ); + connection, + PasskeyAscii::to_num(passkey) + ); } ble_error_t GenericSecurityManager::sendKeypressNotification( connection_handle_t connection, Keypress_t keypress -) { +) +{ return _pal.send_keypress_notification(connection, keypress); } ble_error_t GenericSecurityManager::legacyPairingOobReceived( const address_t *address, const oob_tk_t *tk -) { +) +{ if (address && tk) { ControlBlock_t *cb = get_control_block(*address); if (!cb) { @@ -571,7 +602,8 @@ ble_error_t GenericSecurityManager::oobReceived( const address_t *address, const oob_lesc_value_t *random, const oob_confirm_t *confirm -) { +) +{ if (address && random && confirm) { _peer_sc_oob_address = *address; _peer_sc_oob_random = *random; @@ -586,7 +618,8 @@ ble_error_t GenericSecurityManager::oobReceived( // Helper functions // -ble_error_t GenericSecurityManager::init_signing() { +ble_error_t GenericSecurityManager::init_signing() +{ const csrk_t *pcsrk = _db.get_local_csrk(); if (!pcsrk) { csrk_t csrk; @@ -602,7 +635,8 @@ ble_error_t GenericSecurityManager::init_signing() { return _pal.set_csrk(*pcsrk); } -ble_error_t GenericSecurityManager::get_random_data(uint8_t *buffer, size_t size) { +ble_error_t GenericSecurityManager::get_random_data(uint8_t *buffer, size_t size) +{ byte_array_t<8> random_data; while (size) { @@ -621,7 +655,8 @@ ble_error_t GenericSecurityManager::get_random_data(uint8_t *buffer, size_t size return BLE_ERROR_NONE; } -ble_error_t GenericSecurityManager::slave_security_request(connection_handle_t connection) { +ble_error_t GenericSecurityManager::slave_security_request(connection_handle_t connection) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return BLE_ERROR_INVALID_PARAM; @@ -631,7 +666,8 @@ ble_error_t GenericSecurityManager::slave_security_request(connection_handle_t c return _pal.slave_security_request(connection, link_authentication); } -ble_error_t GenericSecurityManager::enable_encryption(connection_handle_t connection) { +ble_error_t GenericSecurityManager::enable_encryption(connection_handle_t connection) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return BLE_ERROR_INVALID_PARAM; @@ -653,8 +689,9 @@ ble_error_t GenericSecurityManager::enable_encryption(connection_handle_t connec void GenericSecurityManager::enable_encryption_cb( pal::SecurityDb::entry_handle_t db_entry, - const SecurityEntryKeys_t* entryKeys -) { + const SecurityEntryKeys_t *entryKeys +) +{ ControlBlock_t *cb = get_control_block(db_entry); if (cb && entryKeys) { @@ -668,8 +705,9 @@ void GenericSecurityManager::enable_encryption_cb( void GenericSecurityManager::set_ltk_cb( pal::SecurityDb::entry_handle_t db_entry, - const SecurityEntryKeys_t* entryKeys -) { + const SecurityEntryKeys_t *entryKeys +) +{ ControlBlock_t *cb = get_control_block(db_entry); if (cb) { @@ -684,7 +722,8 @@ void GenericSecurityManager::set_ltk_cb( void GenericSecurityManager::return_csrk_cb( pal::SecurityDb::entry_handle_t db_entry, const csrk_t *csrk -) { +) +{ ControlBlock_t *cb = get_control_block(db_entry); if (!cb) { return; @@ -700,26 +739,27 @@ void GenericSecurityManager::return_csrk_cb( #if defined(MBEDTLS_CMAC_C) void GenericSecurityManager::generate_secure_connections_oob( connection_handle_t connection -) { - oob_confirm_t confirm; - oob_lesc_value_t random; - - ControlBlock_t *cb = get_control_block(connection); - if (!cb) { - return; - } - - ble_error_t ret = get_random_data(random.buffer(), random.size()); - if (ret != BLE_ERROR_NONE) { - return; - } - - crypto_toolbox_f4( - _db.get_public_key_x(), - _db.get_public_key_y(), - random, - confirm - ); +) +{ + oob_confirm_t confirm; + oob_lesc_value_t random; + + ControlBlock_t *cb = get_control_block(connection); + if (!cb) { + return; + } + + ble_error_t ret = get_random_data(random.buffer(), random.size()); + if (ret != BLE_ERROR_NONE) { + return; + } + + crypto_toolbox_f4( + _db.get_public_key_x(), + _db.get_public_key_y(), + random, + confirm + ); eventHandler->oobGenerated( &cb->local_address, @@ -731,7 +771,8 @@ void GenericSecurityManager::generate_secure_connections_oob( } #endif -void GenericSecurityManager::update_oob_presence(connection_handle_t connection) { +void GenericSecurityManager::update_oob_presence(connection_handle_t connection) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return; @@ -754,11 +795,12 @@ void GenericSecurityManager::update_oob_presence(connection_handle_t connection) #if defined(MBEDTLS_CMAC_C) bool GenericSecurityManager::crypto_toolbox_f4( - const public_key_coord_t& U, - const public_key_coord_t& V, - const oob_lesc_value_t& X, - oob_confirm_t& confirm -) { + const public_key_coord_t &U, + const public_key_coord_t &V, + const oob_lesc_value_t &X, + oob_confirm_t &confirm +) +{ mbedtls_cipher_context_t context; const mbedtls_cipher_info_t *info = mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_128_ECB); @@ -769,11 +811,11 @@ bool GenericSecurityManager::crypto_toolbox_f4( /* it's either this chaining or a goto */ if (mbedtls_cipher_setup(&context, info) == 0 - && mbedtls_cipher_cmac_starts(&context, X.data(), 128) == 0 - && mbedtls_cipher_cmac_update(&context, U.data(), 16) == 0 - && mbedtls_cipher_cmac_update(&context, V.data(), 16) == 0 - && mbedtls_cipher_cmac_update(&context, &Z, 1) == 0 - && mbedtls_cipher_cmac_finish(&context, &confirm[0]) == 0) { + && mbedtls_cipher_cmac_starts(&context, X.data(), 128) == 0 + && mbedtls_cipher_cmac_update(&context, U.data(), 16) == 0 + && mbedtls_cipher_cmac_update(&context, V.data(), 16) == 0 + && mbedtls_cipher_cmac_update(&context, &Z, 1) == 0 + && mbedtls_cipher_cmac_finish(&context, &confirm[0]) == 0) { success = true; } @@ -782,7 +824,8 @@ bool GenericSecurityManager::crypto_toolbox_f4( } #endif -void GenericSecurityManager::set_mitm_performed(connection_handle_t connection, bool enable) { +void GenericSecurityManager::set_mitm_performed(connection_handle_t connection, bool enable) +{ ControlBlock_t *cb = get_control_block(connection); if (cb) { cb->mitm_performed = enable; @@ -797,7 +840,8 @@ void GenericSecurityManager::on_connected( BLEProtocol::AddressType_t local_address_type, const BLEProtocol::AddressBytes_t local_address, const Gap::ConnectionParams_t *connection_params -) { +) +{ ControlBlock_t *cb = acquire_control_block(connection); if (!cb) { return; @@ -813,18 +857,19 @@ void GenericSecurityManager::on_connected( // get the associated db handle and the distribution flags if any cb->db_entry = _db.open_entry(peer_address_type, peer_address); - const pal::SecurityDistributionFlags_t* dist_flags = + const pal::SecurityDistributionFlags_t *dist_flags = _db.get_distribution_flags(cb->db_entry); if (dist_flags) { - *static_cast(cb) = *dist_flags; + *static_cast(cb) = *dist_flags; } } void GenericSecurityManager::on_disconnected( connection_handle_t connection, Gap::DisconnectionReason_t reason -) { +) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return; @@ -848,7 +893,8 @@ void GenericSecurityManager::on_pairing_request( AuthenticationMask authentication, KeyDistribution initiator_dist, KeyDistribution responder_dist -) { +) +{ /* cancel pairing if secure connection paring is not possible */ if (!_legacy_pairing_allowed && !authentication.get_secure_connections()) { cancelPairingRequest(connection); @@ -874,7 +920,8 @@ void GenericSecurityManager::on_pairing_request( void GenericSecurityManager::on_pairing_error( connection_handle_t connection, pairing_failure_t error -) { +) +{ set_mitm_performed(connection, false); eventHandler->pairingResult( @@ -893,7 +940,8 @@ void GenericSecurityManager::on_pairing_error( } } -void GenericSecurityManager::on_pairing_timed_out(connection_handle_t connection) { +void GenericSecurityManager::on_pairing_timed_out(connection_handle_t connection) +{ set_mitm_performed(connection, false); eventHandler->pairingResult( @@ -902,7 +950,8 @@ void GenericSecurityManager::on_pairing_timed_out(connection_handle_t connection ); } -void GenericSecurityManager::on_pairing_completed(connection_handle_t connection) { +void GenericSecurityManager::on_pairing_completed(connection_handle_t connection) +{ ControlBlock_t *cb = get_control_block(connection); if (cb) { // set the distribution flags in the db @@ -919,27 +968,29 @@ void GenericSecurityManager::on_pairing_completed(connection_handle_t connection // Security // -void GenericSecurityManager::on_valid_mic_timeout(connection_handle_t connection) { +void GenericSecurityManager::on_valid_mic_timeout(connection_handle_t connection) +{ (void)connection; } void GenericSecurityManager::on_slave_security_request( connection_handle_t connection, AuthenticationMask authentication -) { +) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return; } if (authentication.get_secure_connections() - && _default_authentication.get_secure_connections() - && !cb->secure_connections_paired) { + && _default_authentication.get_secure_connections() + && !cb->secure_connections_paired) { requestPairing(connection); } if (authentication.get_mitm() - && !cb->ltk_mitm_protected) { + && !cb->ltk_mitm_protected) { cb->mitm_requested = true; requestPairing(connection); } @@ -952,7 +1003,8 @@ void GenericSecurityManager::on_slave_security_request( void GenericSecurityManager::on_link_encryption_result( connection_handle_t connection, link_encryption_t result -) { +) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { @@ -989,7 +1041,8 @@ void GenericSecurityManager::on_link_encryption_result( void GenericSecurityManager::on_link_encryption_request_timed_out( connection_handle_t connection -) { +) +{ eventHandler->linkEncryptionResult( connection, link_encryption_t::NOT_ENCRYPTED @@ -1003,7 +1056,8 @@ void GenericSecurityManager::on_link_encryption_request_timed_out( void GenericSecurityManager::on_passkey_display( connection_handle_t connection, passkey_num_t passkey -) { +) +{ set_mitm_performed(connection); eventHandler->passkeyDisplay(connection, PasskeyAscii(passkey).value()); } @@ -1011,22 +1065,26 @@ void GenericSecurityManager::on_passkey_display( void GenericSecurityManager::on_keypress_notification( connection_handle_t connection, SecurityManager::Keypress_t keypress -) { +) +{ set_mitm_performed(connection); eventHandler->keypressNotification(connection, keypress); } -void GenericSecurityManager::on_passkey_request(connection_handle_t connection) { +void GenericSecurityManager::on_passkey_request(connection_handle_t connection) +{ set_mitm_performed(connection); eventHandler->passkeyRequest(connection); } -void GenericSecurityManager::on_confirmation_request(connection_handle_t connection) { +void GenericSecurityManager::on_confirmation_request(connection_handle_t connection) +{ set_mitm_performed(connection); eventHandler->confirmationRequest(connection); } -void GenericSecurityManager::on_legacy_pairing_oob_request(connection_handle_t connection) { +void GenericSecurityManager::on_legacy_pairing_oob_request(connection_handle_t connection) +{ set_mitm_performed(connection); eventHandler->legacyPairingOobRequest(connection); } @@ -1035,7 +1093,8 @@ void GenericSecurityManager::on_oob_data_verification_request( connection_handle_t connection, const public_key_coord_t &peer_public_key_x, const public_key_coord_t &peer_public_key_y -) { +) +{ #if defined(MBEDTLS_CMAC_C) ControlBlock_t *cb = get_control_block(connection); @@ -1049,7 +1108,7 @@ void GenericSecurityManager::on_oob_data_verification_request( ); if (cb && (cb->peer_address == _peer_sc_oob_address) - && (confirm_verify == _peer_sc_oob_confirm)) { + && (confirm_verify == _peer_sc_oob_confirm)) { _pal.oob_data_verified(connection, _local_sc_oob_random, _peer_sc_oob_random); } else { _pal.cancel_pairing(connection, pairing_failure_t::CONFIRM_VALUE_FAILED); @@ -1064,7 +1123,8 @@ void GenericSecurityManager::on_oob_data_verification_request( void GenericSecurityManager::on_public_key_generated( const public_key_coord_t &public_key_x, const public_key_coord_t &public_key_y -) { +) +{ _db.set_public_key(public_key_x, public_key_y); _public_keys_generated = true; } @@ -1072,7 +1132,8 @@ void GenericSecurityManager::on_public_key_generated( void GenericSecurityManager::on_secure_connections_ltk_generated( connection_handle_t connection, const ltk_t <k -) { +) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return; @@ -1087,7 +1148,8 @@ void GenericSecurityManager::on_secure_connections_ltk_generated( void GenericSecurityManager::on_keys_distributed_ltk( connection_handle_t connection, const ltk_t <k -) { +) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return; @@ -1100,7 +1162,8 @@ void GenericSecurityManager::on_keys_distributed_ediv_rand( connection_handle_t connection, const ediv_t &ediv, const rand_t &rand -) { +) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return; @@ -1112,7 +1175,8 @@ void GenericSecurityManager::on_keys_distributed_ediv_rand( void GenericSecurityManager::on_keys_distributed_local_ltk( connection_handle_t connection, const ltk_t <k -) { +) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return; @@ -1125,7 +1189,8 @@ void GenericSecurityManager::on_keys_distributed_local_ediv_rand( connection_handle_t connection, const ediv_t &ediv, const rand_t &rand -) { +) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return; @@ -1137,7 +1202,8 @@ void GenericSecurityManager::on_keys_distributed_local_ediv_rand( void GenericSecurityManager::on_keys_distributed_irk( connection_handle_t connection, const irk_t &irk -) { +) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return; @@ -1150,7 +1216,8 @@ void GenericSecurityManager::on_keys_distributed_bdaddr( connection_handle_t connection, advertising_peer_address_type_t peer_address_type, const address_t &peer_identity_address -) { +) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return; @@ -1166,7 +1233,8 @@ void GenericSecurityManager::on_keys_distributed_bdaddr( void GenericSecurityManager::on_keys_distributed_csrk( connection_handle_t connection, const csrk_t &csrk -) { +) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return; @@ -1187,7 +1255,8 @@ void GenericSecurityManager::on_ltk_request( connection_handle_t connection, const ediv_t &ediv, const rand_t &rand -) { +) +{ ControlBlock_t *cb = get_control_block(connection); if (!cb) { return; @@ -1235,13 +1304,13 @@ void GenericSecurityManager::on_ltk_request(connection_handle_t connection) ); } -GenericSecurityManager::ControlBlock_t* +GenericSecurityManager::ControlBlock_t * GenericSecurityManager::acquire_control_block(connection_handle_t connection) { /* grab the first disconnected slot*/ for (size_t i = 0; i < MAX_CONTROL_BLOCKS; i++) { if (!_control_blocks[i].connected) { - ControlBlock_t* cb = &_control_blocks[i]; + ControlBlock_t *cb = &_control_blocks[i]; cb->connected = true; cb->connection = connection; return cb; @@ -1251,9 +1320,10 @@ GenericSecurityManager::acquire_control_block(connection_handle_t connection) return NULL; } -GenericSecurityManager::ControlBlock_t* GenericSecurityManager::get_control_block( +GenericSecurityManager::ControlBlock_t *GenericSecurityManager::get_control_block( connection_handle_t connection -) { +) +{ for (size_t i = 0; i < MAX_CONTROL_BLOCKS; i++) { if (!_control_blocks[i].connected) { continue; @@ -1264,9 +1334,10 @@ GenericSecurityManager::ControlBlock_t* GenericSecurityManager::get_control_bloc return NULL; } -GenericSecurityManager::ControlBlock_t* GenericSecurityManager::get_control_block( +GenericSecurityManager::ControlBlock_t *GenericSecurityManager::get_control_block( const address_t &peer_address -) { +) +{ for (size_t i = 0; i < MAX_CONTROL_BLOCKS; i++) { if (!_control_blocks[i].connected) { continue; @@ -1277,9 +1348,10 @@ GenericSecurityManager::ControlBlock_t* GenericSecurityManager::get_control_bloc return NULL; } -GenericSecurityManager::ControlBlock_t* GenericSecurityManager::get_control_block( +GenericSecurityManager::ControlBlock_t *GenericSecurityManager::get_control_block( pal::SecurityDb::entry_handle_t db_entry -) { +) +{ for (size_t i = 0; i < MAX_CONTROL_BLOCKS; i++) { if (!_control_blocks[i].connected) { continue; @@ -1290,7 +1362,7 @@ GenericSecurityManager::ControlBlock_t* GenericSecurityManager::get_control_bloc return NULL; } -void GenericSecurityManager::release_control_block(ControlBlock_t* cb) +void GenericSecurityManager::release_control_block(ControlBlock_t *cb) { *cb = ControlBlock_t(); } diff --git a/features/FEATURE_UVISOR/includes/uvisor-lib/rtx/rtx_box_index.h b/features/FEATURE_UVISOR/includes/uvisor-lib/rtx/rtx_box_index.h index 3275e8de3d9..327e21272ce 100644 --- a/features/FEATURE_UVISOR/includes/uvisor-lib/rtx/rtx_box_index.h +++ b/features/FEATURE_UVISOR/includes/uvisor-lib/rtx/rtx_box_index.h @@ -24,8 +24,7 @@ extern "C" { #endif -typedef struct -{ +typedef struct { /* The uvisor box index must be placed at the beginning */ UvisorBoxIndex index; diff --git a/features/FEATURE_UVISOR/includes/uvisor-lib/rtx/secure_allocator.h b/features/FEATURE_UVISOR/includes/uvisor-lib/rtx/secure_allocator.h index d25010942fc..fcbeb1aa15a 100644 --- a/features/FEATURE_UVISOR/includes/uvisor-lib/rtx/secure_allocator.h +++ b/features/FEATURE_UVISOR/includes/uvisor-lib/rtx/secure_allocator.h @@ -25,7 +25,7 @@ extern "C" { #endif /** Contains the allocator data and backing page table. */ -typedef void * SecureAllocator; +typedef void *SecureAllocator; /** Create an allocator in-place in an existing pool without using pages. * Use this to turn statically allocated memory into a heap. @@ -36,7 +36,7 @@ typedef void * SecureAllocator; * @returns the allocator or `NULL` on failure */ SecureAllocator secure_allocator_create_with_pool( - void * mem, + void *mem, size_t bytes); /** Create an allocator using pages from the page heap. @@ -66,32 +66,32 @@ int secure_allocator_destroy( SecureAllocator allocator); /** Drop-in for `malloc`. */ -void * secure_malloc( +void *secure_malloc( SecureAllocator allocator, size_t size); /** Drop-in for `aligned_alloc`. */ -void * secure_aligned_alloc( +void *secure_aligned_alloc( SecureAllocator allocator, size_t alignment, size_t size); /** Drop-in for `calloc`. */ -void * secure_calloc( +void *secure_calloc( SecureAllocator allocator, size_t nmemb, size_t size); /** Drop-in for `realloc`. */ -void * secure_realloc( +void *secure_realloc( SecureAllocator allocator, - void * ptr, + void *ptr, size_t size); /** Drop-in for `free`. */ void secure_free( SecureAllocator allocator, - void * ptr); + void *ptr); #ifdef __cplusplus } /* extern "C" */ diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/api.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/api.h index 46c29c3e255..99759937080 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/api.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/api.h @@ -45,32 +45,32 @@ typedef struct { void (*init)(uint32_t caller); - void (*irq_enable)(uint32_t irqn); - void (*irq_disable)(uint32_t irqn); - void (*irq_disable_all)(void); - void (*irq_enable_all)(void); - void (*irq_set_vector)(uint32_t irqn, uint32_t vector); + void (*irq_enable)(uint32_t irqn); + void (*irq_disable)(uint32_t irqn); + void (*irq_disable_all)(void); + void (*irq_enable_all)(void); + void (*irq_set_vector)(uint32_t irqn, uint32_t vector); uint32_t (*irq_get_vector)(uint32_t irqn); - void (*irq_set_priority)(uint32_t irqn, uint32_t priority); + void (*irq_set_priority)(uint32_t irqn, uint32_t priority); uint32_t (*irq_get_priority)(uint32_t irqn); - void (*irq_set_pending)(uint32_t irqn); + void (*irq_set_pending)(uint32_t irqn); uint32_t (*irq_get_pending)(uint32_t irqn); - void (*irq_clear_pending)(uint32_t irqn); - int (*irq_get_level)(void); - void (*irq_system_reset)(TResetReason reason); + void (*irq_clear_pending)(uint32_t irqn); + int (*irq_get_level)(void); + void (*irq_system_reset)(TResetReason reason); - int (*page_malloc)(UvisorPageTable * const table); - int (*page_free)(const UvisorPageTable * const table); + int (*page_malloc)(UvisorPageTable *const table); + int (*page_free)(const UvisorPageTable *const table); int (*box_namespace)(int box_id, char *box_namespace, size_t length); - int (*box_id_for_namespace)(int * const box_id, const char * const box_namespace); + int (*box_id_for_namespace)(int *const box_id, const char *const box_namespace); void (*error)(THaltUserError reason); void (*start)(void); void (*vmpu_mem_invalidate)(void); - int (*pool_init)(uvisor_pool_t *, void *, size_t, size_t); - int (*pool_queue_init)(uvisor_pool_queue_t *, uvisor_pool_t *, void *, size_t, size_t); + int (*pool_init)(uvisor_pool_t *, void *, size_t, size_t); + int (*pool_queue_init)(uvisor_pool_queue_t *, uvisor_pool_t *, void *, size_t, size_t); uvisor_pool_slot_t (*pool_allocate)(uvisor_pool_t *); uvisor_pool_slot_t (*pool_try_allocate)(uvisor_pool_t *); uvisor_pool_slot_t (*pool_queue_enqueue)(uvisor_pool_queue_t *, uvisor_pool_slot_t); @@ -84,10 +84,10 @@ typedef struct { uvisor_pool_slot_t (*pool_queue_find_first)(uvisor_pool_queue_t *, TQueryFN_Ptr, void *); uvisor_pool_slot_t (*pool_queue_try_find_first)(uvisor_pool_queue_t *, TQueryFN_Ptr, void *); - void (*spin_init)(UvisorSpinlock * spinlock); - bool (*spin_trylock)(UvisorSpinlock * spinlock); - void (*spin_lock)(UvisorSpinlock * spinlock); - void (*spin_unlock)(UvisorSpinlock * spinlock); + void (*spin_init)(UvisorSpinlock *spinlock); + bool (*spin_trylock)(UvisorSpinlock *spinlock); + void (*spin_lock)(UvisorSpinlock *spinlock); + void (*spin_unlock)(UvisorSpinlock *spinlock); void (*debug_semihosting_enable)(void); diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/box_config.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/box_config.h index 1f21d6554f3..cd5d7619084 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/box_config.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/box_config.h @@ -26,7 +26,7 @@ #include UVISOR_EXTERN const uint32_t __uvisor_mode; -UVISOR_EXTERN void const * const public_box_cfg_ptr; +UVISOR_EXTERN void const *const public_box_cfg_ptr; /* All pointers in the box index need to be 4-byte aligned. * We therefore also need to round up all sizes to 4-byte multiples to diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/box_id.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/box_id.h index 1f75fd5ddaa..440d8bd3d85 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/box_id.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/box_id.h @@ -40,7 +40,7 @@ static UVISOR_FORCEINLINE int uvisor_box_namespace(int box_id, char *box_namespa return uvisor_api.box_namespace(box_id, box_namespace, length); } -static UVISOR_FORCEINLINE int uvisor_box_id_for_namespace(int * const box_id, const char * const box_namespace) +static UVISOR_FORCEINLINE int uvisor_box_id_for_namespace(int *const box_id, const char *const box_namespace) { return uvisor_api.box_id_for_namespace(box_id, box_namespace); } diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/box_init.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/box_init.h index c59632e137a..67defd7284c 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/box_init.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/box_init.h @@ -19,6 +19,6 @@ #include "api/inc/uvisor-lib.h" -UVISOR_EXTERN void __uvisor_lib_box_init(void * lib_config); +UVISOR_EXTERN void __uvisor_lib_box_init(void *lib_config); #endif diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/debug_exports.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/debug_exports.h index 2c8fc3395e0..3e244b682d8 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/debug_exports.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/debug_exports.h @@ -31,7 +31,7 @@ typedef struct TUvisorDebugDriver { const uint32_t magic; const uint32_t version; - const UvisorBoxConfig * const box_cfg_ptr; + const UvisorBoxConfig *const box_cfg_ptr; void (*halt_error)(THaltError, const THaltInfo *); } TUvisorDebugDriver; diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/ipc.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/ipc.h index 4186df4c5a3..a06364f282a 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/ipc.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/ipc.h @@ -34,7 +34,7 @@ * other value means wait forever. * @return 0 on success, non-zero error code otherwise */ -UVISOR_EXTERN int ipc_waitforany(uint32_t wait_tokens, uint32_t * done_tokens, uint32_t timeout_ms); +UVISOR_EXTERN int ipc_waitforany(uint32_t wait_tokens, uint32_t *done_tokens, uint32_t timeout_ms); /** Wait for all of the specified IPC operations to complete. * @@ -47,7 +47,7 @@ UVISOR_EXTERN int ipc_waitforany(uint32_t wait_tokens, uint32_t * done_tokens, u * Any other value means wait forever. * @return 0 on success, non-zero error code otherwise */ -UVISOR_EXTERN int ipc_waitforall(uint32_t wait_tokens, uint32_t * done_tokens, uint32_t timeout_ms); +UVISOR_EXTERN int ipc_waitforall(uint32_t wait_tokens, uint32_t *done_tokens, uint32_t timeout_ms); /** Asynchronously send an IPC message * @@ -61,7 +61,7 @@ UVISOR_EXTERN int ipc_waitforall(uint32_t wait_tokens, uint32_t * done_tokens, u * * @return 0 on success, non-zero error code otherwise * */ -UVISOR_EXTERN int ipc_send(uvisor_ipc_desc_t * desc, const void * msg); +UVISOR_EXTERN int ipc_send(uvisor_ipc_desc_t *desc, const void *msg); /** Asynchronously receive an IPC message * @@ -75,6 +75,6 @@ UVISOR_EXTERN int ipc_send(uvisor_ipc_desc_t * desc, const void * msg); * * @return 0 on success, non-zero error code otherwise */ -UVISOR_EXTERN int ipc_recv(uvisor_ipc_desc_t * desc, void * msg); +UVISOR_EXTERN int ipc_recv(uvisor_ipc_desc_t *desc, void *msg); #endif /* __UVISOR_API_IPC_H__ */ diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/ipc_exports.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/ipc_exports.h index 72de5f3f126..77c6dae3e20 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/ipc_exports.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/ipc_exports.h @@ -77,8 +77,8 @@ typedef struct uvisor_ipc_desc { /* IPC IO Request Structure */ typedef struct uvisor_ipc_io { - uvisor_ipc_desc_t * desc; - void * msg; + uvisor_ipc_desc_t *desc; + void *msg; uvisor_ipc_io_state_t state; } uvisor_ipc_io_t; @@ -109,7 +109,7 @@ typedef struct uvisor_ipc { uint32_t completed_tokens; /* uVisor and endpoints read and write. */ } uvisor_ipc_t; -static inline uvisor_ipc_t * uvisor_ipc(UvisorBoxIndex * const index) +static inline uvisor_ipc_t *uvisor_ipc(UvisorBoxIndex *const index) { return (uvisor_ipc_t *) index->bss.address_of.ipc; } diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/lib_hook_exports.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/lib_hook_exports.h index 74c790d43e2..7da62cc824e 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/lib_hook_exports.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/lib_hook_exports.h @@ -28,9 +28,9 @@ typedef struct uvisor_semaphore UvisorSemaphore; * All functions that uVisor needs to call that are implemented in uvisor-lib. * These functions will be run by unprivileged code only. */ typedef struct { - void (*box_init)(void * lib_config); - int (*semaphore_init)(UvisorSemaphore * semaphore, uint32_t initial_count, uint32_t max_count); - int (*semaphore_pend)(UvisorSemaphore * semaphore, uint32_t timeout_ms); + void (*box_init)(void *lib_config); + int (*semaphore_init)(UvisorSemaphore *semaphore, uint32_t initial_count, uint32_t max_count); + int (*semaphore_pend)(UvisorSemaphore *semaphore, uint32_t timeout_ms); } UvisorLibHooks; #endif diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/page_allocator.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/page_allocator.h index 35ab826c8ba..9677d9dfac9 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/page_allocator.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/page_allocator.h @@ -30,7 +30,7 @@ UVISOR_EXTERN_C_BEGIN * @param table.page_origins[out] Pointers to the page origins. The table must be large enough to hold page_count entries. * @returns Non-zero on failure with failure class `UVISOR_ERROR_CLASS_PAGE`. See `UVISOR_ERROR_PAGE_*`. */ -static UVISOR_FORCEINLINE int uvisor_page_malloc(UvisorPageTable * const table) +static UVISOR_FORCEINLINE int uvisor_page_malloc(UvisorPageTable *const table) { return uvisor_api.page_malloc(table); } @@ -38,7 +38,7 @@ static UVISOR_FORCEINLINE int uvisor_page_malloc(UvisorPageTable * const table) /* Free the pages associated with the table, only if it passes validation. * @returns Non-zero on failure with failure class `UVISOR_ERROR_CLASS_PAGE`. See `UVISOR_ERROR_PAGE_*`. */ -static UVISOR_FORCEINLINE int uvisor_page_free(const UvisorPageTable * const table) +static UVISOR_FORCEINLINE int uvisor_page_free(const UvisorPageTable *const table) { return uvisor_api.page_free(table); } diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/page_allocator_exports.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/page_allocator_exports.h index 52c24ec925c..f6033b817b7 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/page_allocator_exports.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/page_allocator_exports.h @@ -37,7 +37,7 @@ UVISOR_EXTERN const uint32_t __uvisor_page_size; typedef struct { uint32_t page_size; /* The page size in bytes. Must be multiple of `UVISOR_PAGE_SIZE`! */ uint32_t page_count; /* The number of pages in the page table. */ - void * page_origins[1]; /* Table of pointers to the origin of each page. */ + void *page_origins[1]; /* Table of pointers to the origin of each page. */ } UvisorPageTable; #endif /* __UVISOR_API_PAGE_ALLOCATOR_EXPORTS_H__ */ diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/pool_queue_exports.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/pool_queue_exports.h index d9764fb3f3d..311b9de0415 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/pool_queue_exports.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/pool_queue_exports.h @@ -59,7 +59,7 @@ typedef struct uvisor_pool { uint32_t magic; /* The array holds slots of data. */ - void const * array; + void const *array; /* The distance between elements in the array. */ size_t stride; @@ -93,71 +93,71 @@ typedef struct uvisor_pool_queue { /* The last allocated slot */ uvisor_pool_slot_t tail; - uvisor_pool_t * pool; + uvisor_pool_t *pool; } uvisor_pool_queue_t; /* Intialize a pool. * Return 0 on success, non-zero otherwise. */ -UVISOR_EXTERN int uvisor_pool_init(uvisor_pool_t * pool, void * array, size_t stride, size_t num); +UVISOR_EXTERN int uvisor_pool_init(uvisor_pool_t *pool, void *array, size_t stride, size_t num); /* Initialize a pool queue. * Return 0 on success, non-zero otherwise. */ -UVISOR_EXTERN int uvisor_pool_queue_init(uvisor_pool_queue_t * pool_queue, uvisor_pool_t * pool, void * array, size_t stride, size_t num); +UVISOR_EXTERN int uvisor_pool_queue_init(uvisor_pool_queue_t *pool_queue, uvisor_pool_t *pool, void *array, size_t stride, size_t num); /* Allocate a slot from the pool. This doesn't put anything in the slot for * you. It's up to you to do that. Return the index of the allocated slot, or * UVISOR_POOL_SLOT_INVALID if there is no available slot. This function will * spin until the spin lock serializing access to the pool can be taken. */ -UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_allocate(uvisor_pool_t * pool); +UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_allocate(uvisor_pool_t *pool); /* Attempt to allocate a slot. This function will fail if the spin lock * serializing access to the pool can not be taken. */ -UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_try_allocate(uvisor_pool_t * pool); +UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_try_allocate(uvisor_pool_t *pool); /* Enqueue the specified slot into the queue. */ -UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_queue_enqueue(uvisor_pool_queue_t * pool_queue, uvisor_pool_slot_t slot); -UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_queue_try_enqueue(uvisor_pool_queue_t * pool_queue, uvisor_pool_slot_t slot); +UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_queue_enqueue(uvisor_pool_queue_t *pool_queue, uvisor_pool_slot_t slot); +UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_queue_try_enqueue(uvisor_pool_queue_t *pool_queue, uvisor_pool_slot_t slot); /* Free the specified slot back into the pool. Invalid slots are ignored. * Return the slot that was freed, or UVISOR_POOL_SLOT_IS_FREE if the slot was * already freed, or UVISOR_POOL_SLOT_INVALID if the slot being requested to * free is outside the range of the queue. */ -UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_free(uvisor_pool_t * pool, uvisor_pool_slot_t slot); -UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_try_free(uvisor_pool_t * pool, uvisor_pool_slot_t slot); +UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_free(uvisor_pool_t *pool, uvisor_pool_slot_t slot); +UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_try_free(uvisor_pool_t *pool, uvisor_pool_slot_t slot); /* Remove the specified slot from the queue. This function does not free the * specified slot back into the pool. Return the slot that was dequeued, or * UVISOR_POOL_SLOT_IS_DEQUEUED if the slot was already dequeued, or * UVISOR_POOL_SLOT_INVALID if the slot being requested to dequeue is outside * the range of the queue. */ -UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_queue_try_dequeue(uvisor_pool_queue_t * pool_queue, uvisor_pool_slot_t slot); -UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_queue_dequeue(uvisor_pool_queue_t * pool_queue, uvisor_pool_slot_t slot); +UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_queue_try_dequeue(uvisor_pool_queue_t *pool_queue, uvisor_pool_slot_t slot); +UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_queue_dequeue(uvisor_pool_queue_t *pool_queue, uvisor_pool_slot_t slot); /* Remove the first slot from the queue. This function does not free the * specified slot back into the pool. Return the slot that was dequeued or * UVISOR_POOL_SLOT_INVALID if the slot being requested to dequeue is outside * the range of the queue. */ -UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_queue_dequeue_first(uvisor_pool_queue_t * pool_queue); -UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_queue_try_dequeue_first(uvisor_pool_queue_t * pool_queue); +UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_queue_dequeue_first(uvisor_pool_queue_t *pool_queue); +UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_queue_try_dequeue_first(uvisor_pool_queue_t *pool_queue); /* Find the first (in queue order) slot that the supplied query function * returns non-zero for. The query function is provided with `context` on every * invocation. This allows query functions to access additional data without * having to use global variables. `uvisor_pool_queue_find_first` is reentrant. */ -typedef int (*TQueryFN_Ptr)(uvisor_pool_slot_t slot, void * context); -UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_queue_try_find_first(uvisor_pool_queue_t * pool_queue, - TQueryFN_Ptr query_fn, void * context); -UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_queue_find_first(uvisor_pool_queue_t * pool_queue, - TQueryFN_Ptr query_fn, void * context); +typedef int (*TQueryFN_Ptr)(uvisor_pool_slot_t slot, void *context); +UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_queue_try_find_first(uvisor_pool_queue_t *pool_queue, + TQueryFN_Ptr query_fn, void *context); +UVISOR_EXTERN uvisor_pool_slot_t uvisor_pool_queue_find_first(uvisor_pool_queue_t *pool_queue, + TQueryFN_Ptr query_fn, void *context); /* Inline helper function to make allocating slots for pool queues easier and * better encapsulated (clients don't need to pull the pool out of the pool * queue, or even realize pool_queue is implemented with a pool) */ -static inline uvisor_pool_slot_t uvisor_pool_queue_allocate(uvisor_pool_queue_t * pool_queue) +static inline uvisor_pool_slot_t uvisor_pool_queue_allocate(uvisor_pool_queue_t *pool_queue) { return uvisor_pool_allocate(pool_queue->pool); } -static inline uvisor_pool_slot_t uvisor_pool_queue_try_allocate(uvisor_pool_queue_t * pool_queue) +static inline uvisor_pool_slot_t uvisor_pool_queue_try_allocate(uvisor_pool_queue_t *pool_queue) { return uvisor_pool_try_allocate(pool_queue->pool); } @@ -165,18 +165,18 @@ static inline uvisor_pool_slot_t uvisor_pool_queue_try_allocate(uvisor_pool_queu /* Inline helper function to make freeing slots for pool queues easier and * better encapsulated (clients don't need to pull the pool out of the pool * queue, or even realize pool_queue is implemented with a pool) */ -static inline uvisor_pool_slot_t uvisor_pool_queue_free(uvisor_pool_queue_t * pool_queue, uvisor_pool_slot_t slot) +static inline uvisor_pool_slot_t uvisor_pool_queue_free(uvisor_pool_queue_t *pool_queue, uvisor_pool_slot_t slot) { return uvisor_pool_free(pool_queue->pool, slot); } -static inline uvisor_pool_slot_t uvisor_pool_queue_try_free(uvisor_pool_queue_t * pool_queue, uvisor_pool_slot_t slot) +static inline uvisor_pool_slot_t uvisor_pool_queue_try_free(uvisor_pool_queue_t *pool_queue, uvisor_pool_slot_t slot) { return uvisor_pool_try_free(pool_queue->pool, slot); } /* Return a pointer to the specified slot within the pool. */ -static inline void * uvisor_pool_pointer_to(uvisor_pool_t * pool, uvisor_pool_slot_t slot) +static inline void *uvisor_pool_pointer_to(uvisor_pool_t *pool, uvisor_pool_slot_t slot) { if (slot >= pool->num) { return NULL; diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/priv_sys_hooks_exports.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/priv_sys_hooks_exports.h index dc5a05a6c4f..42859a6476f 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/priv_sys_hooks_exports.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/priv_sys_hooks_exports.h @@ -34,7 +34,7 @@ typedef struct { void (*priv_pendsv)(void); void (*priv_systick)(void); int32_t (*priv_os_suspend)(void); - int (*priv_uvisor_semaphore_post)(UvisorSemaphore * semaphore); + int (*priv_uvisor_semaphore_post)(UvisorSemaphore *semaphore); } UvisorPrivSystemHooks; /* Use this macro to register privileged system IRQ hooks. If you don't want to diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/rpc.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/rpc.h index ca36474b1b8..7d4079fdd26 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/rpc.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/rpc.h @@ -36,7 +36,7 @@ * @param timeout_ms specifies how long to wait (in ms) for an incoming * RPC message before returning */ -UVISOR_EXTERN int rpc_fncall_waitfor(const TFN_Ptr fn_ptr_array[], size_t fn_count, int * box_id_caller, uint32_t timeout_ms); +UVISOR_EXTERN int rpc_fncall_waitfor(const TFN_Ptr fn_ptr_array[], size_t fn_count, int *box_id_caller, uint32_t timeout_ms); /** Wait for an outgoing RPC to finish. * @@ -51,6 +51,6 @@ UVISOR_EXTERN int rpc_fncall_waitfor(const TFN_Ptr fn_ptr_array[], size_t fn_cou * the target function * @returns Non-zero on error or timeout, zero on successful wait */ -UVISOR_EXTERN int rpc_fncall_wait(uvisor_rpc_result_t result, uint32_t timeout_ms, uint32_t * ret); +UVISOR_EXTERN int rpc_fncall_wait(uvisor_rpc_result_t result, uint32_t timeout_ms, uint32_t *ret); #endif /* __UVISOR_API_RPC_H__ */ diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/rpc_exports.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/rpc_exports.h index c4494862536..fc958162a43 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/rpc_exports.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/rpc_exports.h @@ -68,7 +68,7 @@ typedef struct uvisor_rpc_message { uint32_t p2; uint32_t p3; - const TRPCGateway * gateway; + const TRPCGateway *gateway; /* The box ID of the other box. For callers, this is the destination box * ID. For callees, this is the source box ID. */ @@ -96,7 +96,7 @@ typedef struct uvisor_rpc_message { typedef struct uvisor_rpc_fn_group { /* A pointer to the function group */ - TFN_Ptr const * fn_ptr_array; + TFN_Ptr const *fn_ptr_array; size_t fn_count; /* The semaphore to wait on for this function group */ @@ -152,7 +152,7 @@ typedef struct uvisor_rpc_t { uint32_t result_counter; } uvisor_rpc_t; -static inline uvisor_rpc_t * uvisor_rpc(UvisorBoxIndex * const index) +static inline uvisor_rpc_t *uvisor_rpc(UvisorBoxIndex *const index) { return (uvisor_rpc_t *) index->bss.address_of.rpc; } diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/rpc_gateway.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/rpc_gateway.h index 84d8016c5da..ecd800fd3da 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/rpc_gateway.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/rpc_gateway.h @@ -263,10 +263,10 @@ /* This function is private to uvisor-lib, but needs to be publicly visible for * the RPC gateway creation macros to work. */ -UVISOR_EXTERN uint32_t rpc_fncall_sync(uint32_t p0, uint32_t p1, uint32_t p2, uint32_t p3, const TRPCGateway * gateway); +UVISOR_EXTERN uint32_t rpc_fncall_sync(uint32_t p0, uint32_t p1, uint32_t p2, uint32_t p3, const TRPCGateway *gateway); /* This function is private to uvisor-lib, but needs to be publicly visible for * the RPC gateway creation macros to work. */ -UVISOR_EXTERN uvisor_rpc_result_t rpc_fncall_async(uint32_t p0, uint32_t p1, uint32_t p2, uint32_t p3, const TRPCGateway * gateway); +UVISOR_EXTERN uvisor_rpc_result_t rpc_fncall_async(uint32_t p0, uint32_t p1, uint32_t p2, uint32_t p3, const TRPCGateway *gateway); #endif /* __UVISOR_API_RPC_GATEWAY_H__ */ diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/secure_access.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/secure_access.h index 56175be7c0e..679ea4e36f3 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/secure_access.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/secure_access.h @@ -22,32 +22,32 @@ #include #include -static UVISOR_FORCEINLINE void uvisor_write32(uint32_t volatile * volatile addr, uint32_t val) +static UVISOR_FORCEINLINE void uvisor_write32(uint32_t volatile *volatile addr, uint32_t val) { UVISOR_ASM_MEMORY_ACCESS(str, uint32_t, addr, val); } -static UVISOR_FORCEINLINE void uvisor_write16(uint16_t volatile * volatile addr, uint16_t val) +static UVISOR_FORCEINLINE void uvisor_write16(uint16_t volatile *volatile addr, uint16_t val) { UVISOR_ASM_MEMORY_ACCESS(strh, uint16_t, addr, val); } -static UVISOR_FORCEINLINE void uvisor_write8(uint8_t volatile * volatile addr, uint8_t val) +static UVISOR_FORCEINLINE void uvisor_write8(uint8_t volatile *volatile addr, uint8_t val) { UVISOR_ASM_MEMORY_ACCESS(strb, uint8_t, addr, val); } -static UVISOR_FORCEINLINE uint32_t uvisor_read32(uint32_t volatile * volatile addr) +static UVISOR_FORCEINLINE uint32_t uvisor_read32(uint32_t volatile *volatile addr) { return UVISOR_ASM_MEMORY_ACCESS(ldr, uint32_t, addr); } -static UVISOR_FORCEINLINE uint16_t uvisor_read16(uint16_t volatile * volatile addr) +static UVISOR_FORCEINLINE uint16_t uvisor_read16(uint16_t volatile *volatile addr) { return UVISOR_ASM_MEMORY_ACCESS(ldrh, uint16_t, addr); } -static UVISOR_FORCEINLINE uint8_t uvisor_read8(uint8_t volatile * volatile addr) +static UVISOR_FORCEINLINE uint8_t uvisor_read8(uint8_t volatile *volatile addr) { return UVISOR_ASM_MEMORY_ACCESS(ldrb, uint8_t, addr); } @@ -56,15 +56,15 @@ static UVISOR_FORCEINLINE uint8_t uvisor_read8(uint8_t volatile * volatile addr) * the sizeof_type. */ static UVISOR_FORCEINLINE void __address_write(size_t sizeof_type, volatile uint32_t *addr, uint32_t val) { - switch(sizeof_type) { + switch (sizeof_type) { case 4: - uvisor_write32((volatile uint32_t * volatile) addr, (uint32_t) val); + uvisor_write32((volatile uint32_t *volatile) addr, (uint32_t) val); break; case 2: - uvisor_write16((volatile uint16_t * volatile) addr, (uint16_t) val); + uvisor_write16((volatile uint16_t *volatile) addr, (uint16_t) val); break; case 1: - uvisor_write8((volatile uint8_t * volatile) addr, (uint8_t) val); + uvisor_write8((volatile uint8_t *volatile) addr, (uint8_t) val); break; default: uvisor_error(USER_NOT_ALLOWED); diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/unsupported.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/unsupported.h index e0ddb5b979e..b50757ee45f 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/unsupported.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/unsupported.h @@ -97,8 +97,7 @@ UVISOR_EXTERN const uint32_t __uvisor_mode; static UVISOR_FORCEINLINE uint32_t uvisor_read(uint32_t addr, uint32_t op, uint32_t mask) { - switch(op) - { + switch (op) { case UVISOR_OP_READ(UVISOR_OP_NOP): return *((uint32_t *) addr); case UVISOR_OP_READ(UVISOR_OP_AND): @@ -117,8 +116,7 @@ static UVISOR_FORCEINLINE uint32_t uvisor_read(uint32_t addr, uint32_t op, uint3 static UVISOR_FORCEINLINE void uvisor_write(uint32_t addr, uint32_t val, uint32_t op, uint32_t mask) { - switch(op) - { + switch (op) { case UVISOR_OP_WRITE(UVISOR_OP_NOP): *((uint32_t *) addr) = val; case UVISOR_OP_WRITE(UVISOR_OP_AND): @@ -179,7 +177,7 @@ static UVISOR_FORCEINLINE uint8_t uvisor_read8(uint8_t volatile *addr) * the sizeof_type. */ static UVISOR_FORCEINLINE void __address_write(size_t sizeof_type, volatile uint32_t *addr, uint32_t val) { - switch(sizeof_type) { + switch (sizeof_type) { case 4: uvisor_write32((volatile uint32_t *) addr, (uint32_t) val); break; diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/uvisor_exports.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/uvisor_exports.h index 3723c4d0998..3da6ace64a7 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/uvisor_exports.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/uvisor_exports.h @@ -79,7 +79,7 @@ * This macro works from both inside and outside function scope. * The implementations differ due to compilation differences, C++ static_assert * is known from C++11 (__cplusplus > 199711L) while mbed-os compiles with c++98, - * and C _Static_assert is known from GCC version 4.6.0. */ + * and C _Static_assert is known from GCC version 4.6.0. */ #define GCC_VERSION (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100 \ + __GNUC_PATCHLEVEL__) @@ -136,7 +136,7 @@ UVISOR_FORCEINLINE void uvisor_noreturn(void) { volatile int var = 1; - while(var); + while (var); } /* declare callee-saved input/output operands for gcc-style inline asm */ diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/uvisor_semaphore.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/uvisor_semaphore.h index a5ce6801ec6..3eb5faa595e 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/uvisor_semaphore.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/uvisor_semaphore.h @@ -21,13 +21,13 @@ /* Initialize a semaphore with the specified initial count. This function is * not safe to call from interrupt context. */ -UVISOR_EXTERN int __uvisor_semaphore_init(UvisorSemaphore * semaphore, uint32_t initial_count, uint32_t max_count); +UVISOR_EXTERN int __uvisor_semaphore_init(UvisorSemaphore *semaphore, uint32_t initial_count, uint32_t max_count); /* This function is not safe to call from interrupt context, even if the * timeout is zero. */ -UVISOR_EXTERN int __uvisor_semaphore_pend(UvisorSemaphore * semaphore, uint32_t timeout_ms); +UVISOR_EXTERN int __uvisor_semaphore_pend(UvisorSemaphore *semaphore, uint32_t timeout_ms); /* This function is safe to call from interrupt context. */ -UVISOR_EXTERN int __uvisor_semaphore_post(UvisorSemaphore * semaphore); +UVISOR_EXTERN int __uvisor_semaphore_post(UvisorSemaphore *semaphore); #endif diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/uvisor_spinlock_exports.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/uvisor_spinlock_exports.h index 66209ada7b6..76076d87f10 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/uvisor_spinlock_exports.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/uvisor_spinlock_exports.h @@ -25,18 +25,18 @@ typedef struct { } UvisorSpinlock; /* This function is safe to call from interrupt context. */ -UVISOR_EXTERN void uvisor_spin_init(UvisorSpinlock * spinlock); +UVISOR_EXTERN void uvisor_spin_init(UvisorSpinlock *spinlock); /* Attempt to spin lock once. Return true if the lock was obtained, false if * otherwise. This function is safe to call from interrupt context. */ -UVISOR_EXTERN bool uvisor_spin_trylock(UvisorSpinlock * spinlock); +UVISOR_EXTERN bool uvisor_spin_trylock(UvisorSpinlock *spinlock); /* Spin in a tight loop until the lock is obtained. This function is safe to * call from interrupt context, but probably not wise. */ -UVISOR_EXTERN void uvisor_spin_lock(UvisorSpinlock * spinlock); +UVISOR_EXTERN void uvisor_spin_lock(UvisorSpinlock *spinlock); /* Unlock the spin lock. This function is safe to call from interrupt context. * */ -UVISOR_EXTERN void uvisor_spin_unlock(UvisorSpinlock * spinlock); +UVISOR_EXTERN void uvisor_spin_unlock(UvisorSpinlock *spinlock); #endif /* __UVISOR_API_UVISOR_SPINLOCK_H__ */ diff --git a/features/FEATURE_UVISOR/includes/uvisor/api/inc/vmpu_exports.h b/features/FEATURE_UVISOR/includes/uvisor/api/inc/vmpu_exports.h index a241c01a457..c4ba3c47e68 100644 --- a/features/FEATURE_UVISOR/includes/uvisor/api/inc/vmpu_exports.h +++ b/features/FEATURE_UVISOR/includes/uvisor/api/inc/vmpu_exports.h @@ -146,7 +146,7 @@ typedef uint32_t UvisorBoxAcl; typedef struct { - void * param1; + void *param1; uint32_t param2; UvisorBoxAcl acl; } UVISOR_PACKED UvisorBoxAclItem; @@ -189,10 +189,10 @@ typedef struct { /* Opaque-to-uVisor data that potentially contains uvisor-lib-specific or * OS-specific per-box configuration */ - const void * const lib_config; + const void *const lib_config; - const char * const box_namespace; - const UvisorBoxAclItem * const acl_list; + const char *const box_namespace; + const UvisorBoxAclItem *const acl_list; const uint32_t acl_count; } UVISOR_PACKED UvisorBoxConfig; @@ -206,7 +206,7 @@ typedef struct { * for loops to scan the pointers to all the SRAM sections and access them * individually. */ union { - void * pointers[UVISOR_BSS_SECTIONS_COUNT]; + void *pointers[UVISOR_BSS_SECTIONS_COUNT]; UvisorBssSections address_of; } bss; @@ -215,13 +215,13 @@ typedef struct { /* Pointer to the currently active heap. * This is set to `NULL` by uVisor, signalling to the user lib that the * box heap needs to be initialized before use! */ - void * active_heap; + void *active_heap; /* Box ID */ int box_id_self; /* Pointer to the box config */ - const UvisorBoxConfig * config; + const UvisorBoxConfig *config; } UVISOR_PACKED UvisorBoxIndex; /* @@ -243,7 +243,7 @@ typedef struct { static UVISOR_FORCEINLINE int vmpu_bits(uint32_t size) { /* If size is 0, the result of __builtin_clz is undefined */ - return (0 == size) ? 0: 32 - __builtin_clz(size); + return (0 == size) ? 0 : 32 - __builtin_clz(size); } #endif /* defined(UVISOR_PRESENT) && UVISOR_PRESENT == 1 */ diff --git a/features/FEATURE_UVISOR/source/page_allocator_config.h b/features/FEATURE_UVISOR/source/page_allocator_config.h index 77bcd656d8d..2a758900fd7 100644 --- a/features/FEATURE_UVISOR/source/page_allocator_config.h +++ b/features/FEATURE_UVISOR/source/page_allocator_config.h @@ -55,7 +55,7 @@ extern uint32_t g_page_head_end_rounded; * @param map an array of `uint32_t` containing the page map * @param page the index of the page to be set */ -static inline void page_allocator_map_set(uint32_t * const map, uint8_t page) +static inline void page_allocator_map_set(uint32_t *const map, uint8_t page) { page += g_page_map_shift; map[page / 32] |= (1UL << (page % 32)); @@ -65,7 +65,7 @@ static inline void page_allocator_map_set(uint32_t * const map, uint8_t page) * @param map an array of `uint32_t` containing the page map * @param page the index of the page to be set */ -static inline void page_allocator_map_clear(uint32_t * const map, uint8_t page) +static inline void page_allocator_map_clear(uint32_t *const map, uint8_t page) { page += g_page_map_shift; map[page / 32] &= ~(1UL << (page % 32)); @@ -77,7 +77,7 @@ static inline void page_allocator_map_clear(uint32_t * const map, uint8_t page) * @retval 0 if page bit is not set * @retval 1 if page bit is set */ -static inline int page_allocator_map_get(const uint32_t * const map, uint8_t page) +static inline int page_allocator_map_get(const uint32_t *const map, uint8_t page) { page += g_page_map_shift; return (map[page / 32] >> (page % 32)) & 0x1; diff --git a/features/FEATURE_UVISOR/source/rtx/box_init.c b/features/FEATURE_UVISOR/source/rtx/box_init.c index e56dc83653a..01890035757 100644 --- a/features/FEATURE_UVISOR/source/rtx/box_init.c +++ b/features/FEATURE_UVISOR/source/rtx/box_init.c @@ -33,7 +33,7 @@ extern int32_t svcRtxKernelLock(void); UVISOR_SET_PRIV_SYS_HOOKS(SVC_Handler, PendSV_Handler, SysTick_Handler, svcRtxKernelLock, __uvisor_semaphore_post); -extern RtxBoxIndex * const __uvisor_ps; +extern RtxBoxIndex *const __uvisor_ps; void __uvisor_initialize_rpc_queues(void) { @@ -42,13 +42,13 @@ void __uvisor_initialize_rpc_queues(void) return; #endif - UvisorBoxIndex * const index = &__uvisor_ps->index; + UvisorBoxIndex *const index = &__uvisor_ps->index; uvisor_pool_slot_t i; - uvisor_rpc_outgoing_message_queue_t * rpc_outgoing_msg_queue = &(uvisor_rpc(index)->outgoing_message_queue); - uvisor_rpc_incoming_message_queue_t * rpc_incoming_msg_queue = &(uvisor_rpc(index)->incoming_message_queue); - uvisor_rpc_fn_group_queue_t * rpc_fn_group_queue = &(uvisor_rpc(index)->fn_group_queue); + uvisor_rpc_outgoing_message_queue_t *rpc_outgoing_msg_queue = &(uvisor_rpc(index)->outgoing_message_queue); + uvisor_rpc_incoming_message_queue_t *rpc_incoming_msg_queue = &(uvisor_rpc(index)->incoming_message_queue); + uvisor_rpc_fn_group_queue_t *rpc_fn_group_queue = &(uvisor_rpc(index)->fn_group_queue); /* Initialize the outgoing RPC message queue. */ if (uvisor_pool_queue_init(&rpc_outgoing_msg_queue->queue, @@ -61,7 +61,7 @@ void __uvisor_initialize_rpc_queues(void) /* Initialize all the result semaphores. */ for (i = 0; i < UVISOR_RPC_OUTGOING_MESSAGE_SLOTS; i++) { - UvisorSemaphore * semaphore = &rpc_outgoing_msg_queue->messages[i].semaphore; + UvisorSemaphore *semaphore = &rpc_outgoing_msg_queue->messages[i].semaphore; if (__uvisor_semaphore_init(semaphore, 1, 0)) { uvisor_error(USER_NOT_ALLOWED); } @@ -96,7 +96,7 @@ void __uvisor_initialize_rpc_queues(void) /* Initialize all the function group semaphores. */ for (i = 0; i < UVISOR_RPC_FN_GROUP_SLOTS; i++) { - UvisorSemaphore * semaphore = &rpc_fn_group_queue->fn_groups[i].semaphore; + UvisorSemaphore *semaphore = &rpc_fn_group_queue->fn_groups[i].semaphore; if (__uvisor_semaphore_init(semaphore, 1, 0)) { uvisor_error(USER_NOT_ALLOWED); } @@ -105,10 +105,10 @@ void __uvisor_initialize_rpc_queues(void) /* This function is called by uVisor in unprivileged mode. On this OS, we * create box main threads for the box. */ -void __uvisor_lib_box_init(void * lib_config) +void __uvisor_lib_box_init(void *lib_config) { osThreadId_t thread_id; - uvisor_box_main_t * box_main = lib_config; + uvisor_box_main_t *box_main = lib_config; osThreadAttr_t thread_attr = { 0 }; __uvisor_initialize_rpc_queues(); diff --git a/features/FEATURE_UVISOR/source/rtx/rtx_malloc_wrapper.c b/features/FEATURE_UVISOR/source/rtx/rtx_malloc_wrapper.c index d701fbd5b72..a572b99dd67 100644 --- a/features/FEATURE_UVISOR/source/rtx/rtx_malloc_wrapper.c +++ b/features/FEATURE_UVISOR/source/rtx/rtx_malloc_wrapper.c @@ -35,7 +35,7 @@ so using printf in malloc may lead to recursive calls! */ #define DPRINTF(...) {}; -extern RtxBoxIndex * const __uvisor_ps; +extern RtxBoxIndex *const __uvisor_ps; /** @retval 0 The kernel is not initialized. * @retval 1 The kernel is initialized.. */ @@ -97,8 +97,8 @@ static int init_allocator() } /* Initialize the process heap. */ SecureAllocator allocator = secure_allocator_create_with_pool( - (void *) __uvisor_ps->index.bss.address_of.heap, - __uvisor_ps->index.box_heap_size); + (void *) __uvisor_ps->index.bss.address_of.heap, + __uvisor_ps->index.box_heap_size); /* Set the allocator. */ ret = allocator ? 0 : -1; __uvisor_ps->index.active_heap = allocator; @@ -106,8 +106,7 @@ static int init_allocator() if (kernel_initialized) { osMutexRelease(__uvisor_ps->mutex_id); } - } - else { + } else { DPRINTF("uvisor_allocator: No process heap available!\n"); ret = -1; } @@ -124,17 +123,17 @@ typedef enum { } MemoryOperation; -static void * memory(MemoryOperation operation, uint32_t * args) +static void *memory(MemoryOperation operation, uint32_t *args) { /* Buffer the return value. */ - void * ret = NULL; + void *ret = NULL; /* Initialize allocator. */ if (init_allocator()) { return NULL; } /* Check if we need to aquire the mutex. */ int mutexed = is_kernel_initialized(); - void * allocator = __uvisor_ps->index.active_heap; + void *allocator = __uvisor_ps->index.active_heap; /* Aquire the mutex if required. * TODO: Mutex use is very coarse here. It may be sufficient to guard @@ -144,8 +143,7 @@ static void * memory(MemoryOperation operation, uint32_t * args) osMutexAcquire(__uvisor_ps->mutex_id, osWaitForever); } /* Perform the required operation. */ - switch(operation) - { + switch (operation) { case MEMOP_MALLOC: ret = secure_malloc(allocator, (size_t) args[0]); break; @@ -174,26 +172,31 @@ static void * memory(MemoryOperation operation, uint32_t * args) /* Wrapped memory management functions. */ #if defined (__GNUC__) -void * __wrap__malloc_r(struct _reent * r, size_t size) { +void *__wrap__malloc_r(struct _reent *r, size_t size) +{ (void) r; return memory(MEMOP_MALLOC, (uint32_t *) &size); } -void * __wrap__memalign_r(struct _reent * r, size_t alignment, size_t bytes) { +void *__wrap__memalign_r(struct _reent *r, size_t alignment, size_t bytes) +{ (void) r; uint32_t args[2] = {(uint32_t) alignment, (uint32_t) bytes}; return memory(MEMOP_MEMALIGN, args); } -void * __wrap__calloc_r(struct _reent * r, size_t nmemb, size_t size) { +void *__wrap__calloc_r(struct _reent *r, size_t nmemb, size_t size) +{ (void) r; uint32_t args[2] = {(uint32_t) nmemb, (uint32_t) size}; return memory(MEMOP_CALLOC, args); } -void * __wrap__realloc_r(struct _reent * r, void * ptr, size_t size) { +void *__wrap__realloc_r(struct _reent *r, void *ptr, size_t size) +{ (void) r; uint32_t args[2] = {(uint32_t) ptr, (uint32_t) size}; return memory(MEMOP_REALLOC, args); } -void __wrap__free_r(struct _reent * r, void * ptr) { +void __wrap__free_r(struct _reent *r, void *ptr) +{ (void) r; memory(MEMOP_FREE, (uint32_t *) &ptr); } diff --git a/features/FEATURE_UVISOR/source/rtx/secure_allocator.c b/features/FEATURE_UVISOR/source/rtx/secure_allocator.c index 3b39972d8ab..00be08c2cd5 100644 --- a/features/FEATURE_UVISOR/source/rtx/secure_allocator.c +++ b/features/FEATURE_UVISOR/source/rtx/secure_allocator.c @@ -27,14 +27,14 @@ * rtx_memory.c, so that uVisor can manage the memory for these control blocks * within pages. */ typedef struct mem_head_s { - uint32_t size; // Memory Pool size - uint32_t used; // Used Memory + uint32_t size; // Memory Pool size + uint32_t used; // Used Memory } mem_head_t; // Memory Block Header structure typedef struct mem_block_s { - struct mem_block_s *next; // Next Memory Block in list - uint32_t info; // Info: length = <31:2>:'00', type = <1:0> + struct mem_block_s *next; // Next Memory Block in list + uint32_t info; // Info: length = <31:2>:'00', type = <1:0> } mem_block_t; /* End copy */ @@ -57,21 +57,24 @@ typedef struct { UvisorPageTable table; } SecureAllocatorInternal; -static inline UvisorPageTable * table(SecureAllocator allocator) { +static inline UvisorPageTable *table(SecureAllocator allocator) +{ return &(((SecureAllocatorInternal *) allocator)->table); } SecureAllocator secure_allocator_create_with_pool( - void * mem, + void *mem, size_t bytes) { - SecureAllocatorInternal * allocator = mem; + SecureAllocatorInternal *allocator = mem; /* Signal that this is non-page allocated memory. */ allocator->table.page_size = bytes; allocator->table.page_count = 0; /* The internal rtx_Memory memory pool structure must be placed AFTER * table.page_origins[0] !!! */ - size_t offset = OFFSETOF(SecureAllocatorInternal, table.page_origins) + sizeof(((UvisorPageTable) {0}).page_origins); + size_t offset = OFFSETOF(SecureAllocatorInternal, table.page_origins) + sizeof(((UvisorPageTable) { + 0 + }).page_origins); uintptr_t page_origin = (uintptr_t) mem + offset; /* Align page_origin to a multiple of 8 (because RTX requries 8-byte @@ -123,9 +126,11 @@ SecureAllocator secure_allocator_create_with_pages( /* Compute the required memory size for the page table. */ size_t allocator_type_size = sizeof(SecureAllocatorInternal); /* Add size for each additional page. */ - allocator_type_size += (page_count - 1) * sizeof(((UvisorPageTable) {0}).page_origins); + allocator_type_size += (page_count - 1) * sizeof(((UvisorPageTable) { + 0 + }).page_origins); /* Allocate this much memory. */ - SecureAllocatorInternal * const allocator = malloc(allocator_type_size); + SecureAllocatorInternal *const allocator = malloc(allocator_type_size); /* If malloc failed, abort. */ if (allocator == NULL) { DPRINTF("secure_allocator_create_with_pages: SecureAllocatorInternal failed to be allocated!\n\n"); @@ -136,20 +141,20 @@ SecureAllocator secure_allocator_create_with_pages( allocator->table.page_size = page_size; allocator->table.page_count = page_count; /* Get me some pages. */ - if (uvisor_page_malloc((UvisorPageTable *) &(allocator->table))) { + if (uvisor_page_malloc((UvisorPageTable *) & (allocator->table))) { free(allocator); DPRINTF("secure_allocator_create_with_pages: Not enough free pages available!\n\n"); return NULL; } /* Initialize a memory pool structure in all pages. */ - for(size_t ii = 0; ii < page_count; ii++) { + for (size_t ii = 0; ii < page_count; ii++) { /* Add each page as a pool. */ osStatus_t status = osRtxMemoryInit(allocator->table.page_origins[ii], page_size); if (status == osOK) { - DPRINTF("secure_allocator_create_with_pages: Created memory pool allocator %p with offset %d page %u\n", allocator->table.page_origins[ii], 0, ii); + DPRINTF("secure_allocator_create_with_pages: Created memory pool allocator %p with offset %d page %u\n", allocator->table.page_origins[ii], 0, ii); } else { - DPRINTF("secure_allocator_create_with_pages: Failed creating memory pool allocator %p with offset %d page %u\n", allocator->table.page_origins[ii], 0, ii); + DPRINTF("secure_allocator_create_with_pages: Failed creating memory pool allocator %p with offset %d page %u\n", allocator->table.page_origins[ii], 0, ii); } } DPRINTF("\n"); @@ -163,7 +168,7 @@ int secure_allocator_destroy( DPRINTF("secure_allocator_destroy: Destroying memory pool allocator at %p\n", table(allocator)->page_origins[0]); /* Check if we are working on statically allocated memory. */ - SecureAllocatorInternal * alloc = (SecureAllocatorInternal * const) allocator; + SecureAllocatorInternal *alloc = (SecureAllocatorInternal * const) allocator; if (alloc->table.page_count == 0) { DPRINTF("secure_allocator_destroy: %p is not page-backed memory, not freeing!\n", allocator); return -1; @@ -182,14 +187,14 @@ int secure_allocator_destroy( return 0; } -void * secure_malloc( +void *secure_malloc( SecureAllocator allocator, size_t size) { size_t index = 0; do { /* Search in this page. */ - void * mem = osRtxMemoryAlloc(table(allocator)->page_origins[index], size, 0); + void *mem = osRtxMemoryAlloc(table(allocator)->page_origins[index], size, 0); /* Return if we found something. */ if (mem) { DPRINTF("secure_malloc: Found %4uB in page %u at %p\n", size, index, mem); @@ -205,7 +210,7 @@ void * secure_malloc( return NULL; } -void * secure_aligned_alloc( +void *secure_aligned_alloc( SecureAllocator allocator, size_t alignment, size_t size) @@ -215,14 +220,14 @@ void * secure_aligned_alloc( return NULL; } /* TODO: THIS IS A NAIVE IMPLEMENTATION, which wastes much memory. */ - void * ptr = secure_malloc(allocator, size + alignment - 1); + void *ptr = secure_malloc(allocator, size + alignment - 1); if (ptr == NULL) { return NULL; } - return (void *) (((uint32_t) ptr + alignment - 1) & ~(alignment - 1)); + return (void *)(((uint32_t) ptr + alignment - 1) & ~(alignment - 1)); } -void * secure_calloc( +void *secure_calloc( SecureAllocator allocator, size_t nmemb, size_t size) @@ -231,7 +236,7 @@ void * secure_calloc( /* (size * nmemb) has overflowed. */ return NULL; } - void * ptr = secure_malloc(allocator, size * nmemb); + void *ptr = secure_malloc(allocator, size * nmemb); if (ptr == NULL) { return NULL; } @@ -239,16 +244,16 @@ void * secure_calloc( return ptr; } -void * secure_realloc( +void *secure_realloc( SecureAllocator allocator, - void * ptr, + void *ptr, size_t new_size) { /* TODO: THIS IS A NAIVE IMPLEMENTATION, which always allocates new memory, and copies the memory, then frees the old memory. */ /* Allocate new memory. */ - void * new_ptr = secure_malloc(allocator, new_size); + void *new_ptr = secure_malloc(allocator, new_size); /* If memory allocation failed, abort. */ if (new_ptr == NULL) { return NULL; @@ -257,7 +262,7 @@ void * secure_realloc( /* Passing NULL as ptr is legal, realloc acts as malloc then. */ if (ptr) { /* Get the size of the ptr memory. */ - size_t size = ((mem_block_t *) ((uint32_t) ptr - sizeof(mem_block_t)))->info & ~0x3; + size_t size = ((mem_block_t *)((uint32_t) ptr - sizeof(mem_block_t)))->info & ~0x3; /* Copy the memory to the new location, min(new_size, size). */ memcpy(new_ptr, ptr, new_size < size ? new_size : size); /* Free the previous memory. */ @@ -268,7 +273,7 @@ void * secure_realloc( void secure_free( SecureAllocator allocator, - void * ptr) + void *ptr) { size_t index = 0; do { diff --git a/features/FEATURE_UVISOR/source/rtx/tz_context.c b/features/FEATURE_UVISOR/source/rtx/tz_context.c index 0f9cbc4899e..807d71fdfdd 100644 --- a/features/FEATURE_UVISOR/source/rtx/tz_context.c +++ b/features/FEATURE_UVISOR/source/rtx/tz_context.c @@ -21,22 +21,27 @@ /* Provide do-nothing stubs for RTX's trustzone context saving hooks. uVisor * doesn't use these on ARMv8-M. */ -uint32_t TZ_InitContextSystem_S(void) { +uint32_t TZ_InitContextSystem_S(void) +{ return 1; /* Success */ } -TZ_MemoryId_t TZ_AllocModuleContext_S(TZ_ModuleId_t module) { +TZ_MemoryId_t TZ_AllocModuleContext_S(TZ_ModuleId_t module) +{ return 1; /* Always hand out slot 1. */ } -uint32_t TZ_FreeModuleContext_S(TZ_MemoryId_t id) { +uint32_t TZ_FreeModuleContext_S(TZ_MemoryId_t id) +{ return 1; /* Success */ } -uint32_t TZ_LoadContext_S(TZ_MemoryId_t id) { +uint32_t TZ_LoadContext_S(TZ_MemoryId_t id) +{ return 1; /* Success */ } -uint32_t TZ_StoreContext_S(TZ_MemoryId_t id) { +uint32_t TZ_StoreContext_S(TZ_MemoryId_t id) +{ return 1; /* Success */ } diff --git a/features/FEATURE_UVISOR/source/rtx/unsupported_malloc.c b/features/FEATURE_UVISOR/source/rtx/unsupported_malloc.c index 47559338e76..cf37e332014 100644 --- a/features/FEATURE_UVISOR/source/rtx/unsupported_malloc.c +++ b/features/FEATURE_UVISOR/source/rtx/unsupported_malloc.c @@ -21,7 +21,7 @@ #include /* for memset */ /* Forward declaration of the page allocator API. */ -extern void page_allocator_init(void * const heap_start, void * const heap_end, const uint32_t * const page_size); +extern void page_allocator_init(void *const heap_start, void *const heap_end, const uint32_t *const page_size); extern uint32_t __end__[]; /* __heap_start */ extern uint32_t __HeapLimit[]; /* __heap_end */ @@ -29,7 +29,7 @@ extern uint32_t __HeapLimit[]; /* __heap_end */ extern uint32_t __StackLimit[]; /* bottom of stack */ /* There is only one box index for box 0. */ -RtxBoxIndex * __uvisor_ps UVISOR_ALIGN(4); +RtxBoxIndex *__uvisor_ps UVISOR_ALIGN(4); static void box_index_init(void *box_bss, uint32_t heap_size) { diff --git a/features/FEATURE_UVISOR/source/rtx/unsupported_page_allocator.c b/features/FEATURE_UVISOR/source/rtx/unsupported_page_allocator.c index 62708609f79..f1df59edff1 100644 --- a/features/FEATURE_UVISOR/source/rtx/unsupported_page_allocator.c +++ b/features/FEATURE_UVISOR/source/rtx/unsupported_page_allocator.c @@ -37,8 +37,8 @@ #define page_allocator_reset_faults(...) {} /* Forward declaration of the page allocator API. */ -int page_allocator_malloc(UvisorPageTable * const table); -int page_allocator_free(const UvisorPageTable * const table); +int page_allocator_malloc(UvisorPageTable *const table); +int page_allocator_free(const UvisorPageTable *const table); int uvisor_page_malloc(UvisorPageTable *const table) { @@ -54,10 +54,10 @@ int uvisor_page_free(const UvisorPageTable *const table) static osMutexId_t g_page_allocator_mutex_id = NULL; static osRtxMutex_t g_page_allocator_mutex_data; static osMutexDef_t g_page_allocator_mutex_attr = { - .name = "uvisor_malloc_mutex", - .attr_bits = 0, /* Non-recursive */ - .cb_mem = &g_page_allocator_mutex_data, - .cb_size = sizeof(g_page_allocator_mutex_data) + .name = "uvisor_malloc_mutex", + .attr_bits = 0, /* Non-recursive */ + .cb_mem = &g_page_allocator_mutex_data, + .cb_size = sizeof(g_page_allocator_mutex_data) }; static void page_allocator_mutex_aquire() diff --git a/features/FEATURE_UVISOR/source/rtx/uvisor_semaphore.c b/features/FEATURE_UVISOR/source/rtx/uvisor_semaphore.c index e064031f6e5..5d7dc9d3b54 100644 --- a/features/FEATURE_UVISOR/source/rtx/uvisor_semaphore.c +++ b/features/FEATURE_UVISOR/source/rtx/uvisor_semaphore.c @@ -13,9 +13,9 @@ typedef struct uvisor_semaphore_internal { UVISOR_STATIC_ASSERT(UVISOR_SEMAPHORE_INTERNAL_SIZE >= sizeof(UvisorSemaphore), semaphore_size_too_small); -int __uvisor_semaphore_init(UvisorSemaphore * s, uint32_t max_count, uint32_t initial_count) +int __uvisor_semaphore_init(UvisorSemaphore *s, uint32_t max_count, uint32_t initial_count) { - uvisor_semaphore_internal_t * semaphore = (uvisor_semaphore_internal_t *) s; + uvisor_semaphore_internal_t *semaphore = (uvisor_semaphore_internal_t *) s; memset(&semaphore->data, 0, sizeof(semaphore->data)); memset(&semaphore->attr, 0, sizeof(semaphore->attr)); @@ -28,9 +28,9 @@ int __uvisor_semaphore_init(UvisorSemaphore * s, uint32_t max_count, uint32_t in return semaphore->id == NULL ? UVISOR_ERROR_OUT_OF_STRUCTURES : 0; } -int __uvisor_semaphore_pend(UvisorSemaphore * s, uint32_t timeout_ms) +int __uvisor_semaphore_pend(UvisorSemaphore *s, uint32_t timeout_ms) { - uvisor_semaphore_internal_t * semaphore = (uvisor_semaphore_internal_t *) s; + uvisor_semaphore_internal_t *semaphore = (uvisor_semaphore_internal_t *) s; osStatus_t status = osSemaphoreAcquire(semaphore->id, timeout_ms); @@ -45,7 +45,8 @@ int __uvisor_semaphore_pend(UvisorSemaphore * s, uint32_t timeout_ms) return 0; } -int __uvisor_semaphore_post(UvisorSemaphore * s) { - uvisor_semaphore_internal_t * semaphore = (uvisor_semaphore_internal_t *) s; +int __uvisor_semaphore_post(UvisorSemaphore *s) +{ + uvisor_semaphore_internal_t *semaphore = (uvisor_semaphore_internal_t *) s; return osSemaphoreRelease(semaphore->id); } diff --git a/features/TESTS/filesystem/fat_filesystem/main.cpp b/features/TESTS/filesystem/fat_filesystem/main.cpp index 45d393ffd97..cca9acca1cf 100644 --- a/features/TESTS/filesystem/fat_filesystem/main.cpp +++ b/features/TESTS/filesystem/fat_filesystem/main.cpp @@ -26,16 +26,17 @@ using namespace utest::v1; #ifndef MBED_EXTENDED_TESTS - #error [NOT_SUPPORTED] Filesystem tests not supported by default +#error [NOT_SUPPORTED] Filesystem tests not supported by default #endif // Test block device #define BLOCK_SIZE 512 -HeapBlockDevice bd(128*BLOCK_SIZE, BLOCK_SIZE); +HeapBlockDevice bd(128 * BLOCK_SIZE, BLOCK_SIZE); // Test formatting -void test_format() { +void test_format() +{ int err = FATFileSystem::format(&bd); TEST_ASSERT_EQUAL(0, err); } @@ -43,7 +44,8 @@ void test_format() { // Simple test for reading/writing files template -void test_read_write() { +void test_read_write() +{ FATFileSystem fs("fat"); int err = fs.mount(&bd); @@ -51,7 +53,7 @@ void test_read_write() { uint8_t *buffer = (uint8_t *)malloc(TEST_SIZE); TEST_ASSERT(buffer); - + // Fill with random sequence srand(1); for (int i = 0; i < TEST_SIZE; i++) { @@ -86,7 +88,8 @@ void test_read_write() { // Simple test for iterating dir entries -void test_read_dir() { +void test_read_dir() +{ FATFileSystem fs("fat"); int err = fs.mount(&bd); @@ -147,20 +150,22 @@ void test_read_dir() { // Test setup -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(10, "default_auto"); return verbose_test_setup_handler(number_of_cases); } Case cases[] = { Case("Testing formating", test_format), - Case("Testing read write < block", test_read_write), - Case("Testing read write > block", test_read_write<2*BLOCK_SIZE>), + Case("Testing read write < block", test_read_write < BLOCK_SIZE / 2 >), + Case("Testing read write > block", test_read_write<2 * BLOCK_SIZE>), Case("Testing dir iteration", test_read_dir), }; Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/features/TESTS/filesystem/heap_block_device/main.cpp b/features/TESTS/filesystem/heap_block_device/main.cpp index 20fbb8d8b94..59c5a199c3b 100644 --- a/features/TESTS/filesystem/heap_block_device/main.cpp +++ b/features/TESTS/filesystem/heap_block_device/main.cpp @@ -25,7 +25,7 @@ using namespace utest::v1; // TODO HACK, replace with available ram/heap property #if defined(TARGET_MTB_MTS_XDOT) - #error [NOT_SUPPORTED] Insufficient heap for heap block device tests +#error [NOT_SUPPORTED] Insufficient heap for heap block device tests #endif #define TEST_BLOCK_SIZE 128 @@ -45,19 +45,20 @@ const struct { // Simple test that read/writes random set of blocks -void test_read_write() { +void test_read_write() +{ HeapBlockDevice bd(TEST_BLOCK_DEVICE_SIZE, TEST_BLOCK_SIZE); int err = bd.init(); TEST_ASSERT_EQUAL(0, err); - for (unsigned a = 0; a < sizeof(ATTRS)/sizeof(ATTRS[0]); a++) { + for (unsigned a = 0; a < sizeof(ATTRS) / sizeof(ATTRS[0]); a++) { static const char *prefixes[] = {"", "k", "M", "G"}; for (int i = 3; i >= 0; i--) { bd_size_t size = (bd.*ATTRS[a].method)(); - if (size >= (1ULL << 10*i)) { + if (size >= (1ULL << 10 * i)) { printf("%s: %llu%sbytes (%llubytes)\n", - ATTRS[a].name, size >> 10*i, prefixes[i], size); + ATTRS[a].name, size >> 10 * i, prefixes[i], size); break; } } @@ -67,11 +68,11 @@ void test_read_write() { uint8_t *write_block = new uint8_t[block_size]; uint8_t *read_block = new uint8_t[block_size]; uint8_t *error_mask = new uint8_t[TEST_ERROR_MASK]; - unsigned addrwidth = ceil(log(float(bd.size()-1)) / log(float(16)))+1; + unsigned addrwidth = ceil(log(float(bd.size() - 1)) / log(float(16))) + 1; for (int b = 0; b < TEST_BLOCK_COUNT; b++) { // Find a random block - bd_addr_t block = (rand()*block_size) % bd.size(); + bd_addr_t block = (rand() * block_size) % bd.size(); // Use next random number as temporary seed to keep // the address progressing in the pseudorandom sequence @@ -109,13 +110,13 @@ void test_read_write() { // Find error mask for debugging memset(error_mask, 0, TEST_ERROR_MASK); - bd_size_t error_scale = block_size / (TEST_ERROR_MASK*8); + bd_size_t error_scale = block_size / (TEST_ERROR_MASK * 8); srand(seed); - for (bd_size_t i = 0; i < TEST_ERROR_MASK*8; i++) { + for (bd_size_t i = 0; i < TEST_ERROR_MASK * 8; i++) { for (bd_size_t j = 0; j < error_scale; j++) { - if ((0xff & rand()) != read_block[i*error_scale + j]) { - error_mask[i/8] |= 1 << (i%8); + if ((0xff & rand()) != read_block[i * error_scale + j]) { + error_mask[i / 8] |= 1 << (i % 8); } } } @@ -132,14 +133,15 @@ void test_read_write() { TEST_ASSERT_EQUAL(0xff & rand(), read_block[i]); } } - + err = bd.deinit(); TEST_ASSERT_EQUAL(0, err); } // Test setup -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(30, "default_auto"); return verbose_test_setup_handler(number_of_cases); } @@ -150,6 +152,7 @@ Case cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/features/TESTS/filesystem/mbr_block_device/main.cpp b/features/TESTS/filesystem/mbr_block_device/main.cpp index 633e7463e2e..0c3523cabb9 100644 --- a/features/TESTS/filesystem/mbr_block_device/main.cpp +++ b/features/TESTS/filesystem/mbr_block_device/main.cpp @@ -26,22 +26,22 @@ using namespace utest::v1; // TODO HACK, replace with available ram/heap property #if defined(TARGET_MTB_MTS_XDOT) - #error [NOT_SUPPORTED] Insufficient heap for heap block device tests +#error [NOT_SUPPORTED] Insufficient heap for heap block device tests #endif #define BLOCK_COUNT 16 #define BLOCK_SIZE 512 -HeapBlockDevice bd(BLOCK_COUNT*BLOCK_SIZE, BLOCK_SIZE); +HeapBlockDevice bd(BLOCK_COUNT *BLOCK_SIZE, BLOCK_SIZE); // Testing formatting of master boot record void test_mbr_format() { // Create two partitions splitting device in ~half - int err = MBRBlockDevice::partition(&bd, 1, 0x83, 0, (BLOCK_COUNT/2)*BLOCK_SIZE); + int err = MBRBlockDevice::partition(&bd, 1, 0x83, 0, (BLOCK_COUNT / 2) * BLOCK_SIZE); TEST_ASSERT_EQUAL(0, err); - err = MBRBlockDevice::partition(&bd, 2, 0x83, -(BLOCK_COUNT/2)*BLOCK_SIZE); + err = MBRBlockDevice::partition(&bd, 2, 0x83, -(BLOCK_COUNT / 2) * BLOCK_SIZE); TEST_ASSERT_EQUAL(0, err); // Load both partitions, as well as a third to check for invalid partitions @@ -87,13 +87,13 @@ void test_mbr_attr() printf("partition 1 erase size: %llu bytes\n", part1.get_erase_size()); printf("partition 1 size: %llu bytes\n", part1.size()); TEST_ASSERT_EQUAL(1, part1.get_partition_number()); - TEST_ASSERT_EQUAL(1*BLOCK_SIZE, part1.get_partition_start()); - TEST_ASSERT_EQUAL((BLOCK_COUNT/2)*BLOCK_SIZE, part1.get_partition_stop()); + TEST_ASSERT_EQUAL(1 * BLOCK_SIZE, part1.get_partition_start()); + TEST_ASSERT_EQUAL((BLOCK_COUNT / 2)*BLOCK_SIZE, part1.get_partition_stop()); TEST_ASSERT_EQUAL(0x83, part1.get_partition_type()); TEST_ASSERT_EQUAL(BLOCK_SIZE, part1.get_read_size()); TEST_ASSERT_EQUAL(BLOCK_SIZE, part1.get_program_size()); TEST_ASSERT_EQUAL(BLOCK_SIZE, part1.get_erase_size()); - TEST_ASSERT_EQUAL(((BLOCK_COUNT/2)-1)*BLOCK_SIZE, part1.size()); + TEST_ASSERT_EQUAL(((BLOCK_COUNT / 2) - 1)*BLOCK_SIZE, part1.size()); printf("partition 2 partition number: %d\n", part2.get_partition_number()); printf("partition 2 partition start: 0x%llx\n", part2.get_partition_start()); @@ -104,13 +104,13 @@ void test_mbr_attr() printf("partition 2 erase size: %llu bytes\n", part2.get_erase_size()); printf("partition 2 size: %llu bytes\n", part2.size()); TEST_ASSERT_EQUAL(2, part2.get_partition_number()); - TEST_ASSERT_EQUAL((BLOCK_COUNT/2)*BLOCK_SIZE, part2.get_partition_start()); - TEST_ASSERT_EQUAL(BLOCK_COUNT*BLOCK_SIZE, part2.get_partition_stop()); + TEST_ASSERT_EQUAL((BLOCK_COUNT / 2)*BLOCK_SIZE, part2.get_partition_start()); + TEST_ASSERT_EQUAL(BLOCK_COUNT * BLOCK_SIZE, part2.get_partition_stop()); TEST_ASSERT_EQUAL(0x83, part2.get_partition_type()); TEST_ASSERT_EQUAL(BLOCK_SIZE, part2.get_read_size()); TEST_ASSERT_EQUAL(BLOCK_SIZE, part2.get_program_size()); TEST_ASSERT_EQUAL(BLOCK_SIZE, part2.get_erase_size()); - TEST_ASSERT_EQUAL((BLOCK_COUNT/2)*BLOCK_SIZE, part2.size()); + TEST_ASSERT_EQUAL((BLOCK_COUNT / 2)*BLOCK_SIZE, part2.size()); // Deinit partitions err = part1.deinit(); @@ -159,7 +159,7 @@ void test_mbr_read_write() } // Check with original block device - err = bd.read(read_block, 1*BLOCK_SIZE, BLOCK_SIZE); + err = bd.read(read_block, 1 * BLOCK_SIZE, BLOCK_SIZE); TEST_ASSERT_EQUAL(0, err); // Check that the data was unmodified @@ -191,7 +191,7 @@ void test_mbr_read_write() } // Check with original block device - err = bd.read(read_block, (BLOCK_COUNT/2)*BLOCK_SIZE, BLOCK_SIZE); + err = bd.read(read_block, (BLOCK_COUNT / 2) * BLOCK_SIZE, BLOCK_SIZE); TEST_ASSERT_EQUAL(0, err); // Check that the data was unmodified @@ -213,7 +213,8 @@ void test_mbr_read_write() // Test setup -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(10, "default_auto"); return verbose_test_setup_handler(number_of_cases); } @@ -226,6 +227,7 @@ Case cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/features/TESTS/filesystem/multipart_fat_filesystem/main.cpp b/features/TESTS/filesystem/multipart_fat_filesystem/main.cpp index 47d7b485d2b..91dc8c16838 100644 --- a/features/TESTS/filesystem/multipart_fat_filesystem/main.cpp +++ b/features/TESTS/filesystem/multipart_fat_filesystem/main.cpp @@ -27,22 +27,23 @@ using namespace utest::v1; #ifndef MBED_EXTENDED_TESTS - #error [NOT_SUPPORTED] Filesystem tests not supported by default +#error [NOT_SUPPORTED] Filesystem tests not supported by default #endif // Test block device #define BLOCK_SIZE 512 #define BLOCK_COUNT 512 -HeapBlockDevice bd(BLOCK_COUNT*BLOCK_SIZE, BLOCK_SIZE); +HeapBlockDevice bd(BLOCK_COUNT *BLOCK_SIZE, BLOCK_SIZE); // Test formatting and partitioning -void test_format() { +void test_format() +{ // Create two partitions splitting device in ~half - int err = MBRBlockDevice::partition(&bd, 1, 0x83, 0, (BLOCK_COUNT/2)*BLOCK_SIZE); + int err = MBRBlockDevice::partition(&bd, 1, 0x83, 0, (BLOCK_COUNT / 2) * BLOCK_SIZE); TEST_ASSERT_EQUAL(0, err); - err = MBRBlockDevice::partition(&bd, 2, 0x83, -(BLOCK_COUNT/2)*BLOCK_SIZE); + err = MBRBlockDevice::partition(&bd, 2, 0x83, -(BLOCK_COUNT / 2) * BLOCK_SIZE); TEST_ASSERT_EQUAL(0, err); // Load both partitions @@ -72,7 +73,8 @@ void test_format() { // Simple multipartition test for reading/writing files template -void test_read_write() { +void test_read_write() +{ // Load both partitions MBRBlockDevice part1(&bd, 1); int err = part1.init(); @@ -97,7 +99,7 @@ void test_read_write() { uint8_t *buffer2 = (uint8_t *)malloc(TEST_SIZE); TEST_ASSERT(buffer2); - + // Fill with random sequence srand(1); @@ -163,37 +165,38 @@ void test_read_write() { TEST_ASSERT_EQUAL(0, err); } -void test_single_mbr() { +void test_single_mbr() +{ int err = bd.init(); TEST_ASSERT_EQUAL(0, err); const bd_addr_t MBR_OFFSET = 0; const bd_addr_t FAT1_OFFSET = 1; - const bd_addr_t FAT2_OFFSET = BLOCK_COUNT/2; + const bd_addr_t FAT2_OFFSET = BLOCK_COUNT / 2; uint8_t *buffer = (uint8_t *)malloc(BLOCK_SIZE); TEST_ASSERT(buffer); // Check that all three header blocks have the 0x55aa signature - err = bd.read(buffer, MBR_OFFSET*BLOCK_SIZE, BLOCK_SIZE); + err = bd.read(buffer, MBR_OFFSET * BLOCK_SIZE, BLOCK_SIZE); TEST_ASSERT_EQUAL(0, err); - TEST_ASSERT(memcmp(&buffer[BLOCK_SIZE-2], "\x55\xaa", 2) == 0); + TEST_ASSERT(memcmp(&buffer[BLOCK_SIZE - 2], "\x55\xaa", 2) == 0); - err = bd.read(buffer, FAT1_OFFSET*BLOCK_SIZE, BLOCK_SIZE); + err = bd.read(buffer, FAT1_OFFSET * BLOCK_SIZE, BLOCK_SIZE); TEST_ASSERT_EQUAL(0, err); - TEST_ASSERT(memcmp(&buffer[BLOCK_SIZE-2], "\x55\xaa", 2) == 0); + TEST_ASSERT(memcmp(&buffer[BLOCK_SIZE - 2], "\x55\xaa", 2) == 0); - err = bd.read(buffer, FAT2_OFFSET*BLOCK_SIZE, BLOCK_SIZE); + err = bd.read(buffer, FAT2_OFFSET * BLOCK_SIZE, BLOCK_SIZE); TEST_ASSERT_EQUAL(0, err); - TEST_ASSERT(memcmp(&buffer[BLOCK_SIZE-2], "\x55\xaa", 2) == 0); + TEST_ASSERT(memcmp(&buffer[BLOCK_SIZE - 2], "\x55\xaa", 2) == 0); // Check that the headers for both filesystems contain a jump code // indicating they are actual FAT superblocks and not an extra MBR - err = bd.read(buffer, FAT1_OFFSET*BLOCK_SIZE, BLOCK_SIZE); + err = bd.read(buffer, FAT1_OFFSET * BLOCK_SIZE, BLOCK_SIZE); TEST_ASSERT_EQUAL(0, err); TEST_ASSERT(buffer[0] == 0xe9 || buffer[0] == 0xeb || buffer[0] == 0xe8); - err = bd.read(buffer, FAT2_OFFSET*BLOCK_SIZE, BLOCK_SIZE); + err = bd.read(buffer, FAT2_OFFSET * BLOCK_SIZE, BLOCK_SIZE); TEST_ASSERT_EQUAL(0, err); TEST_ASSERT(buffer[0] == 0xe9 || buffer[0] == 0xeb || buffer[0] == 0xe8); @@ -205,20 +208,22 @@ void test_single_mbr() { // Test setup -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(10, "default_auto"); return verbose_test_setup_handler(number_of_cases); } Case cases[] = { Case("Testing formating", test_format), - Case("Testing read write < block", test_read_write), - Case("Testing read write > block", test_read_write<2*BLOCK_SIZE>), + Case("Testing read write < block", test_read_write < BLOCK_SIZE / 2 >), + Case("Testing read write > block", test_read_write<2 * BLOCK_SIZE>), Case("Testing for no extra MBRs", test_single_mbr), }; Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/features/TESTS/filesystem/util_block_device/main.cpp b/features/TESTS/filesystem/util_block_device/main.cpp index 1d1721a105c..f42b414ea09 100644 --- a/features/TESTS/filesystem/util_block_device/main.cpp +++ b/features/TESTS/filesystem/util_block_device/main.cpp @@ -28,7 +28,7 @@ using namespace utest::v1; // TODO HACK, replace with available ram/heap property #if defined(TARGET_MTB_MTS_XDOT) - #error [NOT_SUPPORTED] Insufficient heap for heap block device tests +#error [NOT_SUPPORTED] Insufficient heap for heap block device tests #endif #define BLOCK_COUNT 16 @@ -36,19 +36,20 @@ using namespace utest::v1; // Simple test which read/writes blocks on a sliced block device -void test_slicing() { - HeapBlockDevice bd(BLOCK_COUNT*BLOCK_SIZE, BLOCK_SIZE); +void test_slicing() +{ + HeapBlockDevice bd(BLOCK_COUNT * BLOCK_SIZE, BLOCK_SIZE); uint8_t *write_block = new uint8_t[BLOCK_SIZE]; uint8_t *read_block = new uint8_t[BLOCK_SIZE]; // Test with first slice of block device - SlicingBlockDevice slice1(&bd, 0, (BLOCK_COUNT/2)*BLOCK_SIZE); + SlicingBlockDevice slice1(&bd, 0, (BLOCK_COUNT / 2)*BLOCK_SIZE); int err = slice1.init(); TEST_ASSERT_EQUAL(0, err); TEST_ASSERT_EQUAL(BLOCK_SIZE, slice1.get_program_size()); - TEST_ASSERT_EQUAL((BLOCK_COUNT/2)*BLOCK_SIZE, slice1.size()); + TEST_ASSERT_EQUAL((BLOCK_COUNT / 2)*BLOCK_SIZE, slice1.size()); // Fill with random sequence srand(1); @@ -84,13 +85,13 @@ void test_slicing() { // Test with second slice of block device - SlicingBlockDevice slice2(&bd, -(BLOCK_COUNT/2)*BLOCK_SIZE); + SlicingBlockDevice slice2(&bd, -(BLOCK_COUNT / 2)*BLOCK_SIZE); err = slice2.init(); TEST_ASSERT_EQUAL(0, err); TEST_ASSERT_EQUAL(BLOCK_SIZE, slice2.get_program_size()); - TEST_ASSERT_EQUAL((BLOCK_COUNT/2)*BLOCK_SIZE, slice2.size()); + TEST_ASSERT_EQUAL((BLOCK_COUNT / 2)*BLOCK_SIZE, slice2.size()); // Fill with random sequence srand(1); @@ -112,7 +113,7 @@ void test_slicing() { } // Check with original block device - err = bd.read(read_block, (BLOCK_COUNT/2)*BLOCK_SIZE, BLOCK_SIZE); + err = bd.read(read_block, (BLOCK_COUNT / 2) * BLOCK_SIZE, BLOCK_SIZE); TEST_ASSERT_EQUAL(0, err); // Check that the data was unmodified @@ -128,9 +129,10 @@ void test_slicing() { } // Simple test which read/writes blocks on a chain of block devices -void test_chaining() { - HeapBlockDevice bd1((BLOCK_COUNT/2)*BLOCK_SIZE, BLOCK_SIZE); - HeapBlockDevice bd2((BLOCK_COUNT/2)*BLOCK_SIZE, BLOCK_SIZE); +void test_chaining() +{ + HeapBlockDevice bd1((BLOCK_COUNT / 2)*BLOCK_SIZE, BLOCK_SIZE); + HeapBlockDevice bd2((BLOCK_COUNT / 2)*BLOCK_SIZE, BLOCK_SIZE); uint8_t *write_block = new uint8_t[BLOCK_SIZE]; uint8_t *read_block = new uint8_t[BLOCK_SIZE]; @@ -142,7 +144,7 @@ void test_chaining() { TEST_ASSERT_EQUAL(0, err); TEST_ASSERT_EQUAL(BLOCK_SIZE, chain.get_program_size()); - TEST_ASSERT_EQUAL(BLOCK_COUNT*BLOCK_SIZE, chain.size()); + TEST_ASSERT_EQUAL(BLOCK_COUNT * BLOCK_SIZE, chain.size()); // Fill with random sequence srand(1); @@ -164,10 +166,10 @@ void test_chaining() { } // Write, sync, and read the block - err = chain.program(write_block, (BLOCK_COUNT/2)*BLOCK_SIZE, BLOCK_SIZE); + err = chain.program(write_block, (BLOCK_COUNT / 2) * BLOCK_SIZE, BLOCK_SIZE); TEST_ASSERT_EQUAL(0, err); - err = chain.read(read_block, (BLOCK_COUNT/2)*BLOCK_SIZE, BLOCK_SIZE); + err = chain.read(read_block, (BLOCK_COUNT / 2) * BLOCK_SIZE, BLOCK_SIZE); TEST_ASSERT_EQUAL(0, err); // Check that the data was unmodified @@ -183,8 +185,9 @@ void test_chaining() { } // Simple test which read/writes blocks on a chain of block devices -void test_profiling() { - HeapBlockDevice bd(BLOCK_COUNT*BLOCK_SIZE, BLOCK_SIZE); +void test_profiling() +{ + HeapBlockDevice bd(BLOCK_COUNT * BLOCK_SIZE, BLOCK_SIZE); uint8_t *write_block = new uint8_t[BLOCK_SIZE]; uint8_t *read_block = new uint8_t[BLOCK_SIZE]; @@ -195,7 +198,7 @@ void test_profiling() { TEST_ASSERT_EQUAL(0, err); TEST_ASSERT_EQUAL(BLOCK_SIZE, profiler.get_erase_size()); - TEST_ASSERT_EQUAL(BLOCK_COUNT*BLOCK_SIZE, profiler.size()); + TEST_ASSERT_EQUAL(BLOCK_COUNT * BLOCK_SIZE, profiler.size()); // Fill with random sequence srand(1); @@ -245,7 +248,8 @@ void test_profiling() { // Test setup -utest::v1::status_t test_setup(const size_t number_of_cases) { +utest::v1::status_t test_setup(const size_t number_of_cases) +{ GREENTEA_SETUP(10, "default_auto"); return verbose_test_setup_handler(number_of_cases); } @@ -258,6 +262,7 @@ Case cases[] = { Specification specification(test_setup, cases); -int main() { +int main() +{ return !Harness::run(specification); } diff --git a/features/cellular/TESTS/cellular/cellular_all/network.cpp b/features/cellular/TESTS/cellular/cellular_all/network.cpp index e7355c4d676..6e097157d07 100644 --- a/features/cellular/TESTS/cellular/cellular_all/network.cpp +++ b/features/cellular/TESTS/cellular/cellular_all/network.cpp @@ -28,7 +28,7 @@ static bool wait_register() } CellularNetwork::RegistrationStatus status; - for (int i=0; i<180; i++) { + for (int i = 0; i < 180; i++) { tr_info("Register to network %d...", i); for (int type = 0; type < CellularNetwork::C_MAX; type++) { if (network->get_registration_status((CellularNetwork::RegistrationType)type, status) == NSAPI_ERROR_OK) { @@ -71,7 +71,7 @@ static bool wait_register() void test_attach() { - cellularDevice.set_timeout(120*1000); // 120 second timeout for at commands after power is up. It might take time to register, attach and connect + cellularDevice.set_timeout(120 * 1000); // 120 second timeout for at commands after power is up. It might take time to register, attach and connect tr_info("Register to network."); TEST_ASSERT(wait_register()); tr_info("Attach to network."); diff --git a/features/cellular/TESTS/cellular/cellular_all/sim.cpp b/features/cellular/TESTS/cellular/cellular_all/sim.cpp index d95069baaf1..8ff0cd132a8 100644 --- a/features/cellular/TESTS/cellular/cellular_all/sim.cpp +++ b/features/cellular/TESTS/cellular/cellular_all/sim.cpp @@ -39,12 +39,12 @@ void test_get_sim_state() } // creates PIN which is different than one defined in MBED_CONF_APP_CELLULAR_SIM_PIN -static void create_random_pin(char* random_pin) +static void create_random_pin(char *random_pin) { char s[11]; do { - sprintf(s,"%d", rand()); + sprintf(s, "%d", rand()); } while (strncmp(s, MBED_CONF_APP_CELLULAR_SIM_PIN, 4) == 0); diff --git a/features/cellular/TESTS/cellular/cellular_all/stack.cpp b/features/cellular/TESTS/cellular/cellular_all/stack.cpp index d4f58c2ede9..615dda00531 100644 --- a/features/cellular/TESTS/cellular/cellular_all/stack.cpp +++ b/features/cellular/TESTS/cellular/cellular_all/stack.cpp @@ -101,7 +101,7 @@ void test_socket_send_receive_non_blocking() int32_t event; event = sock_event.wait(10000); - TEST_ASSERT_MESSAGE( event>=1, "No Socket event within 10 seconds"); + TEST_ASSERT_MESSAGE(event >= 1, "No Socket event within 10 seconds"); // Read response SocketAddress address; diff --git a/features/cellular/UNITTESTS/at/at_cellularbase/at_cellularbasetest.cpp b/features/cellular/UNITTESTS/at/at_cellularbase/at_cellularbasetest.cpp index 4ad85917da7..fa544050ad8 100644 --- a/features/cellular/UNITTESTS/at/at_cellularbase/at_cellularbasetest.cpp +++ b/features/cellular/UNITTESTS/at/at_cellularbase/at_cellularbasetest.cpp @@ -20,15 +20,13 @@ TEST_GROUP(AT_CellularBase) { - Test_AT_CellularBase* unit; + Test_AT_CellularBase *unit; - void setup() - { + void setup() { unit = new Test_AT_CellularBase(); } - void teardown() - { + void teardown() { delete unit; } }; diff --git a/features/cellular/UNITTESTS/at/at_cellularbase/main.cpp b/features/cellular/UNITTESTS/at/at_cellularbase/main.cpp index a7c8e49fd98..2c5e6a63560 100644 --- a/features/cellular/UNITTESTS/at/at_cellularbase/main.cpp +++ b/features/cellular/UNITTESTS/at/at_cellularbase/main.cpp @@ -19,7 +19,7 @@ #include "CppUTest/TestPlugin.h" #include "CppUTest/TestRegistry.h" #include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char** av) +int main(int ac, char **av) { return CommandLineTestRunner::RunAllTests(ac, av); } diff --git a/features/cellular/UNITTESTS/at/at_cellularbase/test_at_cellularbase.h b/features/cellular/UNITTESTS/at/at_cellularbase/test_at_cellularbase.h index b384b9cc839..4c68cda977e 100644 --- a/features/cellular/UNITTESTS/at/at_cellularbase/test_at_cellularbase.h +++ b/features/cellular/UNITTESTS/at/at_cellularbase/test_at_cellularbase.h @@ -17,8 +17,7 @@ #ifndef TEST_AT_CELLULARBASE_H #define TEST_AT_CELLULARBASE_H -class Test_AT_CellularBase -{ +class Test_AT_CellularBase { public: Test_AT_CellularBase(); diff --git a/features/cellular/UNITTESTS/at/at_cellulardevice/at_cellulardevicetest.cpp b/features/cellular/UNITTESTS/at/at_cellulardevice/at_cellulardevicetest.cpp index 1c5165203ce..6c89176df90 100644 --- a/features/cellular/UNITTESTS/at/at_cellulardevice/at_cellulardevicetest.cpp +++ b/features/cellular/UNITTESTS/at/at_cellulardevice/at_cellulardevicetest.cpp @@ -19,15 +19,13 @@ TEST_GROUP(AT_CellularDevice) { - Test_AT_CellularDevice* unit; + Test_AT_CellularDevice *unit; - void setup() - { + void setup() { unit = new Test_AT_CellularDevice(); } - void teardown() - { + void teardown() { delete unit; } }; diff --git a/features/cellular/UNITTESTS/at/at_cellulardevice/main.cpp b/features/cellular/UNITTESTS/at/at_cellulardevice/main.cpp index c498759f38a..827f00e9d43 100644 --- a/features/cellular/UNITTESTS/at/at_cellulardevice/main.cpp +++ b/features/cellular/UNITTESTS/at/at_cellulardevice/main.cpp @@ -19,7 +19,7 @@ #include "CppUTest/TestPlugin.h" #include "CppUTest/TestRegistry.h" #include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char** av) +int main(int ac, char **av) { return CommandLineTestRunner::RunAllTests(ac, av); } diff --git a/features/cellular/UNITTESTS/at/at_cellulardevice/test_at_cellulardevice.h b/features/cellular/UNITTESTS/at/at_cellulardevice/test_at_cellulardevice.h index 83873ec4a50..4dac0d59d5e 100644 --- a/features/cellular/UNITTESTS/at/at_cellulardevice/test_at_cellulardevice.h +++ b/features/cellular/UNITTESTS/at/at_cellulardevice/test_at_cellulardevice.h @@ -17,8 +17,7 @@ #ifndef TEST_AT_CELLULARDEVICE_H #define TEST_AT_CELLULARDEVICE_H -class Test_AT_CellularDevice -{ +class Test_AT_CellularDevice { public: Test_AT_CellularDevice(); diff --git a/features/cellular/UNITTESTS/at/at_cellularinformation/at_cellularinformationtest.cpp b/features/cellular/UNITTESTS/at/at_cellularinformation/at_cellularinformationtest.cpp index 0fec4753c14..a79a4e5e11a 100644 --- a/features/cellular/UNITTESTS/at/at_cellularinformation/at_cellularinformationtest.cpp +++ b/features/cellular/UNITTESTS/at/at_cellularinformation/at_cellularinformationtest.cpp @@ -19,15 +19,13 @@ TEST_GROUP(AT_CellularInformation) { - Test_AT_CellularInformation* unit; + Test_AT_CellularInformation *unit; - void setup() - { + void setup() { unit = new Test_AT_CellularInformation(); } - void teardown() - { + void teardown() { delete unit; } }; diff --git a/features/cellular/UNITTESTS/at/at_cellularinformation/main.cpp b/features/cellular/UNITTESTS/at/at_cellularinformation/main.cpp index 48b9907f07d..bba3df884f4 100644 --- a/features/cellular/UNITTESTS/at/at_cellularinformation/main.cpp +++ b/features/cellular/UNITTESTS/at/at_cellularinformation/main.cpp @@ -19,7 +19,7 @@ #include "CppUTest/TestPlugin.h" #include "CppUTest/TestRegistry.h" #include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char** av) +int main(int ac, char **av) { return CommandLineTestRunner::RunAllTests(ac, av); } diff --git a/features/cellular/UNITTESTS/at/at_cellularinformation/test_at_cellularinformation.h b/features/cellular/UNITTESTS/at/at_cellularinformation/test_at_cellularinformation.h index 458d5a08106..c736a2d5e3d 100644 --- a/features/cellular/UNITTESTS/at/at_cellularinformation/test_at_cellularinformation.h +++ b/features/cellular/UNITTESTS/at/at_cellularinformation/test_at_cellularinformation.h @@ -17,8 +17,7 @@ #ifndef TEST_AT_CELLULARINFORMATION_H #define TEST_AT_CELLULARINFORMATION_H -class Test_AT_CellularInformation -{ +class Test_AT_CellularInformation { public: Test_AT_CellularInformation(); diff --git a/features/cellular/UNITTESTS/at/at_cellularnetwork/at_cellularnetworktest.cpp b/features/cellular/UNITTESTS/at/at_cellularnetwork/at_cellularnetworktest.cpp index 48e35182963..6fdfd1f3a76 100644 --- a/features/cellular/UNITTESTS/at/at_cellularnetwork/at_cellularnetworktest.cpp +++ b/features/cellular/UNITTESTS/at/at_cellularnetwork/at_cellularnetworktest.cpp @@ -19,15 +19,13 @@ TEST_GROUP(AT_CellularNetwork) { - Test_AT_CellularNetwork* unit; + Test_AT_CellularNetwork *unit; - void setup() - { + void setup() { unit = new Test_AT_CellularNetwork(); } - void teardown() - { + void teardown() { delete unit; } }; diff --git a/features/cellular/UNITTESTS/at/at_cellularnetwork/main.cpp b/features/cellular/UNITTESTS/at/at_cellularnetwork/main.cpp index 2c45fb6cbf4..aec2c257bdc 100644 --- a/features/cellular/UNITTESTS/at/at_cellularnetwork/main.cpp +++ b/features/cellular/UNITTESTS/at/at_cellularnetwork/main.cpp @@ -19,7 +19,7 @@ #include "CppUTest/TestPlugin.h" #include "CppUTest/TestRegistry.h" #include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char** av) +int main(int ac, char **av) { return CommandLineTestRunner::RunAllTests(ac, av); } diff --git a/features/cellular/UNITTESTS/at/at_cellularnetwork/test_at_cellularnetwork.cpp b/features/cellular/UNITTESTS/at/at_cellularnetwork/test_at_cellularnetwork.cpp index c0571e36d8a..e4b035425ed 100644 --- a/features/cellular/UNITTESTS/at/at_cellularnetwork/test_at_cellularnetwork.cpp +++ b/features/cellular/UNITTESTS/at/at_cellularnetwork/test_at_cellularnetwork.cpp @@ -32,7 +32,10 @@ class my_AT_CN : public AT_CellularNetwork { public: my_AT_CN(ATHandler &atHandler) : AT_CellularNetwork(atHandler) {} virtual ~my_AT_CN() {} - NetworkStack *get_stack() {return AT_CellularNetwork::get_stack();} + NetworkStack *get_stack() + { + return AT_CellularNetwork::get_stack(); + } }; void conn_stat_cb(nsapi_error_t error) @@ -277,11 +280,11 @@ void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_extended_signal_qualit ATHandler at(&fh1, que, 0, ","); AT_CellularNetwork cn(at); - int rx,be,rs,ec,rsrq,rsrp; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.get_extended_signal_quality(rx, be,rs,ec,rsrq, rsrp)); + int rx, be, rs, ec, rsrq, rsrp; + CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.get_extended_signal_quality(rx, be, rs, ec, rsrq, rsrp)); ATHandler_stub::int_value = 1; - CHECK(NSAPI_ERROR_OK == cn.get_extended_signal_quality(rx, be,rs,ec,rsrq, rsrp)); + CHECK(NSAPI_ERROR_OK == cn.get_extended_signal_quality(rx, be, rs, ec, rsrq, rsrp)); } void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_signal_quality() @@ -291,11 +294,11 @@ void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_signal_quality() ATHandler at(&fh1, que, 0, ","); AT_CellularNetwork cn(at); - int rs,ber; - CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.get_signal_quality(rs,ber)); + int rs, ber; + CHECK(NSAPI_ERROR_DEVICE_ERROR == cn.get_signal_quality(rs, ber)); ATHandler_stub::int_value = 1; - CHECK(NSAPI_ERROR_OK == cn.get_signal_quality(rs,ber)); + CHECK(NSAPI_ERROR_OK == cn.get_signal_quality(rs, ber)); } void Test_AT_CellularNetwork::test_AT_CellularNetwork_get_cell_id() diff --git a/features/cellular/UNITTESTS/at/at_cellularnetwork/test_at_cellularnetwork.h b/features/cellular/UNITTESTS/at/at_cellularnetwork/test_at_cellularnetwork.h index f36fdf034a5..2f150787f00 100644 --- a/features/cellular/UNITTESTS/at/at_cellularnetwork/test_at_cellularnetwork.h +++ b/features/cellular/UNITTESTS/at/at_cellularnetwork/test_at_cellularnetwork.h @@ -17,8 +17,7 @@ #ifndef TEST_AT_CELLULARNETWORK_H #define TEST_AT_CELLULARNETWORK_H -class Test_AT_CellularNetwork -{ +class Test_AT_CellularNetwork { public: Test_AT_CellularNetwork(); diff --git a/features/cellular/UNITTESTS/at/at_cellularpower/at_cellularpowertest.cpp b/features/cellular/UNITTESTS/at/at_cellularpower/at_cellularpowertest.cpp index e7c70726061..ace200ec08d 100644 --- a/features/cellular/UNITTESTS/at/at_cellularpower/at_cellularpowertest.cpp +++ b/features/cellular/UNITTESTS/at/at_cellularpower/at_cellularpowertest.cpp @@ -19,15 +19,13 @@ TEST_GROUP(AT_CellularPower) { - Test_AT_CellularPower* unit; + Test_AT_CellularPower *unit; - void setup() - { + void setup() { unit = new Test_AT_CellularPower(); } - void teardown() - { + void teardown() { delete unit; } }; diff --git a/features/cellular/UNITTESTS/at/at_cellularpower/main.cpp b/features/cellular/UNITTESTS/at/at_cellularpower/main.cpp index a610f2976be..5580d261667 100644 --- a/features/cellular/UNITTESTS/at/at_cellularpower/main.cpp +++ b/features/cellular/UNITTESTS/at/at_cellularpower/main.cpp @@ -19,7 +19,7 @@ #include "CppUTest/TestPlugin.h" #include "CppUTest/TestRegistry.h" #include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char** av) +int main(int ac, char **av) { return CommandLineTestRunner::RunAllTests(ac, av); } diff --git a/features/cellular/UNITTESTS/at/at_cellularpower/test_at_cellularpower.cpp b/features/cellular/UNITTESTS/at/at_cellularpower/test_at_cellularpower.cpp index f26485e2e23..41edb552d30 100644 --- a/features/cellular/UNITTESTS/at/at_cellularpower/test_at_cellularpower.cpp +++ b/features/cellular/UNITTESTS/at/at_cellularpower/test_at_cellularpower.cpp @@ -108,22 +108,22 @@ void Test_AT_CellularPower::test_AT_CellularPower_opt_power_save_mode() AT_CellularPower pow(at); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_AUTH_FAILURE; - CHECK(NSAPI_ERROR_AUTH_FAILURE == pow.opt_power_save_mode(0,0)); + CHECK(NSAPI_ERROR_AUTH_FAILURE == pow.opt_power_save_mode(0, 0)); - CHECK(NSAPI_ERROR_AUTH_FAILURE == pow.opt_power_save_mode(10,0)); + CHECK(NSAPI_ERROR_AUTH_FAILURE == pow.opt_power_save_mode(10, 0)); - CHECK(NSAPI_ERROR_AUTH_FAILURE == pow.opt_power_save_mode(912,0)); + CHECK(NSAPI_ERROR_AUTH_FAILURE == pow.opt_power_save_mode(912, 0)); - CHECK(NSAPI_ERROR_AUTH_FAILURE == pow.opt_power_save_mode(1834,1834)); + CHECK(NSAPI_ERROR_AUTH_FAILURE == pow.opt_power_save_mode(1834, 1834)); - CHECK(NSAPI_ERROR_AUTH_FAILURE == pow.opt_power_save_mode(18345,18345)); + CHECK(NSAPI_ERROR_AUTH_FAILURE == pow.opt_power_save_mode(18345, 18345)); - CHECK(NSAPI_ERROR_AUTH_FAILURE == pow.opt_power_save_mode(101234,101234)); + CHECK(NSAPI_ERROR_AUTH_FAILURE == pow.opt_power_save_mode(101234, 101234)); - CHECK(NSAPI_ERROR_AUTH_FAILURE == pow.opt_power_save_mode(1012345,1012345)); + CHECK(NSAPI_ERROR_AUTH_FAILURE == pow.opt_power_save_mode(1012345, 1012345)); ATHandler_stub::nsapi_error_value = NSAPI_ERROR_OK; - CHECK(NSAPI_ERROR_OK == pow.opt_power_save_mode(39612345,39612345)); + CHECK(NSAPI_ERROR_OK == pow.opt_power_save_mode(39612345, 39612345)); } void Test_AT_CellularPower::test_AT_CellularPower_opt_receive_period() diff --git a/features/cellular/UNITTESTS/at/at_cellularpower/test_at_cellularpower.h b/features/cellular/UNITTESTS/at/at_cellularpower/test_at_cellularpower.h index cd32d6acd67..c10c05615af 100644 --- a/features/cellular/UNITTESTS/at/at_cellularpower/test_at_cellularpower.h +++ b/features/cellular/UNITTESTS/at/at_cellularpower/test_at_cellularpower.h @@ -17,8 +17,7 @@ #ifndef TEST_AT_CELLULARPOWER_H #define TEST_AT_CELLULARPOWER_H -class Test_AT_CellularPower -{ +class Test_AT_CellularPower { public: Test_AT_CellularPower(); diff --git a/features/cellular/UNITTESTS/at/at_cellularsim/at_cellularsimtest.cpp b/features/cellular/UNITTESTS/at/at_cellularsim/at_cellularsimtest.cpp index f472d2afb47..44261b9021d 100644 --- a/features/cellular/UNITTESTS/at/at_cellularsim/at_cellularsimtest.cpp +++ b/features/cellular/UNITTESTS/at/at_cellularsim/at_cellularsimtest.cpp @@ -19,15 +19,13 @@ TEST_GROUP(AT_CellularSIM) { - Test_AT_CellularSIM* unit; + Test_AT_CellularSIM *unit; - void setup() - { + void setup() { unit = new Test_AT_CellularSIM(); } - void teardown() - { + void teardown() { delete unit; } }; diff --git a/features/cellular/UNITTESTS/at/at_cellularsim/main.cpp b/features/cellular/UNITTESTS/at/at_cellularsim/main.cpp index 0566c80f336..394a1f7d6d1 100644 --- a/features/cellular/UNITTESTS/at/at_cellularsim/main.cpp +++ b/features/cellular/UNITTESTS/at/at_cellularsim/main.cpp @@ -19,7 +19,7 @@ #include "CppUTest/TestPlugin.h" #include "CppUTest/TestRegistry.h" #include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char** av) +int main(int ac, char **av) { return CommandLineTestRunner::RunAllTests(ac, av); } diff --git a/features/cellular/UNITTESTS/at/at_cellularsim/test_at_cellularsim.h b/features/cellular/UNITTESTS/at/at_cellularsim/test_at_cellularsim.h index 95e296270ff..9f14d6cb8fe 100644 --- a/features/cellular/UNITTESTS/at/at_cellularsim/test_at_cellularsim.h +++ b/features/cellular/UNITTESTS/at/at_cellularsim/test_at_cellularsim.h @@ -17,8 +17,7 @@ #ifndef TEST_AT_CELLULARSIM_H #define TEST_AT_CELLULARSIM_H -class Test_AT_CellularSIM -{ +class Test_AT_CellularSIM { public: Test_AT_CellularSIM(); diff --git a/features/cellular/UNITTESTS/at/at_cellularsms/at_cellularsmstest.cpp b/features/cellular/UNITTESTS/at/at_cellularsms/at_cellularsmstest.cpp index 88754bfc4ab..2f2d48cf0dd 100644 --- a/features/cellular/UNITTESTS/at/at_cellularsms/at_cellularsmstest.cpp +++ b/features/cellular/UNITTESTS/at/at_cellularsms/at_cellularsmstest.cpp @@ -19,15 +19,13 @@ TEST_GROUP(AT_CellularSMS) { - Test_AT_CellularSMS* unit; + Test_AT_CellularSMS *unit; - void setup() - { + void setup() { unit = new Test_AT_CellularSMS(); } - void teardown() - { + void teardown() { delete unit; } }; diff --git a/features/cellular/UNITTESTS/at/at_cellularsms/main.cpp b/features/cellular/UNITTESTS/at/at_cellularsms/main.cpp index a1fc31e69af..04d6d690b0a 100644 --- a/features/cellular/UNITTESTS/at/at_cellularsms/main.cpp +++ b/features/cellular/UNITTESTS/at/at_cellularsms/main.cpp @@ -19,7 +19,7 @@ #include "CppUTest/TestPlugin.h" #include "CppUTest/TestRegistry.h" #include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char** av) +int main(int ac, char **av) { return CommandLineTestRunner::RunAllTests(ac, av); } diff --git a/features/cellular/UNITTESTS/at/at_cellularsms/test_at_cellularsms.h b/features/cellular/UNITTESTS/at/at_cellularsms/test_at_cellularsms.h index 43eb7ebdf58..c83d312fa1d 100644 --- a/features/cellular/UNITTESTS/at/at_cellularsms/test_at_cellularsms.h +++ b/features/cellular/UNITTESTS/at/at_cellularsms/test_at_cellularsms.h @@ -17,8 +17,7 @@ #ifndef TEST_AT_CELLULARSMS_H #define TEST_AT_CELLULARSMS_H -class Test_AT_CellularSMS -{ +class Test_AT_CellularSMS { public: Test_AT_CellularSMS(); diff --git a/features/cellular/UNITTESTS/at/at_cellularstack/at_cellularstacktest.cpp b/features/cellular/UNITTESTS/at/at_cellularstack/at_cellularstacktest.cpp index d4815f92ae6..bd3993e3f28 100644 --- a/features/cellular/UNITTESTS/at/at_cellularstack/at_cellularstacktest.cpp +++ b/features/cellular/UNITTESTS/at/at_cellularstack/at_cellularstacktest.cpp @@ -19,15 +19,13 @@ TEST_GROUP(AT_CellularStack) { - Test_AT_CellularStack* unit; + Test_AT_CellularStack *unit; - void setup() - { + void setup() { unit = new Test_AT_CellularStack(); } - void teardown() - { + void teardown() { delete unit; } }; diff --git a/features/cellular/UNITTESTS/at/at_cellularstack/main.cpp b/features/cellular/UNITTESTS/at/at_cellularstack/main.cpp index 46520ddd58e..ee45007ddea 100644 --- a/features/cellular/UNITTESTS/at/at_cellularstack/main.cpp +++ b/features/cellular/UNITTESTS/at/at_cellularstack/main.cpp @@ -19,7 +19,7 @@ #include "CppUTest/TestPlugin.h" #include "CppUTest/TestRegistry.h" #include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char** av) +int main(int ac, char **av) { return CommandLineTestRunner::RunAllTests(ac, av); } diff --git a/features/cellular/UNITTESTS/at/at_cellularstack/test_at_cellularstack.cpp b/features/cellular/UNITTESTS/at/at_cellularstack/test_at_cellularstack.cpp index 331dde5027d..413aa304a6c 100644 --- a/features/cellular/UNITTESTS/at/at_cellularstack/test_at_cellularstack.cpp +++ b/features/cellular/UNITTESTS/at/at_cellularstack/test_at_cellularstack.cpp @@ -45,48 +45,102 @@ class MyStack : public AT_CellularStack { max_packet_size = 0; } - virtual int get_max_socket_count(){return max_sock_value;} + virtual int get_max_socket_count() + { + return max_sock_value; + } - virtual int get_max_packet_size(){return max_packet_size;} + virtual int get_max_packet_size() + { + return max_packet_size; + } - virtual bool is_protocol_supported(nsapi_protocol_t protocol){return bool_value;} + virtual bool is_protocol_supported(nsapi_protocol_t protocol) + { + return bool_value; + } - virtual nsapi_error_t socket_close_impl(int sock_id){return NSAPI_ERROR_OK;} + virtual nsapi_error_t socket_close_impl(int sock_id) + { + return NSAPI_ERROR_OK; + } - virtual nsapi_error_t create_socket_impl(CellularSocket *socket){return create_error;} + virtual nsapi_error_t create_socket_impl(CellularSocket *socket) + { + return create_error; + } virtual nsapi_size_or_error_t socket_sendto_impl(CellularSocket *socket, const SocketAddress &address, - const void *data, nsapi_size_t size){return NSAPI_ERROR_OK;} + const void *data, nsapi_size_t size) + { + return NSAPI_ERROR_OK; + } virtual nsapi_size_or_error_t socket_recvfrom_impl(CellularSocket *socket, SocketAddress *address, - void *buffer, nsapi_size_t size) {return NSAPI_ERROR_OK;} + void *buffer, nsapi_size_t size) + { + return NSAPI_ERROR_OK; + } - virtual nsapi_error_t socket_open(nsapi_socket_t *handle, nsapi_protocol_t proto) {return AT_CellularStack::socket_open(handle, proto);} + virtual nsapi_error_t socket_open(nsapi_socket_t *handle, nsapi_protocol_t proto) + { + return AT_CellularStack::socket_open(handle, proto); + } - virtual nsapi_error_t socket_close(nsapi_socket_t handle) {return AT_CellularStack::socket_close(handle);} + virtual nsapi_error_t socket_close(nsapi_socket_t handle) + { + return AT_CellularStack::socket_close(handle); + } - virtual nsapi_error_t socket_bind(nsapi_socket_t handle, const SocketAddress &address) {return AT_CellularStack::socket_bind(handle, address);} + virtual nsapi_error_t socket_bind(nsapi_socket_t handle, const SocketAddress &address) + { + return AT_CellularStack::socket_bind(handle, address); + } - virtual nsapi_error_t socket_listen(nsapi_socket_t handle, int backlog) {return AT_CellularStack::socket_listen(handle, backlog);} + virtual nsapi_error_t socket_listen(nsapi_socket_t handle, int backlog) + { + return AT_CellularStack::socket_listen(handle, backlog); + } - virtual nsapi_error_t socket_connect(nsapi_socket_t handle, const SocketAddress &address) {return AT_CellularStack::socket_connect(handle, address);} + virtual nsapi_error_t socket_connect(nsapi_socket_t handle, const SocketAddress &address) + { + return AT_CellularStack::socket_connect(handle, address); + } virtual nsapi_error_t socket_accept(nsapi_socket_t server, - nsapi_socket_t *handle, SocketAddress *address=0) {return AT_CellularStack::socket_accept(server, handle, address);} + nsapi_socket_t *handle, SocketAddress *address = 0) + { + return AT_CellularStack::socket_accept(server, handle, address); + } virtual nsapi_size_or_error_t socket_send(nsapi_socket_t handle, - const void *data, nsapi_size_t size) {return AT_CellularStack::socket_send(handle, data, size);} + const void *data, nsapi_size_t size) + { + return AT_CellularStack::socket_send(handle, data, size); + } virtual nsapi_size_or_error_t socket_recv(nsapi_socket_t handle, - void *data, nsapi_size_t size) {return AT_CellularStack::socket_recv(handle, data, size);} + void *data, nsapi_size_t size) + { + return AT_CellularStack::socket_recv(handle, data, size); + } virtual nsapi_size_or_error_t socket_sendto(nsapi_socket_t handle, const SocketAddress &address, - const void *data, nsapi_size_t size) {return AT_CellularStack::socket_sendto(handle, address, data, size);} + const void *data, nsapi_size_t size) + { + return AT_CellularStack::socket_sendto(handle, address, data, size); + } virtual nsapi_size_or_error_t socket_recvfrom(nsapi_socket_t handle, SocketAddress *address, - void *buffer, nsapi_size_t size) {return AT_CellularStack::socket_recvfrom(handle, address, buffer, size);} + void *buffer, nsapi_size_t size) + { + return AT_CellularStack::socket_recvfrom(handle, address, buffer, size); + } - virtual void socket_attach(nsapi_socket_t handle, void (*callback)(void *), void *data) {return AT_CellularStack::socket_attach(handle, callback, data);} + virtual void socket_attach(nsapi_socket_t handle, void (*callback)(void *), void *data) + { + return AT_CellularStack::socket_attach(handle, callback, data); + } }; Test_AT_CellularStack::Test_AT_CellularStack() diff --git a/features/cellular/UNITTESTS/at/at_cellularstack/test_at_cellularstack.h b/features/cellular/UNITTESTS/at/at_cellularstack/test_at_cellularstack.h index 1c77553618f..b86a6d761c0 100644 --- a/features/cellular/UNITTESTS/at/at_cellularstack/test_at_cellularstack.h +++ b/features/cellular/UNITTESTS/at/at_cellularstack/test_at_cellularstack.h @@ -17,8 +17,7 @@ #ifndef TEST_AT_CELLULARSTACK_H #define TEST_AT_CELLULARSTACK_H -class Test_AT_CellularStack -{ +class Test_AT_CellularStack { public: Test_AT_CellularStack(); diff --git a/features/cellular/UNITTESTS/at/athandler/athandlertest.cpp b/features/cellular/UNITTESTS/at/athandler/athandlertest.cpp index 916608c0dd9..7d79d2b4e28 100644 --- a/features/cellular/UNITTESTS/at/athandler/athandlertest.cpp +++ b/features/cellular/UNITTESTS/at/athandler/athandlertest.cpp @@ -19,15 +19,13 @@ TEST_GROUP(ATHandler) { - Test_ATHandler* unit; + Test_ATHandler *unit; - void setup() - { + void setup() { unit = new Test_ATHandler(); } - void teardown() - { + void teardown() { delete unit; } }; diff --git a/features/cellular/UNITTESTS/at/athandler/main.cpp b/features/cellular/UNITTESTS/at/athandler/main.cpp index beac7f7f370..3f7505ccbbb 100644 --- a/features/cellular/UNITTESTS/at/athandler/main.cpp +++ b/features/cellular/UNITTESTS/at/athandler/main.cpp @@ -19,7 +19,7 @@ #include "CppUTest/TestPlugin.h" #include "CppUTest/TestRegistry.h" #include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char** av) +int main(int ac, char **av) { return CommandLineTestRunner::RunAllTests(ac, av); } diff --git a/features/cellular/UNITTESTS/at/athandler/test_athandler.cpp b/features/cellular/UNITTESTS/at/athandler/test_athandler.cpp index 7dd90756034..9a836268274 100644 --- a/features/cellular/UNITTESTS/at/athandler/test_athandler.cpp +++ b/features/cellular/UNITTESTS/at/athandler/test_athandler.cpp @@ -313,7 +313,7 @@ void Test_ATHandler::test_ATHandler_write_int() at.write_int(2147483647); - at.write_int(2147483647+1); + at.write_int(2147483647 + 1); // at.at_error(0, DeviceErrorType(0)); // at.write_int(4); @@ -548,7 +548,7 @@ void Test_ATHandler::test_ATHandler_read_int() ATHandler at(&fh1, que, 0, ","); - int32_t ret= at.read_int(); + int32_t ret = at.read_int(); CHECK(-1 == ret); char table[] = "\",\"OK\r\n\0"; @@ -559,7 +559,7 @@ void Test_ATHandler::test_ATHandler_read_int() at.clear_error(); at.resp_start(); - ret= at.read_int(); + ret = at.read_int(); CHECK(-1 == ret); char table2[] = "\"2,\"OK\r\n\0"; @@ -570,7 +570,7 @@ void Test_ATHandler::test_ATHandler_read_int() at.clear_error(); at.resp_start(); - ret= at.read_int(); + ret = at.read_int(); CHECK(2 == ret); } diff --git a/features/cellular/UNITTESTS/at/athandler/test_athandler.h b/features/cellular/UNITTESTS/at/athandler/test_athandler.h index 0acecc693c0..017e2b09729 100644 --- a/features/cellular/UNITTESTS/at/athandler/test_athandler.h +++ b/features/cellular/UNITTESTS/at/athandler/test_athandler.h @@ -17,8 +17,7 @@ #ifndef TEST_ATHANDLER_H #define TEST_ATHANDLER_H -class Test_ATHandler -{ +class Test_ATHandler { public: Test_ATHandler(); diff --git a/features/cellular/UNITTESTS/common/util/main.cpp b/features/cellular/UNITTESTS/common/util/main.cpp index 4438de28a82..6ebe3291333 100644 --- a/features/cellular/UNITTESTS/common/util/main.cpp +++ b/features/cellular/UNITTESTS/common/util/main.cpp @@ -19,7 +19,7 @@ #include "CppUTest/TestPlugin.h" #include "CppUTest/TestRegistry.h" #include "CppUTestExt/MockSupportPlugin.h" -int main(int ac, char** av) +int main(int ac, char **av) { return CommandLineTestRunner::RunAllTests(ac, av); } diff --git a/features/cellular/UNITTESTS/common/util/test_util.cpp b/features/cellular/UNITTESTS/common/util/test_util.cpp index 30459e02d0a..a8078dcf5b4 100644 --- a/features/cellular/UNITTESTS/common/util/test_util.cpp +++ b/features/cellular/UNITTESTS/common/util/test_util.cpp @@ -116,7 +116,7 @@ void Test_util::test_util_prefer_ipv6() void Test_util::test_util_separate_ip_addresses() { - char* s = (char*)malloc(128); + char *s = (char *)malloc(128); char ip[64] = {0}; char subnet[64] = {0}; diff --git a/features/cellular/UNITTESTS/common/util/test_util.h b/features/cellular/UNITTESTS/common/util/test_util.h index 1a343db2562..7f6b28ee5f5 100644 --- a/features/cellular/UNITTESTS/common/util/test_util.h +++ b/features/cellular/UNITTESTS/common/util/test_util.h @@ -17,8 +17,7 @@ #ifndef TEST_UTIL_H #define TEST_UTIL_H -class Test_util -{ +class Test_util { public: Test_util(); diff --git a/features/cellular/UNITTESTS/common/util/utiltest.cpp b/features/cellular/UNITTESTS/common/util/utiltest.cpp index dff7b105add..839cdf2f986 100644 --- a/features/cellular/UNITTESTS/common/util/utiltest.cpp +++ b/features/cellular/UNITTESTS/common/util/utiltest.cpp @@ -19,15 +19,13 @@ TEST_GROUP(util) { - Test_util* unit; + Test_util *unit; - void setup() - { + void setup() { unit = new Test_util(); } - void teardown() - { + void teardown() { delete unit; } }; diff --git a/features/cellular/UNITTESTS/stubs/ATCmdParser.cpp b/features/cellular/UNITTESTS/stubs/ATCmdParser.cpp index 8bee7b9d1fa..d9157ec8481 100644 --- a/features/cellular/UNITTESTS/stubs/ATCmdParser.cpp +++ b/features/cellular/UNITTESTS/stubs/ATCmdParser.cpp @@ -76,7 +76,7 @@ void ATCmdParser::flush() int ATCmdParser::write(const char *data, int size) { int i = 0; - for ( ; i < size; i++) { + for (; i < size; i++) { if (putc(data[i]) < 0) { return -1; } @@ -87,7 +87,7 @@ int ATCmdParser::write(const char *data, int size) int ATCmdParser::read(char *data, int size) { int i = 0; - for ( ; i < size; i++) { + for (; i < size; i++) { int c = getc(); if (c < 0) { return -1; @@ -107,7 +107,7 @@ int ATCmdParser::vprintf(const char *format, va_list args) } int i = 0; - for ( ; _buffer[i]; i++) { + for (; _buffer[i]; i++) { if (putc(_buffer[i]) < 0) { return -1; } @@ -125,7 +125,7 @@ int ATCmdParser::vscanf(const char *format, va_list args) int offset = 0; while (format[i]) { - if (format[i] == '%' && format[i+1] != '%' && format[i+1] != '*') { + if (format[i] == '%' && format[i + 1] != '%' && format[i + 1] != '*') { _buffer[offset++] = '%'; _buffer[offset++] = '*'; i++; @@ -152,7 +152,7 @@ int ATCmdParser::vscanf(const char *format, va_list args) while (true) { // Ran out of space - if (j+1 >= _buffer_size - offset) { + if (j + 1 >= _buffer_size - offset) { return false; } // Recieve next character @@ -165,12 +165,12 @@ int ATCmdParser::vscanf(const char *format, va_list args) // Check for match int count = -1; - sscanf(_buffer+offset, _buffer, &count); + sscanf(_buffer + offset, _buffer, &count); // We only succeed if all characters in the response are matched if (count == j) { // Store the found results - vsscanf(_buffer+offset, format, args); + vsscanf(_buffer + offset, format, args); return j; } } @@ -217,14 +217,14 @@ bool ATCmdParser::vrecv(const char *response, va_list args) bool whole_line_wanted = false; while (response[i]) { - if (response[i] == '%' && response[i+1] != '%' && response[i+1] != '*') { + if (response[i] == '%' && response[i + 1] != '%' && response[i + 1] != '*') { _buffer[offset++] = '%'; _buffer[offset++] = '*'; i++; } else { _buffer[offset++] = response[i++]; // Find linebreaks, taking care not to be fooled if they're in a %[^\n] conversion specification - if (response[i - 1] == '\n' && !(i >= 3 && response[i-3] == '[' && response[i-2] == '^')) { + if (response[i - 1] == '\n' && !(i >= 3 && response[i - 3] == '[' && response[i - 2] == '^')) { whole_line_wanted = true; break; } @@ -257,7 +257,7 @@ bool ATCmdParser::vrecv(const char *response, va_list args) } // Simplify newlines (borrowed from retarget.cpp) if ((c == CR && _in_prev != LF) || - (c == LF && _in_prev != CR)) { + (c == LF && _in_prev != CR)) { _in_prev = c; c = '\n'; } else if ((c == CR && _in_prev == LF) || @@ -274,7 +274,7 @@ bool ATCmdParser::vrecv(const char *response, va_list args) // Check for oob data for (struct oob *oob = _oobs; oob; oob = oob->next) { if ((unsigned)j == oob->len && memcmp( - oob->prefix, _buffer+offset, oob->len) == 0) { + oob->prefix, _buffer + offset, oob->len) == 0) { debug_if(_dbg_on, "AT! %s\n", oob->prefix); oob->cb(); @@ -295,18 +295,18 @@ bool ATCmdParser::vrecv(const char *response, va_list args) // This allows recv("Foo: %s\n") to work, and not match with just the first character of a string // (scanf does not itself match whitespace in its format string, so \n is not significant to it) } else { - sscanf(_buffer+offset, _buffer, &count); + sscanf(_buffer + offset, _buffer, &count); } // We only succeed if all characters in the response are matched if (count == j) { - debug_if(_dbg_on, "AT= %s\n", _buffer+offset); + debug_if(_dbg_on, "AT= %s\n", _buffer + offset); // Reuse the front end of the buffer memcpy(_buffer, response, i); _buffer[i] = 0; // Store the found results - vsscanf(_buffer+offset, _buffer, args); + vsscanf(_buffer + offset, _buffer, args); // Jump to next line and continue parsing response += i; @@ -315,8 +315,8 @@ bool ATCmdParser::vrecv(const char *response, va_list args) // Clear the buffer when we hit a newline or ran out of space // running out of space usually means we ran into binary data - if (c == '\n' || j+1 >= _buffer_size - offset) { - debug_if(_dbg_on, "AT< %s", _buffer+offset); + if (c == '\n' || j + 1 >= _buffer_size - offset) { + debug_if(_dbg_on, "AT< %s", _buffer + offset); j = 0; } } @@ -398,18 +398,18 @@ bool ATCmdParser::process_oob() struct oob *oob = _oobs; while (oob) { if (i == (int)oob->len && memcmp( - oob->prefix, _buffer, oob->len) == 0) { + oob->prefix, _buffer, oob->len) == 0) { debug_if(_dbg_on, "AT! %s\r\n", oob->prefix); oob->cb(); return true; } oob = oob->next; } - + // Clear the buffer when we hit a newline or ran out of space // running out of space usually means we ran into binary data - if (i+1 >= _buffer_size || - strcmp(&_buffer[i-_output_delim_size], _output_delimiter) == 0) { + if (i + 1 >= _buffer_size || + strcmp(&_buffer[i - _output_delim_size], _output_delimiter) == 0) { debug_if(_dbg_on, "AT< %s", _buffer); i = 0; diff --git a/features/cellular/UNITTESTS/stubs/ATHandler_stub.cpp b/features/cellular/UNITTESTS/stubs/ATHandler_stub.cpp index 33489c1338b..cba82b6ad94 100644 --- a/features/cellular/UNITTESTS/stubs/ATHandler_stub.cpp +++ b/features/cellular/UNITTESTS/stubs/ATHandler_stub.cpp @@ -32,7 +32,7 @@ nsapi_error_t ATHandler_stub::nsapi_error_value = 0; uint8_t ATHandler_stub::nsapi_error_ok_counter = 0; int ATHandler_stub::int_value = -1; ssize_t ATHandler_stub::ssize_value = 0; -char* ATHandler_stub::read_string_value = NULL; +char *ATHandler_stub::read_string_value = NULL; size_t ATHandler_stub::size_value = 0; size_t ATHandler_stub::return_given_size = false; bool ATHandler_stub::bool_value = false; @@ -122,7 +122,8 @@ void ATHandler::clear_error() { } -void ATHandler::skip_param(uint32_t count) { +void ATHandler::skip_param(uint32_t count) +{ } @@ -192,7 +193,7 @@ void ATHandler::resp_stop() { } -void ATHandler::cmd_start(const char* cmd) +void ATHandler::cmd_start(const char *cmd) { } @@ -200,11 +201,11 @@ void ATHandler::write_int(int param) { } -void ATHandler::write_string(const char* param, bool useQuotations) +void ATHandler::write_string(const char *param, bool useQuotations) { } -size_t ATHandler::write_bytes(const uint8_t* param, size_t len) +size_t ATHandler::write_bytes(const uint8_t *param, size_t len) { if (ATHandler_stub::return_given_size) { return len; diff --git a/features/cellular/UNITTESTS/stubs/ATHandler_stub.h b/features/cellular/UNITTESTS/stubs/ATHandler_stub.h index 72fd2695838..309cbe263ee 100644 --- a/features/cellular/UNITTESTS/stubs/ATHandler_stub.h +++ b/features/cellular/UNITTESTS/stubs/ATHandler_stub.h @@ -25,17 +25,17 @@ namespace ATHandler_stub { - extern nsapi_error_t nsapi_error_value; - extern uint8_t nsapi_error_ok_counter; - extern int int_value; - extern ssize_t ssize_value; - extern char* read_string_value; - extern size_t size_value; - extern size_t return_given_size; - extern bool bool_value; - extern uint8_t resp_info_true_counter; - extern uint8_t uint8_value; - extern mbed::FileHandle_stub *fh_value; - extern mbed::device_err_t device_err_value; - extern mbed::Callback callback; +extern nsapi_error_t nsapi_error_value; +extern uint8_t nsapi_error_ok_counter; +extern int int_value; +extern ssize_t ssize_value; +extern char *read_string_value; +extern size_t size_value; +extern size_t return_given_size; +extern bool bool_value; +extern uint8_t resp_info_true_counter; +extern uint8_t uint8_value; +extern mbed::FileHandle_stub *fh_value; +extern mbed::device_err_t device_err_value; +extern mbed::Callback callback; } diff --git a/features/cellular/UNITTESTS/stubs/AT_CellularBase_stub.cpp b/features/cellular/UNITTESTS/stubs/AT_CellularBase_stub.cpp index 0a6daf2d008..caf7c0a3cdc 100644 --- a/features/cellular/UNITTESTS/stubs/AT_CellularBase_stub.cpp +++ b/features/cellular/UNITTESTS/stubs/AT_CellularBase_stub.cpp @@ -26,12 +26,12 @@ ATHandler *AT_CellularBase_stub::handler_value = NULL; ATHandler *AT_CellularBase_stub::handler_at_constructor_value = NULL; device_err_t AT_CellularBase_stub::device_err_value; -AT_CellularBase::AT_CellularBase(ATHandler& at) : _at(at) +AT_CellularBase::AT_CellularBase(ATHandler &at) : _at(at) { AT_CellularBase_stub::handler_at_constructor_value = &_at; } -ATHandler& AT_CellularBase::get_at_handler() +ATHandler &AT_CellularBase::get_at_handler() { return *AT_CellularBase_stub::handler_value; } diff --git a/features/cellular/UNITTESTS/stubs/AT_CellularBase_stub.h b/features/cellular/UNITTESTS/stubs/AT_CellularBase_stub.h index dd57c8a547f..a4a8ae1fa19 100644 --- a/features/cellular/UNITTESTS/stubs/AT_CellularBase_stub.h +++ b/features/cellular/UNITTESTS/stubs/AT_CellularBase_stub.h @@ -18,7 +18,7 @@ #include "ATHandler.h" namespace AT_CellularBase_stub { - extern mbed::ATHandler *handler_value; - extern mbed::ATHandler *handler_at_constructor_value; - extern mbed::device_err_t device_err_value; +extern mbed::ATHandler *handler_value; +extern mbed::ATHandler *handler_at_constructor_value; +extern mbed::device_err_t device_err_value; } diff --git a/features/cellular/UNITTESTS/stubs/AT_CellularDevice_stub.cpp b/features/cellular/UNITTESTS/stubs/AT_CellularDevice_stub.cpp index 7051910e0c5..2010018ced2 100644 --- a/features/cellular/UNITTESTS/stubs/AT_CellularDevice_stub.cpp +++ b/features/cellular/UNITTESTS/stubs/AT_CellularDevice_stub.cpp @@ -26,14 +26,14 @@ AT_CellularDevice::~AT_CellularDevice() { } -ATHandler* AT_CellularDevice::get_at_handler(FileHandle *fileHandle) +ATHandler *AT_CellularDevice::get_at_handler(FileHandle *fileHandle) { return NULL; } -void AT_CellularDevice::release_at_handler(ATHandler* at_handler) +void AT_CellularDevice::release_at_handler(ATHandler *at_handler) { - + } CellularNetwork *AT_CellularDevice::open_network(FileHandle *fh) diff --git a/features/cellular/UNITTESTS/stubs/AT_CellularNetwork_stub.cpp b/features/cellular/UNITTESTS/stubs/AT_CellularNetwork_stub.cpp index c18cd32b4c9..cf0f19a4d89 100644 --- a/features/cellular/UNITTESTS/stubs/AT_CellularNetwork_stub.cpp +++ b/features/cellular/UNITTESTS/stubs/AT_CellularNetwork_stub.cpp @@ -40,7 +40,7 @@ nsapi_error_t AT_CellularNetwork::set_credentials(const char *apn, } nsapi_error_t AT_CellularNetwork::set_credentials(const char *apn, - AuthenticationType type, const char *username, const char *password) + AuthenticationType type, const char *username, const char *password) { return NSAPI_ERROR_OK; } @@ -95,7 +95,7 @@ nsapi_error_t AT_CellularNetwork::set_context_to_be_activated() // return false; //} -nsapi_ip_stack_t AT_CellularNetwork::string_to_stack_type(const char* pdp_type) +nsapi_ip_stack_t AT_CellularNetwork::string_to_stack_type(const char *pdp_type) { return IPV4_STACK; } @@ -187,26 +187,26 @@ nsapi_error_t AT_CellularNetwork::scan_plmn(operList_t &operators, int &opsCount } nsapi_error_t AT_CellularNetwork::set_ciot_optimization_config(Supported_UE_Opt supported_opt, - Preferred_UE_Opt preferred_opt) + Preferred_UE_Opt preferred_opt) { return NSAPI_ERROR_OK; } -nsapi_error_t AT_CellularNetwork::get_ciot_optimization_config(Supported_UE_Opt& supported_opt, - Preferred_UE_Opt& preferred_opt) +nsapi_error_t AT_CellularNetwork::get_ciot_optimization_config(Supported_UE_Opt &supported_opt, + Preferred_UE_Opt &preferred_opt) { return NSAPI_ERROR_OK; } nsapi_error_t AT_CellularNetwork::get_rate_control( - CellularNetwork::RateControlExceptionReports &reports, - CellularNetwork::RateControlUplinkTimeUnit &timeUnit, int &uplinkRate) + CellularNetwork::RateControlExceptionReports &reports, + CellularNetwork::RateControlUplinkTimeUnit &timeUnit, int &uplinkRate) { return NSAPI_ERROR_OK; } -nsapi_error_t AT_CellularNetwork::get_pdpcontext_params(pdpContextList_t& params_list) +nsapi_error_t AT_CellularNetwork::get_pdpcontext_params(pdpContextList_t ¶ms_list) { return NSAPI_ERROR_OK; } diff --git a/features/cellular/UNITTESTS/stubs/AT_CellularSIM_stub.cpp b/features/cellular/UNITTESTS/stubs/AT_CellularSIM_stub.cpp index 85a7f04a645..fc8820c88a7 100644 --- a/features/cellular/UNITTESTS/stubs/AT_CellularSIM_stub.cpp +++ b/features/cellular/UNITTESTS/stubs/AT_CellularSIM_stub.cpp @@ -48,7 +48,7 @@ nsapi_error_t AT_CellularSIM::set_pin_query(const char *sim_pin, bool query_pin) return NSAPI_ERROR_OK; } -nsapi_error_t AT_CellularSIM::get_imsi(char* imsi) +nsapi_error_t AT_CellularSIM::get_imsi(char *imsi) { return NSAPI_ERROR_OK; } diff --git a/features/cellular/UNITTESTS/stubs/AT_CellularSMS_stub.cpp b/features/cellular/UNITTESTS/stubs/AT_CellularSMS_stub.cpp index 5f9461c1a3b..56c3567658b 100644 --- a/features/cellular/UNITTESTS/stubs/AT_CellularSMS_stub.cpp +++ b/features/cellular/UNITTESTS/stubs/AT_CellularSMS_stub.cpp @@ -35,7 +35,7 @@ const uint16_t SMS_MAX_GSM7_CONCATENATED_SINGLE_SMS_SIZE = 153; AT_CellularSMS::AT_CellularSMS(ATHandler &at) : AT_CellularBase(at), _cb(0), _mode(CellularSMSMmodeText), - _use_8bit_encoding(false), _sim_wait_time(0), _sms_message_ref_number(1), _sms_info(NULL) + _use_8bit_encoding(false), _sim_wait_time(0), _sms_message_ref_number(1), _sms_info(NULL) { } @@ -80,13 +80,13 @@ void AT_CellularSMS::set_extra_sim_wait_time(int sim_wait_time) { } -char* AT_CellularSMS::create_pdu(const char* phone_number, const char* message, uint8_t message_length, uint8_t msg_parts, - uint8_t msg_part_number, uint8_t& header_size) +char *AT_CellularSMS::create_pdu(const char *phone_number, const char *message, uint8_t message_length, uint8_t msg_parts, + uint8_t msg_part_number, uint8_t &header_size) { return NULL; } -nsapi_size_or_error_t AT_CellularSMS::send_sms(const char* phone_number, const char* message, int msg_len) +nsapi_size_or_error_t AT_CellularSMS::send_sms(const char *phone_number, const char *message, int msg_len) { return NSAPI_ERROR_OK; } @@ -115,7 +115,7 @@ nsapi_size_or_error_t AT_CellularSMS::set_cscs(const char *chr_set) // return NSAPI_ERROR_OK; //} -nsapi_error_t AT_CellularSMS::delete_sms(sms_info_t* sms) +nsapi_error_t AT_CellularSMS::delete_sms(sms_info_t *sms) { return NSAPI_ERROR_OK; } @@ -125,35 +125,35 @@ nsapi_error_t AT_CellularSMS::delete_all_messages() return NSAPI_ERROR_OK; } -nsapi_size_or_error_t AT_CellularSMS::read_sms_from_index(int msg_index, char* buf, uint16_t len, char* phone_num, char* time_stamp) +nsapi_size_or_error_t AT_CellularSMS::read_sms_from_index(int msg_index, char *buf, uint16_t len, char *phone_num, char *time_stamp) { return NSAPI_ERROR_OK; } // read msg in PDU mode -nsapi_size_or_error_t AT_CellularSMS::read_sms(sms_info_t* sms, char* buf, char* phone_num, char* time_stamp) +nsapi_size_or_error_t AT_CellularSMS::read_sms(sms_info_t *sms, char *buf, char *phone_num, char *time_stamp) { return NSAPI_ERROR_OK; } -nsapi_size_or_error_t AT_CellularSMS::get_sms(char* buf, uint16_t len, char* phone_num, uint16_t phone_len, - char* time_stamp, uint16_t time_len, int *buf_size) +nsapi_size_or_error_t AT_CellularSMS::get_sms(char *buf, uint16_t len, char *phone_num, uint16_t phone_len, + char *time_stamp, uint16_t time_len, int *buf_size) { return NSAPI_ERROR_OK; } -nsapi_size_or_error_t AT_CellularSMS::get_data_from_pdu(const char* pdu, sms_info_t *info, int *part_number, char *phone_number, char *msg) +nsapi_size_or_error_t AT_CellularSMS::get_data_from_pdu(const char *pdu, sms_info_t *info, int *part_number, char *phone_number, char *msg) { return NSAPI_ERROR_OK; } - // read params from User DEfined Header -int AT_CellularSMS::read_udh_from_pdu(const char* pdu, sms_info_t *info, int &part_number, int &padding_bits) +// read params from User DEfined Header +int AT_CellularSMS::read_udh_from_pdu(const char *pdu, sms_info_t *info, int &part_number, int &padding_bits) { return 0; } -nsapi_size_or_error_t AT_CellularSMS::read_pdu_payload(const char* pdu, int msg_len, int scheme, char *msg, int padding_bits) +nsapi_size_or_error_t AT_CellularSMS::read_pdu_payload(const char *pdu, int msg_len, int scheme, char *msg, int padding_bits) { return NSAPI_ERROR_OK; } @@ -162,7 +162,7 @@ void AT_CellularSMS::free_linked_list() { } -void AT_CellularSMS::add_info(sms_info_t* info, int index, int part_number) +void AT_CellularSMS::add_info(sms_info_t *info, int index, int part_number) { } @@ -172,18 +172,18 @@ nsapi_error_t AT_CellularSMS::list_messages() return NSAPI_ERROR_OK; } -AT_CellularSMS::sms_info_t* AT_CellularSMS::get_oldest_sms_index() +AT_CellularSMS::sms_info_t *AT_CellularSMS::get_oldest_sms_index() { return NULL; } // if time_string_1 is greater (more fresh date) then return 1, same 0, smaller -1. Error -2 -int AT_CellularSMS::compare_time_strings(const char* time_string_1, const char* time_string_2) +int AT_CellularSMS::compare_time_strings(const char *time_string_1, const char *time_string_2) { return 0; } -bool AT_CellularSMS::create_time(const char* time_string, time_t* time) +bool AT_CellularSMS::create_time(const char *time_string, time_t *time) { return 0; } diff --git a/features/cellular/UNITTESTS/stubs/CellularUtil_stub.cpp b/features/cellular/UNITTESTS/stubs/CellularUtil_stub.cpp index d6c9a1658f3..d4bcaf49166 100644 --- a/features/cellular/UNITTESTS/stubs/CellularUtil_stub.cpp +++ b/features/cellular/UNITTESTS/stubs/CellularUtil_stub.cpp @@ -31,39 +31,39 @@ void str_remove_char(char *src, char c) { } -void uint_to_binary_str(uint32_t num, char* str, uint8_t str_size, uint8_t bit_cnt) +void uint_to_binary_str(uint32_t num, char *str, uint8_t str_size, uint8_t bit_cnt) { } // converts the given str to hex string to buf -uint16_t char_str_to_hex(const char* str, uint16_t len, char *buf, bool omit_leading_zero) +uint16_t char_str_to_hex(const char *str, uint16_t len, char *buf, bool omit_leading_zero) { return 0; } -void convert_ipv6(char* ip) +void convert_ipv6(char *ip) { } -char* find_dot_number(char* str, int dot_number) +char *find_dot_number(char *str, int dot_number) { return NULL; } -void separate_ip4like_addresses(char* orig, char* ip, size_t ip_size, char* ip2, size_t ip2_size) +void separate_ip4like_addresses(char *orig, char *ip, size_t ip_size, char *ip2, size_t ip2_size) { } -void separate_ip_addresses(char* orig, char* ip, size_t ip_size, char* ip2, size_t ip2_size) +void separate_ip_addresses(char *orig, char *ip, size_t ip_size, char *ip2, size_t ip2_size) { } -void prefer_ipv6(char* ip, size_t ip_size, char* ip2, size_t ip2_size) +void prefer_ipv6(char *ip, size_t ip_size, char *ip2, size_t ip2_size) { } -void int_to_hex_str(uint8_t num, char* buf) +void int_to_hex_str(uint8_t num, char *buf) { buf[0] = '0'; buf[1] = '2'; @@ -74,17 +74,17 @@ int hex_str_to_int(const char *hex_string, int hex_string_length) return 0; } -int hex_str_to_char_str(const char* str, uint16_t len, char *buf) +int hex_str_to_char_str(const char *str, uint16_t len, char *buf) { return 0; } -void uint_to_binary_str(uint32_t num, char* str, int str_size, int bit_cnt) +void uint_to_binary_str(uint32_t num, char *str, int str_size, int bit_cnt) { } -int char_str_to_hex_str(const char* str, uint16_t len, char *buf, bool omit_leading_zero) +int char_str_to_hex_str(const char *str, uint16_t len, char *buf, bool omit_leading_zero) { //The code is dependent on this, so this is easiest just to put here if (!str || !buf) { @@ -92,17 +92,17 @@ int char_str_to_hex_str(const char* str, uint16_t len, char *buf, bool omit_lead } char *ptr = buf; - int i=0; + int i = 0; while (i < len) { - if (omit_leading_zero == true && i == 0 && !(str[i]>>4 & 0x0F)) { + if (omit_leading_zero == true && i == 0 && !(str[i] >> 4 & 0x0F)) { *ptr++ = hex_values[(str[i]) & 0x0F]; } else { - *ptr++ = hex_values[((str[i])>>4) & 0x0F]; + *ptr++ = hex_values[((str[i]) >> 4) & 0x0F]; *ptr++ = hex_values[(str[i]) & 0x0F]; } i++; } - return ptr-buf; + return ptr - buf; } uint16_t get_dynamic_ip_port() diff --git a/features/cellular/UNITTESTS/stubs/EventQueue_stub.cpp b/features/cellular/UNITTESTS/stubs/EventQueue_stub.cpp index 235e69b6c58..2df60289771 100644 --- a/features/cellular/UNITTESTS/stubs/EventQueue_stub.cpp +++ b/features/cellular/UNITTESTS/stubs/EventQueue_stub.cpp @@ -22,29 +22,37 @@ using namespace mbed; namespace events { -EventQueue::EventQueue(unsigned event_size, unsigned char *event_pointer) { +EventQueue::EventQueue(unsigned event_size, unsigned char *event_pointer) +{ } -EventQueue::~EventQueue() { +EventQueue::~EventQueue() +{ } -void EventQueue::dispatch(int ms) { +void EventQueue::dispatch(int ms) +{ } -void EventQueue::break_dispatch() { +void EventQueue::break_dispatch() +{ } -unsigned EventQueue::tick() { +unsigned EventQueue::tick() +{ return 0; } -void EventQueue::cancel(int id) { +void EventQueue::cancel(int id) +{ } -void EventQueue::background(Callback update) { +void EventQueue::background(Callback update) +{ } -void EventQueue::chain(EventQueue *target) { +void EventQueue::chain(EventQueue *target) +{ } } diff --git a/features/cellular/UNITTESTS/stubs/FileHandle_stub.h b/features/cellular/UNITTESTS/stubs/FileHandle_stub.h index 6097f902806..c1258557fdd 100644 --- a/features/cellular/UNITTESTS/stubs/FileHandle_stub.h +++ b/features/cellular/UNITTESTS/stubs/FileHandle_stub.h @@ -26,14 +26,17 @@ static uint8_t filehandle_stub_short_value_counter = 0; static char *filehandle_stub_table = NULL; static uint8_t filehandle_stub_table_pos = 0; -class FileHandle_stub : public FileHandle -{ +class FileHandle_stub : public FileHandle { public: size_t size_value; - FileHandle_stub() {size_value = 0;} + FileHandle_stub() + { + size_value = 0; + } - virtual ssize_t read(void *buffer, size_t size){ + virtual ssize_t read(void *buffer, size_t size) + { if (filehandle_stub_table) { ssize_t ret = strlen(filehandle_stub_table) - filehandle_stub_table_pos; if (size < ret) { @@ -46,19 +49,24 @@ class FileHandle_stub : public FileHandle return 0; } - virtual ssize_t write(const void *buffer, size_t size){ - if( size_value ) { + virtual ssize_t write(const void *buffer, size_t size) + { + if (size_value) { size_value--; return size; } return 0; } - virtual off_t seek(off_t offset, int whence = SEEK_SET){return 0;} + virtual off_t seek(off_t offset, int whence = SEEK_SET) + { + return 0; + } - virtual int close(){} + virtual int close() {} - virtual short poll(short events) const{ + virtual short poll(short events) const + { if (filehandle_stub_short_value_counter) { filehandle_stub_short_value_counter--; return short_value; @@ -66,7 +74,10 @@ class FileHandle_stub : public FileHandle return 0; } - virtual void sigio(Callback func){func();} + virtual void sigio(Callback func) + { + func(); + } short short_value; }; diff --git a/features/cellular/UNITTESTS/stubs/Semaphore_stub.cpp b/features/cellular/UNITTESTS/stubs/Semaphore_stub.cpp index 3782b77f8ca..ada09df114c 100644 --- a/features/cellular/UNITTESTS/stubs/Semaphore_stub.cpp +++ b/features/cellular/UNITTESTS/stubs/Semaphore_stub.cpp @@ -19,37 +19,37 @@ namespace rtos { -Semaphore::Semaphore(int32_t count) +Semaphore::Semaphore(int32_t count) { } -Semaphore::Semaphore(int32_t count, uint16_t max_count) +Semaphore::Semaphore(int32_t count, uint16_t max_count) { } -void Semaphore::constructor(int32_t count, uint16_t max_count) +void Semaphore::constructor(int32_t count, uint16_t max_count) { - + } -int32_t Semaphore::wait(uint32_t millisec) +int32_t Semaphore::wait(uint32_t millisec) { return 0; } -int32_t Semaphore::wait_until(uint64_t millisec) +int32_t Semaphore::wait_until(uint64_t millisec) { return 0; } -osStatus Semaphore::release(void) +osStatus Semaphore::release(void) { return 0; } -Semaphore::~Semaphore() +Semaphore::~Semaphore() { } diff --git a/features/cellular/UNITTESTS/stubs/Timer_stub.cpp b/features/cellular/UNITTESTS/stubs/Timer_stub.cpp index db3ba4cd957..2e20c161aee 100644 --- a/features/cellular/UNITTESTS/stubs/Timer_stub.cpp +++ b/features/cellular/UNITTESTS/stubs/Timer_stub.cpp @@ -20,35 +20,45 @@ namespace mbed { -Timer::Timer() { +Timer::Timer() +{ } -Timer::Timer(const ticker_data_t *data) { +Timer::Timer(const ticker_data_t *data) +{ } -Timer::~Timer() { +Timer::~Timer() +{ } -void Timer::start() { +void Timer::start() +{ } -void Timer::stop() {; +void Timer::stop() +{ + ; } -int Timer::read_us() { +int Timer::read_us() +{ return 0; } -float Timer::read() { +float Timer::read() +{ return 0; } -int Timer::read_ms() { +int Timer::read_ms() +{ timer_stub_value += timer_stub_step; return timer_stub_value; } -us_timestamp_t Timer::read_high_resolution_us() { +us_timestamp_t Timer::read_high_resolution_us() +{ return 0; } @@ -56,7 +66,8 @@ void Timer::reset() { } -Timer::operator float() { +Timer::operator float() +{ return 0; } diff --git a/features/cellular/UNITTESTS/stubs/equeue_stub.c b/features/cellular/UNITTESTS/stubs/equeue_stub.c index cc5c267df13..55a52174e71 100644 --- a/features/cellular/UNITTESTS/stubs/equeue_stub.c +++ b/features/cellular/UNITTESTS/stubs/equeue_stub.c @@ -93,7 +93,7 @@ void equeue_cancel(equeue_t *queue, int id) } void equeue_background(equeue_t *queue, - void (*update)(void *timer, int ms), void *timer) + void (*update)(void *timer, int ms), void *timer) { } diff --git a/features/cellular/UNITTESTS/stubs/mbed_poll_stub.h b/features/cellular/UNITTESTS/stubs/mbed_poll_stub.h index 4d92b60b8eb..6c0a4327a92 100644 --- a/features/cellular/UNITTESTS/stubs/mbed_poll_stub.h +++ b/features/cellular/UNITTESTS/stubs/mbed_poll_stub.h @@ -20,8 +20,8 @@ #include namespace mbed_poll_stub { - extern int revents_value; - extern int int_value; +extern int revents_value; +extern int int_value; } #endif diff --git a/features/cellular/UNITTESTS/stubs/mbed_wait_api_stub.cpp b/features/cellular/UNITTESTS/stubs/mbed_wait_api_stub.cpp index 5e4873be388..f8b240544d8 100644 --- a/features/cellular/UNITTESTS/stubs/mbed_wait_api_stub.cpp +++ b/features/cellular/UNITTESTS/stubs/mbed_wait_api_stub.cpp @@ -17,11 +17,14 @@ #include "mbed_wait_api.h" -void wait(float s) { +void wait(float s) +{ } -void wait_ms(int ms) { +void wait_ms(int ms) +{ } -void wait_us(int us) { +void wait_us(int us) +{ } diff --git a/features/cellular/UNITTESTS/stubs/us_ticker_stub.cpp b/features/cellular/UNITTESTS/stubs/us_ticker_stub.cpp index 3727e1f618c..69c96accee0 100644 --- a/features/cellular/UNITTESTS/stubs/us_ticker_stub.cpp +++ b/features/cellular/UNITTESTS/stubs/us_ticker_stub.cpp @@ -19,7 +19,7 @@ #include "stdlib.h" #include "us_ticker_api.h" -const ticker_data_t* get_us_ticker_data(void) +const ticker_data_t *get_us_ticker_data(void) { return NULL; } diff --git a/features/cellular/UNITTESTS/target_h/ATCmdParser.h b/features/cellular/UNITTESTS/target_h/ATCmdParser.h index 9e562817027..c1994cc2afc 100644 --- a/features/cellular/UNITTESTS/target_h/ATCmdParser.h +++ b/features/cellular/UNITTESTS/target_h/ATCmdParser.h @@ -21,13 +21,12 @@ #include #include "FileHandle.h" -class ATCmdParser -{ +class ATCmdParser { public: ATCmdParser(mbed::FileHandle *fh, const char *output_delimiter = "\r", - int buffer_size = 256, int timeout = 8000, bool debug = false){} + int buffer_size = 256, int timeout = 8000, bool debug = false) {} - ~ATCmdParser(){} + ~ATCmdParser() {} }; #endif //__AT_CMD_PARSER_H__ diff --git a/features/cellular/UNITTESTS/target_h/rtx_os.h b/features/cellular/UNITTESTS/target_h/rtx_os.h index 3f47ec8cf05..05ecefbb7da 100644 --- a/features/cellular/UNITTESTS/target_h/rtx_os.h +++ b/features/cellular/UNITTESTS/target_h/rtx_os.h @@ -21,13 +21,13 @@ #include "inttypes.h" typedef struct osRtxSemaphore_s { - uint8_t id; ///< Object Identifier - uint8_t state; ///< Object State - uint8_t flags; ///< Object Flags - uint8_t reserved; - const char *name; ///< Object Name - uint16_t tokens; ///< Current number of tokens - uint16_t max_tokens; ///< Maximum number of tokens + uint8_t id; ///< Object Identifier + uint8_t state; ///< Object State + uint8_t flags; ///< Object Flags + uint8_t reserved; + const char *name; ///< Object Name + uint16_t tokens; ///< Current number of tokens + uint16_t max_tokens; ///< Maximum number of tokens } osRtxSemaphore_t; -#endif +#endif diff --git a/features/cellular/UNITTESTS/target_h/sys/syslimits.h b/features/cellular/UNITTESTS/target_h/sys/syslimits.h index bd27d352d56..5c90b373f14 100644 --- a/features/cellular/UNITTESTS/target_h/sys/syslimits.h +++ b/features/cellular/UNITTESTS/target_h/sys/syslimits.h @@ -14,4 +14,4 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#define NAME_MAX 255 +#define NAME_MAX 255 diff --git a/features/cellular/easy_cellular/CellularConnectionFSM.cpp b/features/cellular/easy_cellular/CellularConnectionFSM.cpp index 2735349bbe6..476e5af5390 100644 --- a/features/cellular/easy_cellular/CellularConnectionFSM.cpp +++ b/features/cellular/easy_cellular/CellularConnectionFSM.cpp @@ -38,8 +38,8 @@ namespace mbed { CellularConnectionFSM::CellularConnectionFSM() : - _serial(0), _state(STATE_INIT), _next_state(_state), _status_callback(0), _network(0), _power(0), _sim(0), - _queue(8 * EVENTS_EVENT_SIZE), _queue_thread(0), _retry_count(0), _state_retry_count(0), _at_queue(8 * EVENTS_EVENT_SIZE) + _serial(0), _state(STATE_INIT), _next_state(_state), _status_callback(0), _network(0), _power(0), _sim(0), + _queue(8 * EVENTS_EVENT_SIZE), _queue_thread(0), _retry_count(0), _state_retry_count(0), _at_queue(8 * EVENTS_EVENT_SIZE) { memset(_sim_pin, 0, sizeof(_sim_pin)); #if MBED_CONF_CELLULAR_RANDOM_MAX_START_DELAY == 0 @@ -60,7 +60,7 @@ CellularConnectionFSM::CellularConnectionFSM() : _retry_timeout_array[8] = 600; _retry_timeout_array[9] = TIMEOUT_NETWORK_MAX; _retry_array_length = MAX_RETRY_ARRAY_SIZE; - + _cellularDevice = new CELLULAR_DEVICE(_at_queue); } @@ -114,7 +114,7 @@ bool CellularConnectionFSM::open_power(FileHandle *fh) return true; } -void CellularConnectionFSM::set_sim_pin(const char * sim_pin) +void CellularConnectionFSM::set_sim_pin(const char *sim_pin) { strncpy(_sim_pin, sim_pin, sizeof(_sim_pin)); } @@ -195,19 +195,19 @@ bool CellularConnectionFSM::get_network_registration(CellularNetwork::Registrati switch (status) { case CellularNetwork::RegisteredRoaming: is_roaming = true; - // fall-through + // fall-through case CellularNetwork::RegisteredHomeNetwork: is_registered = true; break; case CellularNetwork::RegisteredSMSOnlyRoaming: is_roaming = true; - // fall-through + // fall-through case CellularNetwork::RegisteredSMSOnlyHome: tr_warn("SMS only network registration!"); break; case CellularNetwork::RegisteredCSFBNotPreferredRoaming: is_roaming = true; - // fall-through + // fall-through case CellularNetwork::RegisteredCSFBNotPreferredHome: tr_warn("Not preferred network registration!"); break; @@ -247,7 +247,7 @@ bool CellularConnectionFSM::set_attach_network() return true; } -void CellularConnectionFSM::report_failure(const char* msg) +void CellularConnectionFSM::report_failure(const char *msg) { tr_error("Cellular network failed: %s", msg); if (_status_callback) { @@ -538,17 +538,17 @@ events::EventQueue *CellularConnectionFSM::get_queue() return &_queue; } -CellularNetwork* CellularConnectionFSM::get_network() +CellularNetwork *CellularConnectionFSM::get_network() { return _network; } -CellularDevice* CellularConnectionFSM::get_device() +CellularDevice *CellularConnectionFSM::get_device() { return _cellularDevice; } -CellularSIM* CellularConnectionFSM::get_sim() +CellularSIM *CellularConnectionFSM::get_sim() { return _sim; } diff --git a/features/cellular/easy_cellular/CellularConnectionFSM.h b/features/cellular/easy_cellular/CellularConnectionFSM.h index 1de56bcac84..d86b71d9a0a 100644 --- a/features/cellular/easy_cellular/CellularConnectionFSM.h +++ b/features/cellular/easy_cellular/CellularConnectionFSM.h @@ -44,8 +44,7 @@ const int MAX_RETRY_ARRAY_SIZE = 10; * * Finite State Machine for connecting to cellular network */ -class CellularConnectionFSM -{ +class CellularConnectionFSM { public: CellularConnectionFSM(); virtual ~CellularConnectionFSM(); @@ -86,7 +85,7 @@ class CellularConnectionFSM /** Get event queue that can be chained to main event queue (or use start_dispatch) * @return event queue */ - events::EventQueue* get_queue(); + events::EventQueue *get_queue(); /** Start event queue dispatching * @return see nsapi_error_t, 0 on success @@ -100,17 +99,17 @@ class CellularConnectionFSM /** Get cellular network interface * @return network interface, NULL on failure */ - CellularNetwork* get_network(); + CellularNetwork *get_network(); /** Get cellular device interface * @return device interface, NULL on failure */ - CellularDevice* get_device(); + CellularDevice *get_device(); /** Get cellular sim interface * @return sim interface, NULL on failure */ - CellularSIM* get_sim(); + CellularSIM *get_sim(); /** Change cellular connection to the target state * @param state to continue @@ -145,7 +144,7 @@ class CellularConnectionFSM private: void device_ready(); - void report_failure(const char* msg); + void report_failure(const char *msg); void event(); UARTSerial *_serial; @@ -160,7 +159,7 @@ class CellularConnectionFSM events::EventQueue _queue; rtos::Thread *_queue_thread; CellularDevice *_cellularDevice; - char _sim_pin[PIN_SIZE+1]; + char _sim_pin[PIN_SIZE + 1]; int _retry_count; int _state_retry_count; int _start_time; diff --git a/features/cellular/easy_cellular/EasyCellularConnection.cpp b/features/cellular/easy_cellular/EasyCellularConnection.cpp index 733490ee908..0297b554f43 100644 --- a/features/cellular/easy_cellular/EasyCellularConnection.cpp +++ b/features/cellular/easy_cellular/EasyCellularConnection.cpp @@ -54,9 +54,9 @@ bool EasyCellularConnection::cellular_status(int state, int next_state) } EasyCellularConnection::EasyCellularConnection(bool debug) : - _is_connected(false), _is_initialized(false), _target_state(CellularConnectionFSM::STATE_POWER_ON), _cellularSerial( - MDMTXD, MDMRXD, MBED_CONF_PLATFORM_DEFAULT_SERIAL_BAUD_RATE), _cellularSemaphore(0), _cellularConnectionFSM(), _credentials_err( - NSAPI_ERROR_OK) + _is_connected(false), _is_initialized(false), _target_state(CellularConnectionFSM::STATE_POWER_ON), _cellularSerial( + MDMTXD, MDMRXD, MBED_CONF_PLATFORM_DEFAULT_SERIAL_BAUD_RATE), _cellularSemaphore(0), _cellularConnectionFSM(), _credentials_err( + NSAPI_ERROR_OK) { tr_info("EasyCellularConnection()"); #if MBED_CONF_CELLULAR_USE_APN_LOOKUP || MBED_CONF_PPP_CELL_IFACE_APN_LOOKUP @@ -99,7 +99,7 @@ void EasyCellularConnection::set_credentials(const char *apn, const char *uname, if (_credentials_err) { return; } - CellularNetwork * network = _cellularConnectionFSM.get_network(); + CellularNetwork *network = _cellularConnectionFSM.get_network(); if (network) { _credentials_err = network->set_credentials(apn, uname, pwd); #if MBED_CONF_CELLULAR_USE_APN_LOOKUP || MBED_CONF_PPP_CELL_IFACE_APN_LOOKUP @@ -168,20 +168,20 @@ nsapi_error_t EasyCellularConnection::connect() _target_state = CellularConnectionFSM::STATE_SIM_PIN; err = _cellularConnectionFSM.continue_to_state(_target_state); if (err == NSAPI_ERROR_OK) { - int sim_wait = _cellularSemaphore.wait(60*1000); // reserve 60 seconds to access to SIM + int sim_wait = _cellularSemaphore.wait(60 * 1000); // reserve 60 seconds to access to SIM if (sim_wait != 1) { tr_error("NO SIM ACCESS"); err = NSAPI_ERROR_NO_CONNECTION; } else { - char imsi[MAX_IMSI_LENGTH+1]; + char imsi[MAX_IMSI_LENGTH + 1]; wait(1); // need to wait to access SIM in some modems err = _cellularConnectionFSM.get_sim()->get_imsi(imsi); if (err == NSAPI_ERROR_OK) { const char *apn_config = apnconfig(imsi); if (apn_config) { - const char* apn = _APN_GET(apn_config); - const char* uname = _APN_GET(apn_config); - const char* pwd = _APN_GET(apn_config); + const char *apn = _APN_GET(apn_config); + const char *uname = _APN_GET(apn_config); + const char *pwd = _APN_GET(apn_config); tr_info("Looked up APN %s", apn); err = _cellularConnectionFSM.get_network()->set_credentials(apn, uname, pwd); } diff --git a/features/cellular/easy_cellular/EasyCellularConnection.h b/features/cellular/easy_cellular/EasyCellularConnection.h index 37d231f72d5..62ea9d15901 100644 --- a/features/cellular/easy_cellular/EasyCellularConnection.h +++ b/features/cellular/easy_cellular/EasyCellularConnection.h @@ -24,15 +24,13 @@ #include "netsocket/CellularBase.h" -namespace mbed -{ +namespace mbed { /** EasyCellularConnection class * * Simplified adapter for cellular connection */ -class EasyCellularConnection: public CellularBase -{ +class EasyCellularConnection: public CellularBase { public: EasyCellularConnection(bool debug = false); diff --git a/features/cellular/framework/API/CellularDevice.h b/features/cellular/framework/API/CellularDevice.h index feec489fa71..d9e8c4fd506 100644 --- a/features/cellular/framework/API/CellularDevice.h +++ b/features/cellular/framework/API/CellularDevice.h @@ -27,8 +27,7 @@ #include "CellularInformation.h" #include "NetworkStack.h" -namespace mbed -{ +namespace mbed { /** * Class CellularDevice @@ -36,8 +35,7 @@ namespace mbed * An abstract interface that defines opening and closing of cellular interfaces. * Deleting/Closing of opened interfaces can be done only via this class. */ -class CellularDevice -{ +class CellularDevice { public: /** virtual Destructor */ diff --git a/features/cellular/framework/API/CellularInformation.h b/features/cellular/framework/API/CellularInformation.h index d2be8769219..ad28cc48a68 100644 --- a/features/cellular/framework/API/CellularInformation.h +++ b/features/cellular/framework/API/CellularInformation.h @@ -28,8 +28,7 @@ namespace mbed { * * An abstract interface that provides information about cellular device. */ -class CellularInformation -{ +class CellularInformation { protected: // friend of CellularDevice so that it's the only way to close/delete this class. friend class CellularDevice; diff --git a/features/cellular/framework/API/CellularNetwork.h b/features/cellular/framework/API/CellularNetwork.h index 672b08b9f1b..e440dee2448 100644 --- a/features/cellular/framework/API/CellularNetwork.h +++ b/features/cellular/framework/API/CellularNetwork.h @@ -36,8 +36,7 @@ const int MAX_OPERATOR_NAME_SHORT = 8; * * An abstract interface for connecting to a network and getting information from it. */ -class CellularNetwork : public NetworkInterface -{ +class CellularNetwork : public NetworkInterface { protected: // friend of CellularDevice so that it's the only way to close/delete this class. friend class CellularDevice; @@ -142,13 +141,14 @@ class CellularNetwork : public NetworkInterface Status op_status; - char op_long[MAX_OPERATOR_NAME_LONG+1]; - char op_short[MAX_OPERATOR_NAME_SHORT+1]; - char op_num[MAX_OPERATOR_NAME_SHORT+1]; + char op_long[MAX_OPERATOR_NAME_LONG + 1]; + char op_short[MAX_OPERATOR_NAME_SHORT + 1]; + char op_num[MAX_OPERATOR_NAME_SHORT + 1]; RadioAccessTechnology op_rat; operator_t *next; - operator_t() { + operator_t() + { op_status = Unknown; op_rat = RAT_UNKNOWN; next = NULL; @@ -159,14 +159,14 @@ class CellularNetwork : public NetworkInterface /* PDP Context information */ struct pdpcontext_params_t { - char apn[MAX_ACCESSPOINT_NAME_LENGTH+1]; - char local_addr[MAX_IPV6_ADDR_IN_IPV4LIKE_DOTTED_FORMAT+1]; - char local_subnet_mask[MAX_IPV6_ADDR_IN_IPV4LIKE_DOTTED_FORMAT+1]; - char gateway_addr[MAX_IPV6_ADDR_IN_IPV4LIKE_DOTTED_FORMAT+1]; - char dns_primary_addr[MAX_IPV6_ADDR_IN_IPV4LIKE_DOTTED_FORMAT+1]; - char dns_secondary_addr[MAX_IPV6_ADDR_IN_IPV4LIKE_DOTTED_FORMAT+1]; - char p_cscf_prim_addr[MAX_IPV6_ADDR_IN_IPV4LIKE_DOTTED_FORMAT+1]; - char p_cscf_sec_addr[MAX_IPV6_ADDR_IN_IPV4LIKE_DOTTED_FORMAT+1]; + char apn[MAX_ACCESSPOINT_NAME_LENGTH + 1]; + char local_addr[MAX_IPV6_ADDR_IN_IPV4LIKE_DOTTED_FORMAT + 1]; + char local_subnet_mask[MAX_IPV6_ADDR_IN_IPV4LIKE_DOTTED_FORMAT + 1]; + char gateway_addr[MAX_IPV6_ADDR_IN_IPV4LIKE_DOTTED_FORMAT + 1]; + char dns_primary_addr[MAX_IPV6_ADDR_IN_IPV4LIKE_DOTTED_FORMAT + 1]; + char dns_secondary_addr[MAX_IPV6_ADDR_IN_IPV4LIKE_DOTTED_FORMAT + 1]; + char p_cscf_prim_addr[MAX_IPV6_ADDR_IN_IPV4LIKE_DOTTED_FORMAT + 1]; + char p_cscf_sec_addr[MAX_IPV6_ADDR_IN_IPV4LIKE_DOTTED_FORMAT + 1]; int cid; int bearer_id; int im_signalling_flag; @@ -176,9 +176,10 @@ class CellularNetwork : public NetworkInterface int local_addr_ind; int non_ip_mtu; int serving_plmn_rate_control_value; - pdpcontext_params_t* next; + pdpcontext_params_t *next; - pdpcontext_params_t() { + pdpcontext_params_t() + { apn[0] = '\0'; local_addr[0] = '\0'; local_subnet_mask[0] = '\0'; @@ -235,14 +236,14 @@ class CellularNetwork : public NetworkInterface * @return 0 on success, negative error code on failure */ virtual nsapi_error_t set_credentials(const char *apn, AuthenticationType type, - const char *username = 0, const char *password = 0) = 0; + const char *username = 0, const char *password = 0) = 0; /** Request attach to network. * * @param timeout milliseconds to wait for attach response * @return zero on success */ - virtual nsapi_error_t set_attach(int timeout = 10*1000) = 0; + virtual nsapi_error_t set_attach(int timeout = 10 * 1000) = 0; /** Request attach status from network. * @@ -260,7 +261,7 @@ class CellularNetwork : public NetworkInterface * @return zero on success */ virtual nsapi_error_t get_rate_control(CellularNetwork::RateControlExceptionReports &reports, - CellularNetwork::RateControlUplinkTimeUnit &time_unit, int &uplink_rate) = 0; + CellularNetwork::RateControlUplinkTimeUnit &time_unit, int &uplink_rate) = 0; /** Get backoff timer value * @@ -291,7 +292,7 @@ class CellularNetwork : public NetworkInterface * @return zero on success */ virtual nsapi_error_t set_ciot_optimization_config(Supported_UE_Opt supported_opt, - Preferred_UE_Opt preferred_opt) = 0; + Preferred_UE_Opt preferred_opt) = 0; /** Get CIoT optimizations. * @@ -299,8 +300,8 @@ class CellularNetwork : public NetworkInterface * @param preferred_opt Preferred CIoT EPS optimizations. * @return zero on success */ - virtual nsapi_error_t get_ciot_optimization_config(Supported_UE_Opt& supported_opt, - Preferred_UE_Opt& preferred_opt) = 0; + virtual nsapi_error_t get_ciot_optimization_config(Supported_UE_Opt &supported_opt, + Preferred_UE_Opt &preferred_opt) = 0; /** Start the interface. Attempts to connect to a cellular network. * @@ -340,7 +341,7 @@ class CellularNetwork : public NetworkInterface * @param params_list reference to linked list which is filled on successful call * @return 0 on success, negative error code on failure */ - virtual nsapi_error_t get_pdpcontext_params(pdpContextList_t& params_list) = 0; + virtual nsapi_error_t get_pdpcontext_params(pdpContextList_t ¶ms_list) = 0; /** Get extended signal quality parameters. * diff --git a/features/cellular/framework/API/CellularPower.h b/features/cellular/framework/API/CellularPower.h index 9d15be1f8a4..201ce3ebfad 100644 --- a/features/cellular/framework/API/CellularPower.h +++ b/features/cellular/framework/API/CellularPower.h @@ -26,8 +26,7 @@ namespace mbed { * * An interface that provides power handling functions for modem/module. */ -class CellularPower -{ +class CellularPower { protected: // friend of CellularDevice so that it's the only way to close/delete this class. friend class CellularDevice; diff --git a/features/cellular/framework/API/CellularSIM.h b/features/cellular/framework/API/CellularSIM.h index 8a152188021..b3f99c7a752 100644 --- a/features/cellular/framework/API/CellularSIM.h +++ b/features/cellular/framework/API/CellularSIM.h @@ -29,8 +29,7 @@ const int MAX_IMSI_LENGTH = 15; * * An abstract interface for SIM card handling. */ -class CellularSIM -{ +class CellularSIM { protected: // friend of CellularDevice so that it's the only way to close/delete this class. friend class CellularDevice; @@ -84,7 +83,7 @@ class CellularSIM * @param imsi preallocated char* which after successful request contains imsi * @return zero on success */ - virtual nsapi_error_t get_imsi(char* imsi) = 0; + virtual nsapi_error_t get_imsi(char *imsi) = 0; }; } // namespace mbed diff --git a/features/cellular/framework/API/CellularSMS.h b/features/cellular/framework/API/CellularSMS.h index 35dbfc3c9cd..3ea5b2c267d 100644 --- a/features/cellular/framework/API/CellularSMS.h +++ b/features/cellular/framework/API/CellularSMS.h @@ -40,8 +40,7 @@ const int SMS_ERROR_MULTIPART_ALL_PARTS_NOT_READ = -5001; * * An abstract interface for SMS sending, reading and deleting. */ -class CellularSMS -{ +class CellularSMS { protected: // friend of CellularDevice so that it's the only way to close/delete this class. friend class CellularDevice; @@ -72,7 +71,7 @@ class CellularSMS * @param msg_len Length of the message * @return possible error code or length of the sent sms */ - virtual nsapi_size_or_error_t send_sms(const char* phone_number, const char* message, int msg_len) = 0; + virtual nsapi_size_or_error_t send_sms(const char *phone_number, const char *message, int msg_len) = 0; /** Gets the oldest received sms. * @@ -88,8 +87,8 @@ class CellularSMS * @return possible error code or size of buf. Will return SMS_ERROR_MULTIPART_ALL_PARTS_NOT_READ * if sms was multipart but not all parts are present/failed to read. */ - virtual nsapi_size_or_error_t get_sms(char* buf, uint16_t buf_len, char* phone_num, uint16_t phone_len, - char* time_stamp, uint16_t time_len, int *buf_size) = 0; + virtual nsapi_size_or_error_t get_sms(char *buf, uint16_t buf_len, char *phone_num, uint16_t phone_len, + char *time_stamp, uint16_t time_len, int *buf_size) = 0; /** Callback which is called when new sms is received. SMS can be fetched via method get_sms(). * diff --git a/features/cellular/framework/AT/ATHandler.cpp b/features/cellular/framework/AT/ATHandler.cpp index 2c3d6006c54..e80bbe67096 100644 --- a/features/cellular/framework/AT/ATHandler.cpp +++ b/features/cellular/framework/AT/ATHandler.cpp @@ -87,7 +87,7 @@ ATHandler::ATHandler(FileHandle *fh, EventQueue &queue, int timeout, const char if (output_delimiter) { _output_delimiter_length = strlen(output_delimiter); _output_delimiter = new char[_output_delimiter_length]; - for (unsigned i=0; i<_output_delimiter_length; i++) { + for (unsigned i = 0; i < _output_delimiter_length; i++) { _output_delimiter[i] = output_delimiter[i]; } } else { @@ -217,7 +217,7 @@ void ATHandler::set_at_timeout(uint32_t timeout_milliseconds, bool default_timeo void ATHandler::restore_at_timeout() { if (_previous_at_timeout != _at_timeout) { - _at_timeout =_previous_at_timeout; + _at_timeout = _previous_at_timeout; } } @@ -269,7 +269,8 @@ void ATHandler::set_filehandle_sigio() void ATHandler::reset_buffer() { tr_debug("%s", __func__); - _recv_pos = 0; _recv_len = 0; + _recv_pos = 0; + _recv_len = 0; } void ATHandler::rewind_buffer() @@ -295,19 +296,19 @@ void ATHandler::fill_buffer() Timer timer; timer.start(); do { - ssize_t len = _fileHandle->read(_recv_buff + _recv_len, sizeof(_recv_buff) - _recv_len); + ssize_t len = _fileHandle->read(_recv_buff + _recv_len, sizeof(_recv_buff) - _recv_len); if (len > 0) { _recv_len += len; - at_debug("\n----------readable----------: %d\n", _recv_len); - for (size_t i = _recv_pos; i < _recv_len; i++) { - at_debug("%c", _recv_buff[i]); - } - at_debug("\n----------readable----------\n"); - return; - } else if (len != -EAGAIN && len != 0) { - tr_warn("%s error: %d while reading", __func__, len); - break; - } + at_debug("\n----------readable----------: %d\n", _recv_len); + for (size_t i = _recv_pos; i < _recv_len; i++) { + at_debug("%c", _recv_buff[i]); + } + at_debug("\n----------readable----------\n"); + return; + } else if (len != -EAGAIN && len != 0) { + tr_warn("%s error: %d while reading", __func__, len); + break; + } #ifdef MBED_CONF_RTOS_PRESENT rtos::Thread::yield(); #endif @@ -417,7 +418,7 @@ ssize_t ATHandler::read_string(char *buf, size_t size, bool read_even_stop_tag) return -1; } - uint8_t *pbuf = (uint8_t*)buf; + uint8_t *pbuf = (uint8_t *)buf; size_t len = 0; size_t match_pos = 0; @@ -461,9 +462,9 @@ int32_t ATHandler::read_int() { tr_debug("%s", __func__); - if (_last_err || !_stop_tag || _stop_tag->found) { - return -1; - } + if (_last_err || !_stop_tag || _stop_tag->found) { + return -1; + } char buff[BUFF_SIZE]; char *first_no_digit; @@ -485,7 +486,7 @@ void ATHandler::set_default_delimiter() _delimiter = DEFAULT_DELIMITER; } -void ATHandler::set_tag(tag_t* tag_dst, const char *tag_seq) +void ATHandler::set_tag(tag_t *tag_dst, const char *tag_seq) { if (tag_seq) { size_t tag_len = strlen(tag_seq); @@ -512,30 +513,30 @@ void ATHandler::set_scope(ScopeType scope_type) if (_current_scope != scope_type) { _current_scope = scope_type; switch (_current_scope) { - case RespType: - _stop_tag = &_resp_stop; - _stop_tag->found = false; - break; - case InfoType: - _stop_tag = &_info_stop; - _stop_tag->found = false; - consume_char(' '); - break; - case ElemType: - _stop_tag = &_elem_stop; - _stop_tag->found = false; - break; - case NotSet: - _stop_tag = NULL; - return; - default: - break; + case RespType: + _stop_tag = &_resp_stop; + _stop_tag->found = false; + break; + case InfoType: + _stop_tag = &_info_stop; + _stop_tag->found = false; + consume_char(' '); + break; + case ElemType: + _stop_tag = &_elem_stop; + _stop_tag->found = false; + break; + case NotSet: + _stop_tag = NULL; + return; + default: + break; } } } // should match from recv_pos? -bool ATHandler::match(const char* str, size_t size) +bool ATHandler::match(const char *str, size_t size) { tr_debug("%s: %s", __func__, str); rewind_buffer(); @@ -636,7 +637,7 @@ void ATHandler::set_3gpp_error(int err, DeviceErrorType error_type) // CMS errors 0-127 maps straight to 3GPP errors _last_3gpp_error = err; } else { - for (size_t i = 0; i= _max_resp_length)) { + if (!prefix && ((_recv_len - _recv_pos) >= _max_resp_length)) { return; } fill_buffer(); @@ -765,7 +766,7 @@ bool ATHandler::info_resp() if (_prefix_matched) { _prefix_matched = false; - return true; + return true; } // If coming here after another info response was started(looping), stop the previous one. @@ -777,9 +778,9 @@ bool ATHandler::info_resp() resp(_info_resp_prefix, false); if (_prefix_matched) { - set_scope(InfoType); - _prefix_matched = false; - return true; + set_scope(InfoType); + _prefix_matched = false; + return true; } // On mismatch go to response scope @@ -858,7 +859,7 @@ bool ATHandler::consume_to_stop_tag() return true; } - if (consume_to_tag((const char*)_stop_tag->tag, true)) { + if (consume_to_tag((const char *)_stop_tag->tag, true)) { return true; } @@ -922,19 +923,19 @@ void ATHandler::set_string(char *dest, const char *src, size_t src_len) dest[src_len] = '\0'; } -const char* ATHandler::mem_str(const char* dest, size_t dest_len, const char* src, size_t src_len) +const char *ATHandler::mem_str(const char *dest, size_t dest_len, const char *src, size_t src_len) { if (dest_len > src_len) { - for(size_t i = 0; i < dest_len-src_len+1; ++i) { - if(memcmp(dest+i, src, src_len) == 0) { - return dest+i; + for (size_t i = 0; i < dest_len - src_len + 1; ++i) { + if (memcmp(dest + i, src, src_len) == 0) { + return dest + i; } } } return NULL; } -void ATHandler::cmd_start(const char* cmd) +void ATHandler::cmd_start(const char *cmd) { tr_debug("AT> %s", cmd); @@ -975,7 +976,7 @@ void ATHandler::write_int(int32_t param) } } -void ATHandler::write_string(const char* param, bool useQuotations) +void ATHandler::write_string(const char *param, bool useQuotations) { tr_debug("write_string: %s, %d", param, useQuotations); // do common checks before sending subparameter @@ -1006,7 +1007,7 @@ void ATHandler::cmd_stop() if (_last_err != NSAPI_ERROR_OK) { return; } - // Finish with CR + // Finish with CR for (size_t i = 0; i < _output_delimiter_length; i++) { if (write_char(_output_delimiter[i]) == false) { break; diff --git a/features/cellular/framework/AT/ATHandler.h b/features/cellular/framework/AT/ATHandler.h index accabe5c791..8f8ff535eb6 100644 --- a/features/cellular/framework/AT/ATHandler.h +++ b/features/cellular/framework/AT/ATHandler.h @@ -64,8 +64,7 @@ struct device_err_t { * * Class for sending AT commands and parsing AT responses. */ -class ATHandler -{ +class ATHandler { public: /** Constructor @@ -201,7 +200,7 @@ class ATHandler bool _processing; int32_t _ref_count; - //************************************* + //************************************* public: /** Starts the command writing by clearing the last error and writing the given command. @@ -209,7 +208,7 @@ class ATHandler * * @param cmd AT command to be written to modem */ - void cmd_start(const char* cmd); + void cmd_start(const char *cmd); /** Writes integer type AT command subparameter. Starts with the delimiter if not the first param after cmd_start. * In case of failure when writing, the last error is set to NSAPI_ERROR_DEVICE_ERROR. @@ -225,7 +224,7 @@ class ATHandler * @param param string to be written to modem as AT command subparameter * @param useQuotations flag indicating whether the string should be included in quotation marks */ - void write_string(const char* param, bool useQuotations = true); + void write_string(const char *param, bool useQuotations = true); /** Stops the AT command by writing command-line terminator CR to mark command as finished. */ @@ -409,10 +408,10 @@ class ATHandler // Returns on first successful read OR on timeout. void fill_buffer(); - void set_tag(tag_t* tag_dest, const char *tag_seq); + void set_tag(tag_t *tag_dest, const char *tag_seq); // Rewinds the receiving buffer and compares it against given str. - bool match(const char* str, size_t size); + bool match(const char *str, size_t size); // Iterates URCs and checks if they match the receiving buffer content. // If URC match sets the scope to information response and after urc's cb returns // finishes the information response scope(consumes to CRLF). @@ -466,7 +465,7 @@ class ATHandler * * @return pointer to first occurrence of src in dest */ - const char* mem_str(const char* dest, size_t dest_len, const char* src, size_t src_len); + const char *mem_str(const char *dest, size_t dest_len, const char *src, size_t src_len); }; } // namespace mbed diff --git a/features/cellular/framework/AT/AT_CellularBase.cpp b/features/cellular/framework/AT/AT_CellularBase.cpp index c4e5183c684..75b2db33960 100644 --- a/features/cellular/framework/AT/AT_CellularBase.cpp +++ b/features/cellular/framework/AT/AT_CellularBase.cpp @@ -19,12 +19,12 @@ using namespace mbed; -AT_CellularBase::AT_CellularBase(ATHandler& at) : _at(at) +AT_CellularBase::AT_CellularBase(ATHandler &at) : _at(at) { } -ATHandler& AT_CellularBase::get_at_handler() +ATHandler &AT_CellularBase::get_at_handler() { return _at; } diff --git a/features/cellular/framework/AT/AT_CellularBase.h b/features/cellular/framework/AT/AT_CellularBase.h index 97416cc7c2a..9662df9447a 100644 --- a/features/cellular/framework/AT/AT_CellularBase.h +++ b/features/cellular/framework/AT/AT_CellularBase.h @@ -26,16 +26,15 @@ namespace mbed { * * A base class for AT-classes. */ -class AT_CellularBase -{ +class AT_CellularBase { public: - AT_CellularBase(ATHandler& at); + AT_CellularBase(ATHandler &at); /** Getter for at handler. Common method for all AT-classes. * * @return reference to ATHandler */ - ATHandler& get_at_handler(); + ATHandler &get_at_handler(); /** Gets the device error that happened when using AT commands/responses. This is at error * returned by the device. Returned CME/CMS errors can be found from 3gpp documents 27007 and 27005. @@ -45,7 +44,7 @@ class AT_CellularBase device_err_t get_device_error() const; protected: - ATHandler& _at; + ATHandler &_at; }; } // namespace mbed diff --git a/features/cellular/framework/AT/AT_CellularDevice.cpp b/features/cellular/framework/AT/AT_CellularDevice.cpp index 6eb88d94858..af8ebabd5b7 100644 --- a/features/cellular/framework/AT/AT_CellularDevice.cpp +++ b/features/cellular/framework/AT/AT_CellularDevice.cpp @@ -46,7 +46,7 @@ AT_CellularDevice::~AT_CellularDevice() } // each parser is associated with one filehandle (that is UART) -ATHandler* AT_CellularDevice::get_at_handler(FileHandle *fileHandle) +ATHandler *AT_CellularDevice::get_at_handler(FileHandle *fileHandle) { if (!fileHandle) { return NULL; @@ -72,7 +72,7 @@ ATHandler* AT_CellularDevice::get_at_handler(FileHandle *fileHandle) return atHandler; } -void AT_CellularDevice::release_at_handler(ATHandler* at_handler) +void AT_CellularDevice::release_at_handler(ATHandler *at_handler) { if (!at_handler) { return; @@ -94,7 +94,7 @@ void AT_CellularDevice::release_at_handler(ATHandler* at_handler) break; } else { prev = atHandler; - atHandler =atHandler->_nextATHandler; + atHandler = atHandler->_nextATHandler; } } } diff --git a/features/cellular/framework/AT/AT_CellularDevice.h b/features/cellular/framework/AT/AT_CellularDevice.h index a2d1171469e..85547ac1875 100644 --- a/features/cellular/framework/AT/AT_CellularDevice.h +++ b/features/cellular/framework/AT/AT_CellularDevice.h @@ -28,8 +28,7 @@ #include "ATHandler.h" -namespace mbed -{ +namespace mbed { /** * Class AT_CellularDevice @@ -37,8 +36,7 @@ namespace mbed * A class defines opening and closing of cellular interfaces. * Deleting/Closing of opened interfaces can be done only through this class. */ -class AT_CellularDevice : public CellularDevice -{ +class AT_CellularDevice : public CellularDevice { public: AT_CellularDevice(events::EventQueue &queue); virtual ~AT_CellularDevice(); @@ -52,7 +50,7 @@ class AT_CellularDevice : public CellularDevice * * @param at_handler */ - void release_at_handler(ATHandler* at_handler); + void release_at_handler(ATHandler *at_handler); public: // CellularDevice virtual CellularNetwork *open_network(FileHandle *fh); @@ -85,8 +83,8 @@ class AT_CellularDevice : public CellularDevice AT_CellularNetwork *_network; AT_CellularSMS *_sms; AT_CellularSIM *_sim; - AT_CellularPower* _power; - AT_CellularInformation* _information; + AT_CellularPower *_power; + AT_CellularInformation *_information; protected: events::EventQueue &_queue; diff --git a/features/cellular/framework/AT/AT_CellularInformation.cpp b/features/cellular/framework/AT/AT_CellularInformation.cpp index b5882947981..e3a438649ab 100644 --- a/features/cellular/framework/AT/AT_CellularInformation.cpp +++ b/features/cellular/framework/AT/AT_CellularInformation.cpp @@ -50,7 +50,7 @@ nsapi_error_t AT_CellularInformation::get_info(const char *cmd, char *buf, size_ _at.cmd_stop(); _at.set_delimiter(0); _at.resp_start(); - _at.read_string(buf, buf_size-1); + _at.read_string(buf, buf_size - 1); _at.resp_stop(); _at.set_default_delimiter(); diff --git a/features/cellular/framework/AT/AT_CellularInformation.h b/features/cellular/framework/AT/AT_CellularInformation.h index 04fe4255dfd..782f1b52c02 100644 --- a/features/cellular/framework/AT/AT_CellularInformation.h +++ b/features/cellular/framework/AT/AT_CellularInformation.h @@ -28,8 +28,7 @@ namespace mbed { * * Class that provides information about cellular device. */ -class AT_CellularInformation : public CellularInformation, public AT_CellularBase -{ +class AT_CellularInformation : public CellularInformation, public AT_CellularBase { public: AT_CellularInformation(ATHandler &atHandler); virtual ~AT_CellularInformation(); diff --git a/features/cellular/framework/AT/AT_CellularNetwork.cpp b/features/cellular/framework/AT/AT_CellularNetwork.cpp index 5c05d35e1f2..faff665230e 100644 --- a/features/cellular/framework/AT/AT_CellularNetwork.cpp +++ b/features/cellular/framework/AT/AT_CellularNetwork.cpp @@ -78,27 +78,27 @@ nsapi_error_t AT_CellularNetwork::set_credentials(const char *apn, { size_t len; if (apn && (len = strlen(apn)) > 0) { - _apn = (char*)malloc(len*sizeof(char)+1); + _apn = (char *)malloc(len * sizeof(char) +1); if (_apn) { - memcpy(_apn, apn, len+1); + memcpy(_apn, apn, len + 1); } else { return NSAPI_ERROR_NO_MEMORY; } } if (username && (len = strlen(username)) > 0) { - _uname = (char*)malloc(len*sizeof(char)+1); + _uname = (char *)malloc(len * sizeof(char) +1); if (_uname) { - memcpy(_uname, username, len+1); + memcpy(_uname, username, len + 1); } else { return NSAPI_ERROR_NO_MEMORY; } } if (password && (len = strlen(password)) > 0) { - _pwd = (char*)malloc(len*sizeof(char)+1); + _pwd = (char *)malloc(len * sizeof(char) +1); if (_pwd) { - memcpy(_pwd, password, len+1); + memcpy(_pwd, password, len + 1); } else { return NSAPI_ERROR_NO_MEMORY; } @@ -357,7 +357,7 @@ bool AT_CellularNetwork::set_new_context(int cid) } } - char pdp_type[8+1] = {0}; + char pdp_type[8 + 1] = {0}; switch (tmp_stack) { case IPV4_STACK: @@ -429,7 +429,7 @@ bool AT_CellularNetwork::get_context() if (pdp_type_len > 0) { apn_len = _at.read_string(apn, sizeof(apn) - 1); if (apn_len >= 0) { - if (_apn && strcmp(apn, _apn) != 0 ) { + if (_apn && strcmp(apn, _apn) != 0) { continue; } nsapi_ip_stack_t pdp_stack = string_to_stack_type(pdp_type_from_context); @@ -459,7 +459,7 @@ bool AT_CellularNetwork::get_context() _cid = cid; break; } - // If PDP is IPV4 or IPV6 they are already checked if supported + // If PDP is IPV4 or IPV6 they are already checked if supported } else { _ip_stack_type = pdp_stack; _cid = cid; @@ -478,16 +478,16 @@ bool AT_CellularNetwork::get_context() } _at.resp_stop(); if (_cid == -1) { // no suitable context was found so create a new one - if (!set_new_context(cid_max+1)) { + if (!set_new_context(cid_max + 1)) { return false; } } // save the apn if (apn_len > 0 && !_apn) { - _apn = (char*)malloc(apn_len*sizeof(char)+1); + _apn = (char *)malloc(apn_len * sizeof(char) +1); if (_apn) { - memcpy(_apn, apn, apn_len+1); + memcpy(_apn, apn, apn_len + 1); } else { return false; } @@ -497,7 +497,7 @@ bool AT_CellularNetwork::get_context() return true; } -nsapi_ip_stack_t AT_CellularNetwork::string_to_stack_type(const char* pdp_type) +nsapi_ip_stack_t AT_CellularNetwork::string_to_stack_type(const char *pdp_type) { nsapi_ip_stack_t stack = DEFAULT_STACK; int len = strlen(pdp_type); @@ -514,7 +514,7 @@ nsapi_ip_stack_t AT_CellularNetwork::string_to_stack_type(const char* pdp_type) nsapi_error_t AT_CellularNetwork::set_registration_urc(bool urc_on) { - for (unsigned int i = 0; i < sizeof(at_reg)/sizeof(at_reg[0]); i++) { + for (unsigned int i = 0; i < sizeof(at_reg) / sizeof(at_reg[0]); i++) { if (has_registration(at_reg[i].type)) { _last_reg_type = at_reg[i].type; if (urc_on) { @@ -598,12 +598,12 @@ nsapi_error_t AT_CellularNetwork::get_registration_status(RegistrationType type, status = (RegistrationStatus)_at.read_int(); int len = _at.read_string(lac_string, LAC_LENGTH); - if (memcmp(lac_string, "ffff", LAC_LENGTH-1) && len >= 0) { + if (memcmp(lac_string, "ffff", LAC_LENGTH - 1) && len >= 0) { lac_read = true; } len = _at.read_string(cell_id_string, CELL_ID_LENGTH); - if (memcmp(cell_id_string, "ffffffff", CELL_ID_LENGTH-1) && len >= 0) { + if (memcmp(cell_id_string, "ffffffff", CELL_ID_LENGTH - 1) && len >= 0) { cell_id_read = true; } @@ -619,12 +619,12 @@ nsapi_error_t AT_CellularNetwork::get_registration_status(RegistrationType type, if (lac_read) { _lac = hex_str_to_int(lac_string, LAC_LENGTH); - tr_debug("lac %s %d", lac_string, _lac ); + tr_debug("lac %s %d", lac_string, _lac); } if (cell_id_read) { _cell_id = hex_str_to_int(cell_id_string, CELL_ID_LENGTH); - tr_debug("cell_id %s %d", cell_id_string, _cell_id ); + tr_debug("cell_id %s %d", cell_id_string, _cell_id); } return ret; @@ -798,7 +798,7 @@ nsapi_error_t AT_CellularNetwork::scan_plmn(operList_t &operators, int &opsCount // Optional - try read an int ret = _at.read_int(); - op->op_rat = (ret == error_code) ? operator_t::RAT_UNKNOWN:(operator_t::RadioAccessTechnology)ret; + op->op_rat = (ret == error_code) ? operator_t::RAT_UNKNOWN : (operator_t::RadioAccessTechnology)ret; if ((_op_act == operator_t::RAT_UNKNOWN) || ((op->op_rat != operator_t::RAT_UNKNOWN) && (op->op_rat == _op_act))) { @@ -832,8 +832,8 @@ nsapi_error_t AT_CellularNetwork::set_ciot_optimization_config(Supported_UE_Opt return _at.unlock_return_error(); } -nsapi_error_t AT_CellularNetwork::get_ciot_optimization_config(Supported_UE_Opt& supported_opt, - Preferred_UE_Opt& preferred_opt) +nsapi_error_t AT_CellularNetwork::get_ciot_optimization_config(Supported_UE_Opt &supported_opt, + Preferred_UE_Opt &preferred_opt) { _at.lock(); @@ -870,7 +870,7 @@ nsapi_error_t AT_CellularNetwork::get_rate_control( int next_element = _at.read_int(); if (next_element >= 0) { reports = (RateControlExceptionReports)next_element; - tr_debug("reports %d",reports); + tr_debug("reports %d", reports); next_element = _at.read_int(); } else { comma_found = false; @@ -878,7 +878,7 @@ nsapi_error_t AT_CellularNetwork::get_rate_control( if (comma_found && next_element >= 0) { timeUnit = (RateControlUplinkTimeUnit)next_element; - tr_debug("time %d",timeUnit); + tr_debug("time %d", timeUnit); next_element = _at.read_int(); } else { comma_found = false; @@ -886,7 +886,7 @@ nsapi_error_t AT_CellularNetwork::get_rate_control( if (comma_found && next_element >= 0) { uplinkRate = next_element; - tr_debug("rate %d",uplinkRate); + tr_debug("rate %d", uplinkRate); } } _at.resp_stop(); @@ -896,16 +896,16 @@ nsapi_error_t AT_CellularNetwork::get_rate_control( return (ret == NSAPI_ERROR_OK) ? NSAPI_ERROR_OK : NSAPI_ERROR_PARAMETER; } -nsapi_error_t AT_CellularNetwork::get_pdpcontext_params(pdpContextList_t& params_list) +nsapi_error_t AT_CellularNetwork::get_pdpcontext_params(pdpContextList_t ¶ms_list) { const int ipv6_subnet_size = 128; const int max_ipv6_size = 64; - char* ipv6_and_subnetmask = (char*)malloc(ipv6_subnet_size); + char *ipv6_and_subnetmask = (char *)malloc(ipv6_subnet_size); if (!ipv6_and_subnetmask) { return NSAPI_ERROR_NO_MEMORY; } - char* temp = (char*)malloc(max_ipv6_size); + char *temp = (char *)malloc(max_ipv6_size); if (!temp) { free(ipv6_and_subnetmask); return NSAPI_ERROR_NO_MEMORY; diff --git a/features/cellular/framework/AT/AT_CellularNetwork.h b/features/cellular/framework/AT/AT_CellularNetwork.h index eaf25c7f8d8..4b453faca92 100644 --- a/features/cellular/framework/AT/AT_CellularNetwork.h +++ b/features/cellular/framework/AT/AT_CellularNetwork.h @@ -31,8 +31,7 @@ namespace mbed { * * Class for connecting to a network and getting information from it. */ -class AT_CellularNetwork : public CellularNetwork, public AT_CellularBase -{ +class AT_CellularNetwork : public CellularNetwork, public AT_CellularBase { public: @@ -47,7 +46,7 @@ class AT_CellularNetwork : public CellularNetwork, public AT_CellularBase const char *username = 0, const char *password = 0); virtual nsapi_error_t set_credentials(const char *apn, AuthenticationType type, - const char *username = 0, const char *password = 0); + const char *username = 0, const char *password = 0); virtual nsapi_error_t connect(const char *apn, const char *username = 0, const char *password = 0); @@ -64,12 +63,12 @@ class AT_CellularNetwork : public CellularNetwork, public AT_CellularBase virtual nsapi_error_t get_registration_status(RegistrationType type, RegistrationStatus &status); - virtual nsapi_error_t set_attach(int timeout = 10*1000); + virtual nsapi_error_t set_attach(int timeout = 10 * 1000); virtual nsapi_error_t get_attach(AttachStatus &status); virtual nsapi_error_t get_rate_control(CellularNetwork::RateControlExceptionReports &reports, - CellularNetwork::RateControlUplinkTimeUnit &time_unit, int &uplink_rate); + CellularNetwork::RateControlUplinkTimeUnit &time_unit, int &uplink_rate); virtual nsapi_error_t get_apn_backoff_timer(int &backoff_timer); @@ -86,16 +85,16 @@ class AT_CellularNetwork : public CellularNetwork, public AT_CellularBase virtual nsapi_error_t scan_plmn(operList_t &operators, int &ops_count); virtual nsapi_error_t set_ciot_optimization_config(Supported_UE_Opt supported_opt, - Preferred_UE_Opt preferred_opt); + Preferred_UE_Opt preferred_opt); - virtual nsapi_error_t get_ciot_optimization_config(Supported_UE_Opt& supported_opt, - Preferred_UE_Opt& preferred_opt); + virtual nsapi_error_t get_ciot_optimization_config(Supported_UE_Opt &supported_opt, + Preferred_UE_Opt &preferred_opt); virtual nsapi_error_t set_stack_type(nsapi_ip_stack_t stack_type); virtual nsapi_ip_stack_t get_stack_type(); - virtual nsapi_error_t get_pdpcontext_params(pdpContextList_t& params_list); + virtual nsapi_error_t get_pdpcontext_params(pdpContextList_t ¶ms_list); virtual nsapi_error_t get_extended_signal_quality(int &rxlev, int &ber, int &rscp, int &ecno, int &rsrq, int &rsrp); @@ -134,7 +133,7 @@ class AT_CellularNetwork : public CellularNetwork, public AT_CellularBase // "NO CARRIER" urc void urc_no_carrier(); nsapi_error_t set_context_to_be_activated(); - nsapi_ip_stack_t string_to_stack_type(const char* pdp_type); + nsapi_ip_stack_t string_to_stack_type(const char *pdp_type); void free_credentials(); diff --git a/features/cellular/framework/AT/AT_CellularPower.cpp b/features/cellular/framework/AT/AT_CellularPower.cpp index e6d21a39c10..682e9b595f0 100644 --- a/features/cellular/framework/AT/AT_CellularPower.cpp +++ b/features/cellular/framework/AT/AT_CellularPower.cpp @@ -110,34 +110,34 @@ nsapi_error_t AT_CellularPower::opt_power_save_mode(int periodic_time, int activ 1 1 0 value is incremented in multiples of 320 hours (NOTE 1) 1 1 1 value indicates that the timer is deactivated (NOTE 2). */ - char pt[8+1];// timer value encoded as 3GPP IE + char pt[8 + 1]; // timer value encoded as 3GPP IE const int ie_value_max = 0x1f; uint32_t periodic_timer = 0; - if (periodic_time <= 2*ie_value_max) { // multiples of 2 seconds - periodic_timer = periodic_time/2; + if (periodic_time <= 2 * ie_value_max) { // multiples of 2 seconds + periodic_timer = periodic_time / 2; strcpy(pt, "01100000"); } else { - if (periodic_time <= 30*ie_value_max) { // multiples of 30 seconds - periodic_timer = periodic_time/30; + if (periodic_time <= 30 * ie_value_max) { // multiples of 30 seconds + periodic_timer = periodic_time / 30; strcpy(pt, "10000000"); } else { - if (periodic_time <= 60*ie_value_max) { // multiples of 1 minute - periodic_timer = periodic_time/60; + if (periodic_time <= 60 * ie_value_max) { // multiples of 1 minute + periodic_timer = periodic_time / 60; strcpy(pt, "10100000"); } else { - if (periodic_time <= 10*60*ie_value_max) { // multiples of 10 minutes - periodic_timer = periodic_time/(10*60); + if (periodic_time <= 10 * 60 * ie_value_max) { // multiples of 10 minutes + periodic_timer = periodic_time / (10 * 60); strcpy(pt, "00000000"); } else { - if (periodic_time <= 60*60*ie_value_max) { // multiples of 1 hour - periodic_timer = periodic_time/(60*60); + if (periodic_time <= 60 * 60 * ie_value_max) { // multiples of 1 hour + periodic_timer = periodic_time / (60 * 60); strcpy(pt, "00100000"); } else { - if (periodic_time <= 10*60*60*ie_value_max) { // multiples of 10 hours - periodic_timer = periodic_time/(10*60*60); + if (periodic_time <= 10 * 60 * 60 * ie_value_max) { // multiples of 10 hours + periodic_timer = periodic_time / (10 * 60 * 60); strcpy(pt, "01000000"); } else { // multiples of 320 hours - int t = periodic_time / (320*60*60); + int t = periodic_time / (320 * 60 * 60); if (t > ie_value_max) { t = ie_value_max; } @@ -150,7 +150,7 @@ nsapi_error_t AT_CellularPower::opt_power_save_mode(int periodic_time, int activ } } - uint_to_binary_str(periodic_timer, &pt[3], sizeof(pt)-3, PSMTimerBits); + uint_to_binary_str(periodic_timer, &pt[3], sizeof(pt) - 3, PSMTimerBits); pt[8] = '\0'; /** @@ -168,17 +168,17 @@ nsapi_error_t AT_CellularPower::opt_power_save_mode(int periodic_time, int activ Other values shall be interpreted as multiples of 1 minute in this version of the protocol. */ - char at[8+1]; + char at[8 + 1]; uint32_t active_timer; // timer value encoded as 3GPP IE - if (active_time <= 2*ie_value_max) { // multiples of 2 seconds - active_timer = active_time/2; + if (active_time <= 2 * ie_value_max) { // multiples of 2 seconds + active_timer = active_time / 2; strcpy(at, "00000000"); } else { - if (active_time <= 60*ie_value_max) { // multiples of 1 minute - active_timer = (1<<5) | (active_time/60); + if (active_time <= 60 * ie_value_max) { // multiples of 1 minute + active_timer = (1 << 5) | (active_time / 60); strcpy(at, "00100000"); } else { // multiples of decihours - int t = active_time / (6*60); + int t = active_time / (6 * 60); if (t > ie_value_max) { t = ie_value_max; } @@ -187,7 +187,7 @@ nsapi_error_t AT_CellularPower::opt_power_save_mode(int periodic_time, int activ } } - uint_to_binary_str(active_timer, &at[3], sizeof(at)-3, PSMTimerBits); + uint_to_binary_str(active_timer, &at[3], sizeof(at) - 3, PSMTimerBits); pt[8] = '\0'; // request for both GPRS and LTE diff --git a/features/cellular/framework/AT/AT_CellularPower.h b/features/cellular/framework/AT/AT_CellularPower.h index 0aaeafcb8db..fbeaa953b3e 100644 --- a/features/cellular/framework/AT/AT_CellularPower.h +++ b/features/cellular/framework/AT/AT_CellularPower.h @@ -28,8 +28,7 @@ namespace mbed { * * Class that provides power handling functions for modem/module. */ -class AT_CellularPower : public CellularPower, public AT_CellularBase -{ +class AT_CellularPower : public CellularPower, public AT_CellularBase { public: AT_CellularPower(ATHandler &atHandler); virtual ~AT_CellularPower(); diff --git a/features/cellular/framework/AT/AT_CellularSIM.cpp b/features/cellular/framework/AT/AT_CellularSIM.cpp index 3f1fb65461e..9282d5b0d6b 100644 --- a/features/cellular/framework/AT/AT_CellularSIM.cpp +++ b/features/cellular/framework/AT/AT_CellularSIM.cpp @@ -38,7 +38,7 @@ nsapi_error_t AT_CellularSIM::get_sim_state(SimState &state) _at.cmd_start("AT+CPIN?"); _at.cmd_stop(); _at.resp_start("+CPIN:"); - ssize_t len = _at.read_string(simstr, sizeof (simstr)); + ssize_t len = _at.read_string(simstr, sizeof(simstr)); if (len != -1) { if (len >= 5 && memcmp(simstr, "READY", 5) == 0) { state = SimStateReady; @@ -115,7 +115,7 @@ nsapi_error_t AT_CellularSIM::set_pin_query(const char *sim_pin, bool query_pin) return _at.unlock_return_error(); } -nsapi_error_t AT_CellularSIM::get_imsi(char* imsi) +nsapi_error_t AT_CellularSIM::get_imsi(char *imsi) { _at.lock(); _at.cmd_start("AT+CIMI"); diff --git a/features/cellular/framework/AT/AT_CellularSIM.h b/features/cellular/framework/AT/AT_CellularSIM.h index be534168201..69651bf53c8 100644 --- a/features/cellular/framework/AT/AT_CellularSIM.h +++ b/features/cellular/framework/AT/AT_CellularSIM.h @@ -28,8 +28,7 @@ namespace mbed { * * Class for SIM card handling. */ -class AT_CellularSIM : public CellularSIM, public AT_CellularBase -{ +class AT_CellularSIM : public CellularSIM, public AT_CellularBase { public: AT_CellularSIM(ATHandler &atHandler); @@ -44,7 +43,7 @@ class AT_CellularSIM : public CellularSIM, public AT_CellularBase virtual nsapi_error_t get_sim_state(SimState &state); - virtual nsapi_error_t get_imsi(char* imsi); + virtual nsapi_error_t get_imsi(char *imsi); }; } // namespace mbed diff --git a/features/cellular/framework/AT/AT_CellularSMS.cpp b/features/cellular/framework/AT/AT_CellularSMS.cpp index faa7a9eb6e4..292d230e737 100644 --- a/features/cellular/framework/AT/AT_CellularSMS.cpp +++ b/features/cellular/framework/AT/AT_CellularSMS.cpp @@ -171,10 +171,10 @@ static const int gsm_to_ascii[] = { 224 // 127 }; -const int GSM_TO_ASCII_TABLE_SIZE = sizeof(gsm_to_ascii)/sizeof(gsm_to_ascii[0]); +const int GSM_TO_ASCII_TABLE_SIZE = sizeof(gsm_to_ascii) / sizeof(gsm_to_ascii[0]); AT_CellularSMS::AT_CellularSMS(ATHandler &at) : AT_CellularBase(at), _cb(0), _mode(CellularSMSMmodeText), - _use_8bit_encoding(false), _sim_wait_time(0), _sms_message_ref_number(1), _sms_info(NULL) + _use_8bit_encoding(false), _sim_wait_time(0), _sms_message_ref_number(1), _sms_info(NULL) { /* URCs, handled out of band */ _at.set_urc_handler("+CMTI:", callback(this, &AT_CellularSMS::cmti_urc)); @@ -278,14 +278,14 @@ void AT_CellularSMS::set_extra_sim_wait_time(int sim_wait_time) _sim_wait_time = sim_wait_time; } -char* AT_CellularSMS::create_pdu(const char* phone_number, const char* message, uint8_t message_length, uint8_t msg_parts, - uint8_t msg_part_number, uint8_t& header_size) +char *AT_CellularSMS::create_pdu(const char *phone_number, const char *message, uint8_t message_length, uint8_t msg_parts, + uint8_t msg_part_number, uint8_t &header_size) { int totalPDULength = 0; int number_len = strlen(phone_number); totalPDULength += number_len; - if (number_len&0x01) {// if phone number length is not even length we must pad it and so +1 + if (number_len & 0x01) { // if phone number length is not even length we must pad it and so +1 totalPDULength += 1; } @@ -294,12 +294,12 @@ char* AT_CellularSMS::create_pdu(const char* phone_number, const char* message, totalPDULength += 12; } // there might be need for padding so some more space - totalPDULength +=2; + totalPDULength += 2; // message 7-bit padded and it will be converted to hex so it will take twice as much space - totalPDULength += (message_length - (message_length/8))*2; + totalPDULength += (message_length - (message_length / 8)) * 2; - char* pdu = (char*)calloc(totalPDULength, sizeof(char)); + char *pdu = (char *)calloc(totalPDULength, sizeof(char)); if (!pdu) { return NULL; } @@ -321,8 +321,8 @@ char* AT_CellularSMS::create_pdu(const char* phone_number, const char* message, pdu[x++] = '0'; pdu[x++] = '0'; // [6] and [7] Length of the Destination Phone Number - int_to_hex_str(number_len, pdu+x); - x+=2; + int_to_hex_str(number_len, pdu + x); + x += 2; // Type of the Destination Phone Number pdu[x++] = '8'; pdu[x++] = '1'; @@ -330,10 +330,10 @@ char* AT_CellularSMS::create_pdu(const char* phone_number, const char* message, // phone number as reverse nibble encoded int i = 0; for (; i < number_len; i += 2) { - if (i+1 == number_len) { + if (i + 1 == number_len) { pdu[x++] = 'f'; } else { - pdu[x++] = phone_number[i+1]; + pdu[x++] = phone_number[i + 1]; } pdu[x++] = phone_number[i]; } @@ -355,7 +355,7 @@ char* AT_CellularSMS::create_pdu(const char* phone_number, const char* message, uint8_t udhlen = 0; // Length can be update after we have created PDU, store position for later use. int lengthPos = x; - x +=2; + x += 2; int paddingBits = 0; if (msg_parts > 1) { // concatenated, must use UDH @@ -383,21 +383,21 @@ char* AT_CellularSMS::create_pdu(const char* phone_number, const char* message, pdu[x++] = '3'; } // A reference number (must be the same for all parts of the same larger messages) - int_to_hex_str(_sms_message_ref_number&0xFF, pdu+x); - x +=2; + int_to_hex_str(_sms_message_ref_number & 0xFF, pdu + x); + x += 2; if (use_16_bit_identifier) { - int_to_hex_str((_sms_message_ref_number>>16)&0xFF, pdu+x); - x +=2; + int_to_hex_str((_sms_message_ref_number >> 16) & 0xFF, pdu + x); + x += 2; } // How many parts does this message have? - int_to_hex_str(msg_parts, pdu+x); - x +=2; + int_to_hex_str(msg_parts, pdu + x); + x += 2; // this is a part number - int_to_hex_str(msg_part_number, pdu+x); - x +=2; + int_to_hex_str(msg_part_number, pdu + x); + x += 2; // if there is padding bits then udhlen is octet bigger as we need to keep septet boundary - paddingBits = (udhlen * 8 ) % 7; + paddingBits = (udhlen * 8) % 7; if (paddingBits) { paddingBits = 7 - paddingBits; udhlen += 1; @@ -405,11 +405,11 @@ char* AT_CellularSMS::create_pdu(const char* phone_number, const char* message, } if (_use_8bit_encoding) { - char_str_to_hex_str(message, message_length, pdu+x); + char_str_to_hex_str(message, message_length, pdu + x); } else { // we might need to send zero length sms if (message_length) { - if (pack_7_bit_gsm_and_hex(message, message_length, pdu+x, paddingBits) == 0) { + if (pack_7_bit_gsm_and_hex(message, message_length, pdu + x, paddingBits) == 0) { free(pdu); return NULL; } @@ -417,16 +417,16 @@ char* AT_CellularSMS::create_pdu(const char* phone_number, const char* message, } // now we know the correct length of the UDL (User Data Length) - int_to_hex_str(message_length + udhlen, pdu+lengthPos); + int_to_hex_str(message_length + udhlen, pdu + lengthPos); header_size = x; return pdu; } -nsapi_size_or_error_t AT_CellularSMS::send_sms(const char* phone_number, const char* message, int msg_len) +nsapi_size_or_error_t AT_CellularSMS::send_sms(const char *phone_number, const char *message, int msg_len) { int single_sms_max_length = _use_8bit_encoding ? SMS_MAX_SIZE_8BIT_SINGLE_SMS_SIZE : - SMS_MAX_SIZE_GSM7_SINGLE_SMS_SIZE; + SMS_MAX_SIZE_GSM7_SINGLE_SMS_SIZE; if ((_mode == CellularSMSMmodeText && msg_len > single_sms_max_length) || !phone_number) { return NSAPI_ERROR_PARAMETER; } @@ -440,14 +440,14 @@ nsapi_size_or_error_t AT_CellularSMS::send_sms(const char* phone_number, const c if (_mode == CellularSMSMmodeText) { _at.cmd_start("AT+CMGS="); - _at.write_string(phone_number+remove_plus_sign); + _at.write_string(phone_number + remove_plus_sign); _at.cmd_stop(); wait_ms(_sim_wait_time); _at.resp_start("> ", true); if (_at.get_last_error() == NSAPI_ERROR_OK) { - write_size = _at.write_bytes((uint8_t*)message, msg_len); + write_size = _at.write_bytes((uint8_t *)message, msg_len); if (write_size < msg_len) { // sending can be cancelled by giving character (IRA 27). _at.cmd_start(ESC); @@ -466,15 +466,15 @@ nsapi_size_or_error_t AT_CellularSMS::send_sms(const char* phone_number, const c // GSM 7 bit default but support is done for 8 bit data. int sms_count; int concatenated_sms_length = _use_8bit_encoding ? SMS_MAX_8BIT_CONCATENATED_SINGLE_SMS_SIZE : - SMS_MAX_GSM7_CONCATENATED_SINGLE_SMS_SIZE; + SMS_MAX_GSM7_CONCATENATED_SINGLE_SMS_SIZE; if (msg_len <= single_sms_max_length) { // single message sms_count = 1; } else { // concatenated message - sms_count = msg_len/concatenated_sms_length; - if (msg_len%concatenated_sms_length != 0) { + sms_count = msg_len / concatenated_sms_length; + if (msg_len % concatenated_sms_length != 0) { sms_count++; } } @@ -493,8 +493,8 @@ nsapi_size_or_error_t AT_CellularSMS::send_sms(const char* phone_number, const c pdu_len = remaining_len > concatenated_sms_length ? concatenated_sms_length : remaining_len; } - pdu_str = create_pdu(phone_number+remove_plus_sign, message + i*concatenated_sms_length, pdu_len, - sms_count, i+1, header_len); + pdu_str = create_pdu(phone_number + remove_plus_sign, message + i * concatenated_sms_length, pdu_len, + sms_count, i + 1, header_len); if (!pdu_str) { _at.unlock(); return NSAPI_ERROR_NO_MEMORY; @@ -503,21 +503,21 @@ nsapi_size_or_error_t AT_CellularSMS::send_sms(const char* phone_number, const c // specification says that service center number should not be included so we subtract -2 from pdu_len as we use '00' for automatic service center number _at.cmd_start("AT+CMGS="); - _at.write_int((pdu_len-2)/2); + _at.write_int((pdu_len - 2) / 2); _at.cmd_stop(); wait_ms(_sim_wait_time); _at.resp_start("> ", true); if (_at.get_last_error() == NSAPI_ERROR_OK) { - write_size = _at.write_bytes((uint8_t*)pdu_str, pdu_len); + write_size = _at.write_bytes((uint8_t *)pdu_str, pdu_len); if (write_size < pdu_len) { // calculate exact size of what we have send if (write_size <= header_len) { // managed only to write header or some of it so actual msg write size in this iteration is 0 write_size = 0; } else { - write_size = (write_size - header_len)/2; // as hex encoded so divide by two + write_size = (write_size - header_len) / 2; // as hex encoded so divide by two } msg_write_len += write_size; @@ -594,7 +594,7 @@ nsapi_size_or_error_t AT_CellularSMS::set_cscs(const char *chr_set) return _at.unlock_return_error(); } -nsapi_error_t AT_CellularSMS::delete_sms(sms_info_t* sms) +nsapi_error_t AT_CellularSMS::delete_sms(sms_info_t *sms) { _at.lock(); for (int i = 0; i < sms->parts; i++) { @@ -623,8 +623,8 @@ nsapi_error_t AT_CellularSMS::delete_all_messages() } // read msg in text mode -nsapi_size_or_error_t AT_CellularSMS::read_sms_from_index(int msg_index, char* buf, uint16_t len, char* phone_num, - char* time_stamp) +nsapi_size_or_error_t AT_CellularSMS::read_sms_from_index(int msg_index, char *buf, uint16_t len, char *phone_num, + char *time_stamp) { /* * +CMGR: ,,,[,,,,,,,]OK @@ -651,8 +651,7 @@ nsapi_size_or_error_t AT_CellularSMS::read_sms_from_index(int msg_index, char* b // Received message if (phone_num) { _at.read_string(phone_num, SMS_MAX_PHONE_NUMBER_SIZE); - } - else { + } else { _at.skip_param(); // , } _at.skip_param(); // @@ -673,7 +672,7 @@ nsapi_size_or_error_t AT_CellularSMS::read_sms_from_index(int msg_index, char* b } // read msg in PDU mode -nsapi_size_or_error_t AT_CellularSMS::read_sms(sms_info_t* sms, char* buf, char* phone_num, char* time_stamp) +nsapi_size_or_error_t AT_CellularSMS::read_sms(sms_info_t *sms, char *buf, char *phone_num, char *time_stamp) { // +CMGR: ,[], int index = -1; @@ -697,15 +696,15 @@ nsapi_size_or_error_t AT_CellularSMS::read_sms(sms_info_t* sms, char* buf, char* if ((_at.get_last_error() == NSAPI_ERROR_OK) && (status == 0 || status == 1)) { msg_len = _at.read_int(); if (msg_len > 0) { - pduSize = msg_len*2 + 20;// *2 as it's hex encoded and +20 as service center number is not included in size given by CMGR - pdu = (char*)calloc(pduSize, sizeof(char)); + pduSize = msg_len * 2 + 20; // *2 as it's hex encoded and +20 as service center number is not included in size given by CMGR + pdu = (char *)calloc(pduSize, sizeof(char)); if (!pdu) { _at.resp_stop(); return NSAPI_ERROR_NO_MEMORY; } _at.read_string(pdu, pduSize, true); if (_at.get_last_error() == NSAPI_ERROR_OK) { - msg_len = get_data_from_pdu(pdu, NULL, NULL, phone_num, buf+index); + msg_len = get_data_from_pdu(pdu, NULL, NULL, phone_num, buf + index); if (msg_len >= 0) { // we need to allow zero length messages index += msg_len; } else { @@ -727,8 +726,7 @@ nsapi_size_or_error_t AT_CellularSMS::read_sms(sms_info_t* sms, char* buf, char* } buf[index] = '\0'; } - } - else { + } else { tr_warn("NOT all concatenated parts were received..."); index = SMS_ERROR_MULTIPART_ALL_PARTS_NOT_READ; } @@ -736,8 +734,8 @@ nsapi_size_or_error_t AT_CellularSMS::read_sms(sms_info_t* sms, char* buf, char* return index; } -nsapi_size_or_error_t AT_CellularSMS::get_sms(char* buf, uint16_t len, char* phone_num, uint16_t phone_len, - char* time_stamp, uint16_t time_len, int *buf_size) +nsapi_size_or_error_t AT_CellularSMS::get_sms(char *buf, uint16_t len, char *phone_num, uint16_t phone_len, + char *time_stamp, uint16_t time_len, int *buf_size) { // validate buffer sizes already here to avoid any necessary function calls and locking of _at if ((phone_num && phone_len < SMS_MAX_PHONE_NUMBER_SIZE) || (time_stamp && time_len < SMS_MAX_TIME_STAMP_SIZE) || @@ -750,10 +748,10 @@ nsapi_size_or_error_t AT_CellularSMS::get_sms(char* buf, uint16_t len, char* pho nsapi_size_or_error_t err = list_messages(); if (err == NSAPI_ERROR_OK) { // we return the oldest sms and delete it after successful read - sms_info_t* info = get_oldest_sms_index(); + sms_info_t *info = get_oldest_sms_index(); if (info) { - if (info->msg_size+1 > len) { // +1 for '\0' + if (info->msg_size + 1 > len) { // +1 for '\0' tr_warn("Given buf too small, len is: %d but is must be: %d", len, info->msg_size); if (buf_size) { *buf_size = info->msg_size; @@ -792,8 +790,8 @@ nsapi_size_or_error_t AT_CellularSMS::get_sms(char* buf, uint16_t len, char* pho return err; } - nsapi_size_or_error_t AT_CellularSMS::get_data_from_pdu(const char* pdu, sms_info_t *info, int *part_number, - char *phone_number, char *msg) +nsapi_size_or_error_t AT_CellularSMS::get_data_from_pdu(const char *pdu, sms_info_t *info, int *part_number, + char *phone_number, char *msg) { int index = 0; int tmp; @@ -805,81 +803,81 @@ nsapi_size_or_error_t AT_CellularSMS::get_sms(char* buf, uint16_t len, char* pho // read Length of the SMSC information oaLength = hex_str_to_int(pdu, 2); index += 2; // length we just read - index += oaLength*2; // skip service center number + index += oaLength * 2; // skip service center number // read first the lower part of first octet as there is message type index++; - tmp = hex_str_to_int(pdu+index, 1); + tmp = hex_str_to_int(pdu + index, 1); //wait_ms(200); if ((tmp & 0x03) == 0) {// SMS-DELIVER type, last two bits should be zero // UDH present? Check from first octets higher part tmp = hex_str_to_int(pdu + (--index), 1); userDataHeader = ((tmp & 0x04) == 0) ? false : true; - index +=2; // we just read the high bits of first octet so move +2 + index += 2; // we just read the high bits of first octet so move +2 // originating address length - oaLength = hex_str_to_int(pdu+index, 2); - index +=2; // add index over address length - index +=2; // skip number type + oaLength = hex_str_to_int(pdu + index, 2); + index += 2; // add index over address length + index += 2; // skip number type if (phone_number) { // phone number as reverse nibble encoded int a = 0; - for (; a < oaLength; a +=2) { - if (a+1 == oaLength) { - phone_number[a] = pdu[index+a+1]; + for (; a < oaLength; a += 2) { + if (a + 1 == oaLength) { + phone_number[a] = pdu[index + a + 1]; } else { - phone_number[a] = pdu[index+a+1]; - phone_number[a+1] = pdu[index+a]; + phone_number[a] = pdu[index + a + 1]; + phone_number[a + 1] = pdu[index + a]; } } phone_number[oaLength] = '\0'; } index += oaLength; - if (oaLength&0x01) { // if phone number length is odd then it has padded F so skip that + if (oaLength & 0x01) { // if phone number length is odd then it has padded F so skip that index++; } - index +=2; // skip TP-Protocol identifier + index += 2; // skip TP-Protocol identifier - dataScheme = hex_str_to_int(pdu+index, 2); - index +=2; // skip TP-Data-Coding-Scheme + dataScheme = hex_str_to_int(pdu + index, 2); + index += 2; // skip TP-Data-Coding-Scheme // next one is date, it's length is 7 octets according to 3GPP TS 23.040 // create time string if (info) { int i = 0; // year - info->date[i++] = pdu[index+1]; + info->date[i++] = pdu[index + 1]; info->date[i++] = pdu[index]; - index+=2; + index += 2; info->date[i++] = '/'; // month - info->date[i++] = pdu[index+1]; + info->date[i++] = pdu[index + 1]; info->date[i++] = pdu[index]; - index+=2; + index += 2; info->date[i++] = '/'; // Day - info->date[i++] = pdu[index+1]; + info->date[i++] = pdu[index + 1]; info->date[i++] = pdu[index]; - index+=2; + index += 2; info->date[i++] = ','; // Hour - info->date[i++] = pdu[index+1]; + info->date[i++] = pdu[index + 1]; info->date[i++] = pdu[index]; - index+=2; + index += 2; info->date[i++] = ':'; // Minute - info->date[i++] = pdu[index+1]; + info->date[i++] = pdu[index + 1]; info->date[i++] = pdu[index]; - index+=2; + index += 2; info->date[i++] = ':'; // Second - info->date[i++] = pdu[index+1]; + info->date[i++] = pdu[index + 1]; info->date[i++] = pdu[index]; - index+=2; + index += 2; // timezone related to GMT. pdu[index+1] most significant bit indicates the sign related to gmt - tmp = hex_str_to_int(pdu+index+1, 1); - if (tmp&0x08) { + tmp = hex_str_to_int(pdu + index + 1, 1); + if (tmp & 0x08) { info->date[i++] = '-'; } else { info->date[i++] = '+'; @@ -890,19 +888,19 @@ nsapi_size_or_error_t AT_CellularSMS::get_sms(char* buf, uint16_t len, char* pho info->date[i++] = '0' + (tmp & 0x07); info->date[i++] = pdu[index]; info->date[i] = '\0'; - index+=2; + index += 2; } else { - index+=14; + index += 14; } - int udl = hex_str_to_int(pdu+index, 2); - index +=2; + int udl = hex_str_to_int(pdu + index, 2); + index += 2; int paddingBits = 0; int partnro = 1; if (userDataHeader) { // we need to read User Defined Header to know what part number this message is. - index += read_udh_from_pdu(pdu+index, info, partnro, paddingBits); + index += read_udh_from_pdu(pdu + index, info, partnro, paddingBits); } if (part_number) { @@ -911,38 +909,37 @@ nsapi_size_or_error_t AT_CellularSMS::get_sms(char* buf, uint16_t len, char* pho if (msg) { // we are reading the message - err = read_pdu_payload(pdu+index, udl, dataScheme, msg, paddingBits); - } - else { + err = read_pdu_payload(pdu + index, udl, dataScheme, msg, paddingBits); + } else { if (dataScheme == 0x00) { // when listing messages we need to calculated length. Other way would be unpacking the whole message. - err = strlen(pdu+index) >> 1; + err = strlen(pdu + index) >> 1; err *= 8; err /= 7; } else if (dataScheme == 0x04) { - err = strlen(pdu+index) >> 1; + err = strlen(pdu + index) >> 1; } else { return NSAPI_ERROR_UNSUPPORTED; } } return err; - } - else { + } else { // message was not DELIVER so discard it return NSAPI_ERROR_UNSUPPORTED; } } - // read params from User Defined Header -int AT_CellularSMS::read_udh_from_pdu(const char* pdu, sms_info_t *info, int &part_number, int &padding_bits) { +// read params from User Defined Header +int AT_CellularSMS::read_udh_from_pdu(const char *pdu, sms_info_t *info, int &part_number, int &padding_bits) +{ int index = 0; int udhLength = hex_str_to_int(pdu, 2); - index +=2; + index += 2; // if there is padding bits then udhlen is octet bigger as we need to keep septet boundary - padding_bits = ((udhLength+1) * 8 ) % 7; // +1 is for udhLength itself + padding_bits = ((udhLength + 1) * 8) % 7; // +1 is for udhLength itself if (padding_bits) { padding_bits = 7 - padding_bits; @@ -950,39 +947,39 @@ int AT_CellularSMS::read_udh_from_pdu(const char* pdu, sms_info_t *info, int &pa padding_bits = 0; } - int tmp = hex_str_to_int(pdu+index, 2); - index +=4; + int tmp = hex_str_to_int(pdu + index, 2); + index += 4; if (tmp == 0) { // 8-bit reference number if (info) { - info->msg_ref_number = (uint16_t)hex_str_to_int(pdu+index, 2); + info->msg_ref_number = (uint16_t)hex_str_to_int(pdu + index, 2); } - index +=2; + index += 2; } else { // 16-bit reference number if (info) { - info->msg_ref_number = (uint16_t)hex_str_to_int(pdu+index+2, 2); - tmp = hex_str_to_int(pdu+index, 2); + info->msg_ref_number = (uint16_t)hex_str_to_int(pdu + index + 2, 2); + tmp = hex_str_to_int(pdu + index, 2); info->msg_ref_number |= (tmp << 8); } - index +=4; + index += 4; } if (info) { - info->parts = hex_str_to_int(pdu+index, 2); + info->parts = hex_str_to_int(pdu + index, 2); } - index +=2; + index += 2; - part_number = hex_str_to_int(pdu+index, 2); - index +=2; + part_number = hex_str_to_int(pdu + index, 2); + index += 2; - return (udhLength*2 + 2); // udh in hex and udhl + return (udhLength * 2 + 2); // udh in hex and udhl } -nsapi_size_or_error_t AT_CellularSMS::read_pdu_payload(const char* pdu, int msg_len, int scheme, char *msg, int padding_bits) +nsapi_size_or_error_t AT_CellularSMS::read_pdu_payload(const char *pdu, int msg_len, int scheme, char *msg, int padding_bits) { if (scheme == 0x00) { // 7 bit gsm encoding, must do the conversions from hex to 7-bit encoding and to ascii - return unpack_7_bit_gsm_to_str(pdu, strlen(pdu)/2, msg, padding_bits, msg_len); + return unpack_7_bit_gsm_to_str(pdu, strlen(pdu) / 2, msg, padding_bits, msg_len); } else if (scheme == 0x04) { // 8bit scheme so just convert hexstring to charstring return hex_str_to_char_str(pdu, strlen(pdu), msg); @@ -994,8 +991,8 @@ nsapi_size_or_error_t AT_CellularSMS::read_pdu_payload(const char* pdu, int msg_ void AT_CellularSMS::free_linked_list() { - sms_info_t* info = _sms_info; - sms_info_t* old; + sms_info_t *info = _sms_info; + sms_info_t *old; while (info) { old = info; info = info->next_info; @@ -1004,17 +1001,18 @@ void AT_CellularSMS::free_linked_list() _sms_info = NULL; } -void AT_CellularSMS::add_info(sms_info_t* info, int index, int part_number) { +void AT_CellularSMS::add_info(sms_info_t *info, int index, int part_number) +{ // check for same message reference id. If found, update it and delete the given info. // if NOT found then add to the end of the list. if (!_sms_info) { - info->msg_index[part_number-1] = index; // part numbering starts from 1 so -1 to put to right index + info->msg_index[part_number - 1] = index; // part numbering starts from 1 so -1 to put to right index _sms_info = info; return; } - sms_info_t* current = _sms_info; - sms_info_t* prev; + sms_info_t *current = _sms_info; + sms_info_t *prev; bool found_msg = false; while (current) { prev = current; @@ -1024,7 +1022,7 @@ void AT_CellularSMS::add_info(sms_info_t* info, int index, int part_number) { info->parts > info->parts_added) { // multipart sms, update msg size and index current->msg_size += info->msg_size; - current->msg_index[part_number-1] = index; // part numbering starts from 1 so -1 to put to right index + current->msg_index[part_number - 1] = index; // part numbering starts from 1 so -1 to put to right index current->parts_added++; // update oldest part as date if (compare_time_strings(info->date, current->date) == -1) { @@ -1041,7 +1039,7 @@ void AT_CellularSMS::add_info(sms_info_t* info, int index, int part_number) { delete info; } else { // message not found, add to linked list - info->msg_index[part_number-1] = index; + info->msg_index[part_number - 1] = index; prev->next_info = info; } } @@ -1059,7 +1057,7 @@ nsapi_error_t AT_CellularSMS::list_messages() } _at.cmd_stop(); - sms_info_t* info = NULL; + sms_info_t *info = NULL; // init for 1 so that in text mode we will add to the correct place without any additional logic in addInfo() in text mode int part_number = 1; int index = 0; @@ -1081,8 +1079,8 @@ nsapi_error_t AT_CellularSMS::list_messages() index = _at.read_int(); _at.skip_param(2); // ,[] length = _at.read_int(); - length = length*2 + 20;// *2 as it's hex encoded and +20 as service center number is not included in size given by CMGL - pdu = (char*)calloc(length, sizeof(char)); + length = length * 2 + 20; // *2 as it's hex encoded and +20 as service center number is not included in size given by CMGL + pdu = (char *)calloc(length, sizeof(char)); if (!pdu) { delete info; _at.resp_stop(); @@ -1116,7 +1114,7 @@ nsapi_error_t AT_CellularSMS::list_messages() return _at.get_last_error(); } -AT_CellularSMS::sms_info_t* AT_CellularSMS::get_oldest_sms_index() +AT_CellularSMS::sms_info_t *AT_CellularSMS::get_oldest_sms_index() { /* * Different scenarios when finding the oldest concatenated sms @@ -1130,8 +1128,8 @@ AT_CellularSMS::sms_info_t* AT_CellularSMS::get_oldest_sms_index() */ // if text mode we need to read sms with +CMGR because time stamp is optional while looping with +CMGL - sms_info_t* retVal = NULL; - sms_info_t* current = _sms_info; + sms_info_t *retVal = NULL; + sms_info_t *current = _sms_info; nsapi_size_or_error_t err = 0; while (current) { if (_mode == CellularSMSMmodeText) { @@ -1155,7 +1153,7 @@ AT_CellularSMS::sms_info_t* AT_CellularSMS::get_oldest_sms_index() } // if time_string_1 is greater (more fresh date) then return 1, same 0, smaller -1. Error -2 -int AT_CellularSMS::compare_time_strings(const char* time_string_1, const char* time_string_2) +int AT_CellularSMS::compare_time_strings(const char *time_string_1, const char *time_string_2) { time_t t1; time_t t2; @@ -1178,7 +1176,7 @@ int AT_CellularSMS::compare_time_strings(const char* time_string_1, const char* return retVal; } -bool AT_CellularSMS::create_time(const char* time_string, time_t* time) +bool AT_CellularSMS::create_time(const char *time_string, time_t *time) { const int kNumberOfElements = 8; tm time_struct = { 0 }; @@ -1202,7 +1200,7 @@ bool AT_CellularSMS::create_time(const char* time_string, time_t* time) return retVal; } -uint16_t AT_CellularSMS::pack_7_bit_gsm_and_hex(const char* str, uint16_t len, char *buf, +uint16_t AT_CellularSMS::pack_7_bit_gsm_and_hex(const char *str, uint16_t len, char *buf, int number_of_padding_bit) { uint16_t strCnt = 0; @@ -1211,12 +1209,12 @@ uint16_t AT_CellularSMS::pack_7_bit_gsm_and_hex(const char* str, uint16_t len, c char tmp; // convert to 7bit gsm first - char* gsm_str = (char*)malloc(len); + char *gsm_str = (char *)malloc(len); if (!gsm_str) { return 0; } for (uint16_t y = 0; y < len; y++) { - for (int x=0; x < GSM_TO_ASCII_TABLE_SIZE; x++) { + for (int x = 0; x < GSM_TO_ASCII_TABLE_SIZE; x++) { if (gsm_to_ascii[x] == str[y]) { gsm_str[y] = x; } @@ -1225,26 +1223,26 @@ uint16_t AT_CellularSMS::pack_7_bit_gsm_and_hex(const char* str, uint16_t len, c // then packing and converting to hex if (number_of_padding_bit) { - tmp = gsm_str[strCnt]<>shift); + if (strCnt + 1 == len) { + tmp = (gsm_str[strCnt] >> shift); } else { - tmp = (gsm_str[strCnt]>>shift) | (gsm_str[strCnt+1] <<(7-shift)); + tmp = (gsm_str[strCnt] >> shift) | (gsm_str[strCnt + 1] << (7 - shift)); } - char_str_to_hex_str(&tmp, 1, buf+(i*2)); + char_str_to_hex_str(&tmp, 1, buf + (i * 2)); if (shift == 6) { strCnt++; @@ -1258,8 +1256,8 @@ uint16_t AT_CellularSMS::pack_7_bit_gsm_and_hex(const char* str, uint16_t len, c return i; } - uint16_t AT_CellularSMS::unpack_7_bit_gsm_to_str(const char* str, int len, char *buf, int padding_bits, - int msg_len) +uint16_t AT_CellularSMS::unpack_7_bit_gsm_to_str(const char *str, int len, char *buf, int padding_bits, + int msg_len) { int strCount = 0; uint16_t decodedCount = 0; @@ -1269,27 +1267,27 @@ uint16_t AT_CellularSMS::pack_7_bit_gsm_and_hex(const char* str, uint16_t len, c if (padding_bits) { hex_str_to_char_str(str, 2, &tmp); - buf[decodedCount] = gsm_to_ascii[(tmp>>padding_bits) & 0x7F]; + buf[decodedCount] = gsm_to_ascii[(tmp >> padding_bits) & 0x7F]; strCount++; decodedCount++; } while (strCount < len) { - shift = (strCount-padding_bits)%7; - hex_str_to_char_str(str + strCount*2, 2, &tmp); + shift = (strCount - padding_bits) % 7; + hex_str_to_char_str(str + strCount * 2, 2, &tmp); if (shift == 0) { buf[decodedCount] = gsm_to_ascii[tmp & 0x7F]; } else if (shift == 6) { - hex_str_to_char_str(str + (strCount-1)*2, 2, &tmp1); - buf[decodedCount] = gsm_to_ascii[(((tmp1>>2)) | (tmp << 6)) & 0x7F]; - if (decodedCount+1 < msg_len) { - hex_str_to_char_str(str + strCount*2, 2, &tmp); + hex_str_to_char_str(str + (strCount - 1) * 2, 2, &tmp1); + buf[decodedCount] = gsm_to_ascii[(((tmp1 >> 2)) | (tmp << 6)) & 0x7F]; + if (decodedCount + 1 < msg_len) { + hex_str_to_char_str(str + strCount * 2, 2, &tmp); decodedCount++; - buf[decodedCount] = gsm_to_ascii[(tmp>>1) & 0x7F]; + buf[decodedCount] = gsm_to_ascii[(tmp >> 1) & 0x7F]; } } else { - hex_str_to_char_str(str + (strCount-1)*2, 2, &tmp1); - buf[decodedCount] = gsm_to_ascii[(((tmp1>>(8- shift))) | ((tmp << shift))) & 0x7F]; + hex_str_to_char_str(str + (strCount - 1) * 2, 2, &tmp1); + buf[decodedCount] = gsm_to_ascii[(((tmp1 >> (8 - shift))) | ((tmp << shift))) & 0x7F]; } strCount++; diff --git a/features/cellular/framework/AT/AT_CellularSMS.h b/features/cellular/framework/AT/AT_CellularSMS.h index 46080518e84..222cf90a67b 100644 --- a/features/cellular/framework/AT/AT_CellularSMS.h +++ b/features/cellular/framework/AT/AT_CellularSMS.h @@ -30,8 +30,7 @@ namespace mbed { * * Class for SMS sending, reading and deleting. */ -class AT_CellularSMS: public CellularSMS, public AT_CellularBase -{ +class AT_CellularSMS: public CellularSMS, public AT_CellularBase { public: AT_CellularSMS(ATHandler &atHandler); @@ -42,10 +41,10 @@ class AT_CellularSMS: public CellularSMS, public AT_CellularBase virtual nsapi_error_t initialize(CellularSMSMmode mode); - virtual nsapi_size_or_error_t send_sms(const char* phone_number, const char* message, int msg_len); + virtual nsapi_size_or_error_t send_sms(const char *phone_number, const char *message, int msg_len); - virtual nsapi_size_or_error_t get_sms(char* buf, uint16_t buf_len, char* phone_num, uint16_t phone_len, - char* time_stamp, uint16_t time_len, int *buf_size); + virtual nsapi_size_or_error_t get_sms(char *buf, uint16_t buf_len, char *phone_num, uint16_t phone_len, + char *time_stamp, uint16_t time_len, int *buf_size); virtual void set_sms_callback(Callback func); @@ -69,7 +68,7 @@ class AT_CellularSMS: public CellularSMS, public AT_CellularBase uint8_t parts_added; uint16_t msg_ref_number; struct sms_info_t *next_info; - sms_info_t() : msg_size(0), parts(1), parts_added(1), msg_ref_number(0), next_info(0){}; + sms_info_t() : msg_size(0), parts(1), parts_added(1), msg_ref_number(0), next_info(0) {}; }; // application callback function for received sms @@ -119,7 +118,7 @@ class AT_CellularSMS: public CellularSMS, public AT_CellularBase * @param sms struct containing index array to delete * @return zero for success */ - nsapi_error_t delete_sms(sms_info_t* sms); + nsapi_error_t delete_sms(sms_info_t *sms); /** * Internal helper methods @@ -127,19 +126,19 @@ class AT_CellularSMS: public CellularSMS, public AT_CellularBase nsapi_error_t list_messages(); int read_sms_params(char *, char *); void free_linked_list(); - void add_info(sms_info_t* info, int index, int part_number); - int read_udh_from_pdu(const char* pdu, sms_info_t *info, int &part_number, int &padding_bits); - nsapi_size_or_error_t get_data_from_pdu(const char* pdu, sms_info_t *info, int *part_number, + void add_info(sms_info_t *info, int index, int part_number); + int read_udh_from_pdu(const char *pdu, sms_info_t *info, int &part_number, int &padding_bits); + nsapi_size_or_error_t get_data_from_pdu(const char *pdu, sms_info_t *info, int *part_number, char *phone_number = NULL, char *msg = NULL); - nsapi_size_or_error_t read_pdu_payload(const char* pdu, int msg_len, int scheme, char *msg, int padding_bits); - sms_info_t* get_oldest_sms_index(); - bool create_time(const char* time_string, time_t* time); - int compare_time_strings(const char* time_string_1, const char* time_string_2); - char* create_pdu(const char* phone_number, const char* message, uint8_t message_length, uint8_t msg_parts, - uint8_t msg_part_number, uint8_t& header_size); - nsapi_size_or_error_t read_sms_from_index(int msg_index, char* buf, uint16_t len, char* phone_num, - char* time_stamp); - nsapi_size_or_error_t read_sms(sms_info_t* sms, char* buf, char* phone_num, char* time_stamp); + nsapi_size_or_error_t read_pdu_payload(const char *pdu, int msg_len, int scheme, char *msg, int padding_bits); + sms_info_t *get_oldest_sms_index(); + bool create_time(const char *time_string, time_t *time); + int compare_time_strings(const char *time_string_1, const char *time_string_2); + char *create_pdu(const char *phone_number, const char *message, uint8_t message_length, uint8_t msg_parts, + uint8_t msg_part_number, uint8_t &header_size); + nsapi_size_or_error_t read_sms_from_index(int msg_index, char *buf, uint16_t len, char *phone_num, + char *time_stamp); + nsapi_size_or_error_t read_sms(sms_info_t *sms, char *buf, char *phone_num, char *time_stamp); /** Packs the given str from ascii to 7bit gsm format and converts it to hex to the given buf. * @@ -149,7 +148,7 @@ class AT_CellularSMS: public CellularSMS, public AT_CellularBase * @param number_of_padding_bit padding bits needed to keep the octet boundary * @return length of buffer buf or zero on failure */ - uint16_t pack_7_bit_gsm_and_hex(const char* str, uint16_t len, char *buf, int number_of_padding_bit); + uint16_t pack_7_bit_gsm_and_hex(const char *str, uint16_t len, char *buf, int number_of_padding_bit); /** Unpacks the given hex- and 7-bit gsm encoded str to ascii string * @@ -161,8 +160,8 @@ class AT_CellularSMS: public CellularSMS, public AT_CellularBase * @return length of the destination buffer buf * */ - uint16_t unpack_7_bit_gsm_to_str(const char* str, int len, char *buf, int padding_bits, - int msg_len); + uint16_t unpack_7_bit_gsm_to_str(const char *str, int len, char *buf, int padding_bits, + int msg_len); }; } // namespace mbed diff --git a/features/cellular/framework/AT/AT_CellularStack.cpp b/features/cellular/framework/AT/AT_CellularStack.cpp index 5abd1fffdb0..d6f853f1921 100644 --- a/features/cellular/framework/AT/AT_CellularStack.cpp +++ b/features/cellular/framework/AT/AT_CellularStack.cpp @@ -22,9 +22,9 @@ using namespace mbed_cellular_util; using namespace mbed; -AT_CellularStack::AT_CellularStack(ATHandler &at, int cid, nsapi_ip_stack_t stack_type) : AT_CellularBase(at), _socket(NULL),_socket_count(0),_cid(cid), _stack_type(stack_type) +AT_CellularStack::AT_CellularStack(ATHandler &at, int cid, nsapi_ip_stack_t stack_type) : AT_CellularBase(at), _socket(NULL), _socket_count(0), _cid(cid), _stack_type(stack_type) { - memset(_ip,0, PDP_IPV6_SIZE); + memset(_ip, 0, PDP_IPV6_SIZE); } AT_CellularStack::~AT_CellularStack() @@ -44,7 +44,7 @@ AT_CellularStack::~AT_CellularStack() /** NetworkStack */ -const char * AT_CellularStack::get_ip_address() +const char *AT_CellularStack::get_ip_address() { _at.lock(); @@ -58,7 +58,7 @@ const char * AT_CellularStack::get_ip_address() _at.skip_param(); - int len = _at.read_string(_ip, NSAPI_IPv4_SIZE-1); + int len = _at.read_string(_ip, NSAPI_IPv4_SIZE - 1); if (len == -1) { _ip[0] = '\0'; _at.unlock(); @@ -68,7 +68,7 @@ const char * AT_CellularStack::get_ip_address() // in case stack type is not IPV4 only, try to look also for IPV6 address if (_stack_type != IPV4_STACK) { - len = _at.read_string(_ip, PDP_IPV6_SIZE-1); + len = _at.read_string(_ip, PDP_IPV6_SIZE - 1); } } @@ -131,7 +131,7 @@ nsapi_error_t AT_CellularStack::socket_close(nsapi_socket_t handle) int err = NSAPI_ERROR_DEVICE_ERROR; struct CellularSocket *socket = (struct CellularSocket *)handle; - if (!socket){ + if (!socket) { return err; } int sock_id = socket->id; diff --git a/features/cellular/framework/AT/AT_CellularStack.h b/features/cellular/framework/AT/AT_CellularStack.h index fe6ee440953..1f57eab68e9 100644 --- a/features/cellular/framework/AT/AT_CellularStack.h +++ b/features/cellular/framework/AT/AT_CellularStack.h @@ -34,8 +34,7 @@ namespace mbed { * * Implements NetworkStack and introduces interface for modem specific stack implementations. */ -class AT_CellularStack : public NetworkStack, public AT_CellularBase -{ +class AT_CellularStack : public NetworkStack, public AT_CellularBase { public: AT_CellularStack(ATHandler &at, int cid, nsapi_ip_stack_t stack_type); @@ -57,7 +56,7 @@ class AT_CellularStack : public NetworkStack, public AT_CellularBase virtual nsapi_error_t socket_connect(nsapi_socket_t handle, const SocketAddress &address); virtual nsapi_error_t socket_accept(nsapi_socket_t server, - nsapi_socket_t *handle, SocketAddress *address=0); + nsapi_socket_t *handle, SocketAddress *address = 0); virtual nsapi_size_or_error_t socket_send(nsapi_socket_t handle, const void *data, nsapi_size_t size); @@ -75,8 +74,7 @@ class AT_CellularStack : public NetworkStack, public AT_CellularBase protected: - class CellularSocket - { + class CellularSocket { public: // Socket id from cellular device int id; diff --git a/features/cellular/framework/common/CellularList.h b/features/cellular/framework/common/CellularList.h index 50f9ab7fc40..a5959c8ae41 100644 --- a/features/cellular/framework/common/CellularList.h +++ b/features/cellular/framework/common/CellularList.h @@ -27,51 +27,50 @@ namespace mbed { * Templated linked list class for common usage. * */ -template class CellularList -{ +template class CellularList { private: T *_head, *_tail; public: CellularList() { - _head=NULL; - _tail=NULL; + _head = NULL; + _tail = NULL; } - T* add_new() + T *add_new() { - T *temp=new T; - if (!temp) { - return NULL; - } - temp->next = NULL; - if (_head == NULL) { - _head = temp; - } else { - _tail->next=temp; - } - _tail = temp; - - return _tail; + T *temp = new T; + if (!temp) { + return NULL; + } + temp->next = NULL; + if (_head == NULL) { + _head = temp; + } else { + _tail->next = temp; + } + _tail = temp; + + return _tail; } void delete_last() { - T* previous = NULL; - T *current=_head; + T *previous = NULL; + T *current = _head; if (!current) { return; } while (current->next != NULL) { - previous=current; - current=current->next; + previous = current; + current = current->next; } if (previous) { - _tail=previous; - previous->next=NULL; + _tail = previous; + previous->next = NULL; } else { _head = NULL; _tail = NULL; diff --git a/features/cellular/framework/common/CellularUtil.cpp b/features/cellular/framework/common/CellularUtil.cpp index 406563951a7..f3e8b3ad9f9 100644 --- a/features/cellular/framework/common/CellularUtil.cpp +++ b/features/cellular/framework/common/CellularUtil.cpp @@ -20,7 +20,7 @@ namespace mbed_cellular_util { -void convert_ipv6(char* ip) +void convert_ipv6(char *ip) { if (!ip) { return; @@ -48,21 +48,21 @@ void convert_ipv6(char* ip) bool set_colon = false; for (i = 0; i < len; i++) { if (ip[i] == '.') { - b = (char)strtol (ip+ip_pos, NULL, 10); // convert to char to int so we can change it to hex string - pos += char_str_to_hex_str(&b, 1, ip+pos, !set_colon); // omit leading zeroes with using set_colon flag + b = (char)strtol(ip + ip_pos, NULL, 10); // convert to char to int so we can change it to hex string + pos += char_str_to_hex_str(&b, 1, ip + pos, !set_colon); // omit leading zeroes with using set_colon flag if (set_colon) { ip[pos++] = ':'; set_colon = false; } else { set_colon = true; } - ip_pos = i+1; // skip the '.' + ip_pos = i + 1; // skip the '.' } // handle the last part which does not end with '.' but '\0' - if (i == len -1) { - b = (char)strtol(ip+ip_pos, NULL, 10); - pos += char_str_to_hex_str(&b, 1, ip+pos, !set_colon); + if (i == len - 1) { + b = (char)strtol(ip + ip_pos, NULL, 10); + pos += char_str_to_hex_str(&b, 1, ip + pos, !set_colon); ip[pos] = '\0'; } } @@ -70,7 +70,7 @@ void convert_ipv6(char* ip) } // For example "32.1.13.184.0.0.205.48.0.0.0.0.0.0.0.0" -void separate_ip4like_addresses(char* orig, char* ip, size_t ip_size, char* ip2, size_t ip2_size) +void separate_ip4like_addresses(char *orig, char *ip, size_t ip_size, char *ip2, size_t ip2_size) { // ipv4-like notation int len = strlen(orig); @@ -100,9 +100,9 @@ void separate_ip4like_addresses(char* orig, char* ip, size_t ip_size, char* ip2, } } else if (count == 7) { // ipv4 and subnet mask. Need to separate those. temp = &orig[pos]; - if ((uint8_t)ip_size > temp-orig) { - memcpy(ip, orig, temp-orig); - ip[temp-orig] = '\0'; + if ((uint8_t)ip_size > temp - orig) { + memcpy(ip, orig, temp - orig); + ip[temp - orig] = '\0'; } temp++; // skip the '.' if (ip2 && (ip2_size > strlen(temp))) { @@ -120,11 +120,11 @@ void separate_ip4like_addresses(char* orig, char* ip, size_t ip_size, char* ip2, if (ip2) { ip2[0] = '\0'; } - } else if (count == 31){ // ipv6 + ipv6subnet mask in ipv4-like notation separated by dot '.' + } else if (count == 31) { // ipv6 + ipv6subnet mask in ipv4-like notation separated by dot '.' temp = &orig[pos]; - if ((uint8_t)ip_size > temp-orig) { - memcpy(ip, orig, temp-orig); - ip[temp-orig] = '\0'; + if ((uint8_t)ip_size > temp - orig) { + memcpy(ip, orig, temp - orig); + ip[temp - orig] = '\0'; convert_ipv6(ip); } temp++; // skip the '.' @@ -136,7 +136,7 @@ void separate_ip4like_addresses(char* orig, char* ip, size_t ip_size, char* ip2, } } -void separate_ip_addresses(char* orig, char* ip, size_t ip_size, char* ip2, size_t ip2_size) +void separate_ip_addresses(char *orig, char *ip, size_t ip_size, char *ip2, size_t ip2_size) { // orig can include ipv4, ipv6, both or two ip4/ipv6 addresses. // also format depends on possible AT+CGPIAF @@ -158,9 +158,9 @@ void separate_ip_addresses(char* orig, char* ip, size_t ip_size, char* ip2, size temp = strstr(orig, " "); // found space as separator and it wasn't in beginning --> contains 2 ip addresses if (temp && temp != orig) { - if ((uint8_t)ip_size > temp-orig) { - memcpy(ip, orig, temp-orig); - ip[temp-orig] = '\0'; + if ((uint8_t)ip_size > temp - orig) { + memcpy(ip, orig, temp - orig); + ip[temp - orig] = '\0'; } else { ip[0] = '\0'; } @@ -193,17 +193,16 @@ void separate_ip_addresses(char* orig, char* ip, size_t ip_size, char* ip2, size // found space as separator and it wasn't in beginning --> contains 2 ip addresses if (temp && temp != orig) { separate_ip4like_addresses(temp++, ip2, ip2_size, NULL, 0); - orig[temp-orig-1] = '\0'; + orig[temp - orig - 1] = '\0'; separate_ip4like_addresses(orig, ip, ip_size, NULL, 0); - orig[temp-orig-1] = ' '; // put space back to keep orig as original - } - else { + orig[temp - orig - 1] = ' '; // put space back to keep orig as original + } else { separate_ip4like_addresses(orig, ip, ip_size, ip2, ip2_size); } } } -void prefer_ipv6(char* ip, size_t ip_size, char* ip2, size_t ip2_size) +void prefer_ipv6(char *ip, size_t ip_size, char *ip2, size_t ip2_size) { if (!ip || !ip2) { return; @@ -234,7 +233,7 @@ void prefer_ipv6(char* ip, size_t ip_size, char* ip2, size_t ip2_size) } } -void int_to_hex_str(uint8_t num, char* buf) +void int_to_hex_str(uint8_t num, char *buf) { char charNum = num; char_str_to_hex_str(&charNum, 1, buf); @@ -245,7 +244,7 @@ int hex_str_to_int(const char *hex_string, int hex_string_length) const int base = 16; int character_as_integer, integer_output = 0; - for (int i=0;i= '0' && hex_string[i] <= '9') { character_as_integer = hex_string[i] - '0'; } else if (hex_string[i] >= 'A' && hex_string[i] <= 'F') { @@ -260,20 +259,20 @@ int hex_str_to_int(const char *hex_string, int hex_string_length) return integer_output; } -int hex_str_to_char_str(const char* str, uint16_t len, char *buf) +int hex_str_to_char_str(const char *str, uint16_t len, char *buf) { int strcount = 0; - for (int i = 0; i+1 < len; i += 2) { - int upper = hex_str_to_int(str+i, 1); - int lower = hex_str_to_int(str+i+1, 1); - buf[strcount] = ((upper<<4) & 0xF0) | (lower & 0x0F); + for (int i = 0; i + 1 < len; i += 2) { + int upper = hex_str_to_int(str + i, 1); + int lower = hex_str_to_int(str + i + 1, 1); + buf[strcount] = ((upper << 4) & 0xF0) | (lower & 0x0F); strcount++; } return strcount; } -void uint_to_binary_str(uint32_t num, char* str, int str_size, int bit_cnt) +void uint_to_binary_str(uint32_t num, char *str, int str_size, int bit_cnt) { if (!str || str_size < bit_cnt) { return; @@ -283,7 +282,7 @@ void uint_to_binary_str(uint32_t num, char* str, int str_size, int bit_cnt) for (int i = 31; i >= 0; i--) { tmp = num >> i; if (i < bit_cnt) { - if (tmp&1) { + if (tmp & 1) { str[pos] = 1 + '0'; } else { str[pos] = 0 + '0'; @@ -293,24 +292,24 @@ void uint_to_binary_str(uint32_t num, char* str, int str_size, int bit_cnt) } } -int char_str_to_hex_str(const char* str, uint16_t len, char *buf, bool omit_leading_zero) +int char_str_to_hex_str(const char *str, uint16_t len, char *buf, bool omit_leading_zero) { if (!str || !buf) { return 0; } char *ptr = buf; - int i=0; + int i = 0; while (i < len) { - if (omit_leading_zero == true && i == 0 && !(str[i]>>4 & 0x0F)) { + if (omit_leading_zero == true && i == 0 && !(str[i] >> 4 & 0x0F)) { *ptr++ = hex_values[(str[i]) & 0x0F]; } else { - *ptr++ = hex_values[((str[i])>>4) & 0x0F]; + *ptr++ = hex_values[((str[i]) >> 4) & 0x0F]; *ptr++ = hex_values[(str[i]) & 0x0F]; } i++; } - return ptr-buf; + return ptr - buf; } uint16_t get_dynamic_ip_port() diff --git a/features/cellular/framework/common/CellularUtil.h b/features/cellular/framework/common/CellularUtil.h index 28fa52be3cb..46f66162e73 100644 --- a/features/cellular/framework/common/CellularUtil.h +++ b/features/cellular/framework/common/CellularUtil.h @@ -38,7 +38,7 @@ static const char hex_values[] = "0123456789ABCDEF"; * * @param ip IP address that can be IPv4 or IPv6 in different formats from AT command +CGPADDR. Converted result uses same buffer. */ -void convert_ipv6(char* ip); +void convert_ipv6(char *ip); /** Separates IP addresses from the given 'orig' string. 'orig' may contain zero, one or two IP addresses in various formats. * See AT command +CGPIAF from 3GPP TS 27.007 for details. Does also needed conversions for IPv6 addresses. @@ -50,7 +50,7 @@ void convert_ipv6(char* ip); * @param ip2_size size of preallocated buffer ip2 * */ -void separate_ip_addresses(char* orig, char* ip, size_t ip_size, char* ip2, size_t ip2_size); +void separate_ip_addresses(char *orig, char *ip, size_t ip_size, char *ip2, size_t ip2_size); /** Swaps the arrays if param IP does not contain IPv6 address but param ip2 does. * @@ -59,14 +59,14 @@ void separate_ip_addresses(char* orig, char* ip, size_t ip_size, char* ip2, size * @param ip2 IP address * @param ip2_size size of buffer ip2 */ -void prefer_ipv6(char* ip, size_t ip_size, char* ip2, size_t ip2_size); +void prefer_ipv6(char *ip, size_t ip_size, char *ip2, size_t ip2_size); /** Converts the given int to two hex characters * * @param num number to be converted to hex string * @param buf preallocated buffer that will contain 2 char length hex value */ -void int_to_hex_str(uint8_t num, char* buf); +void int_to_hex_str(uint8_t num, char *buf); /** Converts the given buffer 'str' to hex buffer 'buf. First 'len' char's are converted to two hex bytes. * @@ -75,7 +75,7 @@ void int_to_hex_str(uint8_t num, char* buf); * @param buf destination buffer for hex converted chars. Buffer should be double the size of str to fit hex-encoded string. * @param omit_leading_zero if true then possible leading zeroes are omitted */ -int char_str_to_hex_str(const char* str, uint16_t len, char *buf, bool omit_leading_zero = false); +int char_str_to_hex_str(const char *str, uint16_t len, char *buf, bool omit_leading_zero = false); /** Converts the given hex string to integer * @@ -92,7 +92,7 @@ int hex_str_to_int(const char *hex_string, int hex_string_length); * @param buf preallocated buffer where result conversion is stored * @return length of the buf */ -int hex_str_to_char_str(const char* str, uint16_t len, char *buf); +int hex_str_to_char_str(const char *str, uint16_t len, char *buf); /** Converts the given uint to binary string. Fills the given str starting from [0] with the number of bits defined by bit_cnt * For example uint_to_binary_string(9, str, 10) would fill str "0000001001" @@ -103,7 +103,7 @@ int hex_str_to_char_str(const char* str, uint16_t len, char *buf); * @param str_size size of the str buffer * @param bit_cnt defines how many bits are filled to buffer started from lsb */ -void uint_to_binary_str(uint32_t num, char* str, int str_size, int bit_cnt); +void uint_to_binary_str(uint32_t num, char *str, int str_size, int bit_cnt); /** Get dynamic port for socket * diff --git a/features/filesystem/Dir.h b/features/filesystem/Dir.h index 9ed97f837a8..4e933bfa4b4 100644 --- a/features/filesystem/Dir.h +++ b/features/filesystem/Dir.h @@ -35,7 +35,7 @@ class Dir : public DirHandle { */ Dir(); - /** Open a directory on a filesystem + /** Open a directory on a filesystem * * @param fs Filesystem as target for a directory * @param path Name of the directory to open @@ -86,7 +86,7 @@ class Dir : public DirHandle { */ virtual void rewind(); - /** Get the sizeof the directory + /** Get the sizeof the directory * * @return Number of files in the directory */ diff --git a/features/filesystem/File.h b/features/filesystem/File.h index d08cf7c0d77..3135763b6aa 100644 --- a/features/filesystem/File.h +++ b/features/filesystem/File.h @@ -35,7 +35,7 @@ class File : public FileHandle { */ File(); - /** Create a file on a filesystem + /** Create a file on a filesystem * * Creates and opens a file on a filesystem * @@ -60,7 +60,7 @@ class File : public FileHandle { * bitwise or'd with one of O_CREAT, O_TRUNC, O_APPEND * @return 0 on success, negative error code on failure */ - virtual int open(FileSystem *fs, const char *path, int flags=O_RDONLY); + virtual int open(FileSystem *fs, const char *path, int flags = O_RDONLY); /** Close a file * @@ -80,7 +80,7 @@ class File : public FileHandle { /** Write the contents of a buffer to a file * * @param buffer The buffer to write from - * @param size The number of bytes to write + * @param size The number of bytes to write * @return The number of bytes written, negative error on failure */ virtual ssize_t write(const void *buffer, size_t size); diff --git a/features/filesystem/FileSystem.cpp b/features/filesystem/FileSystem.cpp index 99f98d2fe99..01c6906d0d9 100644 --- a/features/filesystem/FileSystem.cpp +++ b/features/filesystem/FileSystem.cpp @@ -139,7 +139,8 @@ size_t FileSystem::dir_size(fs_dir_t dir) template class Managed : public F { public: - virtual int close() { + virtual int close() + { int err = F::close(); delete this; return err; @@ -159,7 +160,8 @@ int FileSystem::open(FileHandle **file, const char *path, int flags) return 0; } -int FileSystem::open(DirHandle **dir, const char *path) { +int FileSystem::open(DirHandle **dir, const char *path) +{ Dir *d = new Managed; int err = d->open(this, path); if (err) { diff --git a/features/filesystem/FileSystem.h b/features/filesystem/FileSystem.h index 9b95e35dd88..180d88372dc 100644 --- a/features/filesystem/FileSystem.h +++ b/features/filesystem/FileSystem.h @@ -115,7 +115,7 @@ class FileSystem : public FileSystemLike { * @param buf The stat buffer to write to * @return 0 on success, negative error code on failure */ - virtual int statvfs(const char *path, struct statvfs *buf); + virtual int statvfs(const char *path, struct statvfs *buf); protected: friend class File; diff --git a/features/filesystem/bd/BlockDevice.h b/features/filesystem/bd/BlockDevice.h index 81159b90aca..27c076c9919 100644 --- a/features/filesystem/bd/BlockDevice.h +++ b/features/filesystem/bd/BlockDevice.h @@ -40,8 +40,7 @@ typedef uint64_t bd_size_t; /** A hardware device capable of writing and reading blocks */ -class BlockDevice -{ +class BlockDevice { public: /** Lifetime of a block device */ @@ -174,9 +173,9 @@ class BlockDevice bool is_valid_read(bd_addr_t addr, bd_size_t size) const { return ( - addr % get_read_size() == 0 && - size % get_read_size() == 0 && - addr + size <= this->size()); + addr % get_read_size() == 0 && + size % get_read_size() == 0 && + addr + size <= this->size()); } /** Convenience function for checking block program validity @@ -188,9 +187,9 @@ class BlockDevice bool is_valid_program(bd_addr_t addr, bd_size_t size) const { return ( - addr % get_program_size() == 0 && - size % get_program_size() == 0 && - addr + size <= this->size()); + addr % get_program_size() == 0 && + size % get_program_size() == 0 && + addr + size <= this->size()); } /** Convenience function for checking block erase validity @@ -202,9 +201,9 @@ class BlockDevice bool is_valid_erase(bd_addr_t addr, bd_size_t size) const { return ( - addr % get_erase_size() == 0 && - size % get_erase_size() == 0 && - addr + size <= this->size()); + addr % get_erase_size() == 0 && + size % get_erase_size() == 0 && + addr + size <= this->size()); } }; diff --git a/features/filesystem/bd/ChainingBlockDevice.cpp b/features/filesystem/bd/ChainingBlockDevice.cpp index 20a5da1f545..fb172c5c3f7 100644 --- a/features/filesystem/bd/ChainingBlockDevice.cpp +++ b/features/filesystem/bd/ChainingBlockDevice.cpp @@ -108,7 +108,7 @@ int ChainingBlockDevice::sync() int ChainingBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size) { MBED_ASSERT(is_valid_read(addr, size)); - uint8_t *buffer = static_cast(b); + uint8_t *buffer = static_cast(b); // Find block devices containing blocks, may span multiple block devices for (size_t i = 0; i < _bd_count && size > 0; i++) { @@ -139,7 +139,7 @@ int ChainingBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size) int ChainingBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size) { MBED_ASSERT(is_valid_program(addr, size)); - const uint8_t *buffer = static_cast(b); + const uint8_t *buffer = static_cast(b); // Find block devices containing blocks, may span multiple block devices for (size_t i = 0; i < _bd_count && size > 0; i++) { diff --git a/features/filesystem/bd/ChainingBlockDevice.h b/features/filesystem/bd/ChainingBlockDevice.h index b6b79365913..ca9d865357c 100644 --- a/features/filesystem/bd/ChainingBlockDevice.h +++ b/features/filesystem/bd/ChainingBlockDevice.h @@ -45,8 +45,7 @@ * ChainingBlockDevice chainmem(bds); * @endcode */ -class ChainingBlockDevice : public BlockDevice -{ +class ChainingBlockDevice : public BlockDevice { public: /** Lifetime of the memory block device * @@ -62,7 +61,7 @@ class ChainingBlockDevice : public BlockDevice * @note All block devices must have the same block size */ template - ChainingBlockDevice(BlockDevice *(&bds)[Size]) + ChainingBlockDevice(BlockDevice * (&bds)[Size]) : _bds(bds), _bd_count(sizeof(bds) / sizeof(bds[0])) , _read_size(0), _program_size(0), _erase_size(0), _size(0) { diff --git a/features/filesystem/bd/ExhaustibleBlockDevice.h b/features/filesystem/bd/ExhaustibleBlockDevice.h index 5d6ff5568bb..529f27833b9 100644 --- a/features/filesystem/bd/ExhaustibleBlockDevice.h +++ b/features/filesystem/bd/ExhaustibleBlockDevice.h @@ -31,8 +31,7 @@ * after a configurable number of cycles. * */ -class ExhaustibleBlockDevice : public BlockDevice -{ +class ExhaustibleBlockDevice : public BlockDevice { public: /** Lifetime of the block device * diff --git a/features/filesystem/bd/HeapBlockDevice.cpp b/features/filesystem/bd/HeapBlockDevice.cpp index f5bb02de769..04a3fdd7ad0 100644 --- a/features/filesystem/bd/HeapBlockDevice.cpp +++ b/features/filesystem/bd/HeapBlockDevice.cpp @@ -46,7 +46,7 @@ HeapBlockDevice::~HeapBlockDevice() int HeapBlockDevice::init() { if (!_blocks) { - _blocks = new uint8_t*[_count]; + _blocks = new uint8_t *[_count]; for (size_t i = 0; i < _count; i++) { _blocks[i] = 0; } @@ -91,7 +91,7 @@ int HeapBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size) { MBED_ASSERT(_blocks != NULL); MBED_ASSERT(is_valid_read(addr, size)); - uint8_t *buffer = static_cast(b); + uint8_t *buffer = static_cast(b); while (size > 0) { bd_addr_t hi = addr / _erase_size; @@ -115,14 +115,14 @@ int HeapBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size) { MBED_ASSERT(_blocks != NULL); MBED_ASSERT(is_valid_program(addr, size)); - const uint8_t *buffer = static_cast(b); + const uint8_t *buffer = static_cast(b); while (size > 0) { bd_addr_t hi = addr / _erase_size; bd_addr_t lo = addr % _erase_size; if (!_blocks[hi]) { - _blocks[hi] = (uint8_t*)malloc(_erase_size); + _blocks[hi] = (uint8_t *)malloc(_erase_size); if (!_blocks[hi]) { return BD_ERROR_DEVICE_ERROR; } diff --git a/features/filesystem/bd/HeapBlockDevice.h b/features/filesystem/bd/HeapBlockDevice.h index afdaeef7440..72bbdabee99 100644 --- a/features/filesystem/bd/HeapBlockDevice.h +++ b/features/filesystem/bd/HeapBlockDevice.h @@ -49,8 +49,7 @@ * } * @endcode */ -class HeapBlockDevice : public BlockDevice -{ +class HeapBlockDevice : public BlockDevice { public: /** Lifetime of the memory block device @@ -59,7 +58,7 @@ class HeapBlockDevice : public BlockDevice * @param block Block size in bytes. Minimum read, program, and erase sizes are * configured to this value */ - HeapBlockDevice(bd_size_t size, bd_size_t block=512); + HeapBlockDevice(bd_size_t size, bd_size_t block = 512); /** Lifetime of the memory block device * * @param size Size of the Block Device in bytes diff --git a/features/filesystem/bd/MBRBlockDevice.cpp b/features/filesystem/bd/MBRBlockDevice.cpp index 8799e1e3fdc..34dc19b230d 100644 --- a/features/filesystem/bd/MBRBlockDevice.cpp +++ b/features/filesystem/bd/MBRBlockDevice.cpp @@ -57,7 +57,7 @@ static inline uint32_t fromle32(uint32_t a) static void tochs(uint32_t lba, uint8_t chs[3]) { - uint32_t sector = std::min(lba, 0xfffffd)+1; + uint32_t sector = std::min(lba, 0xfffffd) + 1; chs[0] = (sector >> 6) & 0xff; chs[1] = ((sector >> 0) & 0x3f) | ((sector >> 16) & 0xc0); chs[2] = (sector >> 14) & 0xff; @@ -67,22 +67,22 @@ static void tochs(uint32_t lba, uint8_t chs[3]) // Partition after address are turned into absolute // addresses, assumes bd is initialized static int partition_absolute( - BlockDevice *bd, int part, uint8_t type, - bd_size_t offset, bd_size_t size) + BlockDevice *bd, int part, uint8_t type, + bd_size_t offset, bd_size_t size) { // Allocate smallest buffer necessary to write MBR uint32_t buffer_size = std::max(bd->get_program_size(), sizeof(struct mbr_table)); uint8_t *buffer = new uint8_t[buffer_size]; // Check for existing MBR - int err = bd->read(buffer, 512-buffer_size, buffer_size); + int err = bd->read(buffer, 512 - buffer_size, buffer_size); if (err) { delete[] buffer; return err; } - struct mbr_table *table = reinterpret_cast( - &buffer[buffer_size - sizeof(struct mbr_table)]); + struct mbr_table *table = reinterpret_cast( + &buffer[buffer_size - sizeof(struct mbr_table)]); if (table->signature[0] != 0x55 || table->signature[1] != 0xaa) { // Setup default values for MBR table->signature[0] = 0x55; @@ -92,19 +92,19 @@ static int partition_absolute( // Setup new partition MBED_ASSERT(part >= 1 && part <= 4); - table->entries[part-1].status = 0x00; // inactive (not bootable) - table->entries[part-1].type = type; + table->entries[part - 1].status = 0x00; // inactive (not bootable) + table->entries[part - 1].type = type; // lba dimensions uint32_t sector = std::max(bd->get_erase_size(), 512); uint32_t lba_offset = offset / sector; uint32_t lba_size = size / sector; - table->entries[part-1].lba_offset = tole32(lba_offset); - table->entries[part-1].lba_size = tole32(lba_size); + table->entries[part - 1].lba_offset = tole32(lba_offset); + table->entries[part - 1].lba_size = tole32(lba_size); // chs dimensions - tochs(lba_offset, table->entries[part-1].chs_start); - tochs(lba_offset+lba_size-1, table->entries[part-1].chs_stop); + tochs(lba_offset, table->entries[part - 1].chs_start); + tochs(lba_offset + lba_size - 1, table->entries[part - 1].chs_stop); // Write out MBR err = bd->erase(0, bd->get_erase_size()); @@ -113,7 +113,7 @@ static int partition_absolute( return err; } - err = bd->program(buffer, 512-buffer_size, buffer_size); + err = bd->program(buffer, 512 - buffer_size, buffer_size); delete[] buffer; return err; } @@ -149,7 +149,7 @@ int MBRBlockDevice::partition(BlockDevice *bd, int part, uint8_t type, bd_addr_t } int MBRBlockDevice::partition(BlockDevice *bd, int part, uint8_t type, - bd_addr_t start, bd_addr_t stop) + bd_addr_t start, bd_addr_t stop) { int err = bd->init(); if (err) { @@ -196,15 +196,15 @@ int MBRBlockDevice::init() uint32_t buffer_size = std::max(_bd->get_read_size(), sizeof(struct mbr_table)); uint8_t *buffer = new uint8_t[buffer_size]; - err = _bd->read(buffer, 512-buffer_size, buffer_size); + err = _bd->read(buffer, 512 - buffer_size, buffer_size); if (err) { delete[] buffer; return err; } // Check for valid table - struct mbr_table *table = reinterpret_cast( - &buffer[buffer_size - sizeof(struct mbr_table)]); + struct mbr_table *table = reinterpret_cast( + &buffer[buffer_size - sizeof(struct mbr_table)]); if (table->signature[0] != 0x55 || table->signature[1] != 0xaa) { delete[] buffer; return BD_ERROR_INVALID_MBR; @@ -213,18 +213,18 @@ int MBRBlockDevice::init() // Check for valid entry // 0x00 = no entry // 0x05, 0x0f = extended partitions, currently not supported - if ((table->entries[_part-1].type == 0x00 || - table->entries[_part-1].type == 0x05 || - table->entries[_part-1].type == 0x0f)) { + if ((table->entries[_part - 1].type == 0x00 || + table->entries[_part - 1].type == 0x05 || + table->entries[_part - 1].type == 0x0f)) { delete[] buffer; return BD_ERROR_INVALID_PARTITION; } // Get partition attributes bd_size_t sector = std::max(_bd->get_erase_size(), 512); - _type = table->entries[_part-1].type; - _offset = fromle32(table->entries[_part-1].lba_offset) * sector; - _size = fromle32(table->entries[_part-1].lba_size) * sector; + _type = table->entries[_part - 1].type; + _offset = fromle32(table->entries[_part - 1].lba_offset) * sector; + _size = fromle32(table->entries[_part - 1].lba_size) * sector; // Check that block addresses are valid MBED_ASSERT(_bd->is_valid_erase(_offset, _size)); @@ -293,7 +293,7 @@ bd_size_t MBRBlockDevice::get_partition_start() const bd_size_t MBRBlockDevice::get_partition_stop() const { - return _offset+_size; + return _offset + _size; } uint8_t MBRBlockDevice::get_partition_type() const diff --git a/features/filesystem/bd/MBRBlockDevice.h b/features/filesystem/bd/MBRBlockDevice.h index c44e5f854a1..e9686e834ad 100644 --- a/features/filesystem/bd/MBRBlockDevice.h +++ b/features/filesystem/bd/MBRBlockDevice.h @@ -88,15 +88,14 @@ enum { * - At most 4 partitions are supported * - Extended partitions are currently not supported and will error during init */ -class MBRBlockDevice : public BlockDevice -{ +class MBRBlockDevice : public BlockDevice { public: /** Format the MBR to contain the following partition * * @param bd Block device to partition * @param part Partition to use, 1-4 * @param type 8-bit partition type to identitfy partition's contents - * @param start Start block address to map to block 0 of partition, + * @param start Start block address to map to block 0 of partition, * negative addresses are calculated from the end of the * underlying block devices. Block 0 is implicitly ignored * from the range to store the MBR. @@ -110,7 +109,7 @@ class MBRBlockDevice : public BlockDevice * @param bd Block device to partition * @param part Partition to use, 1-4 * @param type 8-bit partition type to identitfy partition's contents - * @param start Start block address to map to block 0 of partition, + * @param start Start block address to map to block 0 of partition, * negative addresses are calculated from the end of the * underlying block devices. Block 0 is implicitly ignored * from the range to store the MBR. diff --git a/features/filesystem/bd/ObservingBlockDevice.h b/features/filesystem/bd/ObservingBlockDevice.h index b4b6aa87d8c..6319653e6a7 100644 --- a/features/filesystem/bd/ObservingBlockDevice.h +++ b/features/filesystem/bd/ObservingBlockDevice.h @@ -27,8 +27,7 @@ #include "Callback.h" -class ObservingBlockDevice : public BlockDevice -{ +class ObservingBlockDevice : public BlockDevice { public: /** Lifetime of the block device diff --git a/features/filesystem/bd/ProfilingBlockDevice.h b/features/filesystem/bd/ProfilingBlockDevice.h index bed93f14f9e..c2f76654762 100644 --- a/features/filesystem/bd/ProfilingBlockDevice.h +++ b/features/filesystem/bd/ProfilingBlockDevice.h @@ -44,8 +44,7 @@ * printf("erase count: %lld\n", profiler.get_erase_count()); * @endcode */ -class ProfilingBlockDevice : public BlockDevice -{ +class ProfilingBlockDevice : public BlockDevice { public: /** Lifetime of the memory block device * diff --git a/features/filesystem/bd/ReadOnlyBlockDevice.h b/features/filesystem/bd/ReadOnlyBlockDevice.h index 1813631655d..fd2eb3fbe33 100644 --- a/features/filesystem/bd/ReadOnlyBlockDevice.h +++ b/features/filesystem/bd/ReadOnlyBlockDevice.h @@ -26,8 +26,7 @@ #include "PlatformMutex.h" -class ReadOnlyBlockDevice : public BlockDevice -{ +class ReadOnlyBlockDevice : public BlockDevice { public: /** Lifetime of the block device diff --git a/features/filesystem/bd/SlicingBlockDevice.h b/features/filesystem/bd/SlicingBlockDevice.h index 90482ed7198..3ce91dc2c7f 100644 --- a/features/filesystem/bd/SlicingBlockDevice.h +++ b/features/filesystem/bd/SlicingBlockDevice.h @@ -46,8 +46,7 @@ * SlicingBlockDevice slice3(&mem, 16*512, -16*512); * @endcode */ -class SlicingBlockDevice : public BlockDevice -{ +class SlicingBlockDevice : public BlockDevice { public: /** Lifetime of the memory block device * diff --git a/features/filesystem/fat/FATFileSystem.cpp b/features/filesystem/fat/FATFileSystem.cpp index 05e48496090..7ffea22dcf0 100644 --- a/features/filesystem/fat/FATFileSystem.cpp +++ b/features/filesystem/fat/FATFileSystem.cpp @@ -34,7 +34,7 @@ static int fat_error_remap(FRESULT res) { - switch(res) { + switch (res) { case FR_OK: /* (0) Succeeded */ return 0; /* no error */ case FR_DISK_ERR: /* (1) A hard error occurred in the low level disk I/O layer */ @@ -78,8 +78,8 @@ class Deferred { T _t; Callback _ondefer; - Deferred(const Deferred&); - Deferred &operator=(const Deferred&); + Deferred(const Deferred &); + Deferred &operator=(const Deferred &); public: Deferred(T t, Callback ondefer = NULL) @@ -107,7 +107,7 @@ static void dodelete(const char *data) // Adds prefix needed internally by fatfs, this can be avoided for the first fatfs // (id 0) otherwise a prefix of "id:/" is inserted in front of the string. -static Deferred fat_path_prefix(int id, const char *path) +static Deferred fat_path_prefix(int id, const char *path) { // We can avoid dynamic allocation when only on fatfs is in use if (id == 0) { @@ -124,7 +124,7 @@ static Deferred fat_path_prefix(int id, const char *path) buffer[1] = ':'; buffer[2] = '/'; strcpy(buffer + strlen("0:/"), path); - return Deferred(buffer, dodelete); + return Deferred(buffer, dodelete); } @@ -142,11 +142,11 @@ DWORD get_fattime(void) time(&rawtime); struct tm *ptm = localtime(&rawtime); return (DWORD)(ptm->tm_year - 80) << 25 - | (DWORD)(ptm->tm_mon + 1 ) << 21 - | (DWORD)(ptm->tm_mday ) << 16 - | (DWORD)(ptm->tm_hour ) << 11 - | (DWORD)(ptm->tm_min ) << 5 - | (DWORD)(ptm->tm_sec/2 ); + | (DWORD)(ptm->tm_mon + 1) << 21 + | (DWORD)(ptm->tm_mday) << 16 + | (DWORD)(ptm->tm_hour) << 11 + | (DWORD)(ptm->tm_min) << 5 + | (DWORD)(ptm->tm_sec / 2); } void *ff_memalloc(UINT size) @@ -196,8 +196,8 @@ DRESULT disk_read(BYTE pdrv, BYTE *buff, DWORD sector, UINT count) { debug_if(FFS_DBG, "disk_read(sector %d, count %d) on pdrv [%d]\n", sector, count, pdrv); DWORD ssize = disk_get_sector_size(pdrv); - bd_addr_t addr = (bd_addr_t)sector*ssize; - bd_size_t size = (bd_size_t)count*ssize; + bd_addr_t addr = (bd_addr_t)sector * ssize; + bd_size_t size = (bd_size_t)count * ssize; int err = _ffs[pdrv]->read(buff, addr, size); return err ? RES_PARERR : RES_OK; } @@ -206,8 +206,8 @@ DRESULT disk_write(BYTE pdrv, const BYTE *buff, DWORD sector, UINT count) { debug_if(FFS_DBG, "disk_write(sector %d, count %d) on pdrv [%d]\n", sector, count, pdrv); DWORD ssize = disk_get_sector_size(pdrv); - bd_addr_t addr = (bd_addr_t)sector*ssize; - bd_size_t size = (bd_size_t)count*ssize; + bd_addr_t addr = (bd_addr_t)sector * ssize; + bd_size_t size = (bd_size_t)count * ssize; int err = _ffs[pdrv]->erase(addr, size); if (err) { return RES_PARERR; @@ -235,27 +235,27 @@ DRESULT disk_ioctl(BYTE pdrv, BYTE cmd, void *buff) if (_ffs[pdrv] == NULL) { return RES_NOTRDY; } else { - *((DWORD*)buff) = disk_get_sector_count(pdrv); + *((DWORD *)buff) = disk_get_sector_count(pdrv); return RES_OK; } case GET_SECTOR_SIZE: if (_ffs[pdrv] == NULL) { return RES_NOTRDY; } else { - *((WORD*)buff) = disk_get_sector_size(pdrv); + *((WORD *)buff) = disk_get_sector_size(pdrv); return RES_OK; } case GET_BLOCK_SIZE: - *((DWORD*)buff) = 1; // default when not known + *((DWORD *)buff) = 1; // default when not known return RES_OK; case CTRL_TRIM: if (_ffs[pdrv] == NULL) { return RES_NOTRDY; } else { - DWORD *sectors = (DWORD*)buff; + DWORD *sectors = (DWORD *)buff; DWORD ssize = disk_get_sector_size(pdrv); - bd_addr_t addr = (bd_addr_t)sectors[0]*ssize; - bd_size_t size = (bd_size_t)(sectors[1]-sectors[0]+1)*ssize; + bd_addr_t addr = (bd_addr_t)sectors[0] * ssize; + bd_size_t size = (bd_size_t)(sectors[1] - sectors[0] + 1) * ssize; int err = _ffs[pdrv]->trim(addr, size); return err ? RES_PARERR : RES_OK; } @@ -269,7 +269,8 @@ DRESULT disk_ioctl(BYTE pdrv, BYTE cmd, void *buff) // Filesystem implementation (See FATFilySystem.h) FATFileSystem::FATFileSystem(const char *name, BlockDevice *bd) - : FileSystem(name), _id(-1) { + : FileSystem(name), _id(-1) +{ if (bd) { mount(bd); } @@ -387,7 +388,7 @@ int FATFileSystem::reformat(BlockDevice *bd, int allocation_unit) int FATFileSystem::remove(const char *path) { - Deferred fpath = fat_path_prefix(_id, path); + Deferred fpath = fat_path_prefix(_id, path); lock(); FRESULT res = f_unlink(fpath); @@ -401,8 +402,8 @@ int FATFileSystem::remove(const char *path) int FATFileSystem::rename(const char *oldpath, const char *newpath) { - Deferred oldfpath = fat_path_prefix(_id, oldpath); - Deferred newfpath = fat_path_prefix(_id, newpath); + Deferred oldfpath = fat_path_prefix(_id, oldpath); + Deferred newfpath = fat_path_prefix(_id, newpath); lock(); FRESULT res = f_rename(oldfpath, newfpath); @@ -416,7 +417,7 @@ int FATFileSystem::rename(const char *oldpath, const char *newpath) int FATFileSystem::mkdir(const char *path, mode_t mode) { - Deferred fpath = fat_path_prefix(_id, path); + Deferred fpath = fat_path_prefix(_id, path); lock(); FRESULT res = f_mkdir(fpath); @@ -430,7 +431,7 @@ int FATFileSystem::mkdir(const char *path, mode_t mode) int FATFileSystem::stat(const char *path, struct stat *st) { - Deferred fpath = fat_path_prefix(_id, path); + Deferred fpath = fat_path_prefix(_id, path); lock(); FILINFO f; @@ -448,8 +449,8 @@ int FATFileSystem::stat(const char *path, struct stat *st) st->st_mode = 0; st->st_mode |= (f.fattrib & AM_DIR) ? S_IFDIR : S_IFREG; st->st_mode |= (f.fattrib & AM_RDO) ? - (S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) : - (S_IRWXU | S_IRWXG | S_IRWXO); + (S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) : + (S_IRWXU | S_IRWXG | S_IRWXO); #endif /* TOOLCHAIN_GCC */ unlock(); @@ -502,7 +503,7 @@ int FATFileSystem::file_open(fs_file_t *file, const char *path, int flags) debug_if(FFS_DBG, "open(%s) on filesystem [%s], drv [%s]\n", path, getName(), _id); FIL *fh = new FIL; - Deferred fpath = fat_path_prefix(_id, path); + Deferred fpath = fat_path_prefix(_id, path); /* POSIX flags -> FatFS open mode */ BYTE openmode; @@ -544,7 +545,7 @@ int FATFileSystem::file_open(fs_file_t *file, const char *path, int flags) int FATFileSystem::file_close(fs_file_t file) { - FIL *fh = static_cast(file); + FIL *fh = static_cast(file); lock(); FRESULT res = f_close(fh); @@ -556,7 +557,7 @@ int FATFileSystem::file_close(fs_file_t file) ssize_t FATFileSystem::file_read(fs_file_t file, void *buffer, size_t len) { - FIL *fh = static_cast(file); + FIL *fh = static_cast(file); lock(); UINT n; @@ -573,7 +574,7 @@ ssize_t FATFileSystem::file_read(fs_file_t file, void *buffer, size_t len) ssize_t FATFileSystem::file_write(fs_file_t file, const void *buffer, size_t len) { - FIL *fh = static_cast(file); + FIL *fh = static_cast(file); lock(); UINT n; @@ -590,7 +591,7 @@ ssize_t FATFileSystem::file_write(fs_file_t file, const void *buffer, size_t len int FATFileSystem::file_sync(fs_file_t file) { - FIL *fh = static_cast(file); + FIL *fh = static_cast(file); lock(); FRESULT res = f_sync(fh); @@ -604,12 +605,12 @@ int FATFileSystem::file_sync(fs_file_t file) off_t FATFileSystem::file_seek(fs_file_t file, off_t offset, int whence) { - FIL *fh = static_cast(file); + FIL *fh = static_cast(file); lock(); if (whence == SEEK_END) { offset += f_size(fh); - } else if(whence==SEEK_CUR) { + } else if (whence == SEEK_CUR) { offset += f_tell(fh); } @@ -627,7 +628,7 @@ off_t FATFileSystem::file_seek(fs_file_t file, off_t offset, int whence) off_t FATFileSystem::file_tell(fs_file_t file) { - FIL *fh = static_cast(file); + FIL *fh = static_cast(file); lock(); off_t res = f_tell(fh); @@ -638,7 +639,7 @@ off_t FATFileSystem::file_tell(fs_file_t file) off_t FATFileSystem::file_size(fs_file_t file) { - FIL *fh = static_cast(file); + FIL *fh = static_cast(file); lock(); off_t res = f_size(fh); @@ -652,7 +653,7 @@ off_t FATFileSystem::file_size(fs_file_t file) int FATFileSystem::dir_open(fs_dir_t *dir, const char *path) { FATFS_DIR *dh = new FATFS_DIR; - Deferred fpath = fat_path_prefix(_id, path); + Deferred fpath = fat_path_prefix(_id, path); lock(); FRESULT res = f_opendir(dh, fpath); @@ -670,7 +671,7 @@ int FATFileSystem::dir_open(fs_dir_t *dir, const char *path) int FATFileSystem::dir_close(fs_dir_t dir) { - FATFS_DIR *dh = static_cast(dir); + FATFS_DIR *dh = static_cast(dir); lock(); FRESULT res = f_closedir(dh); @@ -682,7 +683,7 @@ int FATFileSystem::dir_close(fs_dir_t dir) ssize_t FATFileSystem::dir_read(fs_dir_t dir, struct dirent *ent) { - FATFS_DIR *dh = static_cast(dir); + FATFS_DIR *dh = static_cast(dir); FILINFO finfo; lock(); @@ -711,7 +712,7 @@ ssize_t FATFileSystem::dir_read(fs_dir_t dir, struct dirent *ent) void FATFileSystem::dir_seek(fs_dir_t dir, off_t offset) { - FATFS_DIR *dh = static_cast(dir); + FATFS_DIR *dh = static_cast(dir); off_t dptr = static_cast(dh->dptr); lock(); @@ -735,7 +736,7 @@ void FATFileSystem::dir_seek(fs_dir_t dir, off_t offset) off_t FATFileSystem::dir_tell(fs_dir_t dir) { - FATFS_DIR *dh = static_cast(dir); + FATFS_DIR *dh = static_cast(dir); lock(); off_t offset = dh->dptr; @@ -746,7 +747,7 @@ off_t FATFileSystem::dir_tell(fs_dir_t dir) void FATFileSystem::dir_rewind(fs_dir_t dir) { - FATFS_DIR *dh = static_cast(dir); + FATFS_DIR *dh = static_cast(dir); lock(); f_rewinddir(dh); diff --git a/features/filesystem/fat/FATFileSystem.h b/features/filesystem/fat/FATFileSystem.h index 29afb9109a4..7e65ef4c852 100644 --- a/features/filesystem/fat/FATFileSystem.h +++ b/features/filesystem/fat/FATFileSystem.h @@ -145,7 +145,7 @@ class FATFileSystem : public FileSystem { * @param buf The stat buffer to write to * @return 0 on success, negative error code on failure */ - virtual int statvfs(const char *path, struct statvfs *buf); + virtual int statvfs(const char *path, struct statvfs *buf); protected: /** Open a file on the filesystem diff --git a/features/filesystem/littlefs/LittleFileSystem.cpp b/features/filesystem/littlefs/LittleFileSystem.cpp index d60d972f7ca..5af0f1b92d3 100644 --- a/features/filesystem/littlefs/LittleFileSystem.cpp +++ b/features/filesystem/littlefs/LittleFileSystem.cpp @@ -26,38 +26,52 @@ extern "C" { static int lfs_toerror(int err) { switch (err) { - case LFS_ERR_OK: return 0; - case LFS_ERR_IO: return -EIO; - case LFS_ERR_NOENT: return -ENOENT; - case LFS_ERR_EXIST: return -EEXIST; - case LFS_ERR_NOTDIR: return -ENOTDIR; - case LFS_ERR_ISDIR: return -EISDIR; - case LFS_ERR_INVAL: return -EINVAL; - case LFS_ERR_NOSPC: return -ENOSPC; - case LFS_ERR_NOMEM: return -ENOMEM; - default: return err; + case LFS_ERR_OK: + return 0; + case LFS_ERR_IO: + return -EIO; + case LFS_ERR_NOENT: + return -ENOENT; + case LFS_ERR_EXIST: + return -EEXIST; + case LFS_ERR_NOTDIR: + return -ENOTDIR; + case LFS_ERR_ISDIR: + return -EISDIR; + case LFS_ERR_INVAL: + return -EINVAL; + case LFS_ERR_NOSPC: + return -ENOSPC; + case LFS_ERR_NOMEM: + return -ENOMEM; + default: + return err; } } static int lfs_fromflags(int flags) { return ( - (((flags & 3) == O_RDONLY) ? LFS_O_RDONLY : 0) | - (((flags & 3) == O_WRONLY) ? LFS_O_WRONLY : 0) | - (((flags & 3) == O_RDWR) ? LFS_O_RDWR : 0) | - ((flags & O_CREAT) ? LFS_O_CREAT : 0) | - ((flags & O_EXCL) ? LFS_O_EXCL : 0) | - ((flags & O_TRUNC) ? LFS_O_TRUNC : 0) | - ((flags & O_APPEND) ? LFS_O_APPEND : 0)); + (((flags & 3) == O_RDONLY) ? LFS_O_RDONLY : 0) | + (((flags & 3) == O_WRONLY) ? LFS_O_WRONLY : 0) | + (((flags & 3) == O_RDWR) ? LFS_O_RDWR : 0) | + ((flags & O_CREAT) ? LFS_O_CREAT : 0) | + ((flags & O_EXCL) ? LFS_O_EXCL : 0) | + ((flags & O_TRUNC) ? LFS_O_TRUNC : 0) | + ((flags & O_APPEND) ? LFS_O_APPEND : 0)); } static int lfs_fromwhence(int whence) { switch (whence) { - case SEEK_SET: return LFS_SEEK_SET; - case SEEK_CUR: return LFS_SEEK_CUR; - case SEEK_END: return LFS_SEEK_END; - default: return whence; + case SEEK_SET: + return LFS_SEEK_SET; + case SEEK_CUR: + return LFS_SEEK_CUR; + case SEEK_END: + return LFS_SEEK_END; + default: + return whence; } } @@ -65,39 +79,47 @@ static int lfs_tomode(int type) { int mode = S_IRWXU | S_IRWXG | S_IRWXO; switch (type) { - case LFS_TYPE_DIR: return mode | S_IFDIR; - case LFS_TYPE_REG: return mode | S_IFREG; - default: return 0; + case LFS_TYPE_DIR: + return mode | S_IFDIR; + case LFS_TYPE_REG: + return mode | S_IFREG; + default: + return 0; } } static int lfs_totype(int type) { switch (type) { - case LFS_TYPE_DIR: return DT_DIR; - case LFS_TYPE_REG: return DT_REG; - default: return DT_UNKNOWN; + case LFS_TYPE_DIR: + return DT_DIR; + case LFS_TYPE_REG: + return DT_REG; + default: + return DT_UNKNOWN; } } ////// Block device operations ////// static int lfs_bd_read(const struct lfs_config *c, lfs_block_t block, - lfs_off_t off, void *buffer, lfs_size_t size) { + lfs_off_t off, void *buffer, lfs_size_t size) +{ BlockDevice *bd = (BlockDevice *)c->context; - return bd->read(buffer, (bd_addr_t)block*c->block_size + off, size); + return bd->read(buffer, (bd_addr_t)block * c->block_size + off, size); } static int lfs_bd_prog(const struct lfs_config *c, lfs_block_t block, - lfs_off_t off, const void *buffer, lfs_size_t size) { + lfs_off_t off, const void *buffer, lfs_size_t size) +{ BlockDevice *bd = (BlockDevice *)c->context; - return bd->program(buffer, (bd_addr_t)block*c->block_size + off, size); + return bd->program(buffer, (bd_addr_t)block * c->block_size + off, size); } static int lfs_bd_erase(const struct lfs_config *c, lfs_block_t block) { BlockDevice *bd = (BlockDevice *)c->context; - return bd->erase((bd_addr_t)block*c->block_size, c->block_size); + return bd->erase((bd_addr_t)block * c->block_size, c->block_size); } static int lfs_bd_sync(const struct lfs_config *c) @@ -111,19 +133,21 @@ static int lfs_bd_sync(const struct lfs_config *c) // Filesystem implementation (See LittleFileSystem.h) LittleFileSystem::LittleFileSystem(const char *name, BlockDevice *bd, - lfs_size_t read_size, lfs_size_t prog_size, - lfs_size_t block_size, lfs_size_t lookahead) - : FileSystem(name) - , _read_size(read_size) - , _prog_size(prog_size) - , _block_size(block_size) - , _lookahead(lookahead) { + lfs_size_t read_size, lfs_size_t prog_size, + lfs_size_t block_size, lfs_size_t lookahead) + : FileSystem(name) + , _read_size(read_size) + , _prog_size(prog_size) + , _block_size(block_size) + , _lookahead(lookahead) +{ if (bd) { mount(bd); } } -LittleFileSystem::~LittleFileSystem() { +LittleFileSystem::~LittleFileSystem() +{ // nop if unmounted unmount(); } @@ -159,7 +183,7 @@ int LittleFileSystem::mount(BlockDevice *bd) _config.block_size = _block_size; } _config.block_count = bd->size() / _config.block_size; - _config.lookahead = 32 * ((_config.block_count+31)/32); + _config.lookahead = 32 * ((_config.block_count + 31) / 32); if (_config.lookahead > _lookahead) { _config.lookahead = _lookahead; } @@ -191,17 +215,18 @@ int LittleFileSystem::unmount() _bd = NULL; } - + LFS_INFO("unmount -> %d", 0); _mutex.unlock(); return 0; } int LittleFileSystem::format(BlockDevice *bd, - lfs_size_t read_size, lfs_size_t prog_size, - lfs_size_t block_size, lfs_size_t lookahead) { + lfs_size_t read_size, lfs_size_t prog_size, + lfs_size_t block_size, lfs_size_t lookahead) +{ LFS_INFO("format(%p, %ld, %ld, %ld, %ld)", - bd, read_size, prog_size, block_size, lookahead); + bd, read_size, prog_size, block_size, lookahead); int err = bd->init(); if (err) { LFS_INFO("format -> %d", err); @@ -210,7 +235,7 @@ int LittleFileSystem::format(BlockDevice *bd, lfs_t _lfs; struct lfs_config _config; - + memset(&_config, 0, sizeof(_config)); _config.context = bd; _config.read = lfs_bd_read; @@ -230,7 +255,7 @@ int LittleFileSystem::format(BlockDevice *bd, _config.block_size = block_size; } _config.block_count = bd->size() / _config.block_size; - _config.lookahead = 32 * ((_config.block_count+31)/32); + _config.lookahead = 32 * ((_config.block_count + 31) / 32); if (_config.lookahead > lookahead) { _config.lookahead = lookahead; } @@ -275,7 +300,7 @@ int LittleFileSystem::reformat(BlockDevice *bd) } int err = LittleFileSystem::format(bd, - _read_size, _prog_size, _block_size, _lookahead); + _read_size, _prog_size, _block_size, _lookahead); if (err) { LFS_INFO("reformat -> %d", err); _mutex.unlock(); diff --git a/features/filesystem/littlefs/LittleFileSystem.h b/features/filesystem/littlefs/LittleFileSystem.h index 6f15a423ba0..dffd7aac320 100644 --- a/features/filesystem/littlefs/LittleFileSystem.h +++ b/features/filesystem/littlefs/LittleFileSystem.h @@ -51,13 +51,13 @@ class LittleFileSystem : public mbed::FileSystem { * The lookahead buffer requires only 1 bit per block so it can be quite * large with little ram impact. Should be a multiple of 32. */ - LittleFileSystem(const char *name=NULL, BlockDevice *bd=NULL, - lfs_size_t read_size=MBED_LFS_READ_SIZE, - lfs_size_t prog_size=MBED_LFS_PROG_SIZE, - lfs_size_t block_size=MBED_LFS_BLOCK_SIZE, - lfs_size_t lookahead=MBED_LFS_LOOKAHEAD); + LittleFileSystem(const char *name = NULL, BlockDevice *bd = NULL, + lfs_size_t read_size = MBED_LFS_READ_SIZE, + lfs_size_t prog_size = MBED_LFS_PROG_SIZE, + lfs_size_t block_size = MBED_LFS_BLOCK_SIZE, + lfs_size_t lookahead = MBED_LFS_LOOKAHEAD); virtual ~LittleFileSystem(); - + /** Formats a block device with the LittleFileSystem * * The block device to format should be mounted when this function is called. @@ -82,10 +82,10 @@ class LittleFileSystem : public mbed::FileSystem { * large with little ram impact. Should be a multiple of 32. */ static int format(BlockDevice *bd, - lfs_size_t read_size=MBED_LFS_READ_SIZE, - lfs_size_t prog_size=MBED_LFS_PROG_SIZE, - lfs_size_t block_size=MBED_LFS_BLOCK_SIZE, - lfs_size_t lookahead=MBED_LFS_LOOKAHEAD); + lfs_size_t read_size = MBED_LFS_READ_SIZE, + lfs_size_t prog_size = MBED_LFS_PROG_SIZE, + lfs_size_t block_size = MBED_LFS_BLOCK_SIZE, + lfs_size_t lookahead = MBED_LFS_LOOKAHEAD); /** Mounts a filesystem to a block device * @@ -182,7 +182,7 @@ class LittleFileSystem : public mbed::FileSystem { * * @param file File handle * @param buffer The buffer to write from - * @param size The number of bytes to write + * @param size The number of bytes to write * @return The number of bytes written, negative error on failure */ virtual ssize_t file_write(mbed::fs_file_t file, const void *buffer, size_t size); @@ -263,7 +263,7 @@ class LittleFileSystem : public mbed::FileSystem { * @param dir Dir handle */ virtual void dir_rewind(mbed::fs_dir_t dir); - + private: lfs_t _lfs; // _the actual filesystem struct lfs_config _config; diff --git a/features/filesystem/littlefs/TESTS/COMMON/atomic_usage.cpp b/features/filesystem/littlefs/TESTS/COMMON/atomic_usage.cpp index bd445b00891..181e9383fda 100644 --- a/features/filesystem/littlefs/TESTS/COMMON/atomic_usage.cpp +++ b/features/filesystem/littlefs/TESTS/COMMON/atomic_usage.cpp @@ -157,9 +157,9 @@ static int file_scanf(File *file, const char *format, ...) int res = file->read(buf, sizeof(buf) - 1); TEST_ASSERT_OR_EXIT(res >= 0); - va_start (args, format); - int count = vsscanf((char*)buf, format, args); - va_end (args); + va_start(args, format); + int count = vsscanf((char *)buf, format, args); + va_end(args); TEST_ASSERT_OR_EXIT(count >= 0); return count; @@ -176,9 +176,9 @@ static int file_printf(File *file, const char *format, ...) { uint8_t buf[BUFFER_SIZE]; va_list args; - va_start (args, format); - int size = vsprintf((char*)buf, format, args); - va_end (args); + va_start(args, format); + int size = vsprintf((char *)buf, format, args); + va_end(args); TEST_ASSERT_OR_EXIT((size >= 0) && (size <= (int)sizeof(buf))); if (file_write(file, buf, size)) { @@ -254,7 +254,7 @@ static void check_file_rename(FileSystem *fs) int files = 0; int valids = 0; - const char * const filenames[] = {FILE_RENAME_A, FILE_RENAME_B}; + const char *const filenames[] = {FILE_RENAME_A, FILE_RENAME_B}; for (int i = 0; i < 2; i++) { File file; @@ -300,7 +300,7 @@ static void setup_file_rename_replace(FileSystem *fs) uint32_t count = 0; uint8_t buf[BUFFER_SIZE]; memset(buf, 0, sizeof(buf)); - const int length = sprintf((char*)buf, FILE_RENAME_REPLACE_FMT, count); + const int length = sprintf((char *)buf, FILE_RENAME_REPLACE_FMT, count); TEST_ASSERT_OR_EXIT(length > 0); res = file.write(buf, length); @@ -602,7 +602,7 @@ static bool format_required(BlockDevice *bd) // Get the test version uint32_t version = 0; - res = sscanf((char*)buf, FILE_SETUP_COMPLETE_FMT, &version); + res = sscanf((char *)buf, FILE_SETUP_COMPLETE_FMT, &version); if (res != 1) { return true; } diff --git a/features/filesystem/littlefs/TESTS/filesystem/dirs/main.cpp b/features/filesystem/littlefs/TESTS/filesystem/dirs/main.cpp index f88b6280da7..8225baba11e 100644 --- a/features/filesystem/littlefs/TESTS/filesystem/dirs/main.cpp +++ b/features/filesystem/littlefs/TESTS/filesystem/dirs/main.cpp @@ -300,8 +300,8 @@ void test_multi_block_directory() res = fs.mkdir("cactus", 0777); TEST_ASSERT_EQUAL(0, res); for (int i = 0; i < 128; i++) { - sprintf((char*)buffer, "cactus/test%d", i); - res = fs.mkdir((char*)buffer, 0777); + sprintf((char *)buffer, "cactus/test%d", i); + res = fs.mkdir((char *)buffer, 0777); TEST_ASSERT_EQUAL(0, res); } res = fs.unmount(); @@ -326,10 +326,10 @@ void test_multi_block_directory() res = ent.d_type; TEST_ASSERT_EQUAL(DT_DIR, res); for (int i = 0; i < 128; i++) { - sprintf((char*)buffer, "test%d", i); + sprintf((char *)buffer, "test%d", i); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); - res = strcmp(ent.d_name, (char*)buffer); + res = strcmp(ent.d_name, (char *)buffer); TEST_ASSERT_EQUAL(0, res); } res = dir[0].read(&ent); diff --git a/features/filesystem/littlefs/TESTS/filesystem/files/main.cpp b/features/filesystem/littlefs/TESTS/filesystem/files/main.cpp index 658867bdb72..e852a0ee7b3 100644 --- a/features/filesystem/littlefs/TESTS/filesystem/files/main.cpp +++ b/features/filesystem/littlefs/TESTS/filesystem/files/main.cpp @@ -167,7 +167,7 @@ void test_small_file_test() chunk = (chunk < size - i) ? chunk : size - i; res = file[0].read(buffer, chunk); TEST_ASSERT_EQUAL(chunk, res); - for (size_t b = 0; b < chunk && i+b < size; b++) { + for (size_t b = 0; b < chunk && i + b < size; b++) { res = buffer[b]; TEST_ASSERT_EQUAL(rand() & 0xff, res); } @@ -221,7 +221,7 @@ void test_medium_file_test() chunk = (chunk < size - i) ? chunk : size - i; res = file[0].read(buffer, chunk); TEST_ASSERT_EQUAL(chunk, res); - for (size_t b = 0; b < chunk && i+b < size; b++) { + for (size_t b = 0; b < chunk && i + b < size; b++) { res = buffer[b]; TEST_ASSERT_EQUAL(rand() & 0xff, res); } @@ -275,7 +275,7 @@ void test_large_file_test() chunk = (chunk < size - i) ? chunk : size - i; res = file[0].read(buffer, chunk); TEST_ASSERT_EQUAL(chunk, res); - for (size_t b = 0; b < chunk && i+b < size; b++) { + for (size_t b = 0; b < chunk && i + b < size; b++) { res = buffer[b]; TEST_ASSERT_EQUAL(rand() & 0xff, res); } @@ -307,7 +307,7 @@ void test_non_overlap_check() chunk = (chunk < size - i) ? chunk : size - i; res = file[0].read(buffer, chunk); TEST_ASSERT_EQUAL(chunk, res); - for (size_t b = 0; b < chunk && i+b < size; b++) { + for (size_t b = 0; b < chunk && i + b < size; b++) { res = buffer[b]; TEST_ASSERT_EQUAL(rand() & 0xff, res); } @@ -330,7 +330,7 @@ void test_non_overlap_check() chunk = (chunk < size - i) ? chunk : size - i; res = file[0].read(buffer, chunk); TEST_ASSERT_EQUAL(chunk, res); - for (size_t b = 0; b < chunk && i+b < size; b++) { + for (size_t b = 0; b < chunk && i + b < size; b++) { res = buffer[b]; TEST_ASSERT_EQUAL(rand() & 0xff, res); } @@ -353,7 +353,7 @@ void test_non_overlap_check() chunk = (chunk < size - i) ? chunk : size - i; res = file[0].read(buffer, chunk); TEST_ASSERT_EQUAL(chunk, res); - for (size_t b = 0; b < chunk && i+b < size; b++) { + for (size_t b = 0; b < chunk && i + b < size; b++) { res = buffer[b]; TEST_ASSERT_EQUAL(rand() & 0xff, res); } @@ -388,28 +388,28 @@ void test_dir_check() TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, "smallavacado"); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, "mediumavacado"); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, "largeavacado"); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = dir[0].read(&ent); TEST_ASSERT_EQUAL(0, res); res = dir[0].close(); diff --git a/features/filesystem/littlefs/TESTS/filesystem/interspersed/main.cpp b/features/filesystem/littlefs/TESTS/filesystem/interspersed/main.cpp index c16a6f56293..51f198af4e7 100644 --- a/features/filesystem/littlefs/TESTS/filesystem/interspersed/main.cpp +++ b/features/filesystem/littlefs/TESTS/filesystem/interspersed/main.cpp @@ -111,18 +111,18 @@ void test_parallel_file_test() TEST_ASSERT_EQUAL(0, res); res = file[3].open(&fs, "d", O_WRONLY | O_CREAT); TEST_ASSERT_EQUAL(0, res); - + for (int i = 0; i < 10; i++) { - res = file[0].write((const void*)"a", 1); + res = file[0].write((const void *)"a", 1); TEST_ASSERT_EQUAL(1, res); - res = file[1].write((const void*)"b", 1); + res = file[1].write((const void *)"b", 1); TEST_ASSERT_EQUAL(1, res); - res = file[2].write((const void*)"c", 1); + res = file[2].write((const void *)"c", 1); TEST_ASSERT_EQUAL(1, res); - res = file[3].write((const void*)"d", 1); + res = file[3].write((const void *)"d", 1); TEST_ASSERT_EQUAL(1, res); } - + file[0].close(); file[1].close(); file[2].close(); @@ -147,28 +147,28 @@ void test_parallel_file_test() TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, "b"); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, "c"); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, "d"); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = dir[0].read(&ent); TEST_ASSERT_EQUAL(0, res); res = dir[0].close(); @@ -181,7 +181,7 @@ void test_parallel_file_test() TEST_ASSERT_EQUAL(0, res); res = file[3].open(&fs, "d", O_RDONLY); TEST_ASSERT_EQUAL(0, res); - + for (int i = 0; i < 10; i++) { res = file[0].read(buffer, 1); TEST_ASSERT_EQUAL(1, res); @@ -200,7 +200,7 @@ void test_parallel_file_test() res = buffer[0]; TEST_ASSERT_EQUAL('d', res); } - + file[0].close(); file[1].close(); file[2].close(); @@ -223,9 +223,9 @@ void test_parallel_remove_file_test() TEST_ASSERT_EQUAL(0, res); res = file[0].open(&fs, "e", O_WRONLY | O_CREAT); TEST_ASSERT_EQUAL(0, res); - + for (int i = 0; i < 5; i++) { - res = file[0].write((const void*)"e", 1); + res = file[0].write((const void *)"e", 1); TEST_ASSERT_EQUAL(1, res); } res = fs.remove("a"); @@ -236,12 +236,12 @@ void test_parallel_remove_file_test() TEST_ASSERT_EQUAL(0, res); res = fs.remove("d"); TEST_ASSERT_EQUAL(0, res); - + for (int i = 0; i < 5; i++) { - res = file[0].write((const void*)"e", 1); + res = file[0].write((const void *)"e", 1); TEST_ASSERT_EQUAL(1, res); } - + file[0].close(); res = dir[0].open(&fs, "/"); TEST_ASSERT_EQUAL(0, res); @@ -263,21 +263,21 @@ void test_parallel_remove_file_test() TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = dir[0].read(&ent); TEST_ASSERT_EQUAL(0, res); res = dir[0].close(); TEST_ASSERT_EQUAL(0, res); res = file[0].open(&fs, "e", O_RDONLY); TEST_ASSERT_EQUAL(0, res); - + for (int i = 0; i < 10; i++) { res = file[0].read(buffer, 1); TEST_ASSERT_EQUAL(1, res); res = buffer[0]; TEST_ASSERT_EQUAL('e', res); } - + file[0].close(); res = fs.unmount(); TEST_ASSERT_EQUAL(0, res); @@ -301,27 +301,27 @@ void test_remove_inconveniently_test() TEST_ASSERT_EQUAL(0, res); res = file[2].open(&fs, "g", O_WRONLY | O_CREAT); TEST_ASSERT_EQUAL(0, res); - + for (int i = 0; i < 5; i++) { - res = file[0].write((const void*)"e", 1); + res = file[0].write((const void *)"e", 1); TEST_ASSERT_EQUAL(1, res); - res = file[1].write((const void*)"f", 1); + res = file[1].write((const void *)"f", 1); TEST_ASSERT_EQUAL(1, res); - res = file[2].write((const void*)"g", 1); + res = file[2].write((const void *)"g", 1); TEST_ASSERT_EQUAL(1, res); } res = fs.remove("f"); TEST_ASSERT_EQUAL(0, res); - + for (int i = 0; i < 5; i++) { - res = file[0].write((const void*)"e", 1); + res = file[0].write((const void *)"e", 1); TEST_ASSERT_EQUAL(1, res); - res = file[1].write((const void*)"f", 1); + res = file[1].write((const void *)"f", 1); TEST_ASSERT_EQUAL(1, res); - res = file[2].write((const void*)"g", 1); + res = file[2].write((const void *)"g", 1); TEST_ASSERT_EQUAL(1, res); } - + file[0].close(); file[1].close(); file[2].close(); @@ -345,14 +345,14 @@ void test_remove_inconveniently_test() TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, "g"); TEST_ASSERT_EQUAL(0, res); res = ent.d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = dir[0].read(&ent); TEST_ASSERT_EQUAL(0, res); res = dir[0].close(); @@ -361,7 +361,7 @@ void test_remove_inconveniently_test() TEST_ASSERT_EQUAL(0, res); res = file[1].open(&fs, "g", O_RDONLY); TEST_ASSERT_EQUAL(0, res); - + for (int i = 0; i < 10; i++) { res = file[0].read(buffer, 1); TEST_ASSERT_EQUAL(1, res); @@ -372,7 +372,7 @@ void test_remove_inconveniently_test() res = buffer[0]; TEST_ASSERT_EQUAL('g', res); } - + file[0].close(); file[1].close(); res = fs.unmount(); diff --git a/features/filesystem/littlefs/TESTS/filesystem/seek/main.cpp b/features/filesystem/littlefs/TESTS/filesystem/seek/main.cpp index 1f00ca476b1..0b41321c31d 100644 --- a/features/filesystem/littlefs/TESTS/filesystem/seek/main.cpp +++ b/features/filesystem/littlefs/TESTS/filesystem/seek/main.cpp @@ -94,11 +94,11 @@ void test_seek_tests() res = fs.mkdir("hello", 0777); TEST_ASSERT_EQUAL(0, res); for (int i = 0; i < 132; i++) { - sprintf((char*)buffer, "hello/kitty%d", i); - res = file[0].open(&fs, (char*)buffer, - O_WRONLY | O_CREAT | O_APPEND); + sprintf((char *)buffer, "hello/kitty%d", i); + res = file[0].open(&fs, (char *)buffer, + O_WRONLY | O_CREAT | O_APPEND); TEST_ASSERT_EQUAL(0, res); - + size = strlen("kittycatcat"); memcpy(buffer, "kittycatcat", size); for (int j = 0; j < 132; j++) { @@ -133,29 +133,29 @@ void test_simple_dir_seek() TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, ".."); TEST_ASSERT_EQUAL(0, res); - + off_t pos; int i; for (i = 0; i < 4; i++) { - sprintf((char*)buffer, "kitty%d", i); + sprintf((char *)buffer, "kitty%d", i); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); - res = strcmp(ent.d_name, (char*)buffer); + res = strcmp(ent.d_name, (char *)buffer); TEST_ASSERT_EQUAL(0, res); pos = dir[0].tell(); } res = pos >= 0; TEST_ASSERT_EQUAL(1, res); - + dir[0].seek(pos); - sprintf((char*)buffer, "kitty%d", i); + sprintf((char *)buffer, "kitty%d", i); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); - res = strcmp(ent.d_name, (char*)buffer); + res = strcmp(ent.d_name, (char *)buffer); TEST_ASSERT_EQUAL(0, res); - + dir[0].rewind(); - sprintf((char*)buffer, "kitty%d", 0); + sprintf((char *)buffer, "kitty%d", 0); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, "."); @@ -166,14 +166,14 @@ void test_simple_dir_seek() TEST_ASSERT_EQUAL(0, res); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); - res = strcmp(ent.d_name, (char*)buffer); + res = strcmp(ent.d_name, (char *)buffer); TEST_ASSERT_EQUAL(0, res); - + dir[0].seek(pos); - sprintf((char*)buffer, "kitty%d", i); + sprintf((char *)buffer, "kitty%d", i); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); - res = strcmp(ent.d_name, (char*)buffer); + res = strcmp(ent.d_name, (char *)buffer); TEST_ASSERT_EQUAL(0, res); res = dir[0].close(); TEST_ASSERT_EQUAL(0, res); @@ -203,29 +203,29 @@ void test_large_dir_seek() TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, ".."); TEST_ASSERT_EQUAL(0, res); - + off_t pos; int i; for (i = 0; i < 128; i++) { - sprintf((char*)buffer, "kitty%d", i); + sprintf((char *)buffer, "kitty%d", i); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); - res = strcmp(ent.d_name, (char*)buffer); + res = strcmp(ent.d_name, (char *)buffer); TEST_ASSERT_EQUAL(0, res); pos = dir[0].tell(); } res = pos >= 0; TEST_ASSERT_EQUAL(1, res); - + dir[0].seek(pos); - sprintf((char*)buffer, "kitty%d", i); + sprintf((char *)buffer, "kitty%d", i); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); - res = strcmp(ent.d_name, (char*)buffer); + res = strcmp(ent.d_name, (char *)buffer); TEST_ASSERT_EQUAL(0, res); - + dir[0].rewind(); - sprintf((char*)buffer, "kitty%d", 0); + sprintf((char *)buffer, "kitty%d", 0); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); res = strcmp(ent.d_name, "."); @@ -236,14 +236,14 @@ void test_large_dir_seek() TEST_ASSERT_EQUAL(0, res); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); - res = strcmp(ent.d_name, (char*)buffer); + res = strcmp(ent.d_name, (char *)buffer); TEST_ASSERT_EQUAL(0, res); - + dir[0].seek(pos); - sprintf((char*)buffer, "kitty%d", i); + sprintf((char *)buffer, "kitty%d", i); res = dir[0].read(&ent); TEST_ASSERT_EQUAL(1, res); - res = strcmp(ent.d_name, (char*)buffer); + res = strcmp(ent.d_name, (char *)buffer); TEST_ASSERT_EQUAL(0, res); res = dir[0].close(); TEST_ASSERT_EQUAL(0, res); @@ -265,7 +265,7 @@ void test_simple_file_seek() TEST_ASSERT_EQUAL(0, res); res = file[0].open(&fs, "hello/kitty42", O_RDONLY); TEST_ASSERT_EQUAL(0, res); - + off_t pos; size = strlen("kittycatcat"); for (int i = 0; i < 4; i++) { @@ -283,7 +283,7 @@ void test_simple_file_seek() TEST_ASSERT_EQUAL(size, res); res = memcmp(buffer, "kittycatcat", size); TEST_ASSERT_EQUAL(0, res); - + file[0].rewind(); res = file[0].read(buffer, size); TEST_ASSERT_EQUAL(size, res); @@ -307,7 +307,7 @@ void test_simple_file_seek() TEST_ASSERT_EQUAL(size, res); res = memcmp(buffer, "kittycatcat", size); TEST_ASSERT_EQUAL(0, res); - + size_t size = file[0].size(); res = file[0].seek(0, SEEK_CUR); TEST_ASSERT_EQUAL(size, res); @@ -331,7 +331,7 @@ void test_large_file_seek() TEST_ASSERT_EQUAL(0, res); res = file[0].open(&fs, "hello/kitty42", O_RDONLY); TEST_ASSERT_EQUAL(0, res); - + off_t pos; size = strlen("kittycatcat"); for (int i = 0; i < 128; i++) { @@ -349,7 +349,7 @@ void test_large_file_seek() TEST_ASSERT_EQUAL(size, res); res = memcmp(buffer, "kittycatcat", size); TEST_ASSERT_EQUAL(0, res); - + file[0].rewind(); res = file[0].read(buffer, size); TEST_ASSERT_EQUAL(size, res); @@ -373,7 +373,7 @@ void test_large_file_seek() TEST_ASSERT_EQUAL(size, res); res = memcmp(buffer, "kittycatcat", size); TEST_ASSERT_EQUAL(0, res); - + size_t size = file[0].size(); res = file[0].seek(0, SEEK_CUR); TEST_ASSERT_EQUAL(size, res); @@ -397,7 +397,7 @@ void test_simple_file_seek_and_write() TEST_ASSERT_EQUAL(0, res); res = file[0].open(&fs, "hello/kitty42", O_RDWR); TEST_ASSERT_EQUAL(0, res); - + off_t pos; size = strlen("kittycatcat"); for (int i = 0; i < 4; i++) { @@ -409,7 +409,7 @@ void test_simple_file_seek_and_write() } res = pos >= 0; TEST_ASSERT_EQUAL(1, res); - + memcpy(buffer, "doggodogdog", size); res = file[0].seek(pos, SEEK_SET); TEST_ASSERT_EQUAL(pos, res); @@ -421,7 +421,7 @@ void test_simple_file_seek_and_write() TEST_ASSERT_EQUAL(size, res); res = memcmp(buffer, "doggodogdog", size); TEST_ASSERT_EQUAL(0, res); - + file[0].rewind(); res = file[0].read(buffer, size); TEST_ASSERT_EQUAL(size, res); @@ -439,7 +439,7 @@ void test_simple_file_seek_and_write() TEST_ASSERT_EQUAL(size, res); res = memcmp(buffer, "kittycatcat", size); TEST_ASSERT_EQUAL(0, res); - + size_t size = file[0].size(); res = file[0].seek(0, SEEK_CUR); TEST_ASSERT_EQUAL(size, res); @@ -463,7 +463,7 @@ void test_large_file_seek_and_write() TEST_ASSERT_EQUAL(0, res); res = file[0].open(&fs, "hello/kitty42", O_RDWR); TEST_ASSERT_EQUAL(0, res); - + off_t pos; size = strlen("kittycatcat"); for (int i = 0; i < 128; i++) { @@ -477,7 +477,7 @@ void test_large_file_seek_and_write() } res = pos >= 0; TEST_ASSERT_EQUAL(1, res); - + memcpy(buffer, "doggodogdog", size); res = file[0].seek(pos, SEEK_SET); TEST_ASSERT_EQUAL(pos, res); @@ -489,7 +489,7 @@ void test_large_file_seek_and_write() TEST_ASSERT_EQUAL(size, res); res = memcmp(buffer, "doggodogdog", size); TEST_ASSERT_EQUAL(0, res); - + file[0].rewind(); res = file[0].read(buffer, size); TEST_ASSERT_EQUAL(size, res); @@ -507,7 +507,7 @@ void test_large_file_seek_and_write() TEST_ASSERT_EQUAL(size, res); res = memcmp(buffer, "kittycatcat", size); TEST_ASSERT_EQUAL(0, res); - + size_t size = file[0].size(); res = file[0].seek(0, SEEK_CUR); TEST_ASSERT_EQUAL(size, res); @@ -531,10 +531,10 @@ void test_boundary_seek_and_write() TEST_ASSERT_EQUAL(0, res); res = file[0].open(&fs, "hello/kitty42", O_RDWR); TEST_ASSERT_EQUAL(0, res); - + size = strlen("hedgehoghog"); const off_t offsets[] = {512, 1020, 513, 1021, 511, 1019}; - + for (int i = 0; i < sizeof(offsets) / sizeof(offsets[0]); i++) { off_t off = offsets[i]; memcpy(buffer, "hedgehoghog", size); @@ -577,29 +577,29 @@ void test_out_of_bounds_seek() TEST_ASSERT_EQUAL(0, res); res = file[0].open(&fs, "hello/kitty42", O_RDWR); TEST_ASSERT_EQUAL(0, res); - + size = strlen("kittycatcat"); res = file[0].size(); - TEST_ASSERT_EQUAL(132*size, res); - res = file[0].seek((132+4)*size, - SEEK_SET); - TEST_ASSERT_EQUAL((132+4)*size, res); + TEST_ASSERT_EQUAL(132 * size, res); + res = file[0].seek((132 + 4) * size, + SEEK_SET); + TEST_ASSERT_EQUAL((132 + 4)*size, res); res = file[0].read(buffer, size); TEST_ASSERT_EQUAL(0, res); - + memcpy(buffer, "porcupineee", size); res = file[0].write(buffer, size); TEST_ASSERT_EQUAL(size, res); - res = file[0].seek((132+4)*size, - SEEK_SET); - TEST_ASSERT_EQUAL((132+4)*size, res); + res = file[0].seek((132 + 4) * size, + SEEK_SET); + TEST_ASSERT_EQUAL((132 + 4)*size, res); res = file[0].read(buffer, size); TEST_ASSERT_EQUAL(size, res); res = memcmp(buffer, "porcupineee", size); TEST_ASSERT_EQUAL(0, res); - res = file[0].seek(132*size, - SEEK_SET); - TEST_ASSERT_EQUAL(132*size, res); + res = file[0].seek(132 * size, + SEEK_SET); + TEST_ASSERT_EQUAL(132 * size, res); res = file[0].read(buffer, size); TEST_ASSERT_EQUAL(size, res); res = memcmp(buffer, "\0\0\0\0\0\0\0\0\0\0\0", size); diff --git a/features/filesystem/littlefs/TESTS/filesystem_recovery/resilience/main.cpp b/features/filesystem/littlefs/TESTS/filesystem_recovery/resilience/main.cpp index c3419afa988..802fb65a841 100644 --- a/features/filesystem/littlefs/TESTS/filesystem_recovery/resilience/main.cpp +++ b/features/filesystem/littlefs/TESTS/filesystem_recovery/resilience/main.cpp @@ -68,7 +68,7 @@ void test_resilience() bd_size_t block_size = bd.get_erase_size(); bd.deinit(); - SlicingBlockDevice slice(&bd, 0, MBED_TEST_BLOCK_COUNT*block_size); + SlicingBlockDevice slice(&bd, 0, MBED_TEST_BLOCK_COUNT * block_size); // Setup the test setup_atomic_operations(&slice, true); diff --git a/features/filesystem/littlefs/TESTS/filesystem_recovery/wear_leveling/main.cpp b/features/filesystem/littlefs/TESTS/filesystem_recovery/wear_leveling/main.cpp index 95efe3eff84..a9b8973ce89 100644 --- a/features/filesystem/littlefs/TESTS/filesystem_recovery/wear_leveling/main.cpp +++ b/features/filesystem/littlefs/TESTS/filesystem_recovery/wear_leveling/main.cpp @@ -62,11 +62,11 @@ static uint32_t test_wear_leveling_size(uint32_t block_count) bd_size_t block_size = bd.get_erase_size(); bd.deinit(); - SlicingBlockDevice slice(&bd, 0, block_count*block_size); + SlicingBlockDevice slice(&bd, 0, block_count * block_size); ExhaustibleBlockDevice ebd(&slice, MBED_TEST_ERASE_CYCLES); printf("Testing size %llu bytes (%lux%llu) blocks\n", - block_count*block_size, block_count, block_size); + block_count * block_size, block_count, block_size); setup_atomic_operations(&ebd, true); int64_t cycles = 0; diff --git a/features/filesystem/littlefs/TESTS/filesystem_retarget/dirs/main.cpp b/features/filesystem/littlefs/TESTS/filesystem_retarget/dirs/main.cpp index 0c91ef5a5fc..8793040512b 100644 --- a/features/filesystem/littlefs/TESTS/filesystem_retarget/dirs/main.cpp +++ b/features/filesystem/littlefs/TESTS/filesystem_retarget/dirs/main.cpp @@ -301,8 +301,8 @@ void test_multi_block_directory() res = mkdir("/fs/" "cactus", 0777); TEST_ASSERT_EQUAL(0, res); for (int i = 0; i < 128; i++) { - sprintf((char*)buffer, "/fs/" "cactus/test%d", i); - res = mkdir((char*)buffer, 0777); + sprintf((char *)buffer, "/fs/" "cactus/test%d", i); + res = mkdir((char *)buffer, 0777); TEST_ASSERT_EQUAL(0, res); } res = fs.unmount(); @@ -327,10 +327,10 @@ void test_multi_block_directory() res = ed->d_type; TEST_ASSERT_EQUAL(DT_DIR, res); for (int i = 0; i < 128; i++) { - sprintf((char*)buffer, "test%d", i); + sprintf((char *)buffer, "test%d", i); res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(1, res); - res = strcmp(ed->d_name, (char*)buffer); + res = strcmp(ed->d_name, (char *)buffer); TEST_ASSERT_EQUAL(0, res); } res = ((ed = readdir(dd[0])) != NULL); diff --git a/features/filesystem/littlefs/TESTS/filesystem_retarget/files/main.cpp b/features/filesystem/littlefs/TESTS/filesystem_retarget/files/main.cpp index c9deae2d92f..120eff16128 100644 --- a/features/filesystem/littlefs/TESTS/filesystem_retarget/files/main.cpp +++ b/features/filesystem/littlefs/TESTS/filesystem_retarget/files/main.cpp @@ -167,7 +167,7 @@ void test_small_file_test() chunk = (chunk < size - i) ? chunk : size - i; res = fread(buffer, 1, chunk, fd[0]); TEST_ASSERT_EQUAL(chunk, res); - for (size_t b = 0; b < chunk && i+b < size; b++) { + for (size_t b = 0; b < chunk && i + b < size; b++) { res = buffer[b]; TEST_ASSERT_EQUAL(rand() & 0xff, res); } @@ -221,7 +221,7 @@ void test_medium_file_test() chunk = (chunk < size - i) ? chunk : size - i; res = fread(buffer, 1, chunk, fd[0]); TEST_ASSERT_EQUAL(chunk, res); - for (size_t b = 0; b < chunk && i+b < size; b++) { + for (size_t b = 0; b < chunk && i + b < size; b++) { res = buffer[b]; TEST_ASSERT_EQUAL(rand() & 0xff, res); } @@ -275,7 +275,7 @@ void test_large_file_test() chunk = (chunk < size - i) ? chunk : size - i; res = fread(buffer, 1, chunk, fd[0]); TEST_ASSERT_EQUAL(chunk, res); - for (size_t b = 0; b < chunk && i+b < size; b++) { + for (size_t b = 0; b < chunk && i + b < size; b++) { res = buffer[b]; TEST_ASSERT_EQUAL(rand() & 0xff, res); } @@ -307,7 +307,7 @@ void test_non_overlap_check() chunk = (chunk < size - i) ? chunk : size - i; res = fread(buffer, 1, chunk, fd[0]); TEST_ASSERT_EQUAL(chunk, res); - for (size_t b = 0; b < chunk && i+b < size; b++) { + for (size_t b = 0; b < chunk && i + b < size; b++) { res = buffer[b]; TEST_ASSERT_EQUAL(rand() & 0xff, res); } @@ -330,7 +330,7 @@ void test_non_overlap_check() chunk = (chunk < size - i) ? chunk : size - i; res = fread(buffer, 1, chunk, fd[0]); TEST_ASSERT_EQUAL(chunk, res); - for (size_t b = 0; b < chunk && i+b < size; b++) { + for (size_t b = 0; b < chunk && i + b < size; b++) { res = buffer[b]; TEST_ASSERT_EQUAL(rand() & 0xff, res); } @@ -353,7 +353,7 @@ void test_non_overlap_check() chunk = (chunk < size - i) ? chunk : size - i; res = fread(buffer, 1, chunk, fd[0]); TEST_ASSERT_EQUAL(chunk, res); - for (size_t b = 0; b < chunk && i+b < size; b++) { + for (size_t b = 0; b < chunk && i + b < size; b++) { res = buffer[b]; TEST_ASSERT_EQUAL(rand() & 0xff, res); } @@ -388,28 +388,28 @@ void test_dir_check() TEST_ASSERT_EQUAL(0, res); res = ed->d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(1, res); res = strcmp(ed->d_name, "smallavacado"); TEST_ASSERT_EQUAL(0, res); res = ed->d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(1, res); res = strcmp(ed->d_name, "mediumavacado"); TEST_ASSERT_EQUAL(0, res); res = ed->d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(1, res); res = strcmp(ed->d_name, "largeavacado"); TEST_ASSERT_EQUAL(0, res); res = ed->d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(0, res); res = closedir(dd[0]); diff --git a/features/filesystem/littlefs/TESTS/filesystem_retarget/interspersed/main.cpp b/features/filesystem/littlefs/TESTS/filesystem_retarget/interspersed/main.cpp index f622c01a6a5..46ee79d4474 100644 --- a/features/filesystem/littlefs/TESTS/filesystem_retarget/interspersed/main.cpp +++ b/features/filesystem/littlefs/TESTS/filesystem_retarget/interspersed/main.cpp @@ -111,18 +111,18 @@ void test_parallel_file_test() TEST_ASSERT_EQUAL(0, res); res = !((fd[3] = fopen("/fs/" "d", "wb")) != NULL); TEST_ASSERT_EQUAL(0, res); - + for (int i = 0; i < 10; i++) { - res = fwrite((const void*)"a", 1, 1, fd[0]); + res = fwrite((const void *)"a", 1, 1, fd[0]); TEST_ASSERT_EQUAL(1, res); - res = fwrite((const void*)"b", 1, 1, fd[1]); + res = fwrite((const void *)"b", 1, 1, fd[1]); TEST_ASSERT_EQUAL(1, res); - res = fwrite((const void*)"c", 1, 1, fd[2]); + res = fwrite((const void *)"c", 1, 1, fd[2]); TEST_ASSERT_EQUAL(1, res); - res = fwrite((const void*)"d", 1, 1, fd[3]); + res = fwrite((const void *)"d", 1, 1, fd[3]); TEST_ASSERT_EQUAL(1, res); } - + fclose(fd[0]); fclose(fd[1]); fclose(fd[2]); @@ -147,28 +147,28 @@ void test_parallel_file_test() TEST_ASSERT_EQUAL(0, res); res = ed->d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(1, res); res = strcmp(ed->d_name, "b"); TEST_ASSERT_EQUAL(0, res); res = ed->d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(1, res); res = strcmp(ed->d_name, "c"); TEST_ASSERT_EQUAL(0, res); res = ed->d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(1, res); res = strcmp(ed->d_name, "d"); TEST_ASSERT_EQUAL(0, res); res = ed->d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(0, res); res = closedir(dd[0]); @@ -181,7 +181,7 @@ void test_parallel_file_test() TEST_ASSERT_EQUAL(0, res); res = !((fd[3] = fopen("/fs/" "d", "rb")) != NULL); TEST_ASSERT_EQUAL(0, res); - + for (int i = 0; i < 10; i++) { res = fread(buffer, 1, 1, fd[0]); TEST_ASSERT_EQUAL(1, res); @@ -200,7 +200,7 @@ void test_parallel_file_test() res = buffer[0]; TEST_ASSERT_EQUAL('d', res); } - + fclose(fd[0]); fclose(fd[1]); fclose(fd[2]); @@ -223,9 +223,9 @@ void test_parallel_remove_file_test() TEST_ASSERT_EQUAL(0, res); res = !((fd[0] = fopen("/fs/" "e", "wb")) != NULL); TEST_ASSERT_EQUAL(0, res); - + for (int i = 0; i < 5; i++) { - res = fwrite((const void*)"e", 1, 1, fd[0]); + res = fwrite((const void *)"e", 1, 1, fd[0]); TEST_ASSERT_EQUAL(1, res); } res = remove("/fs/" "a"); @@ -236,12 +236,12 @@ void test_parallel_remove_file_test() TEST_ASSERT_EQUAL(0, res); res = remove("/fs/" "d"); TEST_ASSERT_EQUAL(0, res); - + for (int i = 0; i < 5; i++) { - res = fwrite((const void*)"e", 1, 1, fd[0]); + res = fwrite((const void *)"e", 1, 1, fd[0]); TEST_ASSERT_EQUAL(1, res); } - + fclose(fd[0]); res = !((dd[0] = opendir("/fs/" "/")) != NULL); TEST_ASSERT_EQUAL(0, res); @@ -263,21 +263,21 @@ void test_parallel_remove_file_test() TEST_ASSERT_EQUAL(0, res); res = ed->d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(0, res); res = closedir(dd[0]); TEST_ASSERT_EQUAL(0, res); res = !((fd[0] = fopen("/fs/" "e", "rb")) != NULL); TEST_ASSERT_EQUAL(0, res); - + for (int i = 0; i < 10; i++) { res = fread(buffer, 1, 1, fd[0]); TEST_ASSERT_EQUAL(1, res); res = buffer[0]; TEST_ASSERT_EQUAL('e', res); } - + fclose(fd[0]); res = fs.unmount(); TEST_ASSERT_EQUAL(0, res); @@ -301,27 +301,27 @@ void test_remove_inconveniently_test() TEST_ASSERT_EQUAL(0, res); res = !((fd[2] = fopen("/fs/" "g", "wb")) != NULL); TEST_ASSERT_EQUAL(0, res); - + for (int i = 0; i < 5; i++) { - res = fwrite((const void*)"e", 1, 1, fd[0]); + res = fwrite((const void *)"e", 1, 1, fd[0]); TEST_ASSERT_EQUAL(1, res); - res = fwrite((const void*)"f", 1, 1, fd[1]); + res = fwrite((const void *)"f", 1, 1, fd[1]); TEST_ASSERT_EQUAL(1, res); - res = fwrite((const void*)"g", 1, 1, fd[2]); + res = fwrite((const void *)"g", 1, 1, fd[2]); TEST_ASSERT_EQUAL(1, res); } res = remove("/fs/" "f"); TEST_ASSERT_EQUAL(0, res); - + for (int i = 0; i < 5; i++) { - res = fwrite((const void*)"e", 1, 1, fd[0]); + res = fwrite((const void *)"e", 1, 1, fd[0]); TEST_ASSERT_EQUAL(1, res); - res = fwrite((const void*)"f", 1, 1, fd[1]); + res = fwrite((const void *)"f", 1, 1, fd[1]); TEST_ASSERT_EQUAL(1, res); - res = fwrite((const void*)"g", 1, 1, fd[2]); + res = fwrite((const void *)"g", 1, 1, fd[2]); TEST_ASSERT_EQUAL(1, res); } - + fclose(fd[0]); fclose(fd[1]); fclose(fd[2]); @@ -345,14 +345,14 @@ void test_remove_inconveniently_test() TEST_ASSERT_EQUAL(0, res); res = ed->d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(1, res); res = strcmp(ed->d_name, "g"); TEST_ASSERT_EQUAL(0, res); res = ed->d_type; TEST_ASSERT_EQUAL(DT_REG, res); - + res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(0, res); res = closedir(dd[0]); @@ -361,7 +361,7 @@ void test_remove_inconveniently_test() TEST_ASSERT_EQUAL(0, res); res = !((fd[1] = fopen("/fs/" "g", "rb")) != NULL); TEST_ASSERT_EQUAL(0, res); - + for (int i = 0; i < 10; i++) { res = fread(buffer, 1, 1, fd[0]); TEST_ASSERT_EQUAL(1, res); @@ -372,7 +372,7 @@ void test_remove_inconveniently_test() res = buffer[0]; TEST_ASSERT_EQUAL('g', res); } - + fclose(fd[0]); fclose(fd[1]); res = fs.unmount(); diff --git a/features/filesystem/littlefs/TESTS/filesystem_retarget/seek/main.cpp b/features/filesystem/littlefs/TESTS/filesystem_retarget/seek/main.cpp index 24ad8705339..6e904fce209 100644 --- a/features/filesystem/littlefs/TESTS/filesystem_retarget/seek/main.cpp +++ b/features/filesystem/littlefs/TESTS/filesystem_retarget/seek/main.cpp @@ -94,11 +94,11 @@ void test_seek_tests() res = mkdir("/fs/" "hello", 0777); TEST_ASSERT_EQUAL(0, res); for (int i = 0; i < 132; i++) { - sprintf((char*)buffer, "/fs/" "hello/kitty%d", i); - res = !((fd[0] = fopen((char*)buffer, - "ab")) != NULL); + sprintf((char *)buffer, "/fs/" "hello/kitty%d", i); + res = !((fd[0] = fopen((char *)buffer, + "ab")) != NULL); TEST_ASSERT_EQUAL(0, res); - + size = strlen("kittycatcat"); memcpy(buffer, "kittycatcat", size); for (int j = 0; j < 132; j++) { @@ -133,29 +133,29 @@ void test_simple_dir_seek() TEST_ASSERT_EQUAL(1, res); res = strcmp(ed->d_name, ".."); TEST_ASSERT_EQUAL(0, res); - + off_t pos; int i; for (i = 0; i < 4; i++) { - sprintf((char*)buffer, "kitty%d", i); + sprintf((char *)buffer, "kitty%d", i); res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(1, res); - res = strcmp(ed->d_name, (char*)buffer); + res = strcmp(ed->d_name, (char *)buffer); TEST_ASSERT_EQUAL(0, res); pos = telldir(dd[0]); } res = pos >= 0; TEST_ASSERT_EQUAL(1, res); - + seekdir(dd[0], pos); - sprintf((char*)buffer, "kitty%d", i); + sprintf((char *)buffer, "kitty%d", i); res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(1, res); - res = strcmp(ed->d_name, (char*)buffer); + res = strcmp(ed->d_name, (char *)buffer); TEST_ASSERT_EQUAL(0, res); - + rewinddir(dd[0]); - sprintf((char*)buffer, "kitty%d", 0); + sprintf((char *)buffer, "kitty%d", 0); res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(1, res); res = strcmp(ed->d_name, "."); @@ -166,14 +166,14 @@ void test_simple_dir_seek() TEST_ASSERT_EQUAL(0, res); res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(1, res); - res = strcmp(ed->d_name, (char*)buffer); + res = strcmp(ed->d_name, (char *)buffer); TEST_ASSERT_EQUAL(0, res); - + seekdir(dd[0], pos); - sprintf((char*)buffer, "kitty%d", i); + sprintf((char *)buffer, "kitty%d", i); res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(1, res); - res = strcmp(ed->d_name, (char*)buffer); + res = strcmp(ed->d_name, (char *)buffer); TEST_ASSERT_EQUAL(0, res); res = closedir(dd[0]); TEST_ASSERT_EQUAL(0, res); @@ -203,29 +203,29 @@ void test_large_dir_seek() TEST_ASSERT_EQUAL(1, res); res = strcmp(ed->d_name, ".."); TEST_ASSERT_EQUAL(0, res); - + off_t pos; int i; for (i = 0; i < 128; i++) { - sprintf((char*)buffer, "kitty%d", i); + sprintf((char *)buffer, "kitty%d", i); res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(1, res); - res = strcmp(ed->d_name, (char*)buffer); + res = strcmp(ed->d_name, (char *)buffer); TEST_ASSERT_EQUAL(0, res); pos = telldir(dd[0]); } res = pos >= 0; TEST_ASSERT_EQUAL(1, res); - + seekdir(dd[0], pos); - sprintf((char*)buffer, "kitty%d", i); + sprintf((char *)buffer, "kitty%d", i); res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(1, res); - res = strcmp(ed->d_name, (char*)buffer); + res = strcmp(ed->d_name, (char *)buffer); TEST_ASSERT_EQUAL(0, res); - + rewinddir(dd[0]); - sprintf((char*)buffer, "kitty%d", 0); + sprintf((char *)buffer, "kitty%d", 0); res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(1, res); res = strcmp(ed->d_name, "."); @@ -236,14 +236,14 @@ void test_large_dir_seek() TEST_ASSERT_EQUAL(0, res); res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(1, res); - res = strcmp(ed->d_name, (char*)buffer); + res = strcmp(ed->d_name, (char *)buffer); TEST_ASSERT_EQUAL(0, res); - + seekdir(dd[0], pos); - sprintf((char*)buffer, "kitty%d", i); + sprintf((char *)buffer, "kitty%d", i); res = ((ed = readdir(dd[0])) != NULL); TEST_ASSERT_EQUAL(1, res); - res = strcmp(ed->d_name, (char*)buffer); + res = strcmp(ed->d_name, (char *)buffer); TEST_ASSERT_EQUAL(0, res); res = closedir(dd[0]); TEST_ASSERT_EQUAL(0, res); @@ -265,7 +265,7 @@ void test_simple_file_seek() TEST_ASSERT_EQUAL(0, res); res = !((fd[0] = fopen("/fs/" "hello/kitty42", "rb")) != NULL); TEST_ASSERT_EQUAL(0, res); - + off_t pos; size = strlen("kittycatcat"); for (int i = 0; i < 4; i++) { @@ -283,7 +283,7 @@ void test_simple_file_seek() TEST_ASSERT_EQUAL(size, res); res = memcmp(buffer, "kittycatcat", size); TEST_ASSERT_EQUAL(0, res); - + rewind(fd[0]); res = fread(buffer, 1, size, fd[0]); TEST_ASSERT_EQUAL(size, res); @@ -307,7 +307,7 @@ void test_simple_file_seek() TEST_ASSERT_EQUAL(size, res); res = memcmp(buffer, "kittycatcat", size); TEST_ASSERT_EQUAL(0, res); - + res = fseek(fd[0], 0, SEEK_CUR); TEST_ASSERT_EQUAL(0, res); res = fclose(fd[0]); @@ -330,7 +330,7 @@ void test_large_file_seek() TEST_ASSERT_EQUAL(0, res); res = !((fd[0] = fopen("/fs/" "hello/kitty42", "rb")) != NULL); TEST_ASSERT_EQUAL(0, res); - + off_t pos; size = strlen("kittycatcat"); for (int i = 0; i < 128; i++) { @@ -348,7 +348,7 @@ void test_large_file_seek() TEST_ASSERT_EQUAL(size, res); res = memcmp(buffer, "kittycatcat", size); TEST_ASSERT_EQUAL(0, res); - + rewind(fd[0]); res = fread(buffer, 1, size, fd[0]); TEST_ASSERT_EQUAL(size, res); @@ -372,7 +372,7 @@ void test_large_file_seek() TEST_ASSERT_EQUAL(size, res); res = memcmp(buffer, "kittycatcat", size); TEST_ASSERT_EQUAL(0, res); - + res = fseek(fd[0], 0, SEEK_CUR); TEST_ASSERT_EQUAL(0, res); res = fclose(fd[0]); @@ -395,7 +395,7 @@ void test_simple_file_seek_and_write() TEST_ASSERT_EQUAL(0, res); res = !((fd[0] = fopen("/fs/" "hello/kitty42", "r+b")) != NULL); TEST_ASSERT_EQUAL(0, res); - + off_t pos; size = strlen("kittycatcat"); for (int i = 0; i < 4; i++) { @@ -407,7 +407,7 @@ void test_simple_file_seek_and_write() } res = pos >= 0; TEST_ASSERT_EQUAL(1, res); - + memcpy(buffer, "doggodogdog", size); res = fseek(fd[0], pos, SEEK_SET); TEST_ASSERT_EQUAL(0, res); @@ -419,7 +419,7 @@ void test_simple_file_seek_and_write() TEST_ASSERT_EQUAL(size, res); res = memcmp(buffer, "doggodogdog", size); TEST_ASSERT_EQUAL(0, res); - + rewind(fd[0]); res = fread(buffer, 1, size, fd[0]); TEST_ASSERT_EQUAL(size, res); @@ -437,7 +437,7 @@ void test_simple_file_seek_and_write() TEST_ASSERT_EQUAL(size, res); res = memcmp(buffer, "kittycatcat", size); TEST_ASSERT_EQUAL(0, res); - + res = fseek(fd[0], 0, SEEK_CUR); TEST_ASSERT_EQUAL(0, res); res = fclose(fd[0]); @@ -460,7 +460,7 @@ void test_large_file_seek_and_write() TEST_ASSERT_EQUAL(0, res); res = !((fd[0] = fopen("/fs/" "hello/kitty42", "r+b")) != NULL); TEST_ASSERT_EQUAL(0, res); - + off_t pos; size = strlen("kittycatcat"); for (int i = 0; i < 128; i++) { @@ -474,7 +474,7 @@ void test_large_file_seek_and_write() } res = pos >= 0; TEST_ASSERT_EQUAL(1, res); - + memcpy(buffer, "doggodogdog", size); res = fseek(fd[0], pos, SEEK_SET); TEST_ASSERT_EQUAL(0, res); @@ -486,7 +486,7 @@ void test_large_file_seek_and_write() TEST_ASSERT_EQUAL(size, res); res = memcmp(buffer, "doggodogdog", size); TEST_ASSERT_EQUAL(0, res); - + rewind(fd[0]); res = fread(buffer, 1, size, fd[0]); TEST_ASSERT_EQUAL(size, res); @@ -504,7 +504,7 @@ void test_large_file_seek_and_write() TEST_ASSERT_EQUAL(size, res); res = memcmp(buffer, "kittycatcat", size); TEST_ASSERT_EQUAL(0, res); - + res = fseek(fd[0], 0, SEEK_CUR); TEST_ASSERT_EQUAL(0, res); res = fclose(fd[0]); @@ -527,10 +527,10 @@ void test_boundary_seek_and_write() TEST_ASSERT_EQUAL(0, res); res = !((fd[0] = fopen("/fs/" "hello/kitty42", "r+b")) != NULL); TEST_ASSERT_EQUAL(0, res); - + size = strlen("hedgehoghog"); const off_t offsets[] = {512, 1020, 513, 1021, 511, 1019}; - + for (int i = 0; i < sizeof(offsets) / sizeof(offsets[0]); i++) { off_t off = offsets[i]; memcpy(buffer, "hedgehoghog", size); @@ -573,30 +573,30 @@ void test_out_of_bounds_seek() TEST_ASSERT_EQUAL(0, res); res = !((fd[0] = fopen("/fs/" "hello/kitty42", "r+b")) != NULL); TEST_ASSERT_EQUAL(0, res); - + size = strlen("kittycatcat"); res = fseek(fd[0], 0, SEEK_END); TEST_ASSERT_EQUAL(0, res); res = ftell(fd[0]); - TEST_ASSERT_EQUAL(132*size, res); - res = fseek(fd[0], (132+4)*size, - SEEK_SET); + TEST_ASSERT_EQUAL(132 * size, res); + res = fseek(fd[0], (132 + 4) * size, + SEEK_SET); TEST_ASSERT_EQUAL(0, res); res = fread(buffer, 1, size, fd[0]); TEST_ASSERT_EQUAL(0, res); - + memcpy(buffer, "porcupineee", size); res = fwrite(buffer, 1, size, fd[0]); TEST_ASSERT_EQUAL(size, res); - res = fseek(fd[0], (132+4)*size, - SEEK_SET); + res = fseek(fd[0], (132 + 4) * size, + SEEK_SET); TEST_ASSERT_EQUAL(0, res); res = fread(buffer, 1, size, fd[0]); TEST_ASSERT_EQUAL(size, res); res = memcmp(buffer, "porcupineee", size); TEST_ASSERT_EQUAL(0, res); - res = fseek(fd[0], 132*size, - SEEK_SET); + res = fseek(fd[0], 132 * size, + SEEK_SET); TEST_ASSERT_EQUAL(0, res); res = fread(buffer, 1, size, fd[0]); TEST_ASSERT_EQUAL(size, res); diff --git a/features/lorawan/LoRaRadio.h b/features/lorawan/LoRaRadio.h index e78bdb3fbf2..b71825c2cd1 100644 --- a/features/lorawan/LoRaRadio.h +++ b/features/lorawan/LoRaRadio.h @@ -166,11 +166,11 @@ typedef struct radio_events { */ mbed::Callback rx_error; - /** - * FHSS Change Channel callback prototype. - * - * @param current_channel The index number of the current channel. - */ + /** + * FHSS Change Channel callback prototype. + * + * @param current_channel The index number of the current channel. + */ mbed::Callback fhss_change_channel; /** @@ -184,8 +184,7 @@ typedef struct radio_events { /** * Interface for the radios, contains the main functions that a radio needs, and five callback functions. */ -class LoRaRadio -{ +class LoRaRadio { public: @@ -246,7 +245,7 @@ class LoRaRadio * @param rx_continuous Sets the reception in continuous mode. * [false: single mode, true: continuous mode] */ - virtual void set_rx_config (radio_modems_t modem, uint32_t bandwidth, + virtual void set_rx_config(radio_modems_t modem, uint32_t bandwidth, uint32_t datarate, uint8_t coderate, uint32_t bandwidth_afc, uint16_t preamble_len, uint16_t symb_timeout, bool fix_len, @@ -284,10 +283,10 @@ class LoRaRadio * @param timeout The transmission timeout [us]. */ virtual void set_tx_config(radio_modems_t modem, int8_t power, uint32_t fdev, - uint32_t bandwidth, uint32_t datarate, - uint8_t coderate, uint16_t preamble_len, - bool fix_len, bool crc_on, bool freq_hop_on, - uint8_t hop_period, bool iq_inverted, uint32_t timeout) = 0; + uint32_t bandwidth, uint32_t datarate, + uint8_t coderate, uint16_t preamble_len, + bool fix_len, bool crc_on, bool freq_hop_on, + uint8_t hop_period, bool iq_inverted, uint32_t timeout) = 0; /** * Sends the buffer of size diff --git a/features/lorawan/LoRaWANBase.h b/features/lorawan/LoRaWANBase.h index f4b3354f5bb..792a1aa5718 100644 --- a/features/lorawan/LoRaWANBase.h +++ b/features/lorawan/LoRaWANBase.h @@ -217,7 +217,7 @@ class LoRaWANBase { * LORAWAN_STATUS_WOULD_BLOCK if another TX is * ongoing, or a negative error code on failure. */ - virtual int16_t send(uint8_t port, const uint8_t* data, + virtual int16_t send(uint8_t port, const uint8_t *data, uint16_t length, int flags) = 0; /** Receives a message from the Network Server. @@ -259,7 +259,7 @@ class LoRaWANBase { * nothing available to read at the moment. * iv) A negative error code on failure. */ - virtual int16_t receive(uint8_t port, uint8_t* data, uint16_t length, + virtual int16_t receive(uint8_t port, uint8_t *data, uint16_t length, int flags) = 0; /** Add application callbacks to the stack. diff --git a/features/lorawan/LoRaWANInterface.cpp b/features/lorawan/LoRaWANInterface.cpp index 8d45b0dee30..0f5aea83d21 100644 --- a/features/lorawan/LoRaWANInterface.cpp +++ b/features/lorawan/LoRaWANInterface.cpp @@ -23,12 +23,12 @@ using namespace events; -inline LoRaWANStack& stk_obj() +inline LoRaWANStack &stk_obj() { return LoRaWANStack::get_lorawan_stack(); } -LoRaWANInterface::LoRaWANInterface(LoRaRadio& radio) : _link_check_requested(false) +LoRaWANInterface::LoRaWANInterface(LoRaRadio &radio) : _link_check_requested(false) { // Pass mac_handlers to radio to the radio driver after // binding radio driver to PHY layer @@ -44,7 +44,7 @@ LoRaWANInterface::~LoRaWANInterface() lorawan_status_t LoRaWANInterface::initialize(EventQueue *queue) { - if(!queue) { + if (!queue) { return LORAWAN_STATUS_PARAMETER_INVALID; } @@ -167,7 +167,7 @@ lorawan_status_t LoRaWANInterface::remove_channel_plan() return stk_obj().drop_channel_list(); } -int16_t LoRaWANInterface::send(uint8_t port, const uint8_t* data, +int16_t LoRaWANInterface::send(uint8_t port, const uint8_t *data, uint16_t length, int flags) { if (_link_check_requested) { @@ -183,7 +183,7 @@ int16_t LoRaWANInterface::send(uint8_t port, const uint8_t* data, } } -int16_t LoRaWANInterface::receive(uint8_t port, uint8_t* data, uint16_t length, +int16_t LoRaWANInterface::receive(uint8_t port, uint8_t *data, uint16_t length, int flags) { if (data && length > 0) { @@ -194,13 +194,13 @@ int16_t LoRaWANInterface::receive(uint8_t port, uint8_t* data, uint16_t length, } lorawan_status_t LoRaWANInterface::add_app_callbacks(lorawan_app_callbacks_t *callbacks) - { +{ - if (!callbacks || !callbacks->events) { - // Event Callback is mandatory - return LORAWAN_STATUS_PARAMETER_INVALID; - } + if (!callbacks || !callbacks->events) { + // Event Callback is mandatory + return LORAWAN_STATUS_PARAMETER_INVALID; + } - stk_obj().set_lora_callbacks(callbacks); - return LORAWAN_STATUS_OK; - } + stk_obj().set_lora_callbacks(callbacks); + return LORAWAN_STATUS_OK; +} diff --git a/features/lorawan/LoRaWANInterface.h b/features/lorawan/LoRaWANInterface.h index f8d35b425fa..42bff1123bf 100644 --- a/features/lorawan/LoRaWANInterface.h +++ b/features/lorawan/LoRaWANInterface.h @@ -33,7 +33,7 @@ class LoRaWANInterface: public LoRaWANBase { * construct a single instance of LoRaWANInterface. * */ - LoRaWANInterface(LoRaRadio& radio); + LoRaWANInterface(LoRaRadio &radio); virtual ~LoRaWANInterface(); /** Initialize the LoRa stack. @@ -313,7 +313,7 @@ class LoRaWANInterface: public LoRaWANBase { * LORAWAN_STATUS_WOULD_BLOCK if another TX is * ongoing, or a negative error code on failure. */ - virtual int16_t send(uint8_t port, const uint8_t* data, uint16_t length, + virtual int16_t send(uint8_t port, const uint8_t *data, uint16_t length, int flags); /** Receives a message from the Network Server. @@ -355,7 +355,7 @@ class LoRaWANInterface: public LoRaWANBase { * nothing available to read at the moment. * iv) A negative error code on failure. */ - virtual int16_t receive(uint8_t port, uint8_t* data, uint16_t length, + virtual int16_t receive(uint8_t port, uint8_t *data, uint16_t length, int flags); /** Add application callbacks to the stack. diff --git a/features/lorawan/LoRaWANStack.cpp b/features/lorawan/LoRaWANStack.cpp index 418322ed141..ba6fd56184e 100644 --- a/features/lorawan/LoRaWANStack.cpp +++ b/features/lorawan/LoRaWANStack.cpp @@ -45,17 +45,17 @@ using namespace mbed; using namespace events; #if defined(LORAWAN_COMPLIANCE_TEST) - /** - * - * User application data buffer size if compliance test is used - */ - #if (MBED_CONF_LORA_PHY == 0 || MBED_CONF_LORA_PHY == 4 || MBED_CONF_LORA_PHY == 6 || MBED_CONF_LORA_PHY == 7) - #define LORAWAN_COMPLIANCE_TEST_DATA_SIZE 16 - #elif (MBED_CONF_LORA_PHY == 1 || MBED_CONF_LORA_PHY == 2 || MBED_CONF_LORA_PHY == 8 || MBED_CONF_LORA_PHY == 9) - #define LORAWAN_COMPLIANCE_TEST_DATA_SIZE 11 - #else - #error "Must set LoRa PHY layer parameters." - #endif +/** + * + * User application data buffer size if compliance test is used + */ +#if (MBED_CONF_LORA_PHY == 0 || MBED_CONF_LORA_PHY == 4 || MBED_CONF_LORA_PHY == 6 || MBED_CONF_LORA_PHY == 7) +#define LORAWAN_COMPLIANCE_TEST_DATA_SIZE 16 +#elif (MBED_CONF_LORA_PHY == 1 || MBED_CONF_LORA_PHY == 2 || MBED_CONF_LORA_PHY == 8 || MBED_CONF_LORA_PHY == 9) +#define LORAWAN_COMPLIANCE_TEST_DATA_SIZE 11 +#else +#error "Must set LoRa PHY layer parameters." +#endif #endif /***************************************************************************** @@ -85,9 +85,9 @@ lorawan_status_t LoRaWANStack::set_application_port(uint8_t port) * Constructor and destructor * ****************************************************************************/ LoRaWANStack::LoRaWANStack() -: _loramac(_lora_time), _lora_phy(_lora_time), - _device_current_state(DEVICE_STATE_NOT_INITIALIZED), _mac_handlers(NULL), - _num_retry(1), _queue(NULL), _duty_cycle_on(MBED_CONF_LORA_DUTY_CYCLE_ON) + : _loramac(_lora_time), _lora_phy(_lora_time), + _device_current_state(DEVICE_STATE_NOT_INITIALIZED), _mac_handlers(NULL), + _num_retry(1), _queue(NULL), _duty_cycle_on(MBED_CONF_LORA_DUTY_CYCLE_ON) { #ifdef MBED_CONF_LORA_APP_PORT // is_port_valid() is not virtual, so we can call it in constructor @@ -101,17 +101,17 @@ LoRaWANStack::LoRaWANStack() #else // initialize it to INVALID_PORT (255) an illegal port number. // user should set the port - _app_port = INVALID_PORT; + _app_port = INVALID_PORT; #endif - memset(&_lw_session, 0, sizeof(_lw_session)); - memset(&_tx_msg, 0, sizeof(_tx_msg)); - memset(&_rx_msg, 0, sizeof(_rx_msg)); + memset(&_lw_session, 0, sizeof(_lw_session)); + memset(&_tx_msg, 0, sizeof(_tx_msg)); + memset(&_rx_msg, 0, sizeof(_rx_msg)); - LoRaMacPrimitives.mcps_confirm = callback(this, &LoRaWANStack::mcps_confirm_handler); - LoRaMacPrimitives.mcps_indication = callback(this, &LoRaWANStack::mcps_indication_handler); - LoRaMacPrimitives.mlme_confirm = callback(this, &LoRaWANStack::mlme_confirm_handler); - LoRaMacPrimitives.mlme_indication = callback(this, &LoRaWANStack::mlme_indication_handler); + LoRaMacPrimitives.mcps_confirm = callback(this, &LoRaWANStack::mcps_confirm_handler); + LoRaMacPrimitives.mcps_indication = callback(this, &LoRaWANStack::mcps_indication_handler); + LoRaMacPrimitives.mlme_confirm = callback(this, &LoRaWANStack::mlme_confirm_handler); + LoRaMacPrimitives.mlme_indication = callback(this, &LoRaWANStack::mlme_indication_handler); } LoRaWANStack::~LoRaWANStack() @@ -121,13 +121,13 @@ LoRaWANStack::~LoRaWANStack() /***************************************************************************** * Public member functions * ****************************************************************************/ -LoRaWANStack& LoRaWANStack::get_lorawan_stack() +LoRaWANStack &LoRaWANStack::get_lorawan_stack() { static LoRaWANStack _lw_stack; return _lw_stack; } -radio_events_t *LoRaWANStack::bind_radio_driver(LoRaRadio& radio) +radio_events_t *LoRaWANStack::bind_radio_driver(LoRaRadio &radio) { // Store pointer to callback routines inside MAC layer (non-IRQ safe) _mac_handlers = _loramac.get_phy_event_handlers(); @@ -138,8 +138,7 @@ radio_events_t *LoRaWANStack::bind_radio_driver(LoRaRadio& radio) lorawan_status_t LoRaWANStack::initialize_mac_layer(EventQueue *queue) { - if (DEVICE_STATE_NOT_INITIALIZED != _device_current_state) - { + if (DEVICE_STATE_NOT_INITIALIZED != _device_current_state) { tr_debug("Initialized already"); return LORAWAN_STATUS_OK; } @@ -197,20 +196,20 @@ void LoRaWANStack::prepare_special_tx_frame(uint8_t port) _tx_msg.f_buffer[2] = _compliance_test.nb_gateways; } else { switch (_compliance_test.state) { - case 4: - _compliance_test.state = 1; - _tx_msg.f_buffer_size = _compliance_test.app_data_size; + case 4: + _compliance_test.state = 1; + _tx_msg.f_buffer_size = _compliance_test.app_data_size; - _tx_msg.f_buffer[0] = _compliance_test.app_data_buffer[0]; - for(uint8_t i = 1; i < MIN(_compliance_test.app_data_size, MBED_CONF_LORA_TX_MAX_SIZE); ++i) { - _tx_msg.f_buffer[i] = _compliance_test.app_data_buffer[i]; - } - break; - case 1: - _tx_msg.f_buffer_size = 2; - _tx_msg.f_buffer[0] = _compliance_test.downlink_counter >> 8; - _tx_msg.f_buffer[1] = _compliance_test.downlink_counter; - break; + _tx_msg.f_buffer[0] = _compliance_test.app_data_buffer[0]; + for (uint8_t i = 1; i < MIN(_compliance_test.app_data_size, MBED_CONF_LORA_TX_MAX_SIZE); ++i) { + _tx_msg.f_buffer[i] = _compliance_test.app_data_buffer[i]; + } + break; + case 1: + _tx_msg.f_buffer_size = 2; + _tx_msg.f_buffer[0] = _compliance_test.downlink_counter >> 8; + _tx_msg.f_buffer[1] = _compliance_test.downlink_counter; + break; } } } @@ -241,7 +240,7 @@ lorawan_status_t LoRaWANStack::send_compliance_test_frame_to_mac() tr_info("Transmit unconfirmed compliance test frame %d bytes.", mcps_req.f_buffer_size); for (uint8_t i = 0; i < mcps_req.f_buffer_size; ++i) { - tr_info("Byte %d, data is 0x%x", i+1, ((uint8_t*)mcps_req.f_buffer)[i]); + tr_info("Byte %d, data is 0x%x", i + 1, ((uint8_t *)mcps_req.f_buffer)[i]); } } else if (_compliance_test.is_tx_confirmed) { mcps_req.type = MCPS_CONFIRMED; @@ -254,7 +253,7 @@ lorawan_status_t LoRaWANStack::send_compliance_test_frame_to_mac() tr_info("Transmit confirmed compliance test frame %d bytes.", mcps_req.f_buffer_size); for (uint8_t i = 0; i < mcps_req.f_buffer_size; ++i) { - tr_info("Byte %d, data is 0x%x", i+1, ((uint8_t*)mcps_req.f_buffer)[i]); + tr_info("Byte %d, data is 0x%x", i + 1, ((uint8_t *)mcps_req.f_buffer)[i]); } } else { return LORAWAN_STATUS_SERVICE_UNKNOWN; @@ -300,7 +299,7 @@ lorawan_status_t LoRaWANStack::send_frame_to_mac() mcps_req.f_buffer_size = _tx_msg.f_buffer_size; mib_get_params.type = MIB_CHANNELS_DATARATE; - if(mib_get_request(&mib_get_params) != LORAWAN_STATUS_OK) { + if (mib_get_request(&mib_get_params) != LORAWAN_STATUS_OK) { tr_debug("Couldn't get MIB parameters: Using default data rate"); mcps_req.req.unconfirmed.data_rate = default_datarate.value; } else { @@ -314,19 +313,19 @@ lorawan_status_t LoRaWANStack::send_frame_to_mac() mcps_req.req.confirmed.nb_trials = _tx_msg.message_u.confirmed.nb_trials; mib_get_params.type = MIB_CHANNELS_DATARATE; - if(mib_get_request(&mib_get_params) != LORAWAN_STATUS_OK) { + if (mib_get_request(&mib_get_params) != LORAWAN_STATUS_OK) { tr_debug("Couldn't get MIB parameters: Using default data rate"); mcps_req.req.confirmed.data_rate = default_datarate.value; } else { mcps_req.req.confirmed.data_rate = mib_get_params.param.channel_data_rate; } - } else if ( mcps_req.type == MCPS_PROPRIETARY) { + } else if (mcps_req.type == MCPS_PROPRIETARY) { mcps_req.f_buffer = _tx_msg.f_buffer; mcps_req.f_buffer_size = _tx_msg.f_buffer_size; mib_get_params.type = MIB_CHANNELS_DATARATE; - if(mib_get_request(&mib_get_params) != LORAWAN_STATUS_OK) { + if (mib_get_request(&mib_get_params) != LORAWAN_STATUS_OK) { tr_debug("Couldn't get MIB parameters: Using default data rate"); mcps_req.req.proprietary.data_rate = default_datarate.value; } else { @@ -365,15 +364,14 @@ void LoRaWANStack::set_device_state(device_states_t new_state) */ void LoRaWANStack::mlme_indication_handler(loramac_mlme_indication_t *mlmeIndication) { - switch( mlmeIndication->indication_type ) - { - case MLME_SCHEDULE_UPLINK: - {// The MAC signals that we shall provide an uplink as soon as possible - // TODO: Sending implementation missing and will be implemented using - // another task. - //OnTxNextPacketTimerEvent( ); - break; - } + switch (mlmeIndication->indication_type) { + case MLME_SCHEDULE_UPLINK: { + // The MAC signals that we shall provide an uplink as soon as possible + // TODO: Sending implementation missing and will be implemented using + // another task. + //OnTxNextPacketTimerEvent( ); + break; + } default: break; } @@ -419,8 +417,7 @@ lorawan_status_t LoRaWANStack::drop_channel_list() lorawan_status_t LoRaWANStack::remove_a_channel(uint8_t channel_id) { - if (_device_current_state == DEVICE_STATE_NOT_INITIALIZED ) - { + if (_device_current_state == DEVICE_STATE_NOT_INITIALIZED) { tr_error("Stack not initialized!"); return LORAWAN_STATUS_NOT_INITIALIZED; } @@ -428,23 +425,21 @@ lorawan_status_t LoRaWANStack::remove_a_channel(uint8_t channel_id) return _loramac.remove_single_channel(channel_id); } -lorawan_status_t LoRaWANStack::get_enabled_channels(lorawan_channelplan_t& channel_plan) +lorawan_status_t LoRaWANStack::get_enabled_channels(lorawan_channelplan_t &channel_plan) { if (_device_current_state == DEVICE_STATE_JOINING || _device_current_state == DEVICE_STATE_NOT_INITIALIZED - || _device_current_state == DEVICE_STATE_INIT) - { + || _device_current_state == DEVICE_STATE_INIT) { tr_error("Cannot get channel plan until Joined!"); return LORAWAN_STATUS_BUSY; } - return _loramac.get_channel_plan(channel_plan); + return _loramac.get_channel_plan(channel_plan); } lorawan_status_t LoRaWANStack::enable_adaptive_datarate(bool adr_enabled) { - if (DEVICE_STATE_NOT_INITIALIZED == _device_current_state) - { + if (DEVICE_STATE_NOT_INITIALIZED == _device_current_state) { tr_error("Stack not initialized!"); return LORAWAN_STATUS_NOT_INITIALIZED; } @@ -459,8 +454,7 @@ lorawan_status_t LoRaWANStack::enable_adaptive_datarate(bool adr_enabled) lorawan_status_t LoRaWANStack::set_channel_data_rate(uint8_t data_rate) { - if (DEVICE_STATE_NOT_INITIALIZED == _device_current_state) - { + if (DEVICE_STATE_NOT_INITIALIZED == _device_current_state) { tr_error("Stack not initialized!"); return LORAWAN_STATUS_NOT_INITIALIZED; } @@ -486,20 +480,20 @@ void LoRaWANStack::commission_device(const lorawan_dev_commission_t &commission_ if (commission_data.connection.connect_type == LORAWAN_CONNECTION_OTAA) { _lw_session.connection.connection_u.otaa.app_eui = - commission_data.connection.connection_u.otaa.app_eui; + commission_data.connection.connection_u.otaa.app_eui; _lw_session.connection.connection_u.otaa.app_key = - commission_data.connection.connection_u.otaa.app_key; + commission_data.connection.connection_u.otaa.app_key; _lw_session.connection.connection_u.otaa.dev_eui = - commission_data.connection.connection_u.otaa.dev_eui; + commission_data.connection.connection_u.otaa.dev_eui; _lw_session.connection.connection_u.otaa.nb_trials = - commission_data.connection.connection_u.otaa.nb_trials; + commission_data.connection.connection_u.otaa.nb_trials; } else { _lw_session.connection.connection_u.abp.dev_addr = - commission_data.connection.connection_u.abp.dev_addr; + commission_data.connection.connection_u.abp.dev_addr; _lw_session.connection.connection_u.abp.nwk_skey = - commission_data.connection.connection_u.abp.nwk_skey; + commission_data.connection.connection_u.abp.nwk_skey; _lw_session.connection.connection_u.abp.app_skey = - commission_data.connection.connection_u.abp.app_skey; + commission_data.connection.connection_u.abp.app_skey; } } @@ -511,8 +505,7 @@ lorawan_status_t LoRaWANStack::join_request_by_otaa(const lorawan_connect_t &par { lorawan_dev_commission_t commission; - if (DEVICE_STATE_NOT_INITIALIZED == _device_current_state) - { + if (DEVICE_STATE_NOT_INITIALIZED == _device_current_state) { tr_error("Stack not initialized!"); return LORAWAN_STATUS_NOT_INITIALIZED; } @@ -579,7 +572,7 @@ lorawan_status_t LoRaWANStack::activation_by_personalization(const lorawan_conne return status; } -int16_t LoRaWANStack::handle_tx(uint8_t port, const uint8_t* data, +int16_t LoRaWANStack::handle_tx(uint8_t port, const uint8_t *data, uint16_t length, uint8_t flags) { if (!_lw_session.active) { @@ -619,7 +612,7 @@ int16_t LoRaWANStack::handle_tx(uint8_t port, const uint8_t* data, } if (flags == 0 - || (flags & MSG_FLAG_MASK) == (MSG_CONFIRMED_FLAG|MSG_UNCONFIRMED_FLAG)) { + || (flags & MSG_FLAG_MASK) == (MSG_CONFIRMED_FLAG | MSG_UNCONFIRMED_FLAG)) { tr_error("CONFIRMED and UNCONFIRMED are mutually exclusive for send()"); return LORAWAN_STATUS_PARAMETER_INVALID; } @@ -660,8 +653,8 @@ int16_t LoRaWANStack::handle_tx(uint8_t port, const uint8_t* data, || (flags & MSG_FLAG_MASK) == MSG_UNCONFIRMED_MULTICAST || (flags & MSG_FLAG_MASK) == MSG_UNCONFIRMED_PROPRIETARY) { - _tx_msg.type = MCPS_UNCONFIRMED; - _tx_msg.message_u.unconfirmed.fport = _app_port; + _tx_msg.type = MCPS_UNCONFIRMED; + _tx_msg.message_u.unconfirmed.fport = _app_port; } // Handles all confirmed messages, including proprietary and multicast @@ -683,7 +676,7 @@ int16_t LoRaWANStack::handle_tx(uint8_t port, const uint8_t* data, return (status == LORAWAN_STATUS_OK) ? _tx_msg.f_buffer_size : (int16_t) status; } -int16_t LoRaWANStack::handle_rx(const uint8_t port, uint8_t* data, +int16_t LoRaWANStack::handle_rx(const uint8_t port, uint8_t *data, uint16_t length, uint8_t flags) { if (!_lw_session.active) { @@ -717,8 +710,8 @@ int16_t LoRaWANStack::handle_rx(const uint8_t port, uint8_t* data, // check if message received is a Confirmed message and user subscribed to it or not if (_rx_msg.msg.mcps_indication.type == MCPS_CONFIRMED && ((flags & MSG_FLAG_MASK) == MSG_CONFIRMED_FLAG - || (flags & MSG_FLAG_MASK) == MSG_CONFIRMED_MULTICAST - || (flags & MSG_FLAG_MASK) == MSG_CONFIRMED_PROPRIETARY)) { + || (flags & MSG_FLAG_MASK) == MSG_CONFIRMED_MULTICAST + || (flags & MSG_FLAG_MASK) == MSG_CONFIRMED_PROPRIETARY)) { tr_debug("RX - Confirmed Message, flags=%d", flags); } @@ -726,8 +719,8 @@ int16_t LoRaWANStack::handle_rx(const uint8_t port, uint8_t* data, // check if message received is a Unconfirmed message and user subscribed to it or not if (_rx_msg.msg.mcps_indication.type == MCPS_UNCONFIRMED && ((flags & MSG_FLAG_MASK) == MSG_UNCONFIRMED_FLAG - || (flags & MSG_FLAG_MASK) == MSG_UNCONFIRMED_MULTICAST - || (flags & MSG_FLAG_MASK) == MSG_UNCONFIRMED_PROPRIETARY)) { + || (flags & MSG_FLAG_MASK) == MSG_UNCONFIRMED_MULTICAST + || (flags & MSG_FLAG_MASK) == MSG_UNCONFIRMED_PROPRIETARY)) { tr_debug("RX - Unconfirmed Message - flags=%d", flags); } @@ -751,7 +744,7 @@ int16_t LoRaWANStack::handle_rx(const uint8_t port, uint8_t* data, // the buffer. Due to checks above, in case of a pending read, this block // will be the only one to get invoked if (_rx_msg.pending_size > 0 && _rx_msg.prev_read_size > 0) { - memcpy(data, base_ptr+_rx_msg.prev_read_size, base_size); + memcpy(data, base_ptr + _rx_msg.prev_read_size, base_size); } // we are done handing over received buffer to user. check if there is @@ -877,7 +870,8 @@ void LoRaWANStack::mcps_confirm_handler(loramac_mcps_confirm_t *mcps_confirm) (void)ret; } return; - } if (mcps_confirm->status == LORAMAC_EVENT_INFO_STATUS_RX2_TIMEOUT) { + } + if (mcps_confirm->status == LORAMAC_EVENT_INFO_STATUS_RX2_TIMEOUT) { tr_debug("Did not receive Ack"); } @@ -906,11 +900,11 @@ void LoRaWANStack::mcps_confirm_handler(loramac_mcps_confirm_t *mcps_confirm) // data rate plus frame counter. _lw_session.uplink_counter = mcps_confirm->ul_frame_counter; _tx_msg.tx_ongoing = false; - if (_callbacks.events) { - const int ret = _queue->call(_callbacks.events, TX_DONE); - MBED_ASSERT(ret != 0); - (void)ret; - } + if (_callbacks.events) { + const int ret = _queue->call(_callbacks.events, TX_DONE); + MBED_ASSERT(ret != 0); + (void)ret; + } } /** MCPS-Indication event function @@ -967,48 +961,48 @@ void LoRaWANStack::mcps_indication_handler(loramac_mcps_indication_t *mcps_indic if (mcps_indication->is_data_recvd == true) { switch (mcps_indication->port) { - case 224: + case 224: #if defined(LORAWAN_COMPLIANCE_TEST) - tr_debug("Compliance test command received."); - compliance_test_handler(mcps_indication); + tr_debug("Compliance test command received."); + compliance_test_handler(mcps_indication); #else - tr_debug("Compliance test disabled."); + tr_debug("Compliance test disabled."); #endif - break; - default: - if (is_port_valid(mcps_indication->port) == true || - mcps_indication->type == MCPS_PROPRIETARY) { + break; + default: + if (is_port_valid(mcps_indication->port) == true || + mcps_indication->type == MCPS_PROPRIETARY) { - // Valid message arrived. - _rx_msg.type = LORAMAC_RX_MCPS_INDICATION; - _rx_msg.msg.mcps_indication.buffer_size = mcps_indication->buffer_size; - _rx_msg.msg.mcps_indication.port = mcps_indication->port; + // Valid message arrived. + _rx_msg.type = LORAMAC_RX_MCPS_INDICATION; + _rx_msg.msg.mcps_indication.buffer_size = mcps_indication->buffer_size; + _rx_msg.msg.mcps_indication.port = mcps_indication->port; - // no copy, just set the pointer for the user - _rx_msg.msg.mcps_indication.buffer = - mcps_indication->buffer; + // no copy, just set the pointer for the user + _rx_msg.msg.mcps_indication.buffer = + mcps_indication->buffer; - // Notify application about received frame.. - tr_debug("Received %d bytes", _rx_msg.msg.mcps_indication.buffer_size); - _rx_msg.receive_ready = true; + // Notify application about received frame.. + tr_debug("Received %d bytes", _rx_msg.msg.mcps_indication.buffer_size); + _rx_msg.receive_ready = true; - if (_callbacks.events) { - const int ret = _queue->call(_callbacks.events, RX_DONE); - MBED_ASSERT(ret != 0); - (void)ret; - } + if (_callbacks.events) { + const int ret = _queue->call(_callbacks.events, RX_DONE); + MBED_ASSERT(ret != 0); + (void)ret; + } - // If fPending bit is set we try to generate an empty packet - // with CONFIRMED flag set. We always set a CONFIRMED flag so - // that we could retry a certain number of times if the uplink - // failed for some reason - if (mcps_indication->fpending_status) { - handle_tx(mcps_indication->port, NULL, 0, MSG_CONFIRMED_FLAG); + // If fPending bit is set we try to generate an empty packet + // with CONFIRMED flag set. We always set a CONFIRMED flag so + // that we could retry a certain number of times if the uplink + // failed for some reason + if (mcps_indication->fpending_status) { + handle_tx(mcps_indication->port, NULL, 0, MSG_CONFIRMED_FLAG); + } + } else { + // Invalid port, ports 0, 224 and 225-255 are reserved. } - } else { - // Invalid port, ports 0, 224 and 225-255 are reserved. - } - break; + break; } } } @@ -1024,10 +1018,10 @@ void LoRaWANStack::compliance_test_handler(loramac_mcps_indication_t *mcps_indic if (_compliance_test.running == false) { // Check compliance test enable command (i) if ((mcps_indication->buffer_size == 4) && - (mcps_indication->buffer[0] == 0x01) && - (mcps_indication->buffer[1] == 0x01) && - (mcps_indication->buffer[2] == 0x01) && - (mcps_indication->buffer[3] == 0x01)) { + (mcps_indication->buffer[0] == 0x01) && + (mcps_indication->buffer[1] == 0x01) && + (mcps_indication->buffer[2] == 0x01) && + (mcps_indication->buffer[3] == 0x01)) { _compliance_test.is_tx_confirmed = false; _compliance_test.app_port = 224; _compliance_test.app_data_size = 2; @@ -1054,96 +1048,96 @@ void LoRaWANStack::compliance_test_handler(loramac_mcps_indication_t *mcps_indic } else { _compliance_test.state = mcps_indication->buffer[0]; switch (_compliance_test.state) { - case 0: // Check compliance test disable command (ii) - _compliance_test.is_tx_confirmed = true; - _compliance_test.app_port = MBED_CONF_LORA_APP_PORT; - _compliance_test.app_data_size = LORAWAN_COMPLIANCE_TEST_DATA_SIZE; - _compliance_test.downlink_counter = 0; - _compliance_test.running = false; - - loramac_mib_req_confirm_t mib_req; - mib_req.type = MIB_ADR; - mib_req.param.is_adr_enable = MBED_CONF_LORA_ADR_ON; - mib_set_request(&mib_req); + case 0: // Check compliance test disable command (ii) + _compliance_test.is_tx_confirmed = true; + _compliance_test.app_port = MBED_CONF_LORA_APP_PORT; + _compliance_test.app_data_size = LORAWAN_COMPLIANCE_TEST_DATA_SIZE; + _compliance_test.downlink_counter = 0; + _compliance_test.running = false; + + loramac_mib_req_confirm_t mib_req; + mib_req.type = MIB_ADR; + mib_req.param.is_adr_enable = MBED_CONF_LORA_ADR_ON; + mib_set_request(&mib_req); #if MBED_CONF_LORA_PHY == 0 - _loramac.LoRaMacTestSetDutyCycleOn(MBED_CONF_LORA_DUTY_CYCLE_ON); + _loramac.LoRaMacTestSetDutyCycleOn(MBED_CONF_LORA_DUTY_CYCLE_ON); #endif - // Go to idle state after compliance test mode. - tr_debug("Compliance test disabled."); - _loramac.LoRaMacStopTxTimer(); - - // Clear any compliance test message stuff before going back to normal operation. - memset(&_tx_msg, 0, sizeof(_tx_msg)); - set_device_state(DEVICE_STATE_IDLE); - lora_state_machine(); - break; - case 1: // (iii, iv) - _compliance_test.app_data_size = 2; - break; - case 2: // Enable confirmed messages (v) - _compliance_test.is_tx_confirmed = true; - _compliance_test.state = 1; - break; - case 3: // Disable confirmed messages (vi) - _compliance_test.is_tx_confirmed = false; - _compliance_test.state = 1; - break; - case 4: // (vii) - _compliance_test.app_data_size = mcps_indication->buffer_size; + // Go to idle state after compliance test mode. + tr_debug("Compliance test disabled."); + _loramac.LoRaMacStopTxTimer(); - _compliance_test.app_data_buffer[0] = 4; - for(uint8_t i = 1; i < MIN(_compliance_test.app_data_size, LORAMAC_PHY_MAXPAYLOAD); ++i) { - _compliance_test.app_data_buffer[i] = mcps_indication->buffer[i] + 1; - } + // Clear any compliance test message stuff before going back to normal operation. + memset(&_tx_msg, 0, sizeof(_tx_msg)); + set_device_state(DEVICE_STATE_IDLE); + lora_state_machine(); + break; + case 1: // (iii, iv) + _compliance_test.app_data_size = 2; + break; + case 2: // Enable confirmed messages (v) + _compliance_test.is_tx_confirmed = true; + _compliance_test.state = 1; + break; + case 3: // Disable confirmed messages (vi) + _compliance_test.is_tx_confirmed = false; + _compliance_test.state = 1; + break; + case 4: // (vii) + _compliance_test.app_data_size = mcps_indication->buffer_size; - send_compliance_test_frame_to_mac(); - break; - case 5: // (viii) - loramac_mlme_req_t mlme_req; - mlme_req.type = MLME_LINK_CHECK; - mlme_request_handler(&mlme_req); - break; - case 6: // (ix) - loramac_mlme_req_t mlme_request; - loramac_mib_req_confirm_t mib_request; - - // Disable TestMode and revert back to normal operation - _compliance_test.is_tx_confirmed = true; - _compliance_test.app_port = MBED_CONF_LORA_APP_PORT; - _compliance_test.app_data_size = LORAWAN_COMPLIANCE_TEST_DATA_SIZE; - _compliance_test.downlink_counter = 0; - _compliance_test.running = false; + _compliance_test.app_data_buffer[0] = 4; + for (uint8_t i = 1; i < MIN(_compliance_test.app_data_size, LORAMAC_PHY_MAXPAYLOAD); ++i) { + _compliance_test.app_data_buffer[i] = mcps_indication->buffer[i] + 1; + } - mib_request.type = MIB_ADR; - mib_request.param.is_adr_enable = MBED_CONF_LORA_ADR_ON; - mib_set_request(&mib_request); -#if MBED_CONF_LORA_PHY == 0 - _loramac.LoRaMacTestSetDutyCycleOn(MBED_CONF_LORA_DUTY_CYCLE_ON); -#endif - mlme_request.type = MLME_JOIN; - mlme_request.req.join.dev_eui = _lw_session.connection.connection_u.otaa.dev_eui; - mlme_request.req.join.app_eui = _lw_session.connection.connection_u.otaa.app_eui; - mlme_request.req.join.app_key = _lw_session.connection.connection_u.otaa.app_key; - mlme_request.req.join.nb_trials = _lw_session.connection.connection_u.otaa.nb_trials; - mlme_request_handler(&mlme_request); - break; - case 7: // (x) - if (mcps_indication->buffer_size == 3) { - loramac_mlme_req_t mlme_req; - mlme_req.type = MLME_TXCW; - mlme_req.req.cw_tx_mode.timeout = (uint16_t)((mcps_indication->buffer[1] << 8) | mcps_indication->buffer[2]); - mlme_request_handler(&mlme_req); - } else if (mcps_indication->buffer_size == 7) { + send_compliance_test_frame_to_mac(); + break; + case 5: // (viii) loramac_mlme_req_t mlme_req; - mlme_req.type = MLME_TXCW_1; - mlme_req.req.cw_tx_mode.timeout = (uint16_t)((mcps_indication->buffer[1] << 8) | mcps_indication->buffer[2]); - mlme_req.req.cw_tx_mode.frequency = (uint32_t)((mcps_indication->buffer[3] << 16) | (mcps_indication->buffer[4] << 8) - | mcps_indication->buffer[5]) * 100; - mlme_req.req.cw_tx_mode.power = mcps_indication->buffer[6]; + mlme_req.type = MLME_LINK_CHECK; mlme_request_handler(&mlme_req); - } - _compliance_test.state = 1; - break; + break; + case 6: // (ix) + loramac_mlme_req_t mlme_request; + loramac_mib_req_confirm_t mib_request; + + // Disable TestMode and revert back to normal operation + _compliance_test.is_tx_confirmed = true; + _compliance_test.app_port = MBED_CONF_LORA_APP_PORT; + _compliance_test.app_data_size = LORAWAN_COMPLIANCE_TEST_DATA_SIZE; + _compliance_test.downlink_counter = 0; + _compliance_test.running = false; + + mib_request.type = MIB_ADR; + mib_request.param.is_adr_enable = MBED_CONF_LORA_ADR_ON; + mib_set_request(&mib_request); +#if MBED_CONF_LORA_PHY == 0 + _loramac.LoRaMacTestSetDutyCycleOn(MBED_CONF_LORA_DUTY_CYCLE_ON); +#endif + mlme_request.type = MLME_JOIN; + mlme_request.req.join.dev_eui = _lw_session.connection.connection_u.otaa.dev_eui; + mlme_request.req.join.app_eui = _lw_session.connection.connection_u.otaa.app_eui; + mlme_request.req.join.app_key = _lw_session.connection.connection_u.otaa.app_key; + mlme_request.req.join.nb_trials = _lw_session.connection.connection_u.otaa.nb_trials; + mlme_request_handler(&mlme_request); + break; + case 7: // (x) + if (mcps_indication->buffer_size == 3) { + loramac_mlme_req_t mlme_req; + mlme_req.type = MLME_TXCW; + mlme_req.req.cw_tx_mode.timeout = (uint16_t)((mcps_indication->buffer[1] << 8) | mcps_indication->buffer[2]); + mlme_request_handler(&mlme_req); + } else if (mcps_indication->buffer_size == 7) { + loramac_mlme_req_t mlme_req; + mlme_req.type = MLME_TXCW_1; + mlme_req.req.cw_tx_mode.timeout = (uint16_t)((mcps_indication->buffer[1] << 8) | mcps_indication->buffer[2]); + mlme_req.req.cw_tx_mode.frequency = (uint32_t)((mcps_indication->buffer[3] << 16) | (mcps_indication->buffer[4] << 8) + | mcps_indication->buffer[5]) * 100; + mlme_req.req.cw_tx_mode.power = mcps_indication->buffer[6]; + mlme_request_handler(&mlme_req); + } + _compliance_test.state = 1; + break; } } } @@ -1159,7 +1153,7 @@ lorawan_status_t LoRaWANStack::mib_set_request(loramac_mib_req_confirm_t *mib_se lorawan_status_t LoRaWANStack::mib_get_request(loramac_mib_req_confirm_t *mib_get_params) { - if(NULL == mib_get_params) { + if (NULL == mib_get_params) { return LORAWAN_STATUS_PARAMETER_INVALID; } return _loramac.mib_get_request_confirm(mib_get_params); diff --git a/features/lorawan/LoRaWANStack.h b/features/lorawan/LoRaWANStack.h index 08daf98ca9a..e24d4145517 100644 --- a/features/lorawan/LoRaWANStack.h +++ b/features/lorawan/LoRaWANStack.h @@ -36,39 +36,39 @@ SPDX-License-Identifier: BSD-3-Clause #include "LoRaRadio.h" #ifdef MBED_CONF_LORA_PHY - #if MBED_CONF_LORA_PHY == 0 - #include "lorawan/lorastack/phy/LoRaPHYEU868.h" - #define LoRaPHY_region LoRaPHYEU868 - #elif MBED_CONF_LORA_PHY == 1 - #include "lorawan/lorastack/phy/LoRaPHYAS923.h" - #define LoRaPHY_region LoRaPHYAS923 - #elif MBED_CONF_LORA_PHY == 2 - #include "lorawan/lorastack/phy/LoRaPHYAU915.h" - #define LoRaPHY_region LoRaPHYAU915; - #elif MBED_CONF_LORA_PHY == 3 - #include "lorawan/lorastack/phy/LoRaPHYCN470.h" - #define LoRaPHY_region LoRaPHYCN470 - #elif MBED_CONF_LORA_PHY == 4 - #include "lorawan/lorastack/phy/LoRaPHYCN779.h" - #define LoRaPHY_region LoRaPHYCN779 - #elif MBED_CONF_LORA_PHY == 5 - #include "lorawan/lorastack/phy/LoRaPHYEU433.h" - #define LoRaPHY_region LoRaPHYEU433 - #elif MBED_CONF_LORA_PHY == 6 - #include "lorawan/lorastack/phy/LoRaPHYIN865.h" - #define LoRaPHY_region LoRaPHYIN865 - #elif MBED_CONF_LORA_PHY == 7 - #include "lorawan/lorastack/phy/LoRaPHYKR920.h" - #define LoRaPHY_region LoRaPHYKR920 - #elif MBED_CONF_LORA_PHY == 8 - #include "lorawan/lorastack/phy/LoRaPHYUS915.h" - #define LoRaPHY_region LoRaPHYUS915 - #elif MBED_CONF_LORA_PHY == 9 - #include "lorawan/lorastack/phy/LoRaPHYUS915Hybrid.h" - #define LoRaPHY_region LoRaPHYUS915Hybrid - #endif //MBED_CONF_LORA_PHY == VALUE +#if MBED_CONF_LORA_PHY == 0 +#include "lorawan/lorastack/phy/LoRaPHYEU868.h" +#define LoRaPHY_region LoRaPHYEU868 +#elif MBED_CONF_LORA_PHY == 1 +#include "lorawan/lorastack/phy/LoRaPHYAS923.h" +#define LoRaPHY_region LoRaPHYAS923 +#elif MBED_CONF_LORA_PHY == 2 +#include "lorawan/lorastack/phy/LoRaPHYAU915.h" +#define LoRaPHY_region LoRaPHYAU915; +#elif MBED_CONF_LORA_PHY == 3 +#include "lorawan/lorastack/phy/LoRaPHYCN470.h" +#define LoRaPHY_region LoRaPHYCN470 +#elif MBED_CONF_LORA_PHY == 4 +#include "lorawan/lorastack/phy/LoRaPHYCN779.h" +#define LoRaPHY_region LoRaPHYCN779 +#elif MBED_CONF_LORA_PHY == 5 +#include "lorawan/lorastack/phy/LoRaPHYEU433.h" +#define LoRaPHY_region LoRaPHYEU433 +#elif MBED_CONF_LORA_PHY == 6 +#include "lorawan/lorastack/phy/LoRaPHYIN865.h" +#define LoRaPHY_region LoRaPHYIN865 +#elif MBED_CONF_LORA_PHY == 7 +#include "lorawan/lorastack/phy/LoRaPHYKR920.h" +#define LoRaPHY_region LoRaPHYKR920 +#elif MBED_CONF_LORA_PHY == 8 +#include "lorawan/lorastack/phy/LoRaPHYUS915.h" +#define LoRaPHY_region LoRaPHYUS915 +#elif MBED_CONF_LORA_PHY == 9 +#include "lorawan/lorastack/phy/LoRaPHYUS915Hybrid.h" +#define LoRaPHY_region LoRaPHYUS915Hybrid +#endif //MBED_CONF_LORA_PHY == VALUE #else - #error "Must set LoRa PHY layer parameters." +#error "Must set LoRa PHY layer parameters." #endif //MBED_CONF_LORA_PHY /** @@ -78,7 +78,7 @@ SPDX-License-Identifier: BSD-3-Clause class LoRaWANStack: private mbed::NonCopyable { public: - static LoRaWANStack& get_lorawan_stack(); + static LoRaWANStack &get_lorawan_stack(); /** Binds radio driver to PHY layer. * @@ -93,7 +93,7 @@ class LoRaWANStack: private mbed::NonCopyable { * @return A list of callbacks from MAC layer that needs to * be passed to radio driver */ - radio_events_t *bind_radio_driver(LoRaRadio& radio); + radio_events_t *bind_radio_driver(LoRaRadio &radio); /** End device initialization. * @param queue A pointer to an EventQueue passed from the application. @@ -258,7 +258,7 @@ class LoRaWANStack: private mbed::NonCopyable { * LORAWAN_STATUS_WOULD_BLOCK if another TX is * ongoing, or a negative error code on failure. */ - int16_t handle_tx(uint8_t port, const uint8_t* data, + int16_t handle_tx(uint8_t port, const uint8_t *data, uint16_t length, uint8_t flags); /** Receives a message from the Network Server. @@ -300,7 +300,7 @@ class LoRaWANStack: private mbed::NonCopyable { * nothing available to read at the moment. * iv) A negative error code on failure. */ - int16_t handle_rx(const uint8_t port, uint8_t* data, + int16_t handle_rx(const uint8_t port, uint8_t *data, uint16_t length, uint8_t flags); /** Send Link Check Request MAC command. diff --git a/features/lorawan/lorastack/mac/LoRaMac.cpp b/features/lorawan/lorastack/mac/LoRaMac.cpp index ab5c2b93587..35ed08a904a 100644 --- a/features/lorawan/lorastack/mac/LoRaMac.cpp +++ b/features/lorawan/lorastack/mac/LoRaMac.cpp @@ -216,12 +216,12 @@ void LoRaMac::handle_rx2_timer_event(void) /*************************************************************************** * Radio event callbacks - delegated to Radio driver * **************************************************************************/ -void LoRaMac::on_radio_tx_done( void ) +void LoRaMac::on_radio_tx_done(void) { get_phy_params_t get_phy; phy_param_t phy_param; set_band_txdone_params_t tx_done_params; - lorawan_time_t cur_time = _lora_time.get_current_time( ); + lorawan_time_t cur_time = _lora_time.get_current_time(); loramac_mlme_confirm_t mlme_confirm = mlme.get_confirmation(); if (_params.dev_class != CLASS_C) { @@ -231,15 +231,15 @@ void LoRaMac::on_radio_tx_done( void ) } // Setup timers - if(_params.is_rx_window_enabled == true) { + if (_params.is_rx_window_enabled == true) { _lora_time.start(_params.timers.rx_window1_timer, _params.rx_window1_delay); if (_params.dev_class != CLASS_C) { _lora_time.start(_params.timers.rx_window2_timer, _params.rx_window2_delay); } - if ((_params.dev_class == CLASS_C ) || - (_params.is_node_ack_requested == true)) { + if ((_params.dev_class == CLASS_C) || + (_params.is_node_ack_requested == true)) { get_phy.attribute = PHY_ACK_TIMEOUT; phy_param = lora_phy->get_phy_params(&get_phy); _lora_time.start(_params.timers.ack_timeout_timer, @@ -258,7 +258,7 @@ void LoRaMac::on_radio_tx_done( void ) // Verify if the last uplink was a join request if ((_params.flags.bits.mlme_req == 1) && - (mlme_confirm.req_type == MLME_JOIN)) { + (mlme_confirm.req_type == MLME_JOIN)) { _params.is_last_tx_join_request = true; } else { _params.is_last_tx_join_request = false; @@ -343,7 +343,7 @@ void LoRaMac::on_radio_rx_done(uint8_t *payload, uint16_t size, int16_t rssi, lora_phy->put_radio_to_sleep(); - _lora_time.stop( _params.timers.rx_window2_timer ); + _lora_time.stop(_params.timers.rx_window2_timer); mac_hdr.value = payload[pkt_header_len++]; @@ -366,7 +366,7 @@ void LoRaMac::on_radio_rx_done(uint8_t *payload, uint16_t size, int16_t rssi, _params.payload[0] = mac_hdr.value; if (0 != compute_join_frame_mic(_params.payload, size - LORAMAC_MFR_LEN, - _params.keys.app_key, &mic)) { + _params.keys.app_key, &mic)) { mcps.get_indication().status = LORAMAC_EVENT_INFO_STATUS_CRYPTO_FAIL; return; } @@ -379,10 +379,10 @@ void LoRaMac::on_radio_rx_done(uint8_t *payload, uint16_t size, int16_t rssi, if (mic_rx == mic) { if (0 != compute_skeys_for_join_frame(_params.keys.app_key, - _params.payload + 1, - _params.dev_nonce, - _params.keys.nwk_skey, - _params.keys.app_skey)) { + _params.payload + 1, + _params.dev_nonce, + _params.keys.nwk_skey, + _params.keys.app_skey)) { mcps.get_indication().status = LORAMAC_EVENT_INFO_STATUS_CRYPTO_FAIL; return; } @@ -426,8 +426,7 @@ void LoRaMac::on_radio_rx_done(uint8_t *payload, uint16_t size, int16_t rssi, break; case FRAME_TYPE_DATA_CONFIRMED_DOWN: - case FRAME_TYPE_DATA_UNCONFIRMED_DOWN: - { + case FRAME_TYPE_DATA_UNCONFIRMED_DOWN: { // Check if the received payload size is valid get_phy.datarate = mcps.get_indication().rx_datarate; get_phy.attribute = PHY_MAX_PAYLOAD; @@ -439,7 +438,7 @@ void LoRaMac::on_radio_rx_done(uint8_t *payload, uint16_t size, int16_t rssi, phy_param = lora_phy->get_phy_params(&get_phy); - if (MAX(0, (int16_t) ((int16_t)size - (int16_t)LORA_MAC_FRMPAYLOAD_OVERHEAD )) > (int32_t)phy_param.value) { + if (MAX(0, (int16_t)((int16_t)size - (int16_t)LORA_MAC_FRMPAYLOAD_OVERHEAD)) > (int32_t)phy_param.value) { mcps.get_indication().status = LORAMAC_EVENT_INFO_STATUS_ERROR; prepare_rx_done_abort(); return; @@ -482,7 +481,7 @@ void LoRaMac::on_radio_rx_done(uint8_t *payload, uint16_t size, int16_t rssi, fctrl.value = payload[pkt_header_len++]; - sequence_counter = (uint16_t )payload[pkt_header_len++]; + sequence_counter = (uint16_t)payload[pkt_header_len++]; sequence_counter |= (uint16_t)payload[pkt_header_len++] << 8; app_payload_start_index = 8 + fctrl.bits.fopts_len; @@ -499,7 +498,7 @@ void LoRaMac::on_radio_rx_done(uint8_t *payload, uint16_t size, int16_t rssi, downlink_counter += sequence_counter_diff; compute_mic(payload, size - LORAMAC_MFR_LEN, nwk_skey, - address, DOWN_LINK, downlink_counter, &mic); + address, DOWN_LINK, downlink_counter, &mic); if (mic_rx == mic) { is_mic_ok = true; } @@ -508,9 +507,9 @@ void LoRaMac::on_radio_rx_done(uint8_t *payload, uint16_t size, int16_t rssi, // check for sequence roll-over uint32_t downlink_counter_tmp = downlink_counter + 0x10000 + (int16_t)sequence_counter_diff; compute_mic(payload, size - LORAMAC_MFR_LEN, nwk_skey, - address, DOWN_LINK, downlink_counter_tmp, &mic); + address, DOWN_LINK, downlink_counter_tmp, &mic); - if (mic_rx == mic ) { + if (mic_rx == mic) { is_mic_ok = true; downlink_counter = downlink_counter_tmp; } @@ -523,7 +522,7 @@ void LoRaMac::on_radio_rx_done(uint8_t *payload, uint16_t size, int16_t rssi, if (sequence_counter_diff >= phy_param.value) { mcps.get_indication().status = LORAMAC_EVENT_INFO_STATUS_DOWNLINK_TOO_MANY_FRAMES_LOSS; mcps.get_indication().dl_frame_counter = downlink_counter; - prepare_rx_done_abort( ); + prepare_rx_done_abort(); return; } @@ -545,7 +544,7 @@ void LoRaMac::on_radio_rx_done(uint8_t *payload, uint16_t size, int16_t rssi, mcps.get_indication().type = MCPS_MULTICAST; if ((cur_multicast_params->dl_frame_counter == downlink_counter) && - (cur_multicast_params->dl_frame_counter != 0)) { + (cur_multicast_params->dl_frame_counter != 0)) { mcps.get_indication().status = LORAMAC_EVENT_INFO_STATUS_DOWNLINK_REPEATED; mcps.get_indication().dl_frame_counter = downlink_counter; @@ -562,8 +561,8 @@ void LoRaMac::on_radio_rx_done(uint8_t *payload, uint16_t size, int16_t rssi, _params.is_srv_ack_requested = true; mcps.get_indication().type = MCPS_CONFIRMED; - if ((_params.dl_frame_counter == downlink_counter ) && - (_params.dl_frame_counter != 0)) { + if ((_params.dl_frame_counter == downlink_counter) && + (_params.dl_frame_counter != 0)) { // Duplicated confirmed downlink. Skip indication. // In this case, the MAC layer shall accept the MAC commands // which are included in the downlink retransmission. @@ -576,7 +575,7 @@ void LoRaMac::on_radio_rx_done(uint8_t *payload, uint16_t size, int16_t rssi, mcps.get_indication().type = MCPS_UNCONFIRMED; if ((_params.dl_frame_counter == downlink_counter) && - (_params.dl_frame_counter != 0)) { + (_params.dl_frame_counter != 0)) { mcps.get_indication().status = LORAMAC_EVENT_INFO_STATUS_DOWNLINK_REPEATED; mcps.get_indication().dl_frame_counter = downlink_counter; prepare_rx_done_abort(); @@ -611,19 +610,19 @@ void LoRaMac::on_radio_rx_done(uint8_t *payload, uint16_t size, int16_t rssi, // Only allow frames which do not have fOpts if (fctrl.bits.fopts_len == 0) { if (0 != decrypt_payload(payload + app_payload_start_index, - frame_len, - nwk_skey, - address, - DOWN_LINK, - downlink_counter, - _params.payload)) { + frame_len, + nwk_skey, + address, + DOWN_LINK, + downlink_counter, + _params.payload)) { mcps.get_indication().status = LORAMAC_EVENT_INFO_STATUS_CRYPTO_FAIL; } // Decode frame payload MAC commands if (mac_commands.process_mac_commands(_params.payload, 0, frame_len, snr, - mlme.get_confirmation(), - _params.sys_params, *lora_phy) != LORAWAN_STATUS_OK) { + mlme.get_confirmation(), + _params.sys_params, *lora_phy) != LORAWAN_STATUS_OK) { mcps.get_indication().status = LORAMAC_EVENT_INFO_STATUS_ERROR; } } else { @@ -633,19 +632,19 @@ void LoRaMac::on_radio_rx_done(uint8_t *payload, uint16_t size, int16_t rssi, if (fctrl.bits.fopts_len > 0) { // Decode Options field MAC commands. Omit the fPort. if (mac_commands.process_mac_commands(payload, 8, app_payload_start_index - 1, snr, - mlme.get_confirmation(), - _params.sys_params, *lora_phy ) != LORAWAN_STATUS_OK) { + mlme.get_confirmation(), + _params.sys_params, *lora_phy) != LORAWAN_STATUS_OK) { mcps.get_indication().status = LORAMAC_EVENT_INFO_STATUS_ERROR; } } if (0 != decrypt_payload(payload + app_payload_start_index, - frame_len, - app_skey, - address, - DOWN_LINK, - downlink_counter, - _params.payload)) { + frame_len, + app_skey, + address, + DOWN_LINK, + downlink_counter, + _params.payload)) { mcps.get_indication().status = LORAMAC_EVENT_INFO_STATUS_CRYPTO_FAIL; } @@ -659,8 +658,8 @@ void LoRaMac::on_radio_rx_done(uint8_t *payload, uint16_t size, int16_t rssi, if (fctrl.bits.fopts_len > 0) { // Decode Options field MAC commands if (mac_commands.process_mac_commands(payload, 8, app_payload_start_index, snr, - mlme.get_confirmation(), - _params.sys_params, *lora_phy) != LORAWAN_STATUS_OK) { + mlme.get_confirmation(), + _params.sys_params, *lora_phy) != LORAWAN_STATUS_OK) { mcps.get_indication().status = LORAMAC_EVENT_INFO_STATUS_ERROR; } } @@ -681,7 +680,7 @@ void LoRaMac::on_radio_rx_done(uint8_t *payload, uint16_t size, int16_t rssi, if (_params.ack_timeout_retry_counter > _params.max_ack_timeout_retries) { // Stop the AckTimeout timer as no more retransmissions // are needed. - _lora_time.stop( _params.timers.ack_timeout_timer ); + _lora_time.stop(_params.timers.ack_timeout_timer); } } } @@ -692,15 +691,14 @@ void LoRaMac::on_radio_rx_done(uint8_t *payload, uint16_t size, int16_t rssi, } else { mcps.get_indication().status = LORAMAC_EVENT_INFO_STATUS_MIC_FAIL; - prepare_rx_done_abort( ); + prepare_rx_done_abort(); return; } } break; - case FRAME_TYPE_PROPRIETARY: - { + case FRAME_TYPE_PROPRIETARY: { memcpy(_params.payload, &payload[pkt_header_len], size); mcps.get_indication().type = MCPS_PROPRIETARY; @@ -721,7 +719,7 @@ void LoRaMac::on_radio_rx_done(uint8_t *payload, uint16_t size, int16_t rssi, _lora_time.start(_params.timers.mac_state_check_timer, 1); } -void LoRaMac::on_radio_tx_timeout( void ) +void LoRaMac::on_radio_tx_timeout(void) { if (_params.dev_class != CLASS_C) { lora_phy->put_radio_to_sleep(); @@ -736,7 +734,7 @@ void LoRaMac::on_radio_tx_timeout( void ) _params.flags.bits.mac_done = 1; } -void LoRaMac::on_radio_rx_error( void ) +void LoRaMac::on_radio_rx_error(void) { if (_params.dev_class != CLASS_C) { lora_phy->put_radio_to_sleep(); @@ -782,7 +780,7 @@ void LoRaMac::on_radio_rx_timeout(void) } mlme.get_confirmation().status = LORAMAC_EVENT_INFO_STATUS_RX1_TIMEOUT; - if (_lora_time.get_elapsed_time(_params.timers.aggregated_last_tx_time ) >= _params.rx_window2_delay) { + if (_lora_time.get_elapsed_time(_params.timers.aggregated_last_tx_time) >= _params.rx_window2_delay) { _lora_time.stop(_params.timers.rx_window2_timer); _params.flags.bits.mac_done = 1; } @@ -822,7 +820,7 @@ void LoRaMac::on_mac_state_check_timer_event(void) if ((_params.flags.bits.mlme_req == 1) || (_params.flags.bits.mcps_req == 1)) { if ((mcps.get_confirmation().status == LORAMAC_EVENT_INFO_STATUS_TX_TIMEOUT) || - ( mlme.get_confirmation().status == LORAMAC_EVENT_INFO_STATUS_TX_TIMEOUT)) { + (mlme.get_confirmation().status == LORAMAC_EVENT_INFO_STATUS_TX_TIMEOUT)) { // Stop transmit cycle due to tx timeout. _params.mac_state &= ~LORAMAC_TX_RUNNING; mac_commands.clear_command_buffer(); @@ -856,7 +854,7 @@ void LoRaMac::on_mac_state_check_timer_event(void) } else { // Procedure for all other frames if ((_params.ul_nb_rep_counter >= _params.sys_params.retry_num) || - (_params.flags.bits.mcps_ind == 1)) { + (_params.flags.bits.mcps_ind == 1)) { if (_params.flags.bits.mcps_ind == 0) { // Maximum repetitions without downlink. Reset MacCommandsBufferIndex. Increase ADR Ack counter. // Only process the case when the MAC did not receive a downlink. @@ -883,7 +881,7 @@ void LoRaMac::on_mac_state_check_timer_event(void) if (_params.flags.bits.mcps_ind == 1) { // Procedure if we received a frame if ((mcps.get_confirmation().ack_received == true) || - (_params.ack_timeout_retry_counter > _params.max_ack_timeout_retries)) { + (_params.ack_timeout_retry_counter > _params.max_ack_timeout_retries)) { _params.is_ack_retry_timeout_expired = false; _params.is_node_ack_requested = false; if (_params.is_ul_frame_counter_fixed == false) { @@ -896,19 +894,19 @@ void LoRaMac::on_mac_state_check_timer_event(void) } if ((_params.is_ack_retry_timeout_expired == true) && - ((_params.mac_state & LORAMAC_TX_DELAYED) == 0)) { + ((_params.mac_state & LORAMAC_TX_DELAYED) == 0)) { // Retransmissions procedure for confirmed uplinks _params.is_ack_retry_timeout_expired = false; if ((_params.ack_timeout_retry_counter < _params.max_ack_timeout_retries) && - (_params.ack_timeout_retry_counter <= MAX_ACK_RETRIES)) { + (_params.ack_timeout_retry_counter <= MAX_ACK_RETRIES)) { _params.ack_timeout_retry_counter++; if ((_params.ack_timeout_retry_counter % 2) == 1) { get_phy.attribute = PHY_NEXT_LOWER_TX_DR; get_phy.datarate = _params.sys_params.channel_data_rate; - phy_param = lora_phy->get_phy_params( &get_phy ); + phy_param = lora_phy->get_phy_params(&get_phy); _params.sys_params.channel_data_rate = phy_param.value; } @@ -980,7 +978,7 @@ void LoRaMac::on_mac_state_check_timer_event(void) if (_params.flags.bits.mcps_ind == 1) { _params.flags.bits.mcps_ind = 0; - if (_params.dev_class== CLASS_C) { + if (_params.dev_class == CLASS_C) { // Activate RX2 window for Class C open_continuous_rx2_window(); } @@ -1009,8 +1007,8 @@ void LoRaMac::on_tx_delayed_timer_event(void) _lora_time.stop(_params.timers.tx_delayed_timer); _params.mac_state &= ~LORAMAC_TX_DELAYED; - if ((_params.flags.bits.mlme_req == 1 ) && - (mlme.get_confirmation().req_type == MLME_JOIN)) { + if ((_params.flags.bits.mlme_req == 1) && + (mlme.get_confirmation().req_type == MLME_JOIN)) { reset_mac_parameters(); @@ -1052,7 +1050,7 @@ void LoRaMac::on_rx_window1_timer_event(void) } lora_phy->rx_config(&_params.rx_window1_config, - (int8_t*) &mcps.get_indication().rx_datarate); + (int8_t *) &mcps.get_indication().rx_datarate); rx_window_setup(_params.rx_window1_config.is_rx_continuous, _params.sys_params.max_rx_win_time); @@ -1076,7 +1074,7 @@ void LoRaMac::on_rx_window2_timer_event(void) } if (lora_phy->rx_config(&_params.rx_window2_config, - (int8_t*) &mcps.get_indication().rx_datarate) == true) { + (int8_t *) &mcps.get_indication().rx_datarate) == true) { rx_window_setup(_params.rx_window2_config.is_rx_continuous, _params.sys_params.max_rx_win_time); @@ -1127,7 +1125,7 @@ bool LoRaMac::validate_payload_length(uint8_t length, int8_t datarate, // Validation of the application payload size if ((payloadSize <= max_value) && - (payloadSize <= LORAMAC_PHY_MAXPAYLOAD)) { + (payloadSize <= LORAMAC_PHY_MAXPAYLOAD)) { return true; } return false; @@ -1214,7 +1212,7 @@ lorawan_status_t LoRaMac::schedule_tx(void) // Compute Rx1 windows parameters uint8_t dr_offset = lora_phy->apply_DR_offset(_params.sys_params.channel_data_rate, - _params.sys_params.rx1_dr_offset); + _params.sys_params.rx1_dr_offset); lora_phy->compute_rx_win_params(dr_offset, _params.sys_params.min_rx_symb, _params.sys_params.max_sys_rx_error, @@ -1228,9 +1226,9 @@ lorawan_status_t LoRaMac::schedule_tx(void) if (_params.is_nwk_joined == false) { _params.rx_window1_delay = _params.sys_params.join_accept_delay1 - + _params.rx_window1_config.window_offset; + + _params.rx_window1_config.window_offset; _params.rx_window2_delay = _params.sys_params.join_accept_delay2 - + _params.rx_window2_config.window_offset; + + _params.rx_window2_config.window_offset; } else { if (validate_payload_length(_params.payload_length, _params.sys_params.channel_data_rate, @@ -1238,9 +1236,9 @@ lorawan_status_t LoRaMac::schedule_tx(void) return LORAWAN_STATUS_LENGTH_ERROR; } _params.rx_window1_delay = _params.sys_params.recv_delay1 - + _params.rx_window1_config.window_offset; + + _params.rx_window1_config.window_offset; _params.rx_window2_delay = _params.sys_params.recv_delay2 - + _params.rx_window2_config.window_offset; + + _params.rx_window2_config.window_offset; } // Schedule transmission of frame @@ -1275,8 +1273,8 @@ void LoRaMac::calculate_backOff(uint8_t channel) // Update aggregated time-off _params.timers.aggregated_timeoff = _params.timers.aggregated_timeoff - + (_params.timers.tx_toa * _params.sys_params.aggregated_duty_cycle - - _params.timers.tx_toa); + + (_params.timers.tx_toa * _params.sys_params.aggregated_duty_cycle + - _params.timers.tx_toa); } void LoRaMac::reset_mac_parameters(void) @@ -1353,7 +1351,7 @@ void LoRaMac::reset_mac_parameters(void) _params.last_channel_idx = _params.channel; } -bool LoRaMac::is_fPort_allowed (uint8_t fPort) +bool LoRaMac::is_fPort_allowed(uint8_t fPort) { if ((fPort == 0) || (fPort > 224)) { return false; @@ -1361,7 +1359,7 @@ bool LoRaMac::is_fPort_allowed (uint8_t fPort) return true; } -void LoRaMac::open_continuous_rx2_window (void) +void LoRaMac::open_continuous_rx2_window(void) { handle_rx2_timer_event(); _params.rx_slot = RX_SLOT_WIN_CLASS_C; @@ -1384,7 +1382,7 @@ lorawan_status_t LoRaMac::prepare_frame(loramac_mhdr_t *machdr, uint16_t i; uint8_t pkt_header_len = 0; uint32_t mic = 0; - const void* payload = fbuffer; + const void *payload = fbuffer; uint8_t frame_port = fport; lorawan_status_t status = LORAWAN_STATUS_OK; @@ -1418,8 +1416,8 @@ lorawan_status_t LoRaMac::prepare_frame(loramac_mhdr_t *machdr, _params.buffer[_params.buffer_pkt_len++] = (_params.dev_nonce >> 8) & 0xFF; if (0 != compute_join_frame_mic(_params.buffer, - _params.buffer_pkt_len & 0xFF, - _params.keys.app_key, &mic)) { + _params.buffer_pkt_len & 0xFF, + _params.keys.app_key, &mic)) { return LORAWAN_STATUS_CRYPTO_FAIL; } @@ -1431,119 +1429,119 @@ lorawan_status_t LoRaMac::prepare_frame(loramac_mhdr_t *machdr, break; case FRAME_TYPE_DATA_CONFIRMED_UP: _params.is_node_ack_requested = true; - //Intentional fallthrough + //Intentional fallthrough case FRAME_TYPE_DATA_UNCONFIRMED_UP: { - if (_params.is_nwk_joined == false) { - // No network has been joined yet - return LORAWAN_STATUS_NO_NETWORK_JOINED; - } + if (_params.is_nwk_joined == false) { + // No network has been joined yet + return LORAWAN_STATUS_NO_NETWORK_JOINED; + } - if (_params.sys_params.adr_on) { - if (lora_phy->get_next_ADR(true, - _params.sys_params.channel_data_rate, - _params.sys_params.channel_tx_power, - _params.adr_ack_counter)) { - fctrl->bits.adr_ack_req = 1; + if (_params.sys_params.adr_on) { + if (lora_phy->get_next_ADR(true, + _params.sys_params.channel_data_rate, + _params.sys_params.channel_tx_power, + _params.adr_ack_counter)) { + fctrl->bits.adr_ack_req = 1; + } } - } - if (_params.is_srv_ack_requested == true) { - _params.is_srv_ack_requested = false; - fctrl->bits.ack = 1; - } + if (_params.is_srv_ack_requested == true) { + _params.is_srv_ack_requested = false; + fctrl->bits.ack = 1; + } - _params.buffer[pkt_header_len++] = (_params.dev_addr) & 0xFF; - _params.buffer[pkt_header_len++] = (_params.dev_addr >> 8) & 0xFF; - _params.buffer[pkt_header_len++] = (_params.dev_addr >> 16) & 0xFF; - _params.buffer[pkt_header_len++] = (_params.dev_addr >> 24) & 0xFF; + _params.buffer[pkt_header_len++] = (_params.dev_addr) & 0xFF; + _params.buffer[pkt_header_len++] = (_params.dev_addr >> 8) & 0xFF; + _params.buffer[pkt_header_len++] = (_params.dev_addr >> 16) & 0xFF; + _params.buffer[pkt_header_len++] = (_params.dev_addr >> 24) & 0xFF; - _params.buffer[pkt_header_len++] = fctrl->value; + _params.buffer[pkt_header_len++] = fctrl->value; - _params.buffer[pkt_header_len++] = _params.ul_frame_counter & 0xFF; - _params.buffer[pkt_header_len++] = (_params.ul_frame_counter >> 8) - & 0xFF; + _params.buffer[pkt_header_len++] = _params.ul_frame_counter & 0xFF; + _params.buffer[pkt_header_len++] = (_params.ul_frame_counter >> 8) + & 0xFF; - // Copy the MAC commands which must be re-send into the MAC command buffer - mac_commands.copy_repeat_commands_to_buffer(); + // Copy the MAC commands which must be re-send into the MAC command buffer + mac_commands.copy_repeat_commands_to_buffer(); - const uint8_t mac_commands_len = mac_commands.get_mac_cmd_length(); + const uint8_t mac_commands_len = mac_commands.get_mac_cmd_length(); - if ((payload != NULL) && (_params.payload_length > 0)) { - if (mac_commands.is_mac_command_in_next_tx() == true) { - if (mac_commands_len <= LORA_MAC_COMMAND_MAX_FOPTS_LENGTH) { - fctrl->bits.fopts_len += mac_commands_len; + if ((payload != NULL) && (_params.payload_length > 0)) { + if (mac_commands.is_mac_command_in_next_tx() == true) { + if (mac_commands_len <= LORA_MAC_COMMAND_MAX_FOPTS_LENGTH) { + fctrl->bits.fopts_len += mac_commands_len; - // Update FCtrl field with new value of OptionsLength - _params.buffer[0x05] = fctrl->value; + // Update FCtrl field with new value of OptionsLength + _params.buffer[0x05] = fctrl->value; - const uint8_t *buffer = + const uint8_t *buffer = mac_commands.get_mac_commands_buffer(); - for (i = 0; i < mac_commands_len; i++) { - _params.buffer[pkt_header_len++] = buffer[i]; + for (i = 0; i < mac_commands_len; i++) { + _params.buffer[pkt_header_len++] = buffer[i]; + } + } else { + _params.payload_length = mac_commands_len; + payload = mac_commands.get_mac_commands_buffer(); + frame_port = 0; } - } else { + } + } else { + if ((mac_commands_len > 0) + && (mac_commands.is_mac_command_in_next_tx() == true)) { _params.payload_length = mac_commands_len; payload = mac_commands.get_mac_commands_buffer(); frame_port = 0; } } - } else { - if ((mac_commands_len > 0) - && (mac_commands.is_mac_command_in_next_tx() == true)) { - _params.payload_length = mac_commands_len; - payload = mac_commands.get_mac_commands_buffer(); - frame_port = 0; - } - } - // Store MAC commands which must be re-send in case the device does not receive a downlink anymore - mac_commands.parse_mac_commands_to_repeat(); + // Store MAC commands which must be re-send in case the device does not receive a downlink anymore + mac_commands.parse_mac_commands_to_repeat(); - if ((payload != NULL) && (_params.payload_length > 0)) { - _params.buffer[pkt_header_len++] = frame_port; + if ((payload != NULL) && (_params.payload_length > 0)) { + _params.buffer[pkt_header_len++] = frame_port; - if (frame_port == 0) { - // Reset buffer index as the mac commands are being sent on port 0 - mac_commands.clear_command_buffer(); - if (0 != encrypt_payload((uint8_t*) payload, _params.payload_length, - _params.keys.nwk_skey, _params.dev_addr, - UP_LINK, - _params.ul_frame_counter, - &_params.buffer[pkt_header_len])) { - status = LORAWAN_STATUS_CRYPTO_FAIL; - } - } else { - if (0 != encrypt_payload((uint8_t*) payload, _params.payload_length, - _params.keys.app_skey, _params.dev_addr, - UP_LINK, - _params.ul_frame_counter, - &_params.buffer[pkt_header_len])) { - status = LORAWAN_STATUS_CRYPTO_FAIL; + if (frame_port == 0) { + // Reset buffer index as the mac commands are being sent on port 0 + mac_commands.clear_command_buffer(); + if (0 != encrypt_payload((uint8_t *) payload, _params.payload_length, + _params.keys.nwk_skey, _params.dev_addr, + UP_LINK, + _params.ul_frame_counter, + &_params.buffer[pkt_header_len])) { + status = LORAWAN_STATUS_CRYPTO_FAIL; + } + } else { + if (0 != encrypt_payload((uint8_t *) payload, _params.payload_length, + _params.keys.app_skey, _params.dev_addr, + UP_LINK, + _params.ul_frame_counter, + &_params.buffer[pkt_header_len])) { + status = LORAWAN_STATUS_CRYPTO_FAIL; + } } } - } - _params.buffer_pkt_len = pkt_header_len + _params.payload_length; + _params.buffer_pkt_len = pkt_header_len + _params.payload_length; - if (0 != compute_mic(_params.buffer, _params.buffer_pkt_len, - _params.keys.nwk_skey, - _params.dev_addr, - UP_LINK, - _params.ul_frame_counter, &mic)) { - status = LORAWAN_STATUS_CRYPTO_FAIL; - } + if (0 != compute_mic(_params.buffer, _params.buffer_pkt_len, + _params.keys.nwk_skey, + _params.dev_addr, + UP_LINK, + _params.ul_frame_counter, &mic)) { + status = LORAWAN_STATUS_CRYPTO_FAIL; + } - _params.buffer[_params.buffer_pkt_len + 0] = mic & 0xFF; - _params.buffer[_params.buffer_pkt_len + 1] = (mic >> 8) & 0xFF; - _params.buffer[_params.buffer_pkt_len + 2] = (mic >> 16) & 0xFF; - _params.buffer[_params.buffer_pkt_len + 3] = (mic >> 24) & 0xFF; + _params.buffer[_params.buffer_pkt_len + 0] = mic & 0xFF; + _params.buffer[_params.buffer_pkt_len + 1] = (mic >> 8) & 0xFF; + _params.buffer[_params.buffer_pkt_len + 2] = (mic >> 16) & 0xFF; + _params.buffer[_params.buffer_pkt_len + 3] = (mic >> 24) & 0xFF; - _params.buffer_pkt_len += LORAMAC_MFR_LEN; - } + _params.buffer_pkt_len += LORAMAC_MFR_LEN; + } break; case FRAME_TYPE_PROPRIETARY: if ((fbuffer != NULL) && (_params.payload_length > 0)) { - memcpy(_params.buffer + pkt_header_len, (uint8_t*) fbuffer, + memcpy(_params.buffer + pkt_header_len, (uint8_t *) fbuffer, _params.payload_length); _params.buffer_pkt_len = pkt_header_len + _params.payload_length; } @@ -1618,8 +1616,8 @@ lorawan_status_t LoRaMac::set_tx_continuous_wave(uint16_t timeout) } lorawan_status_t LoRaMac::set_tx_continuous_wave1(uint16_t timeout, - uint32_t frequency, - uint8_t power) + uint32_t frequency, + uint8_t power) { cw_mode_params_t continuous_wave; @@ -1808,13 +1806,13 @@ void LoRaMac::disconnect() } lorawan_status_t LoRaMac::query_tx_possible(uint8_t size, - loramac_tx_info_t* tx_info) + loramac_tx_info_t *tx_info) { get_phy_params_t get_phy; phy_param_t phy_param; uint8_t fopt_len = mac_commands.get_mac_cmd_length() - + mac_commands.get_repeat_commands_length(); + + mac_commands.get_repeat_commands_length(); if (tx_info == NULL) { return LORAWAN_STATUS_PARAMETER_INVALID; @@ -1858,7 +1856,7 @@ lorawan_status_t LoRaMac::query_tx_possible(uint8_t size, return LORAWAN_STATUS_OK; } -lorawan_status_t LoRaMac::add_channel_plan(const lorawan_channelplan_t& plan) +lorawan_status_t LoRaMac::add_channel_plan(const lorawan_channelplan_t &plan) { // Validate if the MAC is in a correct state if ((_params.mac_state & LORAMAC_TX_RUNNING) == LORAMAC_TX_RUNNING) { @@ -1882,7 +1880,7 @@ lorawan_status_t LoRaMac::remove_channel_plan() } -lorawan_status_t LoRaMac::get_channel_plan(lorawan_channelplan_t& plan) +lorawan_status_t LoRaMac::get_channel_plan(lorawan_channelplan_t &plan) { return channel_plan.get_plan(plan, &_params); } @@ -1928,7 +1926,7 @@ lorawan_status_t LoRaMac::multicast_channel_link(multicast_params_t *channel_par } lorawan_status_t LoRaMac::multicast_channel_unlink( - multicast_params_t *channel_param) + multicast_params_t *channel_param) { if (channel_param == NULL) { return LORAWAN_STATUS_PARAMETER_INVALID; @@ -1959,12 +1957,12 @@ lorawan_status_t LoRaMac::multicast_channel_unlink( return LORAWAN_STATUS_OK; } -lorawan_status_t LoRaMac::mlme_request( loramac_mlme_req_t *mlmeRequest ) +lorawan_status_t LoRaMac::mlme_request(loramac_mlme_req_t *mlmeRequest) { return mlme.set_request(mlmeRequest, &_params); } -lorawan_status_t LoRaMac::mcps_request( loramac_mcps_req_t *mcpsRequest ) +lorawan_status_t LoRaMac::mcps_request(loramac_mcps_req_t *mcpsRequest) { if (_params.mac_state != LORAMAC_IDLE) { return LORAWAN_STATUS_BUSY; @@ -1973,12 +1971,12 @@ lorawan_status_t LoRaMac::mcps_request( loramac_mcps_req_t *mcpsRequest ) return mcps.set_request(mcpsRequest, &_params); } -lorawan_status_t LoRaMac::mib_get_request_confirm( loramac_mib_req_confirm_t *mibGet ) +lorawan_status_t LoRaMac::mib_get_request_confirm(loramac_mib_req_confirm_t *mibGet) { return mib.get_request(mibGet, &_params); } -lorawan_status_t LoRaMac::mib_set_request_confirm( loramac_mib_req_confirm_t *mibSet ) +lorawan_status_t LoRaMac::mib_set_request_confirm(loramac_mib_req_confirm_t *mibSet) { return mib.set_request(mibSet, &_params); } @@ -1999,42 +1997,41 @@ radio_events_t *LoRaMac::get_phy_event_handlers() * Compliance testing * **************************************************************************/ -lorawan_status_t LoRaMac::LoRaMacSetTxTimer( uint32_t TxDutyCycleTime ) +lorawan_status_t LoRaMac::LoRaMacSetTxTimer(uint32_t TxDutyCycleTime) { _lora_time.start(tx_next_packet_timer, TxDutyCycleTime); return LORAWAN_STATUS_OK; } - lorawan_status_t LoRaMac::LoRaMacStopTxTimer( ) +lorawan_status_t LoRaMac::LoRaMacStopTxTimer() { _lora_time.stop(tx_next_packet_timer); return LORAWAN_STATUS_OK; } -void LoRaMac::LoRaMacTestRxWindowsOn( bool enable ) +void LoRaMac::LoRaMacTestRxWindowsOn(bool enable) { _params.is_rx_window_enabled = enable; } -void LoRaMac::LoRaMacTestSetMic( uint16_t txPacketCounter ) +void LoRaMac::LoRaMacTestSetMic(uint16_t txPacketCounter) { _params.ul_frame_counter = txPacketCounter; _params.is_ul_frame_counter_fixed = true; } -void LoRaMac::LoRaMacTestSetDutyCycleOn( bool enable ) +void LoRaMac::LoRaMacTestSetDutyCycleOn(bool enable) { VerifyParams_t verify; verify.DutyCycle = enable; - if(lora_phy->verify(&verify, PHY_DUTY_CYCLE) == true) - { + if (lora_phy->verify(&verify, PHY_DUTY_CYCLE) == true) { _params.is_dutycycle_on = enable; } } -void LoRaMac::LoRaMacTestSetChannel( uint8_t channel ) +void LoRaMac::LoRaMacTestSetChannel(uint8_t channel) { _params.channel = channel; } diff --git a/features/lorawan/lorastack/mac/LoRaMac.h b/features/lorawan/lorastack/mac/LoRaMac.h index b1676f84890..b74698de864 100644 --- a/features/lorawan/lorastack/mac/LoRaMac.h +++ b/features/lorawan/lorastack/mac/LoRaMac.h @@ -116,7 +116,7 @@ class LoRaMac { * If the query is valid, and the LoRaMAC is able to send the frame, * the function returns \ref LORAWAN_STATUS_OK. */ - lorawan_status_t query_tx_possible(uint8_t size, loramac_tx_info_t* tx_info); + lorawan_status_t query_tx_possible(uint8_t size, loramac_tx_info_t *tx_info); /** * @brief Adds a channel plan to the system. @@ -134,7 +134,7 @@ class LoRaMac { * \ref LORAWAN_STATUS_BUSY * \ref LORAWAN_STATUS_PARAMETER_INVALID */ - lorawan_status_t add_channel_plan(const lorawan_channelplan_t& plan); + lorawan_status_t add_channel_plan(const lorawan_channelplan_t &plan); /** * @brief Removes a channel plan from the system. @@ -165,7 +165,7 @@ class LoRaMac { * \ref LORAWAN_STATUS_BUSY * \ref LORAWAN_STATUS_PARAMETER_INVALID */ - lorawan_status_t get_channel_plan(lorawan_channelplan_t& plan); + lorawan_status_t get_channel_plan(lorawan_channelplan_t &plan); /** * @brief Remove a given channel from the active plan. @@ -441,7 +441,7 @@ class LoRaMac { * \ref LORAWAN_STATUS_OK * \ref LORAWAN_STATUS_PARAMETER_INVALID */ - lorawan_status_t LoRaMacSetTxTimer( uint32_t NextTxTime ); + lorawan_status_t LoRaMacSetTxTimer(uint32_t NextTxTime); /** * \brief LoRaMAC stop tx timer. @@ -452,7 +452,7 @@ class LoRaMac { * \ref LORAWAN_STATUS_OK * \ref LORAWAN_STATUS_PARAMETER_INVALID */ - lorawan_status_t LoRaMacStopTxTimer( ); + lorawan_status_t LoRaMacStopTxTimer(); /** * \brief Enabled or disables the reception windows @@ -462,7 +462,7 @@ class LoRaMac { * * \param [in] enable - Enabled or disables the reception windows */ - void LoRaMacTestRxWindowsOn( bool enable ); + void LoRaMacTestRxWindowsOn(bool enable); /** * \brief Enables the MIC field test @@ -472,7 +472,7 @@ class LoRaMac { * * \param [in] txPacketCounter - Fixed Tx packet counter value */ - void LoRaMacTestSetMic( uint16_t txPacketCounter ); + void LoRaMacTestSetMic(uint16_t txPacketCounter); /** * \brief Enabled or disables the duty cycle @@ -482,7 +482,7 @@ class LoRaMac { * * \param [in] enable - Enabled or disables the duty cycle */ - void LoRaMacTestSetDutyCycleOn( bool enable ); + void LoRaMacTestSetDutyCycleOn(bool enable); /** * \brief Sets the channel index @@ -492,7 +492,7 @@ class LoRaMac { * * \param [in] channel - Channel index */ - void LoRaMacTestSetChannel( uint8_t channel ); + void LoRaMacTestSetChannel(uint8_t channel); private: /** diff --git a/features/lorawan/lorastack/mac/LoRaMacChannelPlan.cpp b/features/lorawan/lorastack/mac/LoRaMacChannelPlan.cpp index 584207de445..9aa2f89bd61 100644 --- a/features/lorawan/lorastack/mac/LoRaMacChannelPlan.cpp +++ b/features/lorawan/lorastack/mac/LoRaMacChannelPlan.cpp @@ -39,7 +39,7 @@ void LoRaMacChannelPlan::activate_channelplan_subsystem(LoRaPHY *phy, LoRaMacMib _mib = mib; } -lorawan_status_t LoRaMacChannelPlan::set_plan(const lorawan_channelplan_t& plan) +lorawan_status_t LoRaMacChannelPlan::set_plan(const lorawan_channelplan_t &plan) { channel_params_t mac_layer_ch_params; lorawan_status_t status; @@ -86,8 +86,8 @@ lorawan_status_t LoRaMacChannelPlan::set_plan(const lorawan_channelplan_t& plan) return LORAWAN_STATUS_OK; } -lorawan_status_t LoRaMacChannelPlan::get_plan(lorawan_channelplan_t& plan, - loramac_protocol_params *params) +lorawan_status_t LoRaMacChannelPlan::get_plan(lorawan_channelplan_t &plan, + loramac_protocol_params *params) { if (params == NULL) { return LORAWAN_STATUS_PARAMETER_INVALID; diff --git a/features/lorawan/lorastack/mac/LoRaMacChannelPlan.h b/features/lorawan/lorastack/mac/LoRaMacChannelPlan.h index adf880de641..032167762d3 100644 --- a/features/lorawan/lorastack/mac/LoRaMacChannelPlan.h +++ b/features/lorawan/lorastack/mac/LoRaMacChannelPlan.h @@ -56,7 +56,7 @@ class LoRaMacChannelPlan { * @param phy pointer to PHY layer * @param mib pointer to MIB subsystem */ - void activate_channelplan_subsystem(LoRaPHY *phy,LoRaMacMib *mib); + void activate_channelplan_subsystem(LoRaPHY *phy, LoRaMacMib *mib); /** Set a given channel plan * @@ -69,7 +69,7 @@ class LoRaMacChannelPlan { * @return LORAWAN_STATUS_OK if everything goes well otherwise * a negative error code is returned. */ - lorawan_status_t set_plan(const lorawan_channelplan_t& plan); + lorawan_status_t set_plan(const lorawan_channelplan_t &plan); /** Access the active channel plan * @@ -83,7 +83,7 @@ class LoRaMacChannelPlan { * @return LORAWAN_STATUS_OK if everything goes well otherwise * a negative error code is returned. */ - lorawan_status_t get_plan(lorawan_channelplan_t& plan, loramac_protocol_params *params); + lorawan_status_t get_plan(lorawan_channelplan_t &plan, loramac_protocol_params *params); /** Remove the active channel plan * @@ -109,7 +109,7 @@ class LoRaMacChannelPlan { * Local handles */ LoRaPHY *_lora_phy; - LoRaMacMib * _mib; + LoRaMacMib *_mib; }; diff --git a/features/lorawan/lorastack/mac/LoRaMacCommand.cpp b/features/lorawan/lorastack/mac/LoRaMacCommand.cpp index 0fc3356de36..210f5e9c508 100644 --- a/features/lorawan/lorastack/mac/LoRaMacCommand.cpp +++ b/features/lorawan/lorastack/mac/LoRaMacCommand.cpp @@ -39,7 +39,7 @@ SPDX-License-Identifier: BSD-3-Clause static const uint8_t max_eirp_table[] = { 8, 10, 12, 13, 14, 16, 18, 20, 21, 24, 26, 27, 29, 30, 33, 36 }; -LoRaMacCommand::LoRaMacCommand(LoRaMac& lora_mac) +LoRaMacCommand::LoRaMacCommand(LoRaMac &lora_mac) : _lora_mac(lora_mac) { mac_cmd_in_next_tx = false; @@ -55,12 +55,12 @@ LoRaMacCommand::~LoRaMacCommand() } lorawan_status_t LoRaMacCommand::add_mac_command(uint8_t cmd, uint8_t p1, - uint8_t p2) + uint8_t p2) { lorawan_status_t status = LORAWAN_STATUS_BUSY; // The maximum buffer length must take MAC commands to re-send into account. const uint8_t bufLen = LORA_MAC_COMMAND_MAX_LENGTH - - mac_cmd_buf_idx_to_repeat; + - mac_cmd_buf_idx_to_repeat; switch (cmd) { case MOTE_MAC_LINK_CHECK_REQ: @@ -173,29 +173,29 @@ void LoRaMacCommand::parse_mac_commands_to_repeat() // STICKY case MOTE_MAC_DL_CHANNEL_ANS: case MOTE_MAC_RX_PARAM_SETUP_ANS: { // 1 byte payload - mac_cmd_buffer_to_repeat[cmd_cnt++] = mac_cmd_buffer[i++]; - mac_cmd_buffer_to_repeat[cmd_cnt++] = mac_cmd_buffer[i]; - break; - } + mac_cmd_buffer_to_repeat[cmd_cnt++] = mac_cmd_buffer[i++]; + mac_cmd_buffer_to_repeat[cmd_cnt++] = mac_cmd_buffer[i]; + break; + } case MOTE_MAC_RX_TIMING_SETUP_ANS: { // 0 byte payload - mac_cmd_buffer_to_repeat[cmd_cnt++] = mac_cmd_buffer[i]; - break; - } - // NON-STICKY + mac_cmd_buffer_to_repeat[cmd_cnt++] = mac_cmd_buffer[i]; + break; + } + // NON-STICKY case MOTE_MAC_DEV_STATUS_ANS: { // 2 bytes payload - i += 2; - break; - } + i += 2; + break; + } case MOTE_MAC_LINK_ADR_ANS: case MOTE_MAC_NEW_CHANNEL_ANS: { // 1 byte payload - i++; - break; - } + i++; + break; + } case MOTE_MAC_TX_PARAM_SETUP_ANS: case MOTE_MAC_DUTY_CYCLE_ANS: case MOTE_MAC_LINK_CHECK_REQ: { // 0 byte payload - break; - } + break; + } default: break; } @@ -237,12 +237,12 @@ bool LoRaMacCommand::is_mac_command_in_next_tx() const } lorawan_status_t LoRaMacCommand::process_mac_commands(uint8_t *payload, - uint8_t mac_index, - uint8_t commands_size, - uint8_t snr, - loramac_mlme_confirm_t& mlme_conf, - lora_mac_system_params_t &mac_sys_params, - LoRaPHY &lora_phy) + uint8_t mac_index, + uint8_t commands_size, + uint8_t snr, + loramac_mlme_confirm_t &mlme_conf, + lora_mac_system_params_t &mac_sys_params, + LoRaPHY &lora_phy) { uint8_t status = 0; lorawan_status_t ret_value = LORAWAN_STATUS_OK; @@ -256,41 +256,41 @@ lorawan_status_t LoRaMacCommand::process_mac_commands(uint8_t *payload, mlme_conf.nb_gateways = payload[mac_index++]; break; case SRV_MAC_LINK_ADR_REQ: { - adr_req_params_t linkAdrReq; - int8_t linkAdrDatarate = DR_0; - int8_t linkAdrTxPower = TX_POWER_0; - uint8_t linkAdrNbRep = 0; - uint8_t linkAdrNbBytesParsed = 0; - - // Fill parameter structure - linkAdrReq.payload = &payload[mac_index - 1]; - linkAdrReq.payload_size = commands_size - (mac_index - 1); - linkAdrReq.adr_enabled = mac_sys_params.adr_on; - linkAdrReq.ul_dwell_time = mac_sys_params.uplink_dwell_time; - linkAdrReq.current_datarate = mac_sys_params.channel_data_rate; - linkAdrReq.current_tx_power = mac_sys_params.channel_tx_power; - linkAdrReq.current_nb_rep = mac_sys_params.retry_num; - - // Process the ADR requests - status = lora_phy.link_ADR_request(&linkAdrReq, - &linkAdrDatarate, - &linkAdrTxPower, - &linkAdrNbRep, - &linkAdrNbBytesParsed); - - if ((status & 0x07) == 0x07) { - mac_sys_params.channel_data_rate = linkAdrDatarate; - mac_sys_params.channel_tx_power = linkAdrTxPower; - mac_sys_params.retry_num = linkAdrNbRep; - } - - // Add the answers to the buffer - for (uint8_t i = 0; i < (linkAdrNbBytesParsed / 5); i++) { - ret_value = add_mac_command(MOTE_MAC_LINK_ADR_ANS, status, 0); + adr_req_params_t linkAdrReq; + int8_t linkAdrDatarate = DR_0; + int8_t linkAdrTxPower = TX_POWER_0; + uint8_t linkAdrNbRep = 0; + uint8_t linkAdrNbBytesParsed = 0; + + // Fill parameter structure + linkAdrReq.payload = &payload[mac_index - 1]; + linkAdrReq.payload_size = commands_size - (mac_index - 1); + linkAdrReq.adr_enabled = mac_sys_params.adr_on; + linkAdrReq.ul_dwell_time = mac_sys_params.uplink_dwell_time; + linkAdrReq.current_datarate = mac_sys_params.channel_data_rate; + linkAdrReq.current_tx_power = mac_sys_params.channel_tx_power; + linkAdrReq.current_nb_rep = mac_sys_params.retry_num; + + // Process the ADR requests + status = lora_phy.link_ADR_request(&linkAdrReq, + &linkAdrDatarate, + &linkAdrTxPower, + &linkAdrNbRep, + &linkAdrNbBytesParsed); + + if ((status & 0x07) == 0x07) { + mac_sys_params.channel_data_rate = linkAdrDatarate; + mac_sys_params.channel_tx_power = linkAdrTxPower; + mac_sys_params.retry_num = linkAdrNbRep; + } + + // Add the answers to the buffer + for (uint8_t i = 0; i < (linkAdrNbBytesParsed / 5); i++) { + ret_value = add_mac_command(MOTE_MAC_LINK_ADR_ANS, status, 0); + } + // Update MAC index + mac_index += linkAdrNbBytesParsed - 1; } - // Update MAC index - mac_index += linkAdrNbBytesParsed - 1; - } break; case SRV_MAC_DUTY_CYCLE_REQ: mac_sys_params.max_duty_cycle = payload[mac_index++]; @@ -298,113 +298,113 @@ lorawan_status_t LoRaMacCommand::process_mac_commands(uint8_t *payload, ret_value = add_mac_command(MOTE_MAC_DUTY_CYCLE_ANS, 0, 0); break; case SRV_MAC_RX_PARAM_SETUP_REQ: { - rx_param_setup_req_t rxParamSetupReq; + rx_param_setup_req_t rxParamSetupReq; - rxParamSetupReq.dr_offset = (payload[mac_index] >> 4) & 0x07; - rxParamSetupReq.datarate = payload[mac_index] & 0x0F; - mac_index++; + rxParamSetupReq.dr_offset = (payload[mac_index] >> 4) & 0x07; + rxParamSetupReq.datarate = payload[mac_index] & 0x0F; + mac_index++; - rxParamSetupReq.frequency = (uint32_t) payload[mac_index++]; - rxParamSetupReq.frequency |= (uint32_t) payload[mac_index++] - << 8; - rxParamSetupReq.frequency |= (uint32_t) payload[mac_index++] - << 16; - rxParamSetupReq.frequency *= 100; + rxParamSetupReq.frequency = (uint32_t) payload[mac_index++]; + rxParamSetupReq.frequency |= (uint32_t) payload[mac_index++] + << 8; + rxParamSetupReq.frequency |= (uint32_t) payload[mac_index++] + << 16; + rxParamSetupReq.frequency *= 100; - // Perform request on region - status = lora_phy.accept_rx_param_setup_req(&rxParamSetupReq); + // Perform request on region + status = lora_phy.accept_rx_param_setup_req(&rxParamSetupReq); - if ((status & 0x07) == 0x07) { - mac_sys_params.rx2_channel.datarate = + if ((status & 0x07) == 0x07) { + mac_sys_params.rx2_channel.datarate = rxParamSetupReq.datarate; - mac_sys_params.rx2_channel.frequency = + mac_sys_params.rx2_channel.frequency = rxParamSetupReq.frequency; - mac_sys_params.rx1_dr_offset = rxParamSetupReq.dr_offset; + mac_sys_params.rx1_dr_offset = rxParamSetupReq.dr_offset; + } + ret_value = add_mac_command(MOTE_MAC_RX_PARAM_SETUP_ANS, status, + 0); } - ret_value = add_mac_command(MOTE_MAC_RX_PARAM_SETUP_ANS, status, - 0); - } break; case SRV_MAC_DEV_STATUS_REQ: { - uint8_t batteryLevel = BAT_LEVEL_NO_MEASURE; - // we don't have a mechanism at the moment to measure - // battery levels - ret_value = add_mac_command(MOTE_MAC_DEV_STATUS_ANS, - batteryLevel, snr); - break; - } + uint8_t batteryLevel = BAT_LEVEL_NO_MEASURE; + // we don't have a mechanism at the moment to measure + // battery levels + ret_value = add_mac_command(MOTE_MAC_DEV_STATUS_ANS, + batteryLevel, snr); + break; + } case SRV_MAC_NEW_CHANNEL_REQ: { - new_channel_req_params_t newChannelReq; - channel_params_t chParam; + new_channel_req_params_t newChannelReq; + channel_params_t chParam; - newChannelReq.channel_id = payload[mac_index++]; - newChannelReq.new_channel = &chParam; + newChannelReq.channel_id = payload[mac_index++]; + newChannelReq.new_channel = &chParam; - chParam.frequency = (uint32_t) payload[mac_index++]; - chParam.frequency |= (uint32_t) payload[mac_index++] << 8; - chParam.frequency |= (uint32_t) payload[mac_index++] << 16; - chParam.frequency *= 100; - chParam.rx1_frequency = 0; - chParam.dr_range.value = payload[mac_index++]; + chParam.frequency = (uint32_t) payload[mac_index++]; + chParam.frequency |= (uint32_t) payload[mac_index++] << 8; + chParam.frequency |= (uint32_t) payload[mac_index++] << 16; + chParam.frequency *= 100; + chParam.rx1_frequency = 0; + chParam.dr_range.value = payload[mac_index++]; - status = lora_phy.request_new_channel(&newChannelReq); + status = lora_phy.request_new_channel(&newChannelReq); - ret_value = add_mac_command(MOTE_MAC_NEW_CHANNEL_ANS, status, 0); - } + ret_value = add_mac_command(MOTE_MAC_NEW_CHANNEL_ANS, status, 0); + } break; case SRV_MAC_RX_TIMING_SETUP_REQ: { - uint8_t delay = payload[mac_index++] & 0x0F; - - if (delay == 0) { - delay++; + uint8_t delay = payload[mac_index++] & 0x0F; + + if (delay == 0) { + delay++; + } + mac_sys_params.recv_delay1 = delay * 1000; + mac_sys_params.recv_delay2 = mac_sys_params.recv_delay1 + 1000; + ret_value = add_mac_command(MOTE_MAC_RX_TIMING_SETUP_ANS, 0, 0); } - mac_sys_params.recv_delay1 = delay * 1000; - mac_sys_params.recv_delay2 = mac_sys_params.recv_delay1 + 1000; - ret_value = add_mac_command(MOTE_MAC_RX_TIMING_SETUP_ANS, 0, 0); - } break; case SRV_MAC_TX_PARAM_SETUP_REQ: { - tx_param_setup_req_t txParamSetupReq; - uint8_t eirpDwellTime = payload[mac_index++]; - - txParamSetupReq.ul_dwell_time = 0; - txParamSetupReq.dl_dwell_time = 0; - - if ((eirpDwellTime & 0x20) == 0x20) { - txParamSetupReq.dl_dwell_time = 1; - } - if ((eirpDwellTime & 0x10) == 0x10) { - txParamSetupReq.ul_dwell_time = 1; - } - txParamSetupReq.max_eirp = eirpDwellTime & 0x0F; - - // Check the status for correctness - if (lora_phy.accept_tx_param_setup_req(&txParamSetupReq)) { - // Accept command - mac_sys_params.uplink_dwell_time = + tx_param_setup_req_t txParamSetupReq; + uint8_t eirpDwellTime = payload[mac_index++]; + + txParamSetupReq.ul_dwell_time = 0; + txParamSetupReq.dl_dwell_time = 0; + + if ((eirpDwellTime & 0x20) == 0x20) { + txParamSetupReq.dl_dwell_time = 1; + } + if ((eirpDwellTime & 0x10) == 0x10) { + txParamSetupReq.ul_dwell_time = 1; + } + txParamSetupReq.max_eirp = eirpDwellTime & 0x0F; + + // Check the status for correctness + if (lora_phy.accept_tx_param_setup_req(&txParamSetupReq)) { + // Accept command + mac_sys_params.uplink_dwell_time = txParamSetupReq.ul_dwell_time; - mac_sys_params.downlink_dwell_time = + mac_sys_params.downlink_dwell_time = txParamSetupReq.dl_dwell_time; - mac_sys_params.max_eirp = + mac_sys_params.max_eirp = max_eirp_table[txParamSetupReq.max_eirp]; - // Add command response - ret_value = add_mac_command(MOTE_MAC_TX_PARAM_SETUP_ANS, 0, 0); + // Add command response + ret_value = add_mac_command(MOTE_MAC_TX_PARAM_SETUP_ANS, 0, 0); + } } - } break; case SRV_MAC_DL_CHANNEL_REQ: { - dl_channel_req_params_t dlChannelReq; + dl_channel_req_params_t dlChannelReq; - dlChannelReq.channel_id = payload[mac_index++]; - dlChannelReq.rx1_frequency = (uint32_t) payload[mac_index++]; - dlChannelReq.rx1_frequency |= (uint32_t) payload[mac_index++] << 8; - dlChannelReq.rx1_frequency |= (uint32_t) payload[mac_index++] << 16; - dlChannelReq.rx1_frequency *= 100; + dlChannelReq.channel_id = payload[mac_index++]; + dlChannelReq.rx1_frequency = (uint32_t) payload[mac_index++]; + dlChannelReq.rx1_frequency |= (uint32_t) payload[mac_index++] << 8; + dlChannelReq.rx1_frequency |= (uint32_t) payload[mac_index++] << 16; + dlChannelReq.rx1_frequency *= 100; - status = lora_phy.dl_channel_request(&dlChannelReq); + status = lora_phy.dl_channel_request(&dlChannelReq); - ret_value = add_mac_command(MOTE_MAC_DL_CHANNEL_ANS, status, 0); - } + ret_value = add_mac_command(MOTE_MAC_DL_CHANNEL_ANS, status, 0); + } break; default: // Unknown command. ABORT MAC commands processing diff --git a/features/lorawan/lorastack/mac/LoRaMacCommand.h b/features/lorawan/lorastack/mac/LoRaMacCommand.h index 3aa54c633d2..3b07f2ee9ce 100644 --- a/features/lorawan/lorastack/mac/LoRaMacCommand.h +++ b/features/lorawan/lorastack/mac/LoRaMacCommand.h @@ -136,9 +136,9 @@ class LoRaMacCommand { */ lorawan_status_t process_mac_commands(uint8_t *payload, uint8_t mac_index, uint8_t commands_size, uint8_t snr, - loramac_mlme_confirm_t& mlme_conf, - lora_mac_system_params_t& mac_params, - LoRaPHY& lora_phy); + loramac_mlme_confirm_t &mlme_conf, + lora_mac_system_params_t &mac_params, + LoRaPHY &lora_phy); /** * @brief Verifies if sticky MAC commands are pending. @@ -148,7 +148,7 @@ class LoRaMacCommand { bool is_sticky_mac_command_pending(); private: - LoRaMac& _lora_mac; + LoRaMac &_lora_mac; /** * Indicates if the MAC layer wants to send MAC commands diff --git a/features/lorawan/lorastack/mac/LoRaMacCrypto.cpp b/features/lorawan/lorastack/mac/LoRaMacCrypto.cpp index 75deb841972..f93f007a190 100644 --- a/features/lorawan/lorastack/mac/LoRaMacCrypto.cpp +++ b/features/lorawan/lorastack/mac/LoRaMacCrypto.cpp @@ -42,7 +42,8 @@ * MIC field computation initial data */ static uint8_t mic_block_b0[] = {0x49, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + }; /** * Contains the computed MIC field. @@ -55,10 +56,12 @@ static uint8_t computed_mic[16]; * Encryption aBlock and sBlock */ static uint8_t a_block[] = {0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + }; static uint8_t s_block[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + }; /** * AES computation context variable @@ -95,39 +98,45 @@ int compute_mic(const uint8_t *buffer, uint16_t size, const uint8_t *key, mbedtls_cipher_init(aes_cmac_ctx); - const mbedtls_cipher_info_t* cipher_info = mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_128_ECB); + const mbedtls_cipher_info_t *cipher_info = mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_128_ECB); if (NULL != cipher_info) { ret = mbedtls_cipher_setup(aes_cmac_ctx, cipher_info); - if (0 != ret) + if (0 != ret) { goto exit; + } ret = mbedtls_cipher_cmac_starts(aes_cmac_ctx, key, AES_CMAC_KEY_LENGTH * 8); - if (0 != ret) + if (0 != ret) { goto exit; + } ret = mbedtls_cipher_cmac_update(aes_cmac_ctx, mic_block_b0, LORAMAC_MIC_BLOCK_B0_SIZE); - if (0 != ret) + if (0 != ret) { goto exit; + } ret = mbedtls_cipher_cmac_update(aes_cmac_ctx, buffer, size & 0xFF); - if (0 != ret) + if (0 != ret) { goto exit; + } ret = mbedtls_cipher_cmac_finish(aes_cmac_ctx, computed_mic); - if (0 != ret) + if (0 != ret) { goto exit; + } - *mic = (uint32_t) ((uint32_t) computed_mic[3] << 24 - | (uint32_t) computed_mic[2] << 16 - | (uint32_t) computed_mic[1] << 8 | (uint32_t) computed_mic[0]); + *mic = (uint32_t)((uint32_t) computed_mic[3] << 24 + | (uint32_t) computed_mic[2] << 16 + | (uint32_t) computed_mic[1] << 8 | (uint32_t) computed_mic[0]); } else { ret = MBEDTLS_ERR_CIPHER_ALLOC_FAILED; } -exit: mbedtls_cipher_free(aes_cmac_ctx); +exit: + mbedtls_cipher_free(aes_cmac_ctx); return ret; } @@ -142,8 +151,9 @@ int encrypt_payload(const uint8_t *buffer, uint16_t size, const uint8_t *key, mbedtls_aes_init(&aes_ctx); ret = mbedtls_aes_setkey_enc(&aes_ctx, key, 16 * 8); - if (0 != ret) + if (0 != ret) { goto exit; + } a_block[5] = dir; @@ -162,8 +172,9 @@ int encrypt_payload(const uint8_t *buffer, uint16_t size, const uint8_t *key, ctr++; ret = mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, a_block, s_block); - if (0 != ret) + if (0 != ret) { goto exit; + } for (i = 0; i < 16; i++) { enc_buffer[bufferIndex + i] = buffer[bufferIndex + i] ^ s_block[i]; @@ -176,15 +187,17 @@ int encrypt_payload(const uint8_t *buffer, uint16_t size, const uint8_t *key, a_block[15] = ((ctr) & 0xFF); ret = mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, a_block, s_block); - if (0 != ret) + if (0 != ret) { goto exit; + } for (i = 0; i < size; i++) { enc_buffer[bufferIndex + i] = buffer[bufferIndex + i] ^ s_block[i]; } } -exit: mbedtls_aes_free(&aes_ctx); +exit: + mbedtls_aes_free(&aes_ctx); return ret; } @@ -202,34 +215,39 @@ int compute_join_frame_mic(const uint8_t *buffer, uint16_t size, int ret = 0; mbedtls_cipher_init(aes_cmac_ctx); - const mbedtls_cipher_info_t* cipher_info = mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_128_ECB); + const mbedtls_cipher_info_t *cipher_info = mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_128_ECB); if (NULL != cipher_info) { ret = mbedtls_cipher_setup(aes_cmac_ctx, cipher_info); - if (0 != ret) + if (0 != ret) { goto exit; + } ret = mbedtls_cipher_cmac_starts(aes_cmac_ctx, key, AES_CMAC_KEY_LENGTH * 8); - if (0 != ret) + if (0 != ret) { goto exit; + } ret = mbedtls_cipher_cmac_update(aes_cmac_ctx, buffer, size & 0xFF); - if (0 != ret) + if (0 != ret) { goto exit; + } ret = mbedtls_cipher_cmac_finish(aes_cmac_ctx, computed_mic); - if (0 != ret) + if (0 != ret) { goto exit; + } - *mic = (uint32_t) ((uint32_t) computed_mic[3] << 24 - | (uint32_t) computed_mic[2] << 16 - | (uint32_t) computed_mic[1] << 8 | (uint32_t) computed_mic[0]); + *mic = (uint32_t)((uint32_t) computed_mic[3] << 24 + | (uint32_t) computed_mic[2] << 16 + | (uint32_t) computed_mic[1] << 8 | (uint32_t) computed_mic[0]); } else { ret = MBEDTLS_ERR_CIPHER_ALLOC_FAILED; } -exit: mbedtls_cipher_free(aes_cmac_ctx); +exit: + mbedtls_cipher_free(aes_cmac_ctx); return ret; } @@ -241,13 +259,15 @@ int decrypt_join_frame(const uint8_t *buffer, uint16_t size, const uint8_t *key, mbedtls_aes_init(&aes_ctx); ret = mbedtls_aes_setkey_enc(&aes_ctx, key, 16 * 8); - if (0 != ret) + if (0 != ret) { goto exit; + } ret = mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, buffer, dec_buffer); - if (0 != ret) + if (0 != ret) { goto exit; + } // Check if optional CFList is included if (size >= 16) { @@ -255,7 +275,8 @@ int decrypt_join_frame(const uint8_t *buffer, uint16_t size, const uint8_t *key, dec_buffer + 16); } -exit: mbedtls_aes_free(&aes_ctx); +exit: + mbedtls_aes_free(&aes_ctx); return ret; } @@ -270,16 +291,18 @@ int compute_skeys_for_join_frame(const uint8_t *key, const uint8_t *app_nonce, mbedtls_aes_init(&aes_ctx); ret = mbedtls_aes_setkey_enc(&aes_ctx, key, 16 * 8); - if (0 != ret) + if (0 != ret) { goto exit; + } memset(nonce, 0, sizeof(nonce)); nonce[0] = 0x01; memcpy(nonce + 1, app_nonce, 6); memcpy(nonce + 7, p_dev_nonce, 2); ret = mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, nonce, nwk_skey); - if (0 != ret) + if (0 != ret) { goto exit; + } memset(nonce, 0, sizeof(nonce)); nonce[0] = 0x02; @@ -287,7 +310,8 @@ int compute_skeys_for_join_frame(const uint8_t *key, const uint8_t *app_nonce, memcpy(nonce + 7, p_dev_nonce, 2); ret = mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, nonce, app_skey); - exit: mbedtls_aes_free(&aes_ctx); +exit: + mbedtls_aes_free(&aes_ctx); return ret; } #else @@ -296,7 +320,7 @@ int compute_skeys_for_join_frame(const uint8_t *key, const uint8_t *app_nonce, // user knows what is wrong and in addition to that these ensure that // Mbed-OS compiles properly under normal conditions where LoRaWAN in conjunction // with mbedTLS is not being used. -int compute_mic(const uint8_t *, uint16_t , const uint8_t *, uint32_t, +int compute_mic(const uint8_t *, uint16_t, const uint8_t *, uint32_t, uint8_t dir, uint32_t, uint32_t *) { MBED_ASSERT("[LoRaCrypto] Must enable AES, CMAC & CIPHER from mbedTLS"); @@ -305,8 +329,8 @@ int compute_mic(const uint8_t *, uint16_t , const uint8_t *, uint32_t, return LORAWAN_STATUS_CRYPTO_FAIL; } -int encrypt_payload(const uint8_t *, uint16_t , const uint8_t *, uint32_t, - uint8_t , uint32_t , uint8_t *) +int encrypt_payload(const uint8_t *, uint16_t, const uint8_t *, uint32_t, + uint8_t, uint32_t, uint8_t *) { MBED_ASSERT("[LoRaCrypto] Must enable AES, CMAC & CIPHER from mbedTLS"); @@ -314,8 +338,8 @@ int encrypt_payload(const uint8_t *, uint16_t , const uint8_t *, uint32_t, return LORAWAN_STATUS_CRYPTO_FAIL; } -int decrypt_payload(const uint8_t *, uint16_t , const uint8_t *, uint32_t, - uint8_t , uint32_t , uint8_t *) +int decrypt_payload(const uint8_t *, uint16_t, const uint8_t *, uint32_t, + uint8_t, uint32_t, uint8_t *) { MBED_ASSERT("[LoRaCrypto] Must enable AES, CMAC & CIPHER from mbedTLS"); @@ -323,7 +347,7 @@ int decrypt_payload(const uint8_t *, uint16_t , const uint8_t *, uint32_t, return LORAWAN_STATUS_CRYPTO_FAIL; } -int compute_join_frame_mic(const uint8_t *, uint16_t , const uint8_t *, uint32_t *) +int compute_join_frame_mic(const uint8_t *, uint16_t, const uint8_t *, uint32_t *) { MBED_ASSERT("[LoRaCrypto] Must enable AES, CMAC & CIPHER from mbedTLS"); @@ -331,7 +355,7 @@ int compute_join_frame_mic(const uint8_t *, uint16_t , const uint8_t *, uint32_t return LORAWAN_STATUS_CRYPTO_FAIL; } -int decrypt_join_frame(const uint8_t *, uint16_t , const uint8_t *, uint8_t *) +int decrypt_join_frame(const uint8_t *, uint16_t, const uint8_t *, uint8_t *) { MBED_ASSERT("[LoRaCrypto] Must enable AES, CMAC & CIPHER from mbedTLS"); @@ -339,7 +363,7 @@ int decrypt_join_frame(const uint8_t *, uint16_t , const uint8_t *, uint8_t *) return LORAWAN_STATUS_CRYPTO_FAIL; } -int compute_skeys_for_join_frame(const uint8_t *, const uint8_t *, uint16_t , +int compute_skeys_for_join_frame(const uint8_t *, const uint8_t *, uint16_t, uint8_t *, uint8_t *) { MBED_ASSERT("[LoRaCrypto] Must enable AES, CMAC & CIPHER from mbedTLS"); diff --git a/features/lorawan/lorastack/mac/LoRaMacCrypto.h b/features/lorawan/lorastack/mac/LoRaMacCrypto.h index af3fa75cff4..1435388fbeb 100644 --- a/features/lorawan/lorastack/mac/LoRaMacCrypto.h +++ b/features/lorawan/lorastack/mac/LoRaMacCrypto.h @@ -40,8 +40,8 @@ SPDX-License-Identifier: BSD-3-Clause * @return 0 if successful, or a cipher specific error code */ int compute_mic(const uint8_t *buffer, uint16_t size, const uint8_t *key, - uint32_t address, uint8_t dir, uint32_t seq_counter, - uint32_t *mic); + uint32_t address, uint8_t dir, uint32_t seq_counter, + uint32_t *mic); /** * Performs payload encryption @@ -89,7 +89,7 @@ int decrypt_payload(const uint8_t *buffer, uint16_t size, const uint8_t *key, * */ int compute_join_frame_mic(const uint8_t *buffer, uint16_t size, - const uint8_t *key, uint32_t *mic); + const uint8_t *key, uint32_t *mic); /** * Computes the LoRaMAC join frame decryption @@ -102,7 +102,7 @@ int compute_join_frame_mic(const uint8_t *buffer, uint16_t size, * @return 0 if successful, or a cipher specific error code */ int decrypt_join_frame(const uint8_t *buffer, uint16_t size, - const uint8_t *key, uint8_t *dec_buffer); + const uint8_t *key, uint8_t *dec_buffer); /** * Computes the LoRaMAC join frame decryption @@ -117,6 +117,6 @@ int decrypt_join_frame(const uint8_t *buffer, uint16_t size, */ int compute_skeys_for_join_frame(const uint8_t *key, const uint8_t *app_nonce, uint16_t dev_nonce, uint8_t *nwk_skey, - uint8_t *app_skey ); + uint8_t *app_skey); #endif // MBED_LORAWAN_MAC_LORAMAC_CRYPTO_H__ diff --git a/features/lorawan/lorastack/mac/LoRaMacMcps.cpp b/features/lorawan/lorastack/mac/LoRaMacMcps.cpp index c5331abd165..7e42bb6a480 100644 --- a/features/lorawan/lorastack/mac/LoRaMacMcps.cpp +++ b/features/lorawan/lorastack/mac/LoRaMacMcps.cpp @@ -27,7 +27,7 @@ SPDX-License-Identifier: BSD-3-Clause #include "lorastack/mac/LoRaMacMcps.h" LoRaMacMcps::LoRaMacMcps() -: _lora_mac(NULL), _lora_phy(NULL) + : _lora_mac(NULL), _lora_phy(NULL) { } @@ -42,7 +42,7 @@ void LoRaMacMcps::activate_mcps_subsystem(LoRaMac *mac, LoRaPHY *phy) } lorawan_status_t LoRaMacMcps::set_request(loramac_mcps_req_t *mcpsRequest, - loramac_protocol_params *params) + loramac_protocol_params *params) { if (mcpsRequest == NULL || _lora_phy == NULL || _lora_mac == NULL) { @@ -63,7 +63,7 @@ lorawan_status_t LoRaMacMcps::set_request(loramac_mcps_req_t *mcpsRequest, machdr.value = 0; // Before performing any MCPS request, clear the confirmation structure - memset((uint8_t*) &confirmation, 0, sizeof(confirmation)); + memset((uint8_t *) &confirmation, 0, sizeof(confirmation)); confirmation.status = LORAMAC_EVENT_INFO_STATUS_ERROR; @@ -72,37 +72,37 @@ lorawan_status_t LoRaMacMcps::set_request(loramac_mcps_req_t *mcpsRequest, switch (mcpsRequest->type) { case MCPS_UNCONFIRMED: { - ready_to_send = true; - params->max_ack_timeout_retries = 1; - - machdr.bits.mtype = FRAME_TYPE_DATA_UNCONFIRMED_UP; - fport = mcpsRequest->req.unconfirmed.fport; - fbuffer = mcpsRequest->f_buffer; - fbuffer_size = mcpsRequest->f_buffer_size; - datarate = mcpsRequest->req.unconfirmed.data_rate; - break; - } + ready_to_send = true; + params->max_ack_timeout_retries = 1; + + machdr.bits.mtype = FRAME_TYPE_DATA_UNCONFIRMED_UP; + fport = mcpsRequest->req.unconfirmed.fport; + fbuffer = mcpsRequest->f_buffer; + fbuffer_size = mcpsRequest->f_buffer_size; + datarate = mcpsRequest->req.unconfirmed.data_rate; + break; + } case MCPS_CONFIRMED: { - ready_to_send = true; - params->max_ack_timeout_retries = mcpsRequest->req.confirmed.nb_trials; - - machdr.bits.mtype = FRAME_TYPE_DATA_CONFIRMED_UP; - fport = mcpsRequest->req.confirmed.fport; - fbuffer = mcpsRequest->f_buffer; - fbuffer_size = mcpsRequest->f_buffer_size; - datarate = mcpsRequest->req.confirmed.data_rate; - break; - } + ready_to_send = true; + params->max_ack_timeout_retries = mcpsRequest->req.confirmed.nb_trials; + + machdr.bits.mtype = FRAME_TYPE_DATA_CONFIRMED_UP; + fport = mcpsRequest->req.confirmed.fport; + fbuffer = mcpsRequest->f_buffer; + fbuffer_size = mcpsRequest->f_buffer_size; + datarate = mcpsRequest->req.confirmed.data_rate; + break; + } case MCPS_PROPRIETARY: { - ready_to_send = true; - params->max_ack_timeout_retries = 1; - - machdr.bits.mtype = FRAME_TYPE_PROPRIETARY; - fbuffer = mcpsRequest->f_buffer; - fbuffer_size = mcpsRequest->f_buffer_size; - datarate = mcpsRequest->req.proprietary.data_rate; - break; - } + ready_to_send = true; + params->max_ack_timeout_retries = 1; + + machdr.bits.mtype = FRAME_TYPE_PROPRIETARY; + fbuffer = mcpsRequest->f_buffer; + fbuffer_size = mcpsRequest->f_buffer_size; + datarate = mcpsRequest->req.proprietary.data_rate; + break; + } default: break; } diff --git a/features/lorawan/lorastack/mac/LoRaMacMcps.h b/features/lorawan/lorastack/mac/LoRaMacMcps.h index 3989c66753c..aef7fab1db1 100644 --- a/features/lorawan/lorastack/mac/LoRaMacMcps.h +++ b/features/lorawan/lorastack/mac/LoRaMacMcps.h @@ -76,7 +76,7 @@ class LoRaMacMcps { * * @return a reference to MCPS confirm data structure */ - inline loramac_mcps_confirm_t& get_confirmation() + inline loramac_mcps_confirm_t &get_confirmation() { return confirmation; } @@ -85,7 +85,7 @@ class LoRaMacMcps { * * @return a reference to MCPS indication data structure */ - inline loramac_mcps_indication_t& get_indication() + inline loramac_mcps_indication_t &get_indication() { return indication; } diff --git a/features/lorawan/lorastack/mac/LoRaMacMib.cpp b/features/lorawan/lorastack/mac/LoRaMacMib.cpp index 39172ef5699..ad5a9031ff0 100644 --- a/features/lorawan/lorastack/mac/LoRaMacMib.cpp +++ b/features/lorawan/lorastack/mac/LoRaMacMib.cpp @@ -27,7 +27,7 @@ SPDX-License-Identifier: BSD-3-Clause #include "lorastack/mac/LoRaMacMib.h" LoRaMacMib::LoRaMacMib() -: _lora_mac(NULL), _lora_phy(NULL) + : _lora_mac(NULL), _lora_phy(NULL) { } @@ -42,10 +42,10 @@ void LoRaMacMib::activate_mib_subsystem(LoRaMac *mac, LoRaPHY *phy) } lorawan_status_t LoRaMacMib::set_request(loramac_mib_req_confirm_t *mibSet, - loramac_protocol_params *params) + loramac_protocol_params *params) { if (mibSet == NULL || _lora_phy == NULL || _lora_mac == NULL) { - return LORAWAN_STATUS_PARAMETER_INVALID; + return LORAWAN_STATUS_PARAMETER_INVALID; } lorawan_status_t status = LORAWAN_STATUS_OK; @@ -54,211 +54,211 @@ lorawan_status_t LoRaMacMib::set_request(loramac_mib_req_confirm_t *mibSet, switch (mibSet->type) { case MIB_DEVICE_CLASS: { - params->dev_class = mibSet->param.dev_class; - switch (params->dev_class) { - case CLASS_A: { - // Set the radio into sleep to setup a defined state - _lora_phy->put_radio_to_sleep(); - break; - } - case CLASS_B: { - break; - } - case CLASS_C: { - // Set the is_node_ack_requested indicator to default - params->is_node_ack_requested = false; - // Set the radio into sleep mode in case we are still in RX mode - _lora_phy->put_radio_to_sleep(); - // Compute Rx2 windows parameters in case the RX2 datarate has changed - _lora_phy->compute_rx_win_params( - params->sys_params.rx2_channel.datarate, - params->sys_params.min_rx_symb, - params->sys_params.max_sys_rx_error, - ¶ms->rx_window2_config); - _lora_mac->open_continuous_rx2_window(); - break; + params->dev_class = mibSet->param.dev_class; + switch (params->dev_class) { + case CLASS_A: { + // Set the radio into sleep to setup a defined state + _lora_phy->put_radio_to_sleep(); + break; + } + case CLASS_B: { + break; + } + case CLASS_C: { + // Set the is_node_ack_requested indicator to default + params->is_node_ack_requested = false; + // Set the radio into sleep mode in case we are still in RX mode + _lora_phy->put_radio_to_sleep(); + // Compute Rx2 windows parameters in case the RX2 datarate has changed + _lora_phy->compute_rx_win_params( + params->sys_params.rx2_channel.datarate, + params->sys_params.min_rx_symb, + params->sys_params.max_sys_rx_error, + ¶ms->rx_window2_config); + _lora_mac->open_continuous_rx2_window(); + break; + } } + break; } - break; - } case MIB_NETWORK_JOINED: { - params->is_nwk_joined = mibSet->param.is_nwk_joined; - break; - } + params->is_nwk_joined = mibSet->param.is_nwk_joined; + break; + } case MIB_ADR: { - params->sys_params.adr_on = mibSet->param.is_adr_enable; - break; - } + params->sys_params.adr_on = mibSet->param.is_adr_enable; + break; + } case MIB_NET_ID: { - params->net_id = mibSet->param.net_id; - break; - } + params->net_id = mibSet->param.net_id; + break; + } case MIB_DEV_ADDR: { - params->dev_addr = mibSet->param.dev_addr; - break; - } + params->dev_addr = mibSet->param.dev_addr; + break; + } case MIB_NWK_SKEY: { - if (mibSet->param.nwk_skey != NULL) { - memcpy(params->keys.nwk_skey, mibSet->param.nwk_skey, - sizeof(params->keys.nwk_skey)); - } else { - status = LORAWAN_STATUS_PARAMETER_INVALID; + if (mibSet->param.nwk_skey != NULL) { + memcpy(params->keys.nwk_skey, mibSet->param.nwk_skey, + sizeof(params->keys.nwk_skey)); + } else { + status = LORAWAN_STATUS_PARAMETER_INVALID; + } + break; } - break; - } case MIB_APP_SKEY: { - if (mibSet->param.app_skey != NULL) { - memcpy(params->keys.app_skey, mibSet->param.app_skey, - sizeof(params->keys.app_skey)); - } else { - status = LORAWAN_STATUS_PARAMETER_INVALID; + if (mibSet->param.app_skey != NULL) { + memcpy(params->keys.app_skey, mibSet->param.app_skey, + sizeof(params->keys.app_skey)); + } else { + status = LORAWAN_STATUS_PARAMETER_INVALID; + } + break; } - break; - } case MIB_PUBLIC_NETWORK: { - params->is_nwk_public = mibSet->param.enable_public_nwk; - _lora_phy->setup_public_network_mode(params->is_nwk_public); - break; - } + params->is_nwk_public = mibSet->param.enable_public_nwk; + _lora_phy->setup_public_network_mode(params->is_nwk_public); + break; + } case MIB_REPEATER_SUPPORT: { - params->is_repeater_supported = mibSet->param.enable_repeater_support; - break; - } + params->is_repeater_supported = mibSet->param.enable_repeater_support; + break; + } case MIB_RX2_CHANNEL: { - verify.datarate = mibSet->param.rx2_channel.datarate; - - if (_lora_phy->verify(&verify, PHY_RX_DR) == true) { - params->sys_params.rx2_channel = mibSet->param.rx2_channel; - - if ((params->dev_class == CLASS_C) - && (params->is_nwk_joined == true)) { - // We can only compute the RX window parameters directly, if we are already - // in class c mode and joined. We cannot setup an RX window in case of any other - // class type. - // Set the radio into sleep mode in case we are still in RX mode - _lora_phy->put_radio_to_sleep(); - // Compute Rx2 windows parameters - _lora_phy->compute_rx_win_params( + verify.datarate = mibSet->param.rx2_channel.datarate; + + if (_lora_phy->verify(&verify, PHY_RX_DR) == true) { + params->sys_params.rx2_channel = mibSet->param.rx2_channel; + + if ((params->dev_class == CLASS_C) + && (params->is_nwk_joined == true)) { + // We can only compute the RX window parameters directly, if we are already + // in class c mode and joined. We cannot setup an RX window in case of any other + // class type. + // Set the radio into sleep mode in case we are still in RX mode + _lora_phy->put_radio_to_sleep(); + // Compute Rx2 windows parameters + _lora_phy->compute_rx_win_params( params->sys_params.rx2_channel.datarate, params->sys_params.min_rx_symb, params->sys_params.max_sys_rx_error, ¶ms->rx_window2_config); - _lora_mac->open_continuous_rx2_window(); + _lora_mac->open_continuous_rx2_window(); + } + } else { + status = LORAWAN_STATUS_PARAMETER_INVALID; } - } else { - status = LORAWAN_STATUS_PARAMETER_INVALID; + break; } - break; - } case MIB_RX2_DEFAULT_CHANNEL: { - verify.datarate = mibSet->param.rx2_channel.datarate; + verify.datarate = mibSet->param.rx2_channel.datarate; - if (_lora_phy->verify(&verify, PHY_RX_DR) == true) { - params->sys_params.rx2_channel = mibSet->param.default_rx2_channel; - } else { - status = LORAWAN_STATUS_PARAMETER_INVALID; + if (_lora_phy->verify(&verify, PHY_RX_DR) == true) { + params->sys_params.rx2_channel = mibSet->param.default_rx2_channel; + } else { + status = LORAWAN_STATUS_PARAMETER_INVALID; + } + break; } - break; - } case MIB_CHANNELS_DEFAULT_MASK: case MIB_CHANNELS_MASK: { - // channel masks must not be tempered with. - // They should be manipulated only on request with certain - // APIs like add_channel() and remove_channel() - // You should be able to get these MIB parameters, not set - status = LORAWAN_STATUS_SERVICE_UNKNOWN; - break; - } + // channel masks must not be tempered with. + // They should be manipulated only on request with certain + // APIs like add_channel() and remove_channel() + // You should be able to get these MIB parameters, not set + status = LORAWAN_STATUS_SERVICE_UNKNOWN; + break; + } case MIB_CHANNELS_NB_REP: { - if ((mibSet->param.channel_nb_rep >= 1) - && (mibSet->param.channel_nb_rep <= 15)) { - params->sys_params.retry_num = mibSet->param.channel_nb_rep; - } else { - status = LORAWAN_STATUS_PARAMETER_INVALID; + if ((mibSet->param.channel_nb_rep >= 1) + && (mibSet->param.channel_nb_rep <= 15)) { + params->sys_params.retry_num = mibSet->param.channel_nb_rep; + } else { + status = LORAWAN_STATUS_PARAMETER_INVALID; + } + break; } - break; - } case MIB_MAX_RX_WINDOW_DURATION: { - params->sys_params.max_rx_win_time = mibSet->param.max_rx_window; - break; - } + params->sys_params.max_rx_win_time = mibSet->param.max_rx_window; + break; + } case MIB_RECEIVE_DELAY_1: { - params->sys_params.recv_delay1 = mibSet->param.recv_delay1; - break; - } + params->sys_params.recv_delay1 = mibSet->param.recv_delay1; + break; + } case MIB_RECEIVE_DELAY_2: { - params->sys_params.recv_delay2 = mibSet->param.recv_delay2; - break; - } + params->sys_params.recv_delay2 = mibSet->param.recv_delay2; + break; + } case MIB_JOIN_ACCEPT_DELAY_1: { - params->sys_params.join_accept_delay1 = mibSet->param.join_accept_delay1; - break; - } + params->sys_params.join_accept_delay1 = mibSet->param.join_accept_delay1; + break; + } case MIB_JOIN_ACCEPT_DELAY_2: { - params->sys_params.join_accept_delay2 = mibSet->param.join_accept_delay2; - break; - } + params->sys_params.join_accept_delay2 = mibSet->param.join_accept_delay2; + break; + } case MIB_CHANNELS_DEFAULT_DATARATE: { - verify.datarate = mibSet->param.default_channel_data_rate; + verify.datarate = mibSet->param.default_channel_data_rate; - if (_lora_phy->verify(&verify, PHY_DEF_TX_DR) == true) { - params->sys_params.channel_data_rate = verify.datarate; - } else { - status = LORAWAN_STATUS_PARAMETER_INVALID; + if (_lora_phy->verify(&verify, PHY_DEF_TX_DR) == true) { + params->sys_params.channel_data_rate = verify.datarate; + } else { + status = LORAWAN_STATUS_PARAMETER_INVALID; + } + break; } - break; - } case MIB_CHANNELS_DATARATE: { - verify.datarate = mibSet->param.channel_data_rate; + verify.datarate = mibSet->param.channel_data_rate; - if (_lora_phy->verify(&verify, PHY_TX_DR) == true) { - params->sys_params.channel_data_rate = verify.datarate; - } else { - status = LORAWAN_STATUS_PARAMETER_INVALID; + if (_lora_phy->verify(&verify, PHY_TX_DR) == true) { + params->sys_params.channel_data_rate = verify.datarate; + } else { + status = LORAWAN_STATUS_PARAMETER_INVALID; + } + break; } - break; - } case MIB_CHANNELS_DEFAULT_TX_POWER: { - verify.tx_power = mibSet->param.default_channel_tx_pwr; + verify.tx_power = mibSet->param.default_channel_tx_pwr; - if (_lora_phy->verify(&verify, PHY_DEF_TX_POWER) == true) { - params->sys_params.channel_tx_power = verify.tx_power; - } else { - status = LORAWAN_STATUS_PARAMETER_INVALID; + if (_lora_phy->verify(&verify, PHY_DEF_TX_POWER) == true) { + params->sys_params.channel_tx_power = verify.tx_power; + } else { + status = LORAWAN_STATUS_PARAMETER_INVALID; + } + break; } - break; - } case MIB_CHANNELS_TX_POWER: { - verify.tx_power = mibSet->param.channel_tx_pwr; + verify.tx_power = mibSet->param.channel_tx_pwr; - if (_lora_phy->verify(&verify, PHY_TX_POWER) == true) { - params->sys_params.channel_tx_power = verify.tx_power; - } else { - status = LORAWAN_STATUS_PARAMETER_INVALID; + if (_lora_phy->verify(&verify, PHY_TX_POWER) == true) { + params->sys_params.channel_tx_power = verify.tx_power; + } else { + status = LORAWAN_STATUS_PARAMETER_INVALID; + } + break; } - break; - } case MIB_UPLINK_COUNTER: { - params->ul_frame_counter = mibSet->param.ul_frame_counter; - break; - } + params->ul_frame_counter = mibSet->param.ul_frame_counter; + break; + } case MIB_DOWNLINK_COUNTER: { - params->dl_frame_counter = mibSet->param.dl_frame_counter; - break; - } + params->dl_frame_counter = mibSet->param.dl_frame_counter; + break; + } case MIB_SYSTEM_MAX_RX_ERROR: { - params->sys_params.max_sys_rx_error = mibSet->param.max_rx_sys_error; - break; - } + params->sys_params.max_sys_rx_error = mibSet->param.max_rx_sys_error; + break; + } case MIB_MIN_RX_SYMBOLS: { - params->sys_params.min_rx_symb = mibSet->param.min_rx_symb; - break; - } + params->sys_params.min_rx_symb = mibSet->param.min_rx_symb; + break; + } case MIB_ANTENNA_GAIN: { - params->sys_params.antenna_gain = mibSet->param.antenna_gain; - break; - } + params->sys_params.antenna_gain = mibSet->param.antenna_gain; + break; + } default: status = LORAWAN_STATUS_SERVICE_UNKNOWN; break; @@ -268,191 +268,159 @@ lorawan_status_t LoRaMacMib::set_request(loramac_mib_req_confirm_t *mibSet, } lorawan_status_t LoRaMacMib::get_request(loramac_mib_req_confirm_t *mibGet, - loramac_protocol_params *params) + loramac_protocol_params *params) { lorawan_status_t status = LORAWAN_STATUS_OK; get_phy_params_t get_phy; phy_param_t phy_param; rx2_channel_params rx2_channel; - if( mibGet == NULL ) - { + if (mibGet == NULL) { return LORAWAN_STATUS_PARAMETER_INVALID; } - switch( mibGet->type ) - { - case MIB_DEVICE_CLASS: - { - mibGet->param.dev_class = params->dev_class; - break; - } - case MIB_NETWORK_JOINED: - { - mibGet->param.is_nwk_joined = params->is_nwk_joined; - break; - } - case MIB_ADR: - { - mibGet->param.is_adr_enable = params->sys_params.adr_on; - break; - } - case MIB_NET_ID: - { - mibGet->param.net_id = params->net_id; - break; - } - case MIB_DEV_ADDR: - { - mibGet->param.dev_addr = params->dev_addr; - break; - } - case MIB_NWK_SKEY: - { - mibGet->param.nwk_skey =params->keys.nwk_skey; - break; - } - case MIB_APP_SKEY: - { - mibGet->param.app_skey = params->keys.app_skey; - break; - } - case MIB_PUBLIC_NETWORK: - { - mibGet->param.enable_public_nwk = params->is_nwk_public; - break; - } - case MIB_REPEATER_SUPPORT: - { - mibGet->param.enable_repeater_support = params->is_repeater_supported; - break; - } - case MIB_CHANNELS: - { - get_phy.attribute = PHY_CHANNELS; - phy_param = _lora_phy->get_phy_params( &get_phy ); + switch (mibGet->type) { + case MIB_DEVICE_CLASS: { + mibGet->param.dev_class = params->dev_class; + break; + } + case MIB_NETWORK_JOINED: { + mibGet->param.is_nwk_joined = params->is_nwk_joined; + break; + } + case MIB_ADR: { + mibGet->param.is_adr_enable = params->sys_params.adr_on; + break; + } + case MIB_NET_ID: { + mibGet->param.net_id = params->net_id; + break; + } + case MIB_DEV_ADDR: { + mibGet->param.dev_addr = params->dev_addr; + break; + } + case MIB_NWK_SKEY: { + mibGet->param.nwk_skey = params->keys.nwk_skey; + break; + } + case MIB_APP_SKEY: { + mibGet->param.app_skey = params->keys.app_skey; + break; + } + case MIB_PUBLIC_NETWORK: { + mibGet->param.enable_public_nwk = params->is_nwk_public; + break; + } + case MIB_REPEATER_SUPPORT: { + mibGet->param.enable_repeater_support = params->is_repeater_supported; + break; + } + case MIB_CHANNELS: { + get_phy.attribute = PHY_CHANNELS; + phy_param = _lora_phy->get_phy_params(&get_phy); - mibGet->param.channel_list = phy_param.channel_params; - break; - } - case MIB_RX2_CHANNEL: - { - mibGet->param.rx2_channel = params->sys_params.rx2_channel; - break; - } - case MIB_RX2_DEFAULT_CHANNEL: - { - get_phy.attribute = PHY_DEF_RX2_DR; - phy_param = _lora_phy->get_phy_params( &get_phy ); - rx2_channel.datarate = phy_param.value; - - get_phy.attribute = PHY_DEF_RX2_FREQUENCY; - phy_param = _lora_phy->get_phy_params( &get_phy ); - rx2_channel.frequency = phy_param.value; - - mibGet->param.rx2_channel = rx2_channel; - break; - } - case MIB_CHANNELS_DEFAULT_MASK: - { - get_phy.attribute = PHY_DEFAULT_CHANNEL_MASK; - phy_param = _lora_phy->get_phy_params( &get_phy ); + mibGet->param.channel_list = phy_param.channel_params; + break; + } + case MIB_RX2_CHANNEL: { + mibGet->param.rx2_channel = params->sys_params.rx2_channel; + break; + } + case MIB_RX2_DEFAULT_CHANNEL: { + get_phy.attribute = PHY_DEF_RX2_DR; + phy_param = _lora_phy->get_phy_params(&get_phy); + rx2_channel.datarate = phy_param.value; - mibGet->param.default_channel_mask = phy_param.channel_mask; - break; - } - case MIB_CHANNELS_MASK: - { - get_phy.attribute = PHY_CHANNEL_MASK; - phy_param = _lora_phy->get_phy_params( &get_phy ); + get_phy.attribute = PHY_DEF_RX2_FREQUENCY; + phy_param = _lora_phy->get_phy_params(&get_phy); + rx2_channel.frequency = phy_param.value; - mibGet->param.channel_mask = phy_param.channel_mask; - break; - } - case MIB_CHANNELS_NB_REP: - { - mibGet->param.channel_nb_rep = params->sys_params.retry_num; - break; - } - case MIB_MAX_RX_WINDOW_DURATION: - { - mibGet->param.max_rx_window = params->sys_params.max_rx_win_time; - break; - } - case MIB_RECEIVE_DELAY_1: - { - mibGet->param.recv_delay1 = params->sys_params.recv_delay1; - break; - } - case MIB_RECEIVE_DELAY_2: - { - mibGet->param.recv_delay2 = params->sys_params.recv_delay2; - break; - } - case MIB_JOIN_ACCEPT_DELAY_1: - { - mibGet->param.join_accept_delay1 = params->sys_params.join_accept_delay1; - break; - } - case MIB_JOIN_ACCEPT_DELAY_2: - { - mibGet->param.join_accept_delay2 = params->sys_params.join_accept_delay2; - break; - } - case MIB_CHANNELS_DEFAULT_DATARATE: - { - get_phy.attribute = PHY_DEF_TX_DR; - phy_param = _lora_phy->get_phy_params( &get_phy ); - mibGet->param.default_channel_data_rate = phy_param.value; - break; - } - case MIB_CHANNELS_DATARATE: - { - mibGet->param.channel_data_rate = params->sys_params.channel_data_rate; - break; - } - case MIB_CHANNELS_DEFAULT_TX_POWER: - { - get_phy.attribute = PHY_DEF_TX_POWER; - phy_param = _lora_phy->get_phy_params( &get_phy ); - mibGet->param.default_channel_tx_pwr = phy_param.value; - break; - } - case MIB_CHANNELS_TX_POWER: - { - mibGet->param.channel_tx_pwr = params->sys_params.channel_tx_power; - break; - } - case MIB_UPLINK_COUNTER: - { - mibGet->param.ul_frame_counter = params->ul_frame_counter; - break; - } - case MIB_DOWNLINK_COUNTER: - { - mibGet->param.dl_frame_counter = params->dl_frame_counter; - break; - } - case MIB_MULTICAST_CHANNEL: - { - mibGet->param.multicast_list = params->multicast_channels; - break; - } - case MIB_SYSTEM_MAX_RX_ERROR: - { - mibGet->param.max_rx_sys_error = params->sys_params.max_sys_rx_error; - break; - } - case MIB_MIN_RX_SYMBOLS: - { - mibGet->param.min_rx_symb = params->sys_params.min_rx_symb; - break; - } - case MIB_ANTENNA_GAIN: - { - mibGet->param.antenna_gain = params->sys_params.antenna_gain; - break; - } + mibGet->param.rx2_channel = rx2_channel; + break; + } + case MIB_CHANNELS_DEFAULT_MASK: { + get_phy.attribute = PHY_DEFAULT_CHANNEL_MASK; + phy_param = _lora_phy->get_phy_params(&get_phy); + + mibGet->param.default_channel_mask = phy_param.channel_mask; + break; + } + case MIB_CHANNELS_MASK: { + get_phy.attribute = PHY_CHANNEL_MASK; + phy_param = _lora_phy->get_phy_params(&get_phy); + + mibGet->param.channel_mask = phy_param.channel_mask; + break; + } + case MIB_CHANNELS_NB_REP: { + mibGet->param.channel_nb_rep = params->sys_params.retry_num; + break; + } + case MIB_MAX_RX_WINDOW_DURATION: { + mibGet->param.max_rx_window = params->sys_params.max_rx_win_time; + break; + } + case MIB_RECEIVE_DELAY_1: { + mibGet->param.recv_delay1 = params->sys_params.recv_delay1; + break; + } + case MIB_RECEIVE_DELAY_2: { + mibGet->param.recv_delay2 = params->sys_params.recv_delay2; + break; + } + case MIB_JOIN_ACCEPT_DELAY_1: { + mibGet->param.join_accept_delay1 = params->sys_params.join_accept_delay1; + break; + } + case MIB_JOIN_ACCEPT_DELAY_2: { + mibGet->param.join_accept_delay2 = params->sys_params.join_accept_delay2; + break; + } + case MIB_CHANNELS_DEFAULT_DATARATE: { + get_phy.attribute = PHY_DEF_TX_DR; + phy_param = _lora_phy->get_phy_params(&get_phy); + mibGet->param.default_channel_data_rate = phy_param.value; + break; + } + case MIB_CHANNELS_DATARATE: { + mibGet->param.channel_data_rate = params->sys_params.channel_data_rate; + break; + } + case MIB_CHANNELS_DEFAULT_TX_POWER: { + get_phy.attribute = PHY_DEF_TX_POWER; + phy_param = _lora_phy->get_phy_params(&get_phy); + mibGet->param.default_channel_tx_pwr = phy_param.value; + break; + } + case MIB_CHANNELS_TX_POWER: { + mibGet->param.channel_tx_pwr = params->sys_params.channel_tx_power; + break; + } + case MIB_UPLINK_COUNTER: { + mibGet->param.ul_frame_counter = params->ul_frame_counter; + break; + } + case MIB_DOWNLINK_COUNTER: { + mibGet->param.dl_frame_counter = params->dl_frame_counter; + break; + } + case MIB_MULTICAST_CHANNEL: { + mibGet->param.multicast_list = params->multicast_channels; + break; + } + case MIB_SYSTEM_MAX_RX_ERROR: { + mibGet->param.max_rx_sys_error = params->sys_params.max_sys_rx_error; + break; + } + case MIB_MIN_RX_SYMBOLS: { + mibGet->param.min_rx_symb = params->sys_params.min_rx_symb; + break; + } + case MIB_ANTENNA_GAIN: { + mibGet->param.antenna_gain = params->sys_params.antenna_gain; + break; + } default: status = LORAWAN_STATUS_SERVICE_UNKNOWN; break; diff --git a/features/lorawan/lorastack/mac/LoRaMacMlme.cpp b/features/lorawan/lorastack/mac/LoRaMacMlme.cpp index 35c0b623a8a..8743f2565d2 100644 --- a/features/lorawan/lorastack/mac/LoRaMacMlme.cpp +++ b/features/lorawan/lorastack/mac/LoRaMacMlme.cpp @@ -27,7 +27,7 @@ SPDX-License-Identifier: BSD-3-Clause #include "lorastack/mac/LoRaMacMlme.h" LoRaMacMlme::LoRaMacMlme() -: _lora_mac(NULL), _lora_phy(NULL), _mac_cmd(NULL) + : _lora_mac(NULL), _lora_phy(NULL), _mac_cmd(NULL) { } @@ -36,7 +36,7 @@ LoRaMacMlme::~LoRaMacMlme() } void LoRaMacMlme::activate_mlme_subsystem(LoRaMac *mac, LoRaPHY *phy, - LoRaMacCommand *cmd) + LoRaMacCommand *cmd) { _lora_mac = mac; _lora_phy = phy; @@ -44,7 +44,7 @@ void LoRaMacMlme::activate_mlme_subsystem(LoRaMac *mac, LoRaPHY *phy, } lorawan_status_t LoRaMacMlme::set_request(loramac_mlme_req_t *request, - loramac_protocol_params *params) + loramac_protocol_params *params) { if (request && params && _lora_mac && _lora_phy && _mac_cmd) { @@ -62,79 +62,79 @@ lorawan_status_t LoRaMacMlme::set_request(loramac_mlme_req_t *request, // Before setting a new MLME request, clear the MLME confirmation // structure - memset((uint8_t*) &confirmation, 0, sizeof(confirmation)); + memset((uint8_t *) &confirmation, 0, sizeof(confirmation)); confirmation.status = LORAMAC_EVENT_INFO_STATUS_ERROR; switch (request->type) { case MLME_JOIN: { - if ((params->mac_state & LORAMAC_TX_DELAYED) - == LORAMAC_TX_DELAYED) { - return LORAWAN_STATUS_BUSY; - } - - if ((request->req.join.dev_eui == NULL) - || (request->req.join.app_eui == NULL) - || (request->req.join.app_key == NULL) - || (request->req.join.nb_trials == 0)) { - return LORAWAN_STATUS_PARAMETER_INVALID; - } - - // Verify the parameter NbTrials for the join procedure - verify.nb_join_trials = request->req.join.nb_trials; - - if (_lora_phy->verify(&verify, PHY_NB_JOIN_TRIALS) == false) { - // Value not supported, get default - get_phy.attribute = PHY_DEF_NB_JOIN_TRIALS; - phy_param = _lora_phy->get_phy_params(&get_phy); - request->req.join.nb_trials = (uint8_t) phy_param.value; - } - - params->flags.bits.mlme_req = 1; - confirmation.req_type = request->type; - - params->keys.dev_eui = request->req.join.dev_eui; - params->keys.app_eui = request->req.join.app_eui; - params->keys.app_key = request->req.join.app_key; - params->max_join_request_trials = request->req.join.nb_trials; - - // Reset variable JoinRequestTrials - params->join_request_trial_counter = 0; - - // Setup header information - machdr.value = 0; - machdr.bits.mtype = FRAME_TYPE_JOIN_REQ; - - _lora_mac->reset_mac_parameters(); - - params->sys_params.channel_data_rate = + if ((params->mac_state & LORAMAC_TX_DELAYED) + == LORAMAC_TX_DELAYED) { + return LORAWAN_STATUS_BUSY; + } + + if ((request->req.join.dev_eui == NULL) + || (request->req.join.app_eui == NULL) + || (request->req.join.app_key == NULL) + || (request->req.join.nb_trials == 0)) { + return LORAWAN_STATUS_PARAMETER_INVALID; + } + + // Verify the parameter NbTrials for the join procedure + verify.nb_join_trials = request->req.join.nb_trials; + + if (_lora_phy->verify(&verify, PHY_NB_JOIN_TRIALS) == false) { + // Value not supported, get default + get_phy.attribute = PHY_DEF_NB_JOIN_TRIALS; + phy_param = _lora_phy->get_phy_params(&get_phy); + request->req.join.nb_trials = (uint8_t) phy_param.value; + } + + params->flags.bits.mlme_req = 1; + confirmation.req_type = request->type; + + params->keys.dev_eui = request->req.join.dev_eui; + params->keys.app_eui = request->req.join.app_eui; + params->keys.app_key = request->req.join.app_key; + params->max_join_request_trials = request->req.join.nb_trials; + + // Reset variable JoinRequestTrials + params->join_request_trial_counter = 0; + + // Setup header information + machdr.value = 0; + machdr.bits.mtype = FRAME_TYPE_JOIN_REQ; + + _lora_mac->reset_mac_parameters(); + + params->sys_params.channel_data_rate = _lora_phy->get_alternate_DR(params->join_request_trial_counter + 1); - status = _lora_mac->send(&machdr, 0, NULL, 0); - break; - } + status = _lora_mac->send(&machdr, 0, NULL, 0); + break; + } case MLME_LINK_CHECK: { - params->flags.bits.mlme_req = 1; - // LoRaMac will send this command piggy-backed - confirmation.req_type = request->type; + params->flags.bits.mlme_req = 1; + // LoRaMac will send this command piggy-backed + confirmation.req_type = request->type; - status = _mac_cmd->add_mac_command(MOTE_MAC_LINK_CHECK_REQ, 0, 0); - break; - } + status = _mac_cmd->add_mac_command(MOTE_MAC_LINK_CHECK_REQ, 0, 0); + break; + } case MLME_TXCW: { - confirmation.req_type = request->type; - params->flags.bits.mlme_req = 1; - status = _lora_mac->set_tx_continuous_wave(request->req.cw_tx_mode.timeout); - break; - } + confirmation.req_type = request->type; + params->flags.bits.mlme_req = 1; + status = _lora_mac->set_tx_continuous_wave(request->req.cw_tx_mode.timeout); + break; + } case MLME_TXCW_1: { - confirmation.req_type = request->type; - params->flags.bits.mlme_req = 1; - status = _lora_mac->set_tx_continuous_wave1(request->req.cw_tx_mode.timeout, - request->req.cw_tx_mode.frequency, - request->req.cw_tx_mode.power); - break; - } + confirmation.req_type = request->type; + params->flags.bits.mlme_req = 1; + status = _lora_mac->set_tx_continuous_wave1(request->req.cw_tx_mode.timeout, + request->req.cw_tx_mode.frequency, + request->req.cw_tx_mode.power); + break; + } default: break; } diff --git a/features/lorawan/lorastack/mac/LoRaMacMlme.h b/features/lorawan/lorastack/mac/LoRaMacMlme.h index 2be3db0b71b..f08504ae9dc 100644 --- a/features/lorawan/lorastack/mac/LoRaMacMlme.h +++ b/features/lorawan/lorastack/mac/LoRaMacMlme.h @@ -78,7 +78,7 @@ class LoRaMacMlme { * * @return a reference to MLME confirm data structure */ - inline loramac_mlme_confirm_t& get_confirmation() + inline loramac_mlme_confirm_t &get_confirmation() { return confirmation; } @@ -87,7 +87,7 @@ class LoRaMacMlme { * * @return a reference to MLME indication data structure */ - inline loramac_mlme_indication_t& get_indication() + inline loramac_mlme_indication_t &get_indication() { return indication; } diff --git a/features/lorawan/lorastack/phy/LoRaPHY.cpp b/features/lorawan/lorastack/phy/LoRaPHY.cpp index 47ba84f03dd..dbe816dc6fa 100644 --- a/features/lorawan/lorastack/phy/LoRaPHY.cpp +++ b/features/lorawan/lorastack/phy/LoRaPHY.cpp @@ -46,18 +46,20 @@ LoRaPHY::~LoRaPHY() _radio = NULL; } -void LoRaPHY::set_radio_instance(LoRaRadio& radio) +void LoRaPHY::set_radio_instance(LoRaRadio &radio) { _radio = &radio; } -void LoRaPHY::put_radio_to_sleep() { +void LoRaPHY::put_radio_to_sleep() +{ _radio->lock(); _radio->sleep(); _radio->unlock(); } -void LoRaPHY::put_radio_to_standby() { +void LoRaPHY::put_radio_to_standby() +{ _radio->lock(); _radio->standby(); _radio->unlock(); @@ -87,7 +89,7 @@ uint32_t LoRaPHY::get_radio_rng() uint32_t rand; _radio->lock(); - rand =_radio->random(); + rand = _radio->random(); _radio->unlock(); return rand; @@ -100,7 +102,7 @@ void LoRaPHY::handle_send(uint8_t *buf, uint8_t size) _radio->unlock(); } -uint8_t LoRaPHY::request_new_channel(new_channel_req_params_t* params) +uint8_t LoRaPHY::request_new_channel(new_channel_req_params_t *params) { if (!phy_params.custom_channelplans_supported) { return 0; @@ -116,30 +118,25 @@ uint8_t LoRaPHY::request_new_channel(new_channel_req_params_t* params) } else { switch (add_channel(params->new_channel, params->channel_id)) { - case LORAWAN_STATUS_OK: - { - break; - } - case LORAWAN_STATUS_FREQUENCY_INVALID: - { - status &= 0xFE; - break; - } - case LORAWAN_STATUS_DATARATE_INVALID: - { - status &= 0xFD; - break; - } - case LORAWAN_STATUS_FREQ_AND_DR_INVALID: - { - status &= 0xFC; - break; - } - default: - { - status &= 0xFC; - break; - } + case LORAWAN_STATUS_OK: { + break; + } + case LORAWAN_STATUS_FREQUENCY_INVALID: { + status &= 0xFE; + break; + } + case LORAWAN_STATUS_DATARATE_INVALID: { + status &= 0xFD; + break; + } + case LORAWAN_STATUS_FREQ_AND_DR_INVALID: { + status &= 0xFC; + break; + } + default: { + status &= 0xFC; + break; + } } } @@ -151,9 +148,9 @@ int32_t LoRaPHY::get_random(int32_t min, int32_t max) return (int32_t) rand() % (max - min + 1) + min; } -bool LoRaPHY::verify_channel_DR(uint8_t nb_channels, uint16_t* channel_mask, +bool LoRaPHY::verify_channel_DR(uint8_t nb_channels, uint16_t *channel_mask, int8_t dr, int8_t min_dr, int8_t max_dr, - channel_params_t* channels) + channel_params_t *channels) { if (val_in_range(dr, min_dr, max_dr) == 0) { return false; @@ -163,7 +160,7 @@ bool LoRaPHY::verify_channel_DR(uint8_t nb_channels, uint16_t* channel_mask, if (mask_bit_test(channel_mask, i)) { // Check datarate validity for enabled channels if (val_in_range(dr, (channels[i].dr_range.fields.min & 0x0F), - (channels[i].dr_range.fields.max & 0x0F))) { + (channels[i].dr_range.fields.max & 0x0F))) { // At least 1 channel has been found we can return OK. return true; } @@ -173,7 +170,7 @@ bool LoRaPHY::verify_channel_DR(uint8_t nb_channels, uint16_t* channel_mask, return false; } -uint8_t LoRaPHY::val_in_range( int8_t value, int8_t min, int8_t max ) +uint8_t LoRaPHY::val_in_range(int8_t value, int8_t min, int8_t max) { if ((value >= min) && (value <= max)) { return 1; @@ -182,7 +179,7 @@ uint8_t LoRaPHY::val_in_range( int8_t value, int8_t min, int8_t max ) return 0; } -bool LoRaPHY::disable_channel(uint16_t* channel_mask, uint8_t id, +bool LoRaPHY::disable_channel(uint16_t *channel_mask, uint8_t id, uint8_t max_channels_num) { uint8_t index = id / 16; @@ -201,7 +198,7 @@ uint8_t LoRaPHY::count_bits(uint16_t mask, uint8_t nbBits) { uint8_t nbActiveBits = 0; - for(uint8_t j = 0; j < nbBits; j++) { + for (uint8_t j = 0; j < nbBits; j++) { if (mask_bit_test(&mask, j)) { nbActiveBits++; } @@ -210,7 +207,7 @@ uint8_t LoRaPHY::count_bits(uint16_t mask, uint8_t nbBits) return nbActiveBits; } -uint8_t LoRaPHY::num_active_channels(uint16_t* channel_mask, uint8_t start_idx, +uint8_t LoRaPHY::num_active_channels(uint16_t *channel_mask, uint8_t start_idx, uint8_t stop_idx) { uint8_t nb_channels = 0; @@ -226,16 +223,16 @@ uint8_t LoRaPHY::num_active_channels(uint16_t* channel_mask, uint8_t start_idx, return nb_channels; } -void LoRaPHY::copy_channel_mask(uint16_t* dest_mask, uint16_t* src_mask, uint8_t len) +void LoRaPHY::copy_channel_mask(uint16_t *dest_mask, uint16_t *src_mask, uint8_t len) { if ((dest_mask != NULL) && (src_mask != NULL)) { - for( uint8_t i = 0; i < len; i++ ) { + for (uint8_t i = 0; i < len; i++) { dest_mask[i] = src_mask[i]; } } } -void LoRaPHY::set_last_tx_done(set_band_txdone_params_t* last_tx_params) +void LoRaPHY::set_last_tx_done(set_band_txdone_params_t *last_tx_params) { if (!last_tx_params) { return; @@ -255,37 +252,37 @@ void LoRaPHY::set_last_tx_done(set_band_txdone_params_t* last_tx_params) } lorawan_time_t LoRaPHY::update_band_timeoff(bool joined, bool duty_cycle, - band_t* bands, uint8_t nb_bands) + band_t *bands, uint8_t nb_bands) { - lorawan_time_t next_tx_delay = (lorawan_time_t) (-1); + lorawan_time_t next_tx_delay = (lorawan_time_t)(-1); // Update bands Time OFF for (uint8_t i = 0; i < nb_bands; i++) { if (joined == false) { uint32_t txDoneTime = MAX(_lora_time.get_elapsed_time(bands[i].last_join_tx_time), - (duty_cycle == true) ? - _lora_time.get_elapsed_time(bands[i].last_tx_time) : 0); + (duty_cycle == true) ? + _lora_time.get_elapsed_time(bands[i].last_tx_time) : 0); if (bands[i].off_time <= txDoneTime) { bands[i].off_time = 0; } if (bands[i].off_time != 0) { - next_tx_delay = MIN( bands[i].off_time - txDoneTime, next_tx_delay ); + next_tx_delay = MIN(bands[i].off_time - txDoneTime, next_tx_delay); } } else { // if network has been joined if (duty_cycle == true) { - if( bands[i].off_time <= _lora_time.get_elapsed_time(bands[i].last_tx_time)) { + if (bands[i].off_time <= _lora_time.get_elapsed_time(bands[i].last_tx_time)) { bands[i].off_time = 0; } - if(bands[i].off_time != 0 ) { + if (bands[i].off_time != 0) { next_tx_delay = MIN(bands[i].off_time - _lora_time.get_elapsed_time(bands[i].last_tx_time), - next_tx_delay); + next_tx_delay); } } else { // if duty cycle is not on @@ -298,7 +295,7 @@ lorawan_time_t LoRaPHY::update_band_timeoff(bool joined, bool duty_cycle, return next_tx_delay; } -uint8_t LoRaPHY::parse_link_ADR_req(uint8_t* payload, link_adr_params_t* params) +uint8_t LoRaPHY::parse_link_ADR_req(uint8_t *payload, link_adr_params_t *params) { uint8_t ret_index = 0; @@ -315,7 +312,7 @@ uint8_t LoRaPHY::parse_link_ADR_req(uint8_t* payload, link_adr_params_t* params) // Parse ChMaskCtrl and nbRep params->nb_rep = payload[4]; - params->ch_mask_ctrl = ( params->nb_rep >> 4 ) & 0x07; + params->ch_mask_ctrl = (params->nb_rep >> 4) & 0x07; params->nb_rep &= 0x0F; // LinkAdrReq has 4 bytes length + 1 byte CMD @@ -325,8 +322,8 @@ uint8_t LoRaPHY::parse_link_ADR_req(uint8_t* payload, link_adr_params_t* params) return ret_index; } -uint8_t LoRaPHY::verify_link_ADR_req(verify_adr_params_t* verify_params, - int8_t* dr, int8_t* tx_pow, uint8_t* nb_rep) +uint8_t LoRaPHY::verify_link_ADR_req(verify_adr_params_t *verify_params, + int8_t *dr, int8_t *tx_pow, uint8_t *nb_rep) { uint8_t status = verify_params->status; int8_t datarate = verify_params->datarate; @@ -395,11 +392,11 @@ double LoRaPHY::compute_symb_timeout_fsk(uint8_t phy_dr) void LoRaPHY::get_rx_window_params(double t_symb, uint8_t min_rx_symb, uint32_t rx_error, uint32_t wakeup_time, - uint32_t* window_timeout, int32_t* window_offset) + uint32_t *window_timeout, int32_t *window_offset) { // Computed number of symbols - *window_timeout = MAX ((uint32_t) ceil(((2 * min_rx_symb - 8) * t_symb + 2 * rx_error) / t_symb), min_rx_symb ); - *window_offset = (int32_t) ceil((4.0 * t_symb) - ((*window_timeout * t_symb) / 2.0 ) - wakeup_time); + *window_timeout = MAX((uint32_t) ceil(((2 * min_rx_symb - 8) * t_symb + 2 * rx_error) / t_symb), min_rx_symb); + *window_offset = (int32_t) ceil((4.0 * t_symb) - ((*window_timeout * t_symb) / 2.0) - wakeup_time); } int8_t LoRaPHY::compute_tx_power(int8_t tx_power_idx, float max_eirp, @@ -430,7 +427,7 @@ uint8_t LoRaPHY::get_bandwidth(uint8_t dr) { uint32_t *bandwidths = (uint32_t *) phy_params.bandwidths.table; - switch(bandwidths[dr]) { + switch (bandwidths[dr]) { default: case 125000: return 0; @@ -453,7 +450,7 @@ uint8_t LoRaPHY::enabled_channel_count(bool joined, uint8_t datarate, if (mask_bit_test(channel_mask, i)) { if (val_in_range(datarate, phy_params.channels.channel_list[i].dr_range.fields.min, - phy_params.channels.channel_list[i].dr_range.fields.max ) == 0) { + phy_params.channels.channel_list[i].dr_range.fields.max) == 0) { // data rate range invalid for this channel continue; } @@ -475,118 +472,118 @@ uint8_t LoRaPHY::enabled_channel_count(bool joined, uint8_t datarate, return count; } -phy_param_t LoRaPHY::get_phy_params(get_phy_params_t* getPhy) +phy_param_t LoRaPHY::get_phy_params(get_phy_params_t *getPhy) { phy_param_t phyParam = { 0 }; switch (getPhy->attribute) { case PHY_MIN_RX_DR: { - if (phy_params.dl_dwell_time_setting == 0) { - phyParam.value = phy_params.min_rx_datarate; - } else { - phyParam.value = phy_params.dwell_limit_datarate; + if (phy_params.dl_dwell_time_setting == 0) { + phyParam.value = phy_params.min_rx_datarate; + } else { + phyParam.value = phy_params.dwell_limit_datarate; + } + break; } - break; - } case PHY_MIN_TX_DR: { - if (phy_params.ul_dwell_time_setting == 0) { - phyParam.value = phy_params.min_tx_datarate; - } else { - phyParam.value = phy_params.dwell_limit_datarate; + if (phy_params.ul_dwell_time_setting == 0) { + phyParam.value = phy_params.min_tx_datarate; + } else { + phyParam.value = phy_params.dwell_limit_datarate; + } + break; } - break; - } case PHY_DEF_TX_DR: { - phyParam.value = phy_params.default_datarate; - break; - } + phyParam.value = phy_params.default_datarate; + break; + } case PHY_NEXT_LOWER_TX_DR: { - if (phy_params.ul_dwell_time_setting == 0) { - phyParam.value = get_next_lower_dr(getPhy->datarate, - phy_params.min_tx_datarate); - } else { - phyParam.value = get_next_lower_dr( - getPhy->datarate, phy_params.dwell_limit_datarate); + if (phy_params.ul_dwell_time_setting == 0) { + phyParam.value = get_next_lower_dr(getPhy->datarate, + phy_params.min_tx_datarate); + } else { + phyParam.value = get_next_lower_dr( + getPhy->datarate, phy_params.dwell_limit_datarate); + } + break; } - break; - } case PHY_DEF_TX_POWER: { - phyParam.value = phy_params.default_tx_power; - break; - } + phyParam.value = phy_params.default_tx_power; + break; + } case PHY_MAX_PAYLOAD: { - uint8_t *payload_table = (uint8_t *) phy_params.payloads.table; - phyParam.value = payload_table[getPhy->datarate]; - break; - } + uint8_t *payload_table = (uint8_t *) phy_params.payloads.table; + phyParam.value = payload_table[getPhy->datarate]; + break; + } case PHY_MAX_PAYLOAD_REPEATER: { - uint8_t *payload_table = (uint8_t *) phy_params.payloads_with_repeater.table; - phyParam.value = payload_table[getPhy->datarate]; - break; - } + uint8_t *payload_table = (uint8_t *) phy_params.payloads_with_repeater.table; + phyParam.value = payload_table[getPhy->datarate]; + break; + } case PHY_DUTY_CYCLE: { - phyParam.value = phy_params.duty_cycle_enabled; - break; - } + phyParam.value = phy_params.duty_cycle_enabled; + break; + } case PHY_MAX_RX_WINDOW: { - phyParam.value = phy_params.max_rx_window; - break; - } + phyParam.value = phy_params.max_rx_window; + break; + } case PHY_RECEIVE_DELAY1: { - phyParam.value = phy_params.recv_delay1; - break; - } + phyParam.value = phy_params.recv_delay1; + break; + } case PHY_RECEIVE_DELAY2: { - phyParam.value = phy_params.recv_delay2; - break; - } + phyParam.value = phy_params.recv_delay2; + break; + } case PHY_JOIN_ACCEPT_DELAY1: { - phyParam.value = phy_params.join_accept_delay1; - break; - } + phyParam.value = phy_params.join_accept_delay1; + break; + } case PHY_JOIN_ACCEPT_DELAY2: { - phyParam.value = phy_params.join_accept_delay2; - break; - } + phyParam.value = phy_params.join_accept_delay2; + break; + } case PHY_MAX_FCNT_GAP: { - phyParam.value = phy_params.max_fcnt_gap; - break; - } + phyParam.value = phy_params.max_fcnt_gap; + break; + } case PHY_ACK_TIMEOUT: { - uint16_t ack_timeout = phy_params.ack_timeout; - uint16_t ack_timeout_rnd = phy_params.ack_timeout_rnd; - phyParam.value = (ack_timeout - + get_random(-ack_timeout_rnd, ack_timeout_rnd)); - break; - } + uint16_t ack_timeout = phy_params.ack_timeout; + uint16_t ack_timeout_rnd = phy_params.ack_timeout_rnd; + phyParam.value = (ack_timeout + + get_random(-ack_timeout_rnd, ack_timeout_rnd)); + break; + } case PHY_DEF_DR1_OFFSET: { - phyParam.value = phy_params.default_rx1_dr_offset; - break; - } + phyParam.value = phy_params.default_rx1_dr_offset; + break; + } case PHY_DEF_RX2_FREQUENCY: { - phyParam.value = phy_params.rx_window2_frequency; - break; - } + phyParam.value = phy_params.rx_window2_frequency; + break; + } case PHY_DEF_RX2_DR: { - phyParam.value = phy_params.rx_window2_datarate; - break; - } + phyParam.value = phy_params.rx_window2_datarate; + break; + } case PHY_CHANNEL_MASK: { - phyParam.channel_mask = phy_params.channels.mask; - break; - } + phyParam.channel_mask = phy_params.channels.mask; + break; + } case PHY_DEFAULT_CHANNEL_MASK: { - phyParam.channel_mask = phy_params.channels.default_mask; - break; - } + phyParam.channel_mask = phy_params.channels.default_mask; + break; + } case PHY_MAX_NB_CHANNELS: { - phyParam.value = phy_params.max_channel_cnt; - break; - } + phyParam.value = phy_params.max_channel_cnt; + break; + } case PHY_CHANNELS: { - phyParam.channel_params = phy_params.channels.channel_list; - break; - } + phyParam.channel_params = phy_params.channels.channel_list; + break; + } case PHY_CUSTOM_CHANNEL_PLAN_SUPPORT: // 0 if custom channel plans are not supported (in LoRaWAN terms // the regions who do not support custom channels are called as @@ -594,29 +591,29 @@ phy_param_t LoRaPHY::get_phy_params(get_phy_params_t* getPhy) phyParam.value = (uint32_t) phy_params.custom_channelplans_supported; break; case PHY_DEF_UPLINK_DWELL_TIME: { - phyParam.value = phy_params.ul_dwell_time_setting; - break; - } + phyParam.value = phy_params.ul_dwell_time_setting; + break; + } case PHY_DEF_DOWNLINK_DWELL_TIME: { - phyParam.value = phy_params.dl_dwell_time_setting; - break; - } + phyParam.value = phy_params.dl_dwell_time_setting; + break; + } case PHY_DEF_MAX_EIRP: { - phyParam.f_value = phy_params.default_max_eirp; - break; - } + phyParam.f_value = phy_params.default_max_eirp; + break; + } case PHY_DEF_ANTENNA_GAIN: { - phyParam.f_value = phy_params.default_antenna_gain; - break; - } + phyParam.f_value = phy_params.default_antenna_gain; + break; + } case PHY_NB_JOIN_TRIALS: case PHY_DEF_NB_JOIN_TRIALS: { - phyParam.value = MBED_CONF_LORA_NB_TRIALS; - break; - } + phyParam.value = MBED_CONF_LORA_NB_TRIALS; + break; + } default: { - break; - } + break; + } } return phyParam; @@ -625,67 +622,61 @@ phy_param_t LoRaPHY::get_phy_params(get_phy_params_t* getPhy) void LoRaPHY::restore_default_channels() { // Restore channels default mask - for (uint8_t i=0; i < phy_params.channels.mask_size; i++) { + for (uint8_t i = 0; i < phy_params.channels.mask_size; i++) { phy_params.channels.mask[i] |= phy_params.channels.default_mask[i]; } } -bool LoRaPHY::verify(verification_params_t* verify, phy_attributes_t phy_attribute) +bool LoRaPHY::verify(verification_params_t *verify, phy_attributes_t phy_attribute) { - switch(phy_attribute) { - case PHY_TX_DR: - { - if (phy_params.ul_dwell_time_setting == 0) { - return val_in_range(verify->datarate, - phy_params.min_tx_datarate, - phy_params.max_tx_datarate); - } else { - return val_in_range(verify->datarate, - phy_params.dwell_limit_datarate, - phy_params.max_tx_datarate); - } + switch (phy_attribute) { + case PHY_TX_DR: { + if (phy_params.ul_dwell_time_setting == 0) { + return val_in_range(verify->datarate, + phy_params.min_tx_datarate, + phy_params.max_tx_datarate); + } else { + return val_in_range(verify->datarate, + phy_params.dwell_limit_datarate, + phy_params.max_tx_datarate); + } - } - case PHY_DEF_TX_DR: - { - return val_in_range(verify->datarate, - phy_params.default_datarate, - phy_params.default_max_datarate); - } - case PHY_RX_DR: - { - if (phy_params.dl_dwell_time_setting == 0) { - return val_in_range(verify->datarate, - phy_params.min_rx_datarate, - phy_params.min_rx_datarate); - } else { + } + case PHY_DEF_TX_DR: { return val_in_range(verify->datarate, - phy_params.dwell_limit_datarate, - phy_params.min_rx_datarate ); + phy_params.default_datarate, + phy_params.default_max_datarate); + } + case PHY_RX_DR: { + if (phy_params.dl_dwell_time_setting == 0) { + return val_in_range(verify->datarate, + phy_params.min_rx_datarate, + phy_params.min_rx_datarate); + } else { + return val_in_range(verify->datarate, + phy_params.dwell_limit_datarate, + phy_params.min_rx_datarate); + } } - } case PHY_DEF_TX_POWER: - case PHY_TX_POWER: - { - // Remark: switched min and max! - return val_in_range(verify->tx_power, phy_params.max_tx_power, - phy_params.min_tx_power); - } - case PHY_DUTY_CYCLE: - { - if (verify->duty_cycle == phy_params.duty_cycle_enabled) { - return true; + case PHY_TX_POWER: { + // Remark: switched min and max! + return val_in_range(verify->tx_power, phy_params.max_tx_power, + phy_params.min_tx_power); } + case PHY_DUTY_CYCLE: { + if (verify->duty_cycle == phy_params.duty_cycle_enabled) { + return true; + } - return false; - } - case PHY_NB_JOIN_TRIALS: - { - if (verify->nb_join_trials < MBED_CONF_LORA_NB_TRIALS) { return false; } - break; - } + case PHY_NB_JOIN_TRIALS: { + if (verify->nb_join_trials < MBED_CONF_LORA_NB_TRIALS) { + return false; + } + break; + } default: return false; } @@ -693,7 +684,7 @@ bool LoRaPHY::verify(verification_params_t* verify, phy_attributes_t phy_attribu return true; } -void LoRaPHY::apply_cf_list(cflist_params_t* cf_list) +void LoRaPHY::apply_cf_list(cflist_params_t *cf_list) { // if the underlying PHY doesn't support CF-List, ignore the request if (!phy_params.cflist_supported) { @@ -704,7 +695,7 @@ void LoRaPHY::apply_cf_list(cflist_params_t* cf_list) // Setup default datarate range new_channel.dr_range.value = (phy_params.default_max_datarate << 4) - | phy_params.default_datarate; + | phy_params.default_datarate; // Size of the optional CF list if (cf_list->size != 16) { @@ -719,7 +710,7 @@ void LoRaPHY::apply_cf_list(cflist_params_t* cf_list) // should override this function in the implementation of that particular // PHY. for (uint8_t i = 0, channel_id = phy_params.default_channel_cnt; - channel_id < phy_params.max_channel_cnt; i+=phy_params.default_channel_cnt, channel_id++) { + channel_id < phy_params.max_channel_cnt; i += phy_params.default_channel_cnt, channel_id++) { if (channel_id < (phy_params.cflist_channel_cnt + phy_params.default_channel_cnt)) { // Channel frequency new_channel.frequency = (uint32_t) cf_list->payload[i]; @@ -745,8 +736,8 @@ void LoRaPHY::apply_cf_list(cflist_params_t* cf_list) } -bool LoRaPHY::get_next_ADR(bool restore_channel_mask, int8_t& dr_out, - int8_t& tx_power_out, uint32_t& adr_ack_cnt) +bool LoRaPHY::get_next_ADR(bool restore_channel_mask, int8_t &dr_out, + int8_t &tx_power_out, uint32_t &adr_ack_cnt) { bool set_adr_ack_bit = false; @@ -796,7 +787,7 @@ void LoRaPHY::compute_rx_win_params(int8_t datarate, uint8_t min_rx_symbols, double t_symbol = 0.0; // Get the datarate, perform a boundary check - rx_conf_params->datarate = MIN( datarate, phy_params.max_rx_datarate); + rx_conf_params->datarate = MIN(datarate, phy_params.max_rx_datarate); rx_conf_params->bandwidth = get_bandwidth(rx_conf_params->datarate); @@ -806,14 +797,14 @@ void LoRaPHY::compute_rx_win_params(int8_t datarate, uint8_t min_rx_symbols, } else { // LoRa t_symbol = compute_symb_timeout_lora(((uint8_t *)phy_params.datarates.table)[rx_conf_params->datarate], - ((uint32_t *)phy_params.bandwidths.table)[rx_conf_params->datarate]); + ((uint32_t *)phy_params.bandwidths.table)[rx_conf_params->datarate]); } get_rx_window_params(t_symbol, min_rx_symbols, rx_error, RADIO_WAKEUP_TIME, &rx_conf_params->window_timeout, &rx_conf_params->window_offset); } -bool LoRaPHY::rx_config(rx_config_params_t* rx_conf, int8_t* datarate) +bool LoRaPHY::rx_config(rx_config_params_t *rx_conf, int8_t *datarate) { radio_modems_t modem; uint8_t dr = rx_conf->datarate; @@ -878,8 +869,8 @@ bool LoRaPHY::rx_config(rx_config_params_t* rx_conf, int8_t* datarate) return true; } -bool LoRaPHY::tx_config(tx_config_params_t* tx_conf, int8_t* tx_power, - lorawan_time_t* tx_toa) +bool LoRaPHY::tx_config(tx_config_params_t *tx_conf, int8_t *tx_power, + lorawan_time_t *tx_toa) { radio_modems_t modem; int8_t phy_dr = ((uint8_t *)phy_params.datarates.table)[tx_conf->datarate]; @@ -904,7 +895,7 @@ bool LoRaPHY::tx_config(tx_config_params_t* tx_conf, int8_t* tx_power, // Setup the radio frequency _radio->set_channel(list[tx_conf->channel].frequency); - if( tx_conf->datarate == phy_params.max_tx_datarate ) { + if (tx_conf->datarate == phy_params.max_tx_datarate) { // High Speed FSK channel modem = MODEM_FSK; _radio->set_tx_config(modem, phy_tx_power, 25000, bandwidth, @@ -913,11 +904,11 @@ bool LoRaPHY::tx_config(tx_config_params_t* tx_conf, int8_t* tx_power, } else { modem = MODEM_LORA; _radio->set_tx_config(modem, phy_tx_power, 0, bandwidth, phy_dr, 1, 8, - false, true, 0, 0, false, 3000 ); + false, true, 0, 0, false, 3000); } // Setup maximum payload lenght of the radio driver - _radio->set_max_payload_length( modem, tx_conf->pkt_len); + _radio->set_max_payload_length(modem, tx_conf->pkt_len); // Get the time-on-air of the next tx frame *tx_toa = _radio->time_on_air(modem, tx_conf->pkt_len); @@ -928,9 +919,9 @@ bool LoRaPHY::tx_config(tx_config_params_t* tx_conf, int8_t* tx_power, return true; } -uint8_t LoRaPHY::link_ADR_request(adr_req_params_t* link_adr_req, - int8_t* dr_out, int8_t* tx_power_out, - uint8_t* nb_rep_out, uint8_t* nb_bytes_processed) +uint8_t LoRaPHY::link_ADR_request(adr_req_params_t *link_adr_req, + int8_t *dr_out, int8_t *tx_power_out, + uint8_t *nb_rep_out, uint8_t *nb_bytes_processed) { uint8_t status = 0x07; link_adr_params_t adr_settings; @@ -948,7 +939,7 @@ uint8_t LoRaPHY::link_ADR_request(adr_req_params_t* link_adr_req, while (bytes_processed < link_adr_req->payload_size) { // Get ADR request parameters next_index = parse_link_ADR_req(&(link_adr_req->payload[bytes_processed]), - &adr_settings); + &adr_settings); if (next_index == 0) { break; // break loop, since no more request has been found @@ -970,7 +961,7 @@ uint8_t LoRaPHY::link_ADR_request(adr_req_params_t* link_adr_req, // channel mask applies to first 16 channels if (adr_settings.ch_mask_ctrl == 0 || - adr_settings.ch_mask_ctrl == 6) { + adr_settings.ch_mask_ctrl == 6) { for (uint8_t i = 0; i < phy_params.max_channel_cnt; i++) { @@ -986,7 +977,7 @@ uint8_t LoRaPHY::link_ADR_request(adr_req_params_t* link_adr_req, // if channel mask control is 0, we test the bits and // frequencies and change the status if we find a discrepancy if ((mask_bit_test(temp_channel_mask, i)) && - (phy_params.channels.channel_list[i].frequency == 0)) { + (phy_params.channels.channel_list[i].frequency == 0)) { // Trying to enable an undefined channel status &= 0xFE; // Channel mask KO } @@ -1035,7 +1026,7 @@ uint8_t LoRaPHY::link_ADR_request(adr_req_params_t* link_adr_req, return status; } -uint8_t LoRaPHY::accept_rx_param_setup_req(rx_param_setup_req_t* params) +uint8_t LoRaPHY::accept_rx_param_setup_req(rx_param_setup_req_t *params) { uint8_t status = 0x07; @@ -1076,9 +1067,9 @@ bool LoRaPHY::verify_frequency(uint32_t freq) // check all sub bands (if there are sub-bands) to check if the given // frequency falls into any of the frequency ranges - for (uint8_t i=0; i= bands_table[i].lower_band_freq) { + && freq >= bands_table[i].lower_band_freq) { return true; } } @@ -1086,7 +1077,7 @@ bool LoRaPHY::verify_frequency(uint32_t freq) return false; } -uint8_t LoRaPHY::dl_channel_request(dl_channel_req_params_t* params) +uint8_t LoRaPHY::dl_channel_request(dl_channel_req_params_t *params) { if (!phy_params.dl_channel_req_supported) { return 0; @@ -1160,7 +1151,7 @@ int8_t LoRaPHY::get_alternate_DR(uint8_t nb_trials) return datarate; } -void LoRaPHY::calculate_backoff(backoff_params_t* calc_backoff) +void LoRaPHY::calculate_backoff(backoff_params_t *calc_backoff) { band_t *band_table = (band_t *) phy_params.bands.table; channel_params_t *channel_list = phy_params.channels.channel_list; @@ -1189,7 +1180,7 @@ void LoRaPHY::calculate_backoff(backoff_params_t* calc_backoff) // No back-off if the last frame was not a join request and when the // duty cycle is not enabled if (calc_backoff->dc_enabled == false && - calc_backoff->last_tx_was_join_req == false) { + calc_backoff->last_tx_was_join_req == false) { band_table[band_idx].off_time = 0; } else { // Apply band time-off. @@ -1197,9 +1188,9 @@ void LoRaPHY::calculate_backoff(backoff_params_t* calc_backoff) } } -bool LoRaPHY::set_next_channel(channel_selection_params_t* params, - uint8_t* channel, lorawan_time_t* time, - lorawan_time_t* aggregate_timeoff) +bool LoRaPHY::set_next_channel(channel_selection_params_t *params, + uint8_t *channel, lorawan_time_t *time, + lorawan_time_t *aggregate_timeoff) { uint8_t channel_count = 0; uint8_t delay_tx = 0; @@ -1211,7 +1202,7 @@ bool LoRaPHY::set_next_channel(channel_selection_params_t* params, // memory we chose to use a magic number of 16 uint8_t enabled_channels[16]; - memset(enabled_channels, 0xFF, sizeof(uint8_t)*16); + memset(enabled_channels, 0xFF, sizeof(uint8_t) * 16); lorawan_time_t next_tx_delay = 0; band_t *band_table = (band_t *) phy_params.bands.table; @@ -1232,17 +1223,17 @@ bool LoRaPHY::set_next_channel(channel_selection_params_t* params, // Update bands Time OFF next_tx_delay = update_band_timeoff(params->joined, - params->dc_enabled, - band_table, phy_params.bands.size); + params->dc_enabled, + band_table, phy_params.bands.size); // Search how many channels are enabled channel_count = enabled_channel_count(params->joined, params->current_datarate, - phy_params.channels.mask, - enabled_channels, &delay_tx); + phy_params.channels.mask, + enabled_channels, &delay_tx); } else { delay_tx++; next_tx_delay = params->aggregate_timeoff - - _lora_time.get_elapsed_time(params->last_aggregate_tx_time); + - _lora_time.get_elapsed_time(params->last_aggregate_tx_time); } if (channel_count > 0) { @@ -1266,7 +1257,7 @@ bool LoRaPHY::set_next_channel(channel_selection_params_t* params, return false; } -lorawan_status_t LoRaPHY::add_channel(channel_params_t* new_channel, uint8_t id) +lorawan_status_t LoRaPHY::add_channel(channel_params_t *new_channel, uint8_t id) { bool dr_invalid = false; bool freq_invalid = false; @@ -1359,7 +1350,7 @@ bool LoRaPHY::remove_channel(uint8_t channel_id) phy_params.max_channel_cnt); } -void LoRaPHY::set_tx_cont_mode(cw_mode_params_t* params, uint32_t given_frequency) +void LoRaPHY::set_tx_cont_mode(cw_mode_params_t *params, uint32_t given_frequency) { band_t *bands_table = (band_t *) phy_params.bands.table; channel_params_t *channels = phy_params.channels.channel_list; @@ -1372,7 +1363,7 @@ void LoRaPHY::set_tx_cont_mode(cw_mode_params_t* params, uint32_t given_frequenc uint32_t frequency = 0; if (given_frequency == 0) { - frequency = channels[params->channel].frequency; + frequency = channels[params->channel].frequency; } else { frequency = given_frequency; } @@ -1380,7 +1371,7 @@ void LoRaPHY::set_tx_cont_mode(cw_mode_params_t* params, uint32_t given_frequenc // Calculate physical TX power if (params->max_eirp > 0 && params->antenna_gain > 0) { phy_tx_power = compute_tx_power(params->tx_power, params->max_eirp, - params->antenna_gain ); + params->antenna_gain); } else { phy_tx_power = params->tx_power; } diff --git a/features/lorawan/lorastack/phy/LoRaPHY.h b/features/lorawan/lorastack/phy/LoRaPHY.h index df8f898e7dc..4b7fcfef141 100644 --- a/features/lorawan/lorastack/phy/LoRaPHY.h +++ b/features/lorawan/lorastack/phy/LoRaPHY.h @@ -51,7 +51,7 @@ class LoRaPHY : private mbed::NonCopyable { * * @param radio a reference to radio driver object */ - void set_radio_instance(LoRaRadio& radio); + void set_radio_instance(LoRaRadio &radio); /** Puts radio in sleep mode. * @@ -110,28 +110,31 @@ class LoRaPHY : private mbed::NonCopyable { * * @param [in] backoff_params A pointer to backoff parameters. */ - void calculate_backoff(backoff_params_t* backoff_params); - - /** - * Tests if a channel is on or off in the channel mask - */ - inline bool mask_bit_test(const uint16_t *mask, unsigned bit) { - return mask[bit/16] & (1U << (bit % 16)); - } - - /** - * Tests if a channel is on or off in the channel mask - */ - inline void mask_bit_set(uint16_t *mask, unsigned bit) { - mask[bit/16] |= (1U << (bit % 16)); - } - - /** - * Tests if a channel is on or off in the channel mask - */ - inline void mask_bit_clear(uint16_t *mask, unsigned bit) { - mask[bit/16] &= ~(1U << (bit % 16)); - } + void calculate_backoff(backoff_params_t *backoff_params); + + /** + * Tests if a channel is on or off in the channel mask + */ + inline bool mask_bit_test(const uint16_t *mask, unsigned bit) + { + return mask[bit / 16] & (1U << (bit % 16)); + } + + /** + * Tests if a channel is on or off in the channel mask + */ + inline void mask_bit_set(uint16_t *mask, unsigned bit) + { + mask[bit / 16] |= (1U << (bit % 16)); + } + + /** + * Tests if a channel is on or off in the channel mask + */ + inline void mask_bit_clear(uint16_t *mask, unsigned bit) + { + mask[bit / 16] &= ~(1U << (bit % 16)); + } /** Entertain a new channel request MAC command. * @@ -143,7 +146,7 @@ class LoRaPHY : private mbed::NonCopyable { * * @return bit mask, according to the LoRaWAN spec 1.0.2. */ - virtual uint8_t request_new_channel(new_channel_req_params_t* new_channel_req); + virtual uint8_t request_new_channel(new_channel_req_params_t *new_channel_req); /** Grants access to PHY layer parameters. * @@ -155,7 +158,7 @@ class LoRaPHY : private mbed::NonCopyable { * * @return A structure containing the requested PHY parameter value. */ - virtual phy_param_t get_phy_params(get_phy_params_t* get_phy); + virtual phy_param_t get_phy_params(get_phy_params_t *get_phy); /** Process PHY layer state after a successful transmission. * @@ -164,7 +167,7 @@ class LoRaPHY : private mbed::NonCopyable { * * @param [in] tx_done A pointer to set_band_txdone_params_t */ - virtual void set_last_tx_done(set_band_txdone_params_t* tx_done); + virtual void set_last_tx_done(set_band_txdone_params_t *tx_done); /** Enables default channels only. * @@ -182,7 +185,7 @@ class LoRaPHY : private mbed::NonCopyable { * * @return True, if the parameter is valid. */ - virtual bool verify(verification_params_t* verify, phy_attributes_t phy_attr); + virtual bool verify(verification_params_t *verify, phy_attributes_t phy_attr); /** Processes the incoming CF-list. * @@ -191,7 +194,7 @@ class LoRaPHY : private mbed::NonCopyable { * * @param cflist_params A pointer to cflist_params_t. */ - virtual void apply_cf_list(cflist_params_t* cflist_params); + virtual void apply_cf_list(cflist_params_t *cflist_params); /** Calculates the next datarate to set, when ADR is on or off. * @@ -206,8 +209,8 @@ class LoRaPHY : private mbed::NonCopyable { * * @return True, if an ADR request should be performed. */ - bool get_next_ADR(bool restore_channel_mask, int8_t& dr_out, - int8_t& tx_power_out, uint32_t& adr_ack_counter); + bool get_next_ADR(bool restore_channel_mask, int8_t &dr_out, + int8_t &tx_power_out, uint32_t &adr_ack_counter); /** Configure radio reception. * @@ -217,7 +220,7 @@ class LoRaPHY : private mbed::NonCopyable { * * @return True, if the configuration was applied successfully. */ - virtual bool rx_config(rx_config_params_t* config, int8_t* datarate); + virtual bool rx_config(rx_config_params_t *config, int8_t *datarate); /** Computing Receive Windows * @@ -287,8 +290,8 @@ class LoRaPHY : private mbed::NonCopyable { * * @return True, if the configuration was applied successfully. */ - virtual bool tx_config(tx_config_params_t* tx_config, int8_t* tx_power, - lorawan_time_t* tx_toa); + virtual bool tx_config(tx_config_params_t *tx_config, int8_t *tx_power, + lorawan_time_t *tx_toa); /** Processes a Link ADR Request. * @@ -304,10 +307,10 @@ class LoRaPHY : private mbed::NonCopyable { * * @return The status of the operation, according to the LoRaMAC specification. */ - virtual uint8_t link_ADR_request(adr_req_params_t* params, - int8_t* dr_out, int8_t* tx_power_out, - uint8_t* nb_rep_out, - uint8_t* nb_bytes_parsed); + virtual uint8_t link_ADR_request(adr_req_params_t *params, + int8_t *dr_out, int8_t *tx_power_out, + uint8_t *nb_rep_out, + uint8_t *nb_bytes_parsed); /** Accept or rejects RxParamSetupReq MAC command * @@ -318,7 +321,7 @@ class LoRaPHY : private mbed::NonCopyable { * * @return The status of the operation, according to the LoRaWAN specification. */ - virtual uint8_t accept_rx_param_setup_req(rx_param_setup_req_t* params); + virtual uint8_t accept_rx_param_setup_req(rx_param_setup_req_t *params); /** Makes decision whether to accept or reject TxParamSetupReq MAC command * @@ -328,7 +331,7 @@ class LoRaPHY : private mbed::NonCopyable { * accepted and MAC can apply TX parameters received * form Network Server. Otherwise false is returned. */ - virtual bool accept_tx_param_setup_req(tx_param_setup_req_t* params); + virtual bool accept_tx_param_setup_req(tx_param_setup_req_t *params); /** Processes a DlChannelReq MAC command. * @@ -336,7 +339,7 @@ class LoRaPHY : private mbed::NonCopyable { * * @return The status of the operation, according to the LoRaWAN specification. */ - virtual uint8_t dl_channel_request(dl_channel_req_params_t* params); + virtual uint8_t dl_channel_request(dl_channel_req_params_t *params); /** Alternates the datarate of the channel for the join request. * @@ -361,9 +364,9 @@ class LoRaPHY : private mbed::NonCopyable { * * @return Function status [1: OK, 0: Unable to find a channel on the current datarate]. */ - virtual bool set_next_channel(channel_selection_params_t* nextChanParams, - uint8_t* channel, lorawan_time_t* time, - lorawan_time_t* aggregatedTimeOff); + virtual bool set_next_channel(channel_selection_params_t *nextChanParams, + uint8_t *channel, lorawan_time_t *time, + lorawan_time_t *aggregatedTimeOff); /** Adds a channel to the channel list. * @@ -377,7 +380,7 @@ class LoRaPHY : private mbed::NonCopyable { * @return LORAWAN_STATUS_OK if everything goes fine, negative error code * otherwise. */ - virtual lorawan_status_t add_channel(channel_params_t* new_channel, uint8_t id); + virtual lorawan_status_t add_channel(channel_params_t *new_channel, uint8_t id); /** Removes a channel from the channel list. * @@ -393,7 +396,7 @@ class LoRaPHY : private mbed::NonCopyable { * * @param [in] frequency Frequency to transmit at */ - virtual void set_tx_cont_mode(cw_mode_params_t* continuous_wave, + virtual void set_tx_cont_mode(cw_mode_params_t *continuous_wave, uint32_t frequency = 0); /** Computes new data rate according to the given offset @@ -427,13 +430,13 @@ class LoRaPHY : private mbed::NonCopyable { /** * Verifies, if a datarate is available on an active channel. */ - bool verify_channel_DR(uint8_t nbChannels, uint16_t* channelsMask, int8_t dr, - int8_t minDr, int8_t maxDr, channel_params_t* channels); + bool verify_channel_DR(uint8_t nbChannels, uint16_t *channelsMask, int8_t dr, + int8_t minDr, int8_t maxDr, channel_params_t *channels); /** * Disables a channel in a given channels mask. */ - bool disable_channel(uint16_t* channel_mask, uint8_t id, uint8_t max_channels); + bool disable_channel(uint16_t *channel_mask, uint8_t id, uint8_t max_channels); /** * Counts number of bits on in a given mask @@ -443,36 +446,36 @@ class LoRaPHY : private mbed::NonCopyable { /** * Counts the number of active channels in a given channels mask. */ - uint8_t num_active_channels(uint16_t* channel_mask, uint8_t start_idx, + uint8_t num_active_channels(uint16_t *channel_mask, uint8_t start_idx, uint8_t stop_idx); /** * Copy channel masks. */ - void copy_channel_mask(uint16_t* dest_mask, uint16_t* src_mask, uint8_t len); + void copy_channel_mask(uint16_t *dest_mask, uint16_t *src_mask, uint8_t len); /** * Updates the time-offs of the bands. */ - lorawan_time_t update_band_timeoff(bool joined, bool dutyCycle, band_t* bands, + lorawan_time_t update_band_timeoff(bool joined, bool dutyCycle, band_t *bands, uint8_t nb_bands); /** * Parses the parameter of an LinkAdrRequest. */ - uint8_t parse_link_ADR_req(uint8_t* payload, link_adr_params_t* adr_params); + uint8_t parse_link_ADR_req(uint8_t *payload, link_adr_params_t *adr_params); /** * Verifies and updates the datarate, the TX power and the number of repetitions * of a LinkAdrRequest. */ - uint8_t verify_link_ADR_req(verify_adr_params_t* verify_params, int8_t* dr, - int8_t* tx_pow, uint8_t* nb_rep); + uint8_t verify_link_ADR_req(verify_adr_params_t *verify_params, int8_t *dr, + int8_t *tx_pow, uint8_t *nb_rep); /** * Computes the symbol time for LoRa modulation. */ - double compute_symb_timeout_lora(uint8_t phy_dr, uint32_t bandwidth ); + double compute_symb_timeout_lora(uint8_t phy_dr, uint32_t bandwidth); /** * Computes the symbol time for FSK modulation. @@ -484,7 +487,7 @@ class LoRaPHY : private mbed::NonCopyable { */ void get_rx_window_params(double t_symbol, uint8_t min_rx_symbols, uint32_t rx_error, uint32_t wakeup_time, - uint32_t* window_timeout, int32_t* window_offset); + uint32_t *window_timeout, int32_t *window_offset); /** * Computes the txPower, based on the max EIRP and the antenna gain. @@ -507,8 +510,8 @@ class LoRaPHY : private mbed::NonCopyable { uint8_t get_bandwidth(uint8_t dr_index); uint8_t enabled_channel_count(bool joined, uint8_t datarate, - const uint16_t *mask, uint8_t* enabledChannels, - uint8_t* delayTx); + const uint16_t *mask, uint8_t *enabledChannels, + uint8_t *delayTx); }; diff --git a/features/lorawan/lorastack/phy/LoRaPHYAS923.cpp b/features/lorawan/lorastack/phy/LoRaPHYAS923.cpp index 5a10bca24b7..a95736dd080 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYAS923.cpp +++ b/features/lorawan/lorastack/phy/LoRaPHYAS923.cpp @@ -194,13 +194,13 @@ static const band_t AS923_BAND0 = {100, AS923_MAX_TX_POWER, 0, 0, 0, 923000000, * LoRaMac default channel 1 * Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band } */ -static const channel_params_t AS923_LC1 = { 923200000, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 0 }; +static const channel_params_t AS923_LC1 = { 923200000, 0, { ((DR_5 << 4) | DR_0) }, 0 }; /*! * LoRaMac default channel 2 * Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band } */ -static const channel_params_t AS923_LC2 = { 923400000, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 0 }; +static const channel_params_t AS923_LC2 = { 923400000, 0, { ((DR_5 << 4) | DR_0) }, 0 }; /*! * LoRaMac channels which are allowed for the join procedure @@ -228,12 +228,12 @@ static const uint8_t datarates_AS923[] = {12, 11, 10, 9, 8, 7, 7, 50}; static const uint32_t bandwidths_AS923[] = {125000, 125000, 125000, 125000, 125000, 125000, 250000, 0}; #if (MBED_CONF_LORA_DWELL_TIME == 0) - static const uint8_t max_payload_table[] = {51, 51, 51, 115, 242, 242, 242, 242}; - static const uint8_t max_payload_table_with_repeater[] = {51, 51, 51, 115, 222, 222, 222, 222}; +static const uint8_t max_payload_table[] = {51, 51, 51, 115, 242, 242, 242, 242}; +static const uint8_t max_payload_table_with_repeater[] = {51, 51, 51, 115, 222, 222, 222, 222}; #else - // this is the default, i.e., - static const uint8_t max_payload_table[] = {0, 0, 11, 53, 125, 242, 242, 242}; - static const uint8_t max_payload_table_with_repeater[] = {0, 0, 11, 53, 125, 242, 242, 242}; +// this is the default, i.e., +static const uint8_t max_payload_table[] = {0, 0, 11, 53, 125, 242, 242, 242}; +static const uint8_t max_payload_table_with_repeater[] = {0, 0, 11, 53, 125, 242, 242, 242}; #endif /*! @@ -334,9 +334,9 @@ int8_t LoRaPHYAS923::get_alternate_DR(uint8_t nb_trials) return AS923_DWELL_LIMIT_DATARATE; } -bool LoRaPHYAS923::set_next_channel(channel_selection_params_t* next_channel_prams, - uint8_t* channel, lorawan_time_t* time, - lorawan_time_t* aggregate_timeoff) +bool LoRaPHYAS923::set_next_channel(channel_selection_params_t *next_channel_prams, + uint8_t *channel, lorawan_time_t *time, + lorawan_time_t *aggregate_timeoff) { uint8_t next_channel_idx = 0; uint8_t nb_enabled_channels = 0; @@ -360,9 +360,9 @@ bool LoRaPHYAS923::set_next_channel(channel_selection_params_t* next_channel_pra // Search how many channels are enabled nb_enabled_channels = enabled_channel_count(next_channel_prams->joined, - next_channel_prams->current_datarate, - channel_mask, - enabled_channels, &delay_tx); + next_channel_prams->current_datarate, + channel_mask, + enabled_channels, &delay_tx); } else { delay_tx++; next_tx_delay = next_channel_prams->aggregate_timeoff - _lora_time.get_elapsed_time(next_channel_prams->last_aggregate_tx_time); @@ -374,7 +374,7 @@ bool LoRaPHYAS923::set_next_channel(channel_selection_params_t* next_channel_pra for (uint8_t i = 0, j = get_random(0, nb_enabled_channels - 1); i < AS923_MAX_NB_CHANNELS; i++) { next_channel_idx = enabled_channels[j]; - j = ( j + 1 ) % nb_enabled_channels; + j = (j + 1) % nb_enabled_channels; // Perform carrier sense for AS923_CARRIER_SENSE_TIME // If the channel is free, we can stop the LBT mechanism @@ -401,7 +401,7 @@ bool LoRaPHYAS923::set_next_channel(channel_selection_params_t* next_channel_pra } // Datarate not supported by any channel, restore defaults - channel_mask[0] |= LC( 1 ) + LC( 2 ); + channel_mask[0] |= LC(1) + LC(2); *time = 0; return false; } diff --git a/features/lorawan/lorastack/phy/LoRaPHYAS923.h b/features/lorawan/lorastack/phy/LoRaPHYAS923.h index 17f943dbce1..87705178e0f 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYAS923.h +++ b/features/lorawan/lorastack/phy/LoRaPHYAS923.h @@ -55,11 +55,11 @@ class LoRaPHYAS923 : public LoRaPHY { virtual int8_t get_alternate_DR(uint8_t nb_trials); - virtual bool set_next_channel(channel_selection_params_t* nextChanParams, - uint8_t* channel, lorawan_time_t* time, - lorawan_time_t* aggregatedTimeOff ); + virtual bool set_next_channel(channel_selection_params_t *nextChanParams, + uint8_t *channel, lorawan_time_t *time, + lorawan_time_t *aggregatedTimeOff); - virtual uint8_t apply_DR_offset(int8_t dr, int8_t drOffset ); + virtual uint8_t apply_DR_offset(int8_t dr, int8_t drOffset); private: channel_params_t channels[AS923_MAX_NB_CHANNELS]; diff --git a/features/lorawan/lorastack/phy/LoRaPHYAU915.cpp b/features/lorawan/lorastack/phy/LoRaPHYAU915.cpp index c1e1ecd2f94..72156cd6211 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYAU915.cpp +++ b/features/lorawan/lorastack/phy/LoRaPHYAU915.cpp @@ -192,37 +192,42 @@ static const uint8_t datarates_AU915[] = {12, 11, 10, 9, 8, 7, 8, 0, 12, 11, 10, * Bandwidths table definition in Hz */ static const uint32_t bandwidths_AU915[] = { 125000, 125000, 125000, 125000, - 125000, 125000, 500000, 0, 500000, 500000, 500000, 500000, 500000, 500000, - 0, 0 }; + 125000, 125000, 500000, 0, 500000, 500000, 500000, 500000, 500000, 500000, + 0, 0 + }; /*! * Up/Down link data rates offset definition */ -static const int8_t datarate_offsets_AU915[7][6] = { { DR_8, DR_8, DR_8, DR_8, -DR_8, DR_8 }, // DR_0 +static const int8_t datarate_offsets_AU915[7][6] = { { + DR_8, DR_8, DR_8, DR_8, + DR_8, DR_8 + }, // DR_0 { DR_9, DR_8, DR_8, DR_8, DR_8, DR_8 }, // DR_1 { DR_10, DR_9, DR_8, DR_8, DR_8, DR_8 }, // DR_2 { DR_11, DR_10, DR_9, DR_8, DR_8, DR_8 }, // DR_3 { DR_12, DR_11, DR_10, DR_9, DR_8, DR_8 }, // DR_4 { DR_13, DR_12, DR_11, DR_10, DR_9, DR_8 }, // DR_5 { DR_13, DR_13, DR_12, DR_11, DR_10, DR_9 }, // DR_6 - }; +}; /*! * Maximum payload with respect to the datarate index. Cannot operate with repeater. */ static const uint8_t max_payload_AU915[] = { 51, 51, 51, 115, 242, 242, - 242, 0, 53, 129, 242, 242, 242, 242, 0, 0 }; + 242, 0, 53, 129, 242, 242, 242, 242, 0, 0 + }; /*! * Maximum payload with respect to the datarate index. Can operate with repeater. */ static const uint8_t max_payload_with_repeater_AU915[] = { 51, 51, 51, 115, - 222, 222, 222, 0, 33, 109, 222, 222, 222, 222, 0, 0 }; + 222, 222, 222, 0, 33, 109, 222, 222, 222, 222, 0, 0 + }; LoRaPHYAU915::LoRaPHYAU915(LoRaWANTimeHandler &lora_time) - : LoRaPHY(lora_time) + : LoRaPHY(lora_time) { bands[0] = AU915_BAND0; @@ -230,14 +235,14 @@ LoRaPHYAU915::LoRaPHYAU915(LoRaWANTimeHandler &lora_time) // 125 kHz channels Upstream only for (uint8_t i = 0; i < AU915_MAX_NB_CHANNELS - 8; i++) { channels[i].frequency = 915200000 + i * 200000; - channels[i].dr_range.value = ( DR_5 << 4) | DR_0; + channels[i].dr_range.value = (DR_5 << 4) | DR_0; channels[i].band = 0; } // 500 kHz channels // Upstream and downstream both for (uint8_t i = AU915_MAX_NB_CHANNELS - 8; i < AU915_MAX_NB_CHANNELS; i++) { - channels[i].frequency = 915900000 + (i - ( AU915_MAX_NB_CHANNELS - 8)) * 1600000; - channels[i].dr_range.value = ( DR_6 << 4) | DR_6; + channels[i].frequency = 915900000 + (i - (AU915_MAX_NB_CHANNELS - 8)) * 1600000; + channels[i].dr_range.value = (DR_6 << 4) | DR_6; channels[i].band = 0; } @@ -328,7 +333,7 @@ LoRaPHYAU915::~LoRaPHYAU915() { } -bool LoRaPHYAU915::rx_config(rx_config_params_t* params, int8_t* datarate) +bool LoRaPHYAU915::rx_config(rx_config_params_t *params, int8_t *datarate) { int8_t dr = params->datarate; uint8_t max_payload = 0; @@ -342,7 +347,7 @@ bool LoRaPHYAU915::rx_config(rx_config_params_t* params, int8_t* datarate) if (params->rx_slot == RX_SLOT_WIN_1) { // Apply window 1 frequency frequency = AU915_FIRST_RX1_CHANNEL - + (params->channel % 8) * AU915_STEPWIDTH_RX1_CHANNEL; + + (params->channel % 8) * AU915_STEPWIDTH_RX1_CHANNEL; } // Read the physical datarate from the datarates table @@ -371,8 +376,8 @@ bool LoRaPHYAU915::rx_config(rx_config_params_t* params, int8_t* datarate) return true; } -bool LoRaPHYAU915::tx_config(tx_config_params_t* params, int8_t* tx_power, - lorawan_time_t* tx_toa) +bool LoRaPHYAU915::tx_config(tx_config_params_t *params, int8_t *tx_power, + lorawan_time_t *tx_toa) { int8_t phy_dr = datarates_AU915[params->datarate]; @@ -408,10 +413,10 @@ bool LoRaPHYAU915::tx_config(tx_config_params_t* params, int8_t* tx_power, return true; } -uint8_t LoRaPHYAU915::link_ADR_request(adr_req_params_t* params, - int8_t* dr_out, int8_t* tx_power_out, - uint8_t* nb_rep_out, - uint8_t* nb_bytes_parsed) +uint8_t LoRaPHYAU915::link_ADR_request(adr_req_params_t *params, + int8_t *dr_out, int8_t *tx_power_out, + uint8_t *nb_rep_out, + uint8_t *nb_bytes_parsed) { uint8_t status = 0x07; link_adr_params_t adr_settings; @@ -504,7 +509,7 @@ uint8_t LoRaPHYAU915::link_ADR_request(adr_req_params_t* params, return status; } -uint8_t LoRaPHYAU915::accept_rx_param_setup_req(rx_param_setup_req_t* params) +uint8_t LoRaPHYAU915::accept_rx_param_setup_req(rx_param_setup_req_t *params) { uint8_t status = 0x07; uint32_t freq = params->frequency; @@ -516,7 +521,7 @@ uint8_t LoRaPHYAU915::accept_rx_param_setup_req(rx_param_setup_req_t* params) || (freq < AU915_FIRST_RX1_CHANNEL) || (freq > AU915_LAST_RX1_CHANNEL) || (((freq - (uint32_t) AU915_FIRST_RX1_CHANNEL) - % (uint32_t) AU915_STEPWIDTH_RX1_CHANNEL) != 0)) { + % (uint32_t) AU915_STEPWIDTH_RX1_CHANNEL) != 0)) { status &= 0xFE; // Channel frequency KO } @@ -555,9 +560,9 @@ int8_t LoRaPHYAU915::get_alternate_DR(uint8_t nb_trials) return datarate; } -bool LoRaPHYAU915::set_next_channel(channel_selection_params_t* next_chan_params, - uint8_t* channel, lorawan_time_t* time, - lorawan_time_t* aggregated_timeOff) +bool LoRaPHYAU915::set_next_channel(channel_selection_params_t *next_chan_params, + uint8_t *channel, lorawan_time_t *time, + lorawan_time_t *aggregated_timeOff) { uint8_t nb_enabled_channels = 0; uint8_t delay_tx = 0; @@ -589,9 +594,9 @@ bool LoRaPHYAU915::set_next_channel(channel_selection_params_t* next_chan_params // Search how many channels are enabled nb_enabled_channels = enabled_channel_count(next_chan_params->joined, - next_chan_params->current_datarate, - current_channel_mask, - enabled_channels, &delay_tx); + next_chan_params->current_datarate, + current_channel_mask, + enabled_channels, &delay_tx); } else { delay_tx++; next_tx_delay = next_chan_params->aggregate_timeoff - _lora_time.get_elapsed_time(next_chan_params->last_aggregate_tx_time); @@ -602,7 +607,7 @@ bool LoRaPHYAU915::set_next_channel(channel_selection_params_t* next_chan_params *channel = enabled_channels[get_random(0, nb_enabled_channels - 1)]; // Disable the channel in the mask disable_channel(current_channel_mask, *channel, - AU915_MAX_NB_CHANNELS - 8); + AU915_MAX_NB_CHANNELS - 8); *time = 0; return true; diff --git a/features/lorawan/lorastack/phy/LoRaPHYAU915.h b/features/lorawan/lorastack/phy/LoRaPHYAU915.h index 5c7c358f610..f2a95464ef8 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYAU915.h +++ b/features/lorawan/lorastack/phy/LoRaPHYAU915.h @@ -49,30 +49,30 @@ #define AU915_CHANNEL_MASK_SIZE 5 -class LoRaPHYAU915 : public LoRaPHY{ +class LoRaPHYAU915 : public LoRaPHY { public: LoRaPHYAU915(LoRaWANTimeHandler &lora_time); virtual ~LoRaPHYAU915(); - virtual bool rx_config(rx_config_params_t* config, int8_t* datarate); + virtual bool rx_config(rx_config_params_t *config, int8_t *datarate); - virtual bool tx_config(tx_config_params_t* config, int8_t* txPower, - lorawan_time_t* txTimeOnAir); + virtual bool tx_config(tx_config_params_t *config, int8_t *txPower, + lorawan_time_t *txTimeOnAir); - virtual uint8_t link_ADR_request(adr_req_params_t* params, - int8_t* drOut, int8_t* txPowOut, - uint8_t* nbRepOut, - uint8_t* nbBytesParsed); + virtual uint8_t link_ADR_request(adr_req_params_t *params, + int8_t *drOut, int8_t *txPowOut, + uint8_t *nbRepOut, + uint8_t *nbBytesParsed); - virtual uint8_t accept_rx_param_setup_req(rx_param_setup_req_t* params); + virtual uint8_t accept_rx_param_setup_req(rx_param_setup_req_t *params); virtual int8_t get_alternate_DR(uint8_t nb_trials); - virtual bool set_next_channel(channel_selection_params_t* next_chan_params, - uint8_t* channel, lorawan_time_t* time, - lorawan_time_t* aggregate_timeoff); + virtual bool set_next_channel(channel_selection_params_t *next_chan_params, + uint8_t *channel, lorawan_time_t *time, + lorawan_time_t *aggregate_timeoff); virtual uint8_t apply_DR_offset(int8_t dr, int8_t dr_offset); diff --git a/features/lorawan/lorastack/phy/LoRaPHYCN470.cpp b/features/lorawan/lorastack/phy/LoRaPHYCN470.cpp index 68ff3f55256..5544229069c 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYCN470.cpp +++ b/features/lorawan/lorastack/phy/LoRaPHYCN470.cpp @@ -205,16 +205,15 @@ static const uint8_t max_payloads_with_repeater_CN470[] = {51, 51, 51, 115, 222, LoRaPHYCN470::LoRaPHYCN470(LoRaWANTimeHandler &lora_time) - : LoRaPHY(lora_time) + : LoRaPHY(lora_time) { bands[0] = CN470_BAND0; // Channels // 125 kHz channels - for( uint8_t i = 0; i < CN470_MAX_NB_CHANNELS; i++ ) - { + for (uint8_t i = 0; i < CN470_MAX_NB_CHANNELS; i++) { channels[i].frequency = 470300000 + i * 200000; - channels[i].dr_range.value = ( DR_5 << 4 ) | DR_0; + channels[i].dr_range.value = (DR_5 << 4) | DR_0; channels[i].band = 0; } @@ -303,7 +302,7 @@ LoRaPHYCN470::~LoRaPHYCN470() { } -bool LoRaPHYCN470::rx_config(rx_config_params_t* config, int8_t* datarate) +bool LoRaPHYCN470::rx_config(rx_config_params_t *config, int8_t *datarate) { int8_t dr = config->datarate; uint8_t max_payload = 0; @@ -319,8 +318,7 @@ bool LoRaPHYCN470::rx_config(rx_config_params_t* config, int8_t* datarate) _radio->unlock(); - if( config->rx_slot == RX_SLOT_WIN_1 ) - { + if (config->rx_slot == RX_SLOT_WIN_1) { // Apply window 1 frequency frequency = CN470_FIRST_RX1_CHANNEL + (config->channel % 48) * CN470_STEPWIDTH_RX1_CHANNEL; } @@ -353,8 +351,8 @@ bool LoRaPHYCN470::rx_config(rx_config_params_t* config, int8_t* datarate) return true; } -bool LoRaPHYCN470::tx_config(tx_config_params_t* config, int8_t* tx_power, - lorawan_time_t* tx_toa) +bool LoRaPHYCN470::tx_config(tx_config_params_t *config, int8_t *tx_power, + lorawan_time_t *tx_toa) { int8_t phy_dr = datarates_CN470[config->datarate]; @@ -373,8 +371,8 @@ bool LoRaPHYCN470::tx_config(tx_config_params_t* config, int8_t* tx_power, _radio->set_channel(channels[config->channel].frequency); - _radio->set_tx_config(MODEM_LORA, phy_tx_power, 0, 0, phy_dr, 1, 8, false, true, - 0, 0, false, 3000); + _radio->set_tx_config(MODEM_LORA, phy_tx_power, 0, 0, phy_dr, 1, 8, false, true, + 0, 0, false, 3000); // Setup maximum payload lenght of the radio driver _radio->set_max_payload_length(MODEM_LORA, config->pkt_len); @@ -389,10 +387,10 @@ bool LoRaPHYCN470::tx_config(tx_config_params_t* config, int8_t* tx_power, return true; } -uint8_t LoRaPHYCN470::link_ADR_request(adr_req_params_t* params, - int8_t* dr_out, int8_t* tx_power_out, - uint8_t* nb_rep_out, - uint8_t* nb_bytes_parsed) +uint8_t LoRaPHYCN470::link_ADR_request(adr_req_params_t *params, + int8_t *dr_out, int8_t *tx_power_out, + uint8_t *nb_rep_out, + uint8_t *nb_bytes_parsed) { uint8_t status = 0x07; link_adr_params_t adr_settings; @@ -405,7 +403,7 @@ uint8_t LoRaPHYCN470::link_ADR_request(adr_req_params_t* params, // Initialize local copy of channels mask copy_channel_mask(temp_channel_masks, channel_mask, CN470_CHANNEL_MASK_SIZE); - while(bytes_processed < params->payload_size) { + while (bytes_processed < params->payload_size) { // Get ADR request parameters next_index = parse_link_ADR_req(&(params->payload[bytes_processed]), &adr_settings); @@ -430,7 +428,7 @@ uint8_t LoRaPHYCN470::link_ADR_request(adr_req_params_t* params, temp_channel_masks[4] = 0xFFFF; temp_channel_masks[5] = 0xFFFF; - } else if( adr_settings.ch_mask_ctrl == 7 ) { + } else if (adr_settings.ch_mask_ctrl == 7) { status &= 0xFE; // Channel mask KO @@ -438,8 +436,8 @@ uint8_t LoRaPHYCN470::link_ADR_request(adr_req_params_t* params, for (uint8_t i = 0; i < 16; i++) { - if (((adr_settings.channel_mask & (1 << i)) != 0 ) && - (channels[adr_settings.ch_mask_ctrl * 16 + i].frequency == 0)) { + if (((adr_settings.channel_mask & (1 << i)) != 0) && + (channels[adr_settings.ch_mask_ctrl * 16 + i].frequency == 0)) { // Trying to enable an undefined channel status &= 0xFE; // Channel mask KO } @@ -479,7 +477,7 @@ uint8_t LoRaPHYCN470::link_ADR_request(adr_req_params_t* params, return status; } -uint8_t LoRaPHYCN470::accept_rx_param_setup_req(rx_param_setup_req_t* params) +uint8_t LoRaPHYCN470::accept_rx_param_setup_req(rx_param_setup_req_t *params) { uint8_t status = 0x07; uint32_t freq = params->frequency; diff --git a/features/lorawan/lorastack/phy/LoRaPHYCN470.h b/features/lorawan/lorastack/phy/LoRaPHYCN470.h index 846c849acb0..efdb330721e 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYCN470.h +++ b/features/lorawan/lorastack/phy/LoRaPHYCN470.h @@ -56,16 +56,16 @@ class LoRaPHYCN470 : public LoRaPHY { LoRaPHYCN470(LoRaWANTimeHandler &lora_time); virtual ~LoRaPHYCN470(); - virtual bool rx_config(rx_config_params_t* config, int8_t* datarate ); + virtual bool rx_config(rx_config_params_t *config, int8_t *datarate); - virtual bool tx_config(tx_config_params_t* config, int8_t* tx_power, - lorawan_time_t* tx_toa); + virtual bool tx_config(tx_config_params_t *config, int8_t *tx_power, + lorawan_time_t *tx_toa); - virtual uint8_t link_ADR_request(adr_req_params_t* params, int8_t* dr_out, - int8_t* tx_power_out, uint8_t* nb_rep_out, - uint8_t* nb_bytes_parsed); + virtual uint8_t link_ADR_request(adr_req_params_t *params, int8_t *dr_out, + int8_t *tx_power_out, uint8_t *nb_rep_out, + uint8_t *nb_bytes_parsed); - virtual uint8_t accept_rx_param_setup_req(rx_param_setup_req_t* params); + virtual uint8_t accept_rx_param_setup_req(rx_param_setup_req_t *params); private: diff --git a/features/lorawan/lorastack/phy/LoRaPHYCN779.cpp b/features/lorawan/lorastack/phy/LoRaPHYCN779.cpp index 66783d32a23..6399f8589fe 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYCN779.cpp +++ b/features/lorawan/lorastack/phy/LoRaPHYCN779.cpp @@ -191,18 +191,18 @@ static const band_t CN779_BAND0 = {100, CN779_MAX_TX_POWER, 0, 0, 0, 779500000, * LoRaMac default channel 1 * Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band } */ -static const channel_params_t CN779_LC1 = {779500000, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 0}; +static const channel_params_t CN779_LC1 = {779500000, 0, { ((DR_5 << 4) | DR_0) }, 0}; /*! * LoRaMac default channel 2 * Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band } */ -static const channel_params_t CN779_LC2 = {779700000, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 0}; +static const channel_params_t CN779_LC2 = {779700000, 0, { ((DR_5 << 4) | DR_0) }, 0}; /*! * LoRaMac default channel 3 * Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band } */ -static const channel_params_t CN779_LC3 = {779900000, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 0}; +static const channel_params_t CN779_LC3 = {779900000, 0, { ((DR_5 << 4) | DR_0) }, 0}; /*! * LoRaMac channels which are allowed for the join procedure @@ -231,7 +231,7 @@ static const uint8_t max_payloads_with_repeater_CN779[] = {51, 51, 51, 115, 222, LoRaPHYCN779::LoRaPHYCN779(LoRaWANTimeHandler &lora_time) - : LoRaPHY(lora_time) + : LoRaPHY(lora_time) { bands[0] = CN779_BAND0; diff --git a/features/lorawan/lorastack/phy/LoRaPHYEU433.cpp b/features/lorawan/lorastack/phy/LoRaPHYEU433.cpp index 6345b5395c8..337f5516fb9 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYEU433.cpp +++ b/features/lorawan/lorastack/phy/LoRaPHYEU433.cpp @@ -191,19 +191,19 @@ static const band_t EU433_BAND0 = {100, EU433_MAX_TX_POWER, 0, 0, 0, 433175000, * LoRaMac default channel 1 * Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band } */ -static const channel_params_t EU433_LC1 = {433175000, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 0}; +static const channel_params_t EU433_LC1 = {433175000, 0, { ((DR_5 << 4) | DR_0) }, 0}; /*! * LoRaMac default channel 2 * Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band } */ -static const channel_params_t EU433_LC2 = {433375000, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 0}; +static const channel_params_t EU433_LC2 = {433375000, 0, { ((DR_5 << 4) | DR_0) }, 0}; /*! * LoRaMac default channel 3 * Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band } */ -static const channel_params_t EU433_LC3 = {433575000, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 0}; +static const channel_params_t EU433_LC3 = {433575000, 0, { ((DR_5 << 4) | DR_0) }, 0}; /*! * LoRaMac channels which are allowed for the join procedure @@ -232,7 +232,7 @@ static const uint8_t max_payloads_with_repeater_EU433[] = {51, 51, 51, 115, 222, LoRaPHYEU433::LoRaPHYEU433(LoRaWANTimeHandler &lora_time) - : LoRaPHY(lora_time) + : LoRaPHY(lora_time) { bands[0] = EU433_BAND0; diff --git a/features/lorawan/lorastack/phy/LoRaPHYEU868.cpp b/features/lorawan/lorastack/phy/LoRaPHYEU868.cpp index fcf8c4ce7fc..c9426b3eb67 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYEU868.cpp +++ b/features/lorawan/lorastack/phy/LoRaPHYEU868.cpp @@ -182,12 +182,12 @@ * Band 0 definition * { DutyCycle, TxMaxPower, LastJoinTxDoneTime, LastTxDoneTime, TimeOff } */ -static const band_t EU868_BAND0 = {100 , EU868_MAX_TX_POWER, 0, 0, 0,865000000, 868000000}; // 1.0 % +static const band_t EU868_BAND0 = {100, EU868_MAX_TX_POWER, 0, 0, 0, 865000000, 868000000}; // 1.0 % /*! * Band 1 definition * { DutyCycle, TxMaxPower, LastJoinTxDoneTime, LastTxDoneTime, TimeOff } */ -static const band_t EU868_BAND1 = {100 , EU868_MAX_TX_POWER, 0, 0, 0, 868100000, 868600000}; // 1.0 % +static const band_t EU868_BAND1 = {100, EU868_MAX_TX_POWER, 0, 0, 0, 868100000, 868600000}; // 1.0 % /*! * Band 2 definition @@ -199,13 +199,13 @@ static const band_t EU868_BAND2 = {1000, EU868_MAX_TX_POWER, 0, 0, 0, 868700000, * Band 3 definition * Band = { DutyCycle, TxMaxPower, LastJoinTxDoneTime, LastTxDoneTime, TimeOff } */ -static const band_t EU868_BAND3 = {10 , EU868_MAX_TX_POWER, 0, 0, 0, 869400000, 869650000}; // 10.0 % +static const band_t EU868_BAND3 = {10, EU868_MAX_TX_POWER, 0, 0, 0, 869400000, 869650000}; // 10.0 % /*! * Band 4 definition * Band = { DutyCycle, TxMaxPower, LastJoinTxDoneTime, LastTxDoneTime, TimeOff } */ -static const band_t EU868_BAND4 = {100 , EU868_MAX_TX_POWER, 0, 0, 0, 869700000, 870000000}; // 1.0 % +static const band_t EU868_BAND4 = {100, EU868_MAX_TX_POWER, 0, 0, 0, 869700000, 870000000}; // 1.0 % /*! * Band 5 definition - It's actually a sub part of Band 2 @@ -217,19 +217,19 @@ static const band_t EU868_BAND5 = {1000, EU868_MAX_TX_POWER, 0, 0, 0, 863000000, * LoRaMac default channel 1 * Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band } */ -static const channel_params_t EU868_LC1 = {868100000, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 1}; +static const channel_params_t EU868_LC1 = {868100000, 0, { ((DR_5 << 4) | DR_0) }, 1}; /*! * LoRaMac default channel 2 * Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band } */ -static const channel_params_t EU868_LC2 = {868300000, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 1}; +static const channel_params_t EU868_LC2 = {868300000, 0, { ((DR_5 << 4) | DR_0) }, 1}; /*! * LoRaMac default channel 3 * Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band } */ -static const channel_params_t EU868_LC3 = {868500000, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 1}; +static const channel_params_t EU868_LC3 = {868500000, 0, { ((DR_5 << 4) | DR_0) }, 1}; /*! * LoRaMac channels which are allowed for the join procedure diff --git a/features/lorawan/lorastack/phy/LoRaPHYIN865.cpp b/features/lorawan/lorastack/phy/LoRaPHYIN865.cpp index 5ab3bc8f35b..4ade510051f 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYIN865.cpp +++ b/features/lorawan/lorastack/phy/LoRaPHYIN865.cpp @@ -182,25 +182,25 @@ * Band 0 definition * { DutyCycle, TxMaxPower, LastJoinTxDoneTime, LastTxDoneTime, TimeOff } */ -static const band_t IN865_BAND0 = { 1 , IN865_MAX_TX_POWER, 0, 0, 0, 865000000, 867000000 }; // 100.0 % +static const band_t IN865_BAND0 = { 1, IN865_MAX_TX_POWER, 0, 0, 0, 865000000, 867000000 }; // 100.0 % /*! * LoRaMac default channel 1 * Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band } */ -static const channel_params_t IN865_LC1 = { 865062500, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 0 }; +static const channel_params_t IN865_LC1 = { 865062500, 0, { ((DR_5 << 4) | DR_0) }, 0 }; /*! * LoRaMac default channel 2 * Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band } */ -static const channel_params_t IN865_LC2 = { 865402500, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 0 }; +static const channel_params_t IN865_LC2 = { 865402500, 0, { ((DR_5 << 4) | DR_0) }, 0 }; /*! * LoRaMac default channel 3 * Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band } */ -static const channel_params_t IN865_LC3 = { 865985000, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 0 }; +static const channel_params_t IN865_LC3 = { 865985000, 0, { ((DR_5 << 4) | DR_0) }, 0 }; /*! * LoRaMac channels which are allowed for the join procedure @@ -233,7 +233,7 @@ static const uint8_t max_payloads_with_repeater[] = { 51, 51, 51, 115, 222, 222, static const int8_t rx1_dr_offset_IN865[] = { 0, 1, 2, 3, 4, 5, -1, -2 }; LoRaPHYIN865::LoRaPHYIN865(LoRaWANTimeHandler &lora_time) - : LoRaPHY(lora_time) + : LoRaPHY(lora_time) { bands[0] = IN865_BAND0; diff --git a/features/lorawan/lorastack/phy/LoRaPHYIN865.h b/features/lorawan/lorastack/phy/LoRaPHYIN865.h index 5d47f67a7a5..6c15265ec47 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYIN865.h +++ b/features/lorawan/lorastack/phy/LoRaPHYIN865.h @@ -55,7 +55,7 @@ class LoRaPHYIN865 : public LoRaPHY { LoRaPHYIN865(LoRaWANTimeHandler &lora_time); virtual ~LoRaPHYIN865(); - virtual uint8_t apply_DR_offset(int8_t dr, int8_t dr_offset ); + virtual uint8_t apply_DR_offset(int8_t dr, int8_t dr_offset); private: /*! diff --git a/features/lorawan/lorastack/phy/LoRaPHYKR920.cpp b/features/lorawan/lorastack/phy/LoRaPHYKR920.cpp index 74f67c5cc8d..e11798498e7 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYKR920.cpp +++ b/features/lorawan/lorastack/phy/LoRaPHYKR920.cpp @@ -186,25 +186,25 @@ * Band 0 definition * { DutyCycle, TxMaxPower, LastJoinTxDoneTime, LastTxDoneTime, TimeOff } */ -static const band_t KR920_BAND0 = { 1 , KR920_MAX_TX_POWER, 0, 0, 0 }; // 100.0 % +static const band_t KR920_BAND0 = { 1, KR920_MAX_TX_POWER, 0, 0, 0 }; // 100.0 % /*! * LoRaMac default channel 1 * Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band } */ -static const channel_params_t KR920_LC1 = { 922100000, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 0 }; +static const channel_params_t KR920_LC1 = { 922100000, 0, { ((DR_5 << 4) | DR_0) }, 0 }; /*! * LoRaMac default channel 2 * Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band } */ -static const channel_params_t KR920_LC2 = { 922300000, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 0 }; +static const channel_params_t KR920_LC2 = { 922300000, 0, { ((DR_5 << 4) | DR_0) }, 0 }; /*! * LoRaMac default channel 3 * Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band } */ -static const channel_params_t KR920_LC3 = { 922500000, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 0 }; +static const channel_params_t KR920_LC3 = { 922500000, 0, { ((DR_5 << 4) | DR_0) }, 0 }; /*! * LoRaMac channels which are allowed for the join procedure @@ -252,7 +252,7 @@ LoRaPHYKR920::LoRaPHYKR920(LoRaWANTimeHandler &lora_time) channels[2] = KR920_LC3; // Initialize the channels default mask - default_channel_mask[0] = LC( 1 ) + LC( 2 ) + LC( 3 ); + default_channel_mask[0] = LC(1) + LC(2) + LC(3); // Update the channels mask copy_channel_mask(channel_mask, default_channel_mask, KR920_CHANNEL_MASK_SIZE); @@ -354,7 +354,7 @@ bool LoRaPHYKR920::verify_frequency(uint32_t freq) // Verify if the frequency is valid. The frequency must be in a specified // range and can be set to specific values. - if ((tmp_freq >= 920900000) && (tmp_freq <=923300000)) { + if ((tmp_freq >= 920900000) && (tmp_freq <= 923300000)) { // Range ok, check for specific value tmp_freq -= 920900000; if ((tmp_freq % 200000) == 0) { @@ -365,8 +365,8 @@ bool LoRaPHYKR920::verify_frequency(uint32_t freq) return false; } -bool LoRaPHYKR920::tx_config(tx_config_params_t* config, int8_t* tx_power, - lorawan_time_t* tx_toa) +bool LoRaPHYKR920::tx_config(tx_config_params_t *config, int8_t *tx_power, + lorawan_time_t *tx_toa) { int8_t phy_dr = datarates_KR920[config->datarate]; @@ -391,12 +391,12 @@ bool LoRaPHYKR920::tx_config(tx_config_params_t* config, int8_t* tx_power, _radio->set_channel(channels[config->channel].frequency); _radio->set_tx_config(MODEM_LORA, phy_tx_power, 0, bandwidth, phy_dr, 1, 8, - false, true, 0, 0, false, 3000 ); + false, true, 0, 0, false, 3000); // Setup maximum payload lenght of the radio driver _radio->set_max_payload_length(MODEM_LORA, config->pkt_len); // Get the time-on-air of the next tx frame - *tx_toa =_radio->time_on_air(MODEM_LORA, config->pkt_len); + *tx_toa = _radio->time_on_air(MODEM_LORA, config->pkt_len); _radio->unlock(); @@ -404,9 +404,9 @@ bool LoRaPHYKR920::tx_config(tx_config_params_t* config, int8_t* tx_power, return true; } -bool LoRaPHYKR920::set_next_channel(channel_selection_params_t* params, - uint8_t* channel, lorawan_time_t* time, - lorawan_time_t* aggregate_timeoff) +bool LoRaPHYKR920::set_next_channel(channel_selection_params_t *params, + uint8_t *channel, lorawan_time_t *time, + lorawan_time_t *aggregate_timeoff) { uint8_t next_channel_idx = 0; uint8_t nb_enabled_channels = 0; @@ -429,8 +429,8 @@ bool LoRaPHYKR920::set_next_channel(channel_selection_params_t* params, // Search how many channels are enabled nb_enabled_channels = enabled_channel_count(params->joined, params->current_datarate, - channel_mask, - enabled_channels, &delay_tx); + channel_mask, + enabled_channels, &delay_tx); } else { delay_tx++; nextTxDelay = params->aggregate_timeoff - _lora_time.get_elapsed_time(params->last_aggregate_tx_time); @@ -439,9 +439,9 @@ bool LoRaPHYKR920::set_next_channel(channel_selection_params_t* params, if (nb_enabled_channels > 0) { for (uint8_t i = 0, j = get_random(0, nb_enabled_channels - 1); - i < KR920_MAX_NB_CHANNELS; i++) { + i < KR920_MAX_NB_CHANNELS; i++) { next_channel_idx = enabled_channels[j]; - j = ( j + 1 ) % nb_enabled_channels; + j = (j + 1) % nb_enabled_channels; // Perform carrier sense for KR920_CARRIER_SENSE_TIME // If the channel is free, we can stop the LBT mechanism @@ -450,7 +450,7 @@ bool LoRaPHYKR920::set_next_channel(channel_selection_params_t* params, if (_radio->perform_carrier_sense(MODEM_LORA, channels[next_channel_idx].frequency, KR920_RSSI_FREE_TH, - KR920_CARRIER_SENSE_TIME ) == true) { + KR920_CARRIER_SENSE_TIME) == true) { // Free channel found *channel = next_channel_idx; *time = 0; @@ -478,7 +478,7 @@ bool LoRaPHYKR920::set_next_channel(channel_selection_params_t* params, } } -void LoRaPHYKR920::set_tx_cont_mode(cw_mode_params_t* params, uint32_t given_frequency) +void LoRaPHYKR920::set_tx_cont_mode(cw_mode_params_t *params, uint32_t given_frequency) { (void)given_frequency; @@ -493,7 +493,7 @@ void LoRaPHYKR920::set_tx_cont_mode(cw_mode_params_t* params, uint32_t given_fre // Take the minimum between the max_eirp and params->max_eirp. // The value of params->max_eirp could have changed during runtime, // e.g. due to a MAC command. - max_eirp = MIN (params->max_eirp, max_eirp); + max_eirp = MIN(params->max_eirp, max_eirp); // Calculate physical TX power phy_tx_power = compute_tx_power(params->tx_power, max_eirp, params->antenna_gain); diff --git a/features/lorawan/lorastack/phy/LoRaPHYKR920.h b/features/lorawan/lorastack/phy/LoRaPHYKR920.h index b95c902a143..ccddf44a178 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYKR920.h +++ b/features/lorawan/lorastack/phy/LoRaPHYKR920.h @@ -56,14 +56,14 @@ class LoRaPHYKR920 : public LoRaPHY { virtual bool verify_frequency(uint32_t freq); - virtual bool tx_config(tx_config_params_t* config, int8_t* tx_power, - lorawan_time_t* tx_toa); + virtual bool tx_config(tx_config_params_t *config, int8_t *tx_power, + lorawan_time_t *tx_toa); - virtual bool set_next_channel(channel_selection_params_t* params, uint8_t* channel, - lorawan_time_t* time, - lorawan_time_t* aggregate_timeOff); + virtual bool set_next_channel(channel_selection_params_t *params, uint8_t *channel, + lorawan_time_t *time, + lorawan_time_t *aggregate_timeOff); - virtual void set_tx_cont_mode(cw_mode_params_t* continuousWave, + virtual void set_tx_cont_mode(cw_mode_params_t *continuousWave, uint32_t frequency = 0); diff --git a/features/lorawan/lorastack/phy/LoRaPHYUS915.cpp b/features/lorawan/lorastack/phy/LoRaPHYUS915.cpp index b89d3550eb9..8cb6b443ebf 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYUS915.cpp +++ b/features/lorawan/lorastack/phy/LoRaPHYUS915.cpp @@ -192,10 +192,9 @@ static const uint32_t bandwidths_US915[] = {125000, 125000, 125000, 125000, 5000 /*! * Up/Down link data rates offset definition */ -static const int8_t datarate_offsets_US915[5][4] = -{ - { DR_10, DR_9 , DR_8 , DR_8 }, // DR_0 - { DR_11, DR_10, DR_9 , DR_8 }, // DR_1 +static const int8_t datarate_offsets_US915[5][4] = { + { DR_10, DR_9, DR_8, DR_8 }, // DR_0 + { DR_11, DR_10, DR_9, DR_8 }, // DR_1 { DR_12, DR_11, DR_10, DR_9 }, // DR_2 { DR_13, DR_12, DR_11, DR_10 }, // DR_3 { DR_13, DR_13, DR_12, DR_11 }, // DR_4 @@ -212,7 +211,7 @@ static const uint8_t max_payloads_US915[] = { 11, 53, 125, 242, 242, 0, 0, 0, 53 static const uint8_t max_payloads_with_repeater_US915[] = {11, 53, 125, 242, 242, 0, 0, 0, 33, 109, 222, 222, 222, 222, 0, 0}; LoRaPHYUS915::LoRaPHYUS915(LoRaWANTimeHandler &lora_time) - : LoRaPHY(lora_time) + : LoRaPHY(lora_time) { bands[0] = US915_BAND0; @@ -220,13 +219,13 @@ LoRaPHYUS915::LoRaPHYUS915(LoRaWANTimeHandler &lora_time) // 125 kHz channels for (uint8_t i = 0; i < US915_MAX_NB_CHANNELS - 8; i++) { channels[i].frequency = 902300000 + i * 200000; - channels[i].dr_range.value = ( DR_3 << 4) | DR_0; + channels[i].dr_range.value = (DR_3 << 4) | DR_0; channels[i].band = 0; } // 500 kHz channels for (uint8_t i = US915_MAX_NB_CHANNELS - 8; i < US915_MAX_NB_CHANNELS; i++) { - channels[i].frequency = 903000000 + (i - ( US915_MAX_NB_CHANNELS - 8)) * 1600000; - channels[i].dr_range.value = ( DR_4 << 4) | DR_4; + channels[i].frequency = 903000000 + (i - (US915_MAX_NB_CHANNELS - 8)) * 1600000; + channels[i].dr_range.value = (DR_4 << 4) | DR_4; channels[i].band = 0; } @@ -326,16 +325,16 @@ int8_t LoRaPHYUS915::limit_tx_power(int8_t tx_power, int8_t max_band_tx_power, int8_t tx_power_out = tx_power; // Limit tx power to the band max - tx_power_out = MAX (tx_power, max_band_tx_power); + tx_power_out = MAX(tx_power, max_band_tx_power); if (datarate == DR_4) { // Limit tx power to max 26dBm - tx_power_out = MAX (tx_power, TX_POWER_2); + tx_power_out = MAX(tx_power, TX_POWER_2); } else { if (num_active_channels(channel_mask, 0, 4) < 50) { // Limit tx power to max 21dBm - tx_power_out = MAX (tx_power, TX_POWER_5); + tx_power_out = MAX(tx_power, TX_POWER_5); } } @@ -347,13 +346,13 @@ void LoRaPHYUS915::restore_default_channels() // Copy channels default mask copy_channel_mask(channel_mask, default_channel_mask, US915_CHANNEL_MASK_SIZE); - for ( uint8_t i = 0; i < US915_CHANNEL_MASK_SIZE; i++ ) { + for (uint8_t i = 0; i < US915_CHANNEL_MASK_SIZE; i++) { // Copy-And the channels mask current_channel_mask[i] &= channel_mask[i]; } } -bool LoRaPHYUS915::rx_config(rx_config_params_t* config, int8_t* datarate) +bool LoRaPHYUS915::rx_config(rx_config_params_t *config, int8_t *datarate) { int8_t dr = config->datarate; uint8_t max_payload = 0; @@ -385,7 +384,7 @@ bool LoRaPHYUS915::rx_config(rx_config_params_t* config, int8_t* datarate) _radio->lock(); - _radio->set_channel( frequency ); + _radio->set_channel(frequency); // Radio configuration _radio->set_rx_config(MODEM_LORA, config->bandwidth, phy_dr, 1, 0, 8, @@ -413,19 +412,19 @@ bool LoRaPHYUS915::rx_config(rx_config_params_t* config, int8_t* datarate) return true; } -bool LoRaPHYUS915::tx_config(tx_config_params_t* config, int8_t* tx_power, - lorawan_time_t* tx_toa) +bool LoRaPHYUS915::tx_config(tx_config_params_t *config, int8_t *tx_power, + lorawan_time_t *tx_toa) { int8_t phy_dr = datarates_US915[config->datarate]; int8_t tx_power_limited = limit_tx_power(config->tx_power, - bands[channels[config->channel].band].max_tx_pwr, - config->datarate); + bands[channels[config->channel].band].max_tx_pwr, + config->datarate); uint32_t bandwidth = get_bandwidth(config->datarate); int8_t phy_tx_power = 0; // Calculate physical TX power - phy_tx_power = compute_tx_power( tx_power_limited, US915_DEFAULT_MAX_ERP, 0 ); + phy_tx_power = compute_tx_power(tx_power_limited, US915_DEFAULT_MAX_ERP, 0); _radio->lock(); @@ -447,9 +446,9 @@ bool LoRaPHYUS915::tx_config(tx_config_params_t* config, int8_t* tx_power, return true; } -uint8_t LoRaPHYUS915::link_ADR_request(adr_req_params_t* params, - int8_t* dr_out, int8_t* tx_power_out, - uint8_t* nb_rep_out, uint8_t* nb_bytes_parsed) +uint8_t LoRaPHYUS915::link_ADR_request(adr_req_params_t *params, + int8_t *dr_out, int8_t *tx_power_out, + uint8_t *nb_rep_out, uint8_t *nb_bytes_parsed) { uint8_t status = 0x07; @@ -508,7 +507,7 @@ uint8_t LoRaPHYUS915::link_ADR_request(adr_req_params_t* params, // FCC 15.247 paragraph F mandates to hop on at least 2 125 kHz channels if ((adr_settings.datarate < DR_4) && - (num_active_channels(temp_channel_masks, 0, 4) < 2)) { + (num_active_channels(temp_channel_masks, 0, 4) < 2)) { status &= 0xFE; // Channel mask KO @@ -549,13 +548,13 @@ uint8_t LoRaPHYUS915::link_ADR_request(adr_req_params_t* params, return status; } -uint8_t LoRaPHYUS915::accept_rx_param_setup_req(rx_param_setup_req_t* params) +uint8_t LoRaPHYUS915::accept_rx_param_setup_req(rx_param_setup_req_t *params) { uint8_t status = 0x07; uint32_t freq = params->frequency; // Verify radio frequency - if ((_radio->check_rf_frequency( freq ) == false) + if ((_radio->check_rf_frequency(freq) == false) || (freq < US915_FIRST_RX1_CHANNEL) || (freq > US915_LAST_RX1_CHANNEL) || (((freq - (uint32_t) US915_FIRST_RX1_CHANNEL) % (uint32_t) US915_STEPWIDTH_RX1_CHANNEL) != 0)) { @@ -578,8 +577,7 @@ uint8_t LoRaPHYUS915::accept_rx_param_setup_req(rx_param_setup_req_t* params) } // Verify datarate offset - if (val_in_range( params->dr_offset, US915_MIN_RX1_DR_OFFSET, US915_MAX_RX1_DR_OFFSET ) == 0 ) - { + if (val_in_range(params->dr_offset, US915_MIN_RX1_DR_OFFSET, US915_MAX_RX1_DR_OFFSET) == 0) { status &= 0xFB; // Rx1DrOffset range KO } @@ -602,9 +600,9 @@ int8_t LoRaPHYUS915::get_alternate_DR(uint8_t nb_trials) return datarate; } -bool LoRaPHYUS915::set_next_channel(channel_selection_params_t* params, - uint8_t* channel, lorawan_time_t* time, - lorawan_time_t* aggregate_timeOff) +bool LoRaPHYUS915::set_next_channel(channel_selection_params_t *params, + uint8_t *channel, lorawan_time_t *time, + lorawan_time_t *aggregate_timeOff) { uint8_t nb_enabled_channels = 0; uint8_t delay_tx = 0; @@ -620,7 +618,7 @@ bool LoRaPHYUS915::set_next_channel(channel_selection_params_t* params, // Check other channels if (params->current_datarate >= DR_4) { - if ((current_channel_mask[4] & 0x00FF ) == 0) { + if ((current_channel_mask[4] & 0x00FF) == 0) { current_channel_mask[4] = channel_mask[4]; } } @@ -634,9 +632,9 @@ bool LoRaPHYUS915::set_next_channel(channel_selection_params_t* params, // Search how many channels are enabled nb_enabled_channels = enabled_channel_count(params->joined, - params->current_datarate, - current_channel_mask, - enabled_channels, &delay_tx); + params->current_datarate, + current_channel_mask, + enabled_channels, &delay_tx); } else { delay_tx++; next_tx_delay = params->aggregate_timeoff - _lora_time.get_elapsed_time(params->last_aggregate_tx_time); @@ -644,7 +642,7 @@ bool LoRaPHYUS915::set_next_channel(channel_selection_params_t* params, if (nb_enabled_channels > 0) { // We found a valid channel - *channel = enabled_channels[get_random( 0, nb_enabled_channels - 1 )]; + *channel = enabled_channels[get_random(0, nb_enabled_channels - 1)]; // Disable the channel in the mask disable_channel(current_channel_mask, *channel, US915_MAX_NB_CHANNELS - 8); @@ -665,13 +663,13 @@ bool LoRaPHYUS915::set_next_channel(channel_selection_params_t* params, } } -void LoRaPHYUS915::set_tx_cont_mode(cw_mode_params_t* params, uint32_t given_frequency) +void LoRaPHYUS915::set_tx_cont_mode(cw_mode_params_t *params, uint32_t given_frequency) { (void)given_frequency; int8_t tx_power_limited = limit_tx_power(params->tx_power, - bands[channels[params->channel].band].max_tx_pwr, - params->datarate); + bands[channels[params->channel].band].max_tx_pwr, + params->datarate); int8_t phyTxPower = 0; uint32_t frequency = channels[params->channel].frequency; diff --git a/features/lorawan/lorastack/phy/LoRaPHYUS915.h b/features/lorawan/lorastack/phy/LoRaPHYUS915.h index f08944e6e7e..41c41e36697 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYUS915.h +++ b/features/lorawan/lorastack/phy/LoRaPHYUS915.h @@ -56,24 +56,24 @@ class LoRaPHYUS915 : public LoRaPHY { virtual void restore_default_channels(); - virtual bool rx_config(rx_config_params_t* config, int8_t* datarate); + virtual bool rx_config(rx_config_params_t *config, int8_t *datarate); - virtual bool tx_config(tx_config_params_t* config, int8_t* tx_power, - lorawan_time_t* tx_toa); + virtual bool tx_config(tx_config_params_t *config, int8_t *tx_power, + lorawan_time_t *tx_toa); - virtual uint8_t link_ADR_request(adr_req_params_t* params, - int8_t* dr_out, int8_t* tx_power_out, - uint8_t* nb_rep_out, - uint8_t* nb_bytes_parsed); + virtual uint8_t link_ADR_request(adr_req_params_t *params, + int8_t *dr_out, int8_t *tx_power_out, + uint8_t *nb_rep_out, + uint8_t *nb_bytes_parsed); - virtual uint8_t accept_rx_param_setup_req(rx_param_setup_req_t* params); + virtual uint8_t accept_rx_param_setup_req(rx_param_setup_req_t *params); virtual int8_t get_alternate_DR(uint8_t nb_trials); - virtual bool set_next_channel(channel_selection_params_t* params, uint8_t* channel, - lorawan_time_t* time, lorawan_time_t* aggregate_timeOff); + virtual bool set_next_channel(channel_selection_params_t *params, uint8_t *channel, + lorawan_time_t *time, lorawan_time_t *aggregate_timeOff); - virtual void set_tx_cont_mode(cw_mode_params_t* continuousWave, + virtual void set_tx_cont_mode(cw_mode_params_t *continuousWave, uint32_t frequency = 0); virtual uint8_t apply_DR_offset(int8_t dr, int8_t dr_offset); diff --git a/features/lorawan/lorastack/phy/LoRaPHYUS915Hybrid.cpp b/features/lorawan/lorastack/phy/LoRaPHYUS915Hybrid.cpp index 9ab99e30fba..fc7485430a0 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYUS915Hybrid.cpp +++ b/features/lorawan/lorastack/phy/LoRaPHYUS915Hybrid.cpp @@ -191,10 +191,9 @@ static const uint32_t bandwidths_US915_HYBRID[] = { 125000, 125000, 125000, 1250 /*! * Up/Down link data rates offset definition */ -static const int8_t datarate_offsets_US915_HYBRID[5][4] = -{ - { DR_10, DR_9 , DR_8 , DR_8 }, // DR_0 - { DR_11, DR_10, DR_9 , DR_8 }, // DR_1 +static const int8_t datarate_offsets_US915_HYBRID[5][4] = { + { DR_10, DR_9, DR_8, DR_8 }, // DR_0 + { DR_11, DR_10, DR_9, DR_8 }, // DR_1 { DR_12, DR_11, DR_10, DR_9 }, // DR_2 { DR_13, DR_12, DR_11, DR_10 }, // DR_3 { DR_13, DR_13, DR_12, DR_11 }, // DR_4 @@ -219,14 +218,14 @@ LoRaPHYUS915Hybrid::LoRaPHYUS915Hybrid(LoRaWANTimeHandler &lora_time) // 125 kHz channels for (uint8_t i = 0; i < US915_HYBRID_MAX_NB_CHANNELS - 8; i++) { channels[i].frequency = 902300000 + i * 200000; - channels[i].dr_range.value = ( DR_3 << 4 ) | DR_0; + channels[i].dr_range.value = (DR_3 << 4) | DR_0; channels[i].band = 0; } // 500 kHz channels for (uint8_t i = US915_HYBRID_MAX_NB_CHANNELS - 8; i < US915_HYBRID_MAX_NB_CHANNELS; i++) { channels[i].frequency = 903000000 + (i - (US915_HYBRID_MAX_NB_CHANNELS - 8)) * 1600000; - channels[i].dr_range.value = ( DR_4 << 4 ) | DR_4; + channels[i].dr_range.value = (DR_4 << 4) | DR_4; channels[i].band = 0; } @@ -329,8 +328,8 @@ void LoRaPHYUS915Hybrid::restore_default_channels() } } -bool LoRaPHYUS915Hybrid::get_next_ADR(bool restore_channel_mask, int8_t& dr_out, - int8_t& tx_power_out, uint32_t& adr_ack_cnt) +bool LoRaPHYUS915Hybrid::get_next_ADR(bool restore_channel_mask, int8_t &dr_out, + int8_t &tx_power_out, uint32_t &adr_ack_cnt) { bool adrAckReq = false; @@ -375,7 +374,7 @@ bool LoRaPHYUS915Hybrid::get_next_ADR(bool restore_channel_mask, int8_t& dr_out, return adrAckReq; } -bool LoRaPHYUS915Hybrid::rx_config(rx_config_params_t* config, int8_t* datarate) +bool LoRaPHYUS915Hybrid::rx_config(rx_config_params_t *config, int8_t *datarate) { int8_t dr = config->datarate; uint8_t max_payload = 0; @@ -403,7 +402,7 @@ bool LoRaPHYUS915Hybrid::rx_config(rx_config_params_t* config, int8_t* datarate) _radio->lock(); - _radio->set_channel( frequency ); + _radio->set_channel(frequency); // Radio configuration _radio->set_rx_config(MODEM_LORA, config->bandwidth, phy_dr, 1, 0, 8, @@ -426,16 +425,16 @@ bool LoRaPHYUS915Hybrid::rx_config(rx_config_params_t* config, int8_t* datarate) return true; } -bool LoRaPHYUS915Hybrid::tx_config(tx_config_params_t* config, int8_t* tx_power, - lorawan_time_t* tx_toa) +bool LoRaPHYUS915Hybrid::tx_config(tx_config_params_t *config, int8_t *tx_power, + lorawan_time_t *tx_toa) { int8_t phy_dr = datarates_US915_HYBRID[config->datarate]; int8_t tx_power_limited = limit_tx_power(config->tx_power, - bands[channels[config->channel].band].max_tx_pwr, - config->datarate); + bands[channels[config->channel].band].max_tx_pwr, + config->datarate); - uint32_t bandwidth = get_bandwidth (config->datarate); + uint32_t bandwidth = get_bandwidth(config->datarate); int8_t phy_tx_power = 0; // Calculate physical TX power @@ -443,7 +442,7 @@ bool LoRaPHYUS915Hybrid::tx_config(tx_config_params_t* config, int8_t* tx_power, _radio->lock(); - _radio->set_channel( channels[config->channel].frequency ); + _radio->set_channel(channels[config->channel].frequency); _radio->set_tx_config(MODEM_LORA, phy_tx_power, 0, bandwidth, phy_dr, 1, 8, false, true, 0, 0, false, 3000); @@ -460,10 +459,10 @@ bool LoRaPHYUS915Hybrid::tx_config(tx_config_params_t* config, int8_t* tx_power, return true; } -uint8_t LoRaPHYUS915Hybrid::link_ADR_request(adr_req_params_t* params, - int8_t* dr_out, int8_t* tx_power_out, - uint8_t* nb_rep_out, - uint8_t* nb_bytes_parsed) +uint8_t LoRaPHYUS915Hybrid::link_ADR_request(adr_req_params_t *params, + int8_t *dr_out, int8_t *tx_power_out, + uint8_t *nb_rep_out, + uint8_t *nb_bytes_parsed) { uint8_t status = 0x07; link_adr_params_t adr_settings; @@ -498,7 +497,7 @@ uint8_t LoRaPHYUS915Hybrid::link_ADR_request(adr_req_params_t* params, temp_channel_mask[3] = 0xFFFF; // Apply chMask to channels 64 to 71 temp_channel_mask[4] = adr_settings.channel_mask; - } else if( adr_settings.ch_mask_ctrl == 7 ) { + } else if (adr_settings.ch_mask_ctrl == 7) { // Disable all 125 kHz channels temp_channel_mask[0] = 0x0000; temp_channel_mask[1] = 0x0000; @@ -506,7 +505,7 @@ uint8_t LoRaPHYUS915Hybrid::link_ADR_request(adr_req_params_t* params, temp_channel_mask[3] = 0x0000; // Apply chMask to channels 64 to 71 temp_channel_mask[4] = adr_settings.channel_mask; - } else if( adr_settings.ch_mask_ctrl == 5 ) { + } else if (adr_settings.ch_mask_ctrl == 5) { // RFU status &= 0xFE; // Channel mask KO } else { @@ -516,11 +515,11 @@ uint8_t LoRaPHYUS915Hybrid::link_ADR_request(adr_req_params_t* params, // FCC 15.247 paragraph F mandates to hop on at least 2 125 kHz channels if ((adr_settings.datarate < DR_4) && - (num_active_channels( temp_channel_mask, 0, 4 ) < 2)) { + (num_active_channels(temp_channel_mask, 0, 4) < 2)) { status &= 0xFE; // Channel mask KO } - if( validate_channel_mask(temp_channel_mask ) == false) { + if (validate_channel_mask(temp_channel_mask) == false) { status &= 0xFE; // Channel mask KO } @@ -560,7 +559,7 @@ uint8_t LoRaPHYUS915Hybrid::link_ADR_request(adr_req_params_t* params, return status; } -uint8_t LoRaPHYUS915Hybrid::accept_rx_param_setup_req(rx_param_setup_req_t* params) +uint8_t LoRaPHYUS915Hybrid::accept_rx_param_setup_req(rx_param_setup_req_t *params) { uint8_t status = 0x07; uint32_t freq = params->frequency; @@ -569,7 +568,7 @@ uint8_t LoRaPHYUS915Hybrid::accept_rx_param_setup_req(rx_param_setup_req_t* para if ((_radio->check_rf_frequency(freq) == false) || (freq < US915_HYBRID_FIRST_RX1_CHANNEL) || (freq > US915_HYBRID_LAST_RX1_CHANNEL) - || (((freq - ( uint32_t ) US915_HYBRID_FIRST_RX1_CHANNEL) % (uint32_t) US915_HYBRID_STEPWIDTH_RX1_CHANNEL) != 0)) { + || (((freq - (uint32_t) US915_HYBRID_FIRST_RX1_CHANNEL) % (uint32_t) US915_HYBRID_STEPWIDTH_RX1_CHANNEL) != 0)) { status &= 0xFE; // Channel frequency KO } @@ -607,9 +606,9 @@ int8_t LoRaPHYUS915Hybrid::get_alternate_DR(uint8_t nb_trials) return datarate; } -bool LoRaPHYUS915Hybrid::set_next_channel(channel_selection_params_t* params, - uint8_t* channel, lorawan_time_t* time, - lorawan_time_t* aggregate_timeOff) +bool LoRaPHYUS915Hybrid::set_next_channel(channel_selection_params_t *params, + uint8_t *channel, lorawan_time_t *time, + lorawan_time_t *aggregate_timeOff) { uint8_t nb_enabled_channels = 0; uint8_t delay_tx = 0; @@ -624,12 +623,12 @@ bool LoRaPHYUS915Hybrid::set_next_channel(channel_selection_params_t* params, // Check other channels if (params->current_datarate >= DR_4) { - if ((current_channel_mask[4] & 0x00FF ) == 0) { + if ((current_channel_mask[4] & 0x00FF) == 0) { current_channel_mask[4] = channel_mask[4]; } } - if (params->aggregate_timeoff <= _lora_time.get_elapsed_time( params->last_aggregate_tx_time)) { + if (params->aggregate_timeoff <= _lora_time.get_elapsed_time(params->last_aggregate_tx_time)) { // Reset Aggregated time off *aggregate_timeOff = 0; @@ -640,9 +639,9 @@ bool LoRaPHYUS915Hybrid::set_next_channel(channel_selection_params_t* params, // Search how many channels are enabled nb_enabled_channels = enabled_channel_count(params->joined, - params->current_datarate, - current_channel_mask, - enabled_channels, &delay_tx); + params->current_datarate, + current_channel_mask, + enabled_channels, &delay_tx); } else { delay_tx++; next_tx_delay = params->aggregate_timeoff - _lora_time.get_elapsed_time(params->last_aggregate_tx_time); @@ -672,13 +671,13 @@ bool LoRaPHYUS915Hybrid::set_next_channel(channel_selection_params_t* params, } } -void LoRaPHYUS915Hybrid::set_tx_cont_mode(cw_mode_params_t* params, uint32_t given_frequency) +void LoRaPHYUS915Hybrid::set_tx_cont_mode(cw_mode_params_t *params, uint32_t given_frequency) { (void)given_frequency; int8_t tx_power_limited = limit_tx_power(params->tx_power, - bands[channels[params->channel].band].max_tx_pwr, - params->datarate); + bands[channels[params->channel].band].max_tx_pwr, + params->datarate); int8_t phy_tx_power = 0; uint32_t frequency = channels[params->channel].frequency; @@ -703,7 +702,7 @@ uint8_t LoRaPHYUS915Hybrid::apply_DR_offset(int8_t dr, int8_t drOffset) } -void LoRaPHYUS915Hybrid::reenable_500khz_channels(uint16_t mask, uint16_t* channelsMask) +void LoRaPHYUS915Hybrid::reenable_500khz_channels(uint16_t mask, uint16_t *channelsMask) { uint16_t blockMask = mask; @@ -722,7 +721,7 @@ void LoRaPHYUS915Hybrid::reenable_500khz_channels(uint16_t mask, uint16_t* chann } int8_t LoRaPHYUS915Hybrid::limit_tx_power(int8_t txPower, int8_t maxBandTxPower, - int8_t datarate) + int8_t datarate) { int8_t txPowerResult = txPower; @@ -745,7 +744,7 @@ int8_t LoRaPHYUS915Hybrid::limit_tx_power(int8_t txPower, int8_t maxBandTxPower, return txPowerResult; } -bool LoRaPHYUS915Hybrid::validate_channel_mask(uint16_t* channel_masks) +bool LoRaPHYUS915Hybrid::validate_channel_mask(uint16_t *channel_masks) { bool mask_state = false; @@ -759,22 +758,22 @@ bool LoRaPHYUS915Hybrid::validate_channel_mask(uint16_t* channel_masks) temp_channel_masks[i] = channel_masks[i]; } - for(uint8_t i = 0; i < 4; i++) { + for (uint8_t i = 0; i < 4; i++) { block1 = temp_channel_masks[i] & 0x00FF; block2 = temp_channel_masks[i] & 0xFF00; if (count_bits(block1, 16) > 5) { temp_channel_masks[i] &= block1; - temp_channel_masks[4] = 1 << ( i * 2 ); + temp_channel_masks[4] = 1 << (i * 2); mask_state = true; index = i; break; - } else if( count_bits( block2, 16 ) > 5 ) { + } else if (count_bits(block2, 16) > 5) { temp_channel_masks[i] &= block2; - temp_channel_masks[4] = 1 << ( i * 2 + 1 ); + temp_channel_masks[4] = 1 << (i * 2 + 1); mask_state = true; index = i; break; diff --git a/features/lorawan/lorastack/phy/LoRaPHYUS915Hybrid.h b/features/lorawan/lorastack/phy/LoRaPHYUS915Hybrid.h index 08f1b58a719..6f5fccecff4 100644 --- a/features/lorawan/lorastack/phy/LoRaPHYUS915Hybrid.h +++ b/features/lorawan/lorastack/phy/LoRaPHYUS915Hybrid.h @@ -57,36 +57,36 @@ class LoRaPHYUS915Hybrid : public LoRaPHY { virtual void restore_default_channels(); - virtual bool get_next_ADR(bool restore_channel_mask, int8_t& dr_out, - int8_t& tx_power_out, uint32_t& adr_ack_cnt); + virtual bool get_next_ADR(bool restore_channel_mask, int8_t &dr_out, + int8_t &tx_power_out, uint32_t &adr_ack_cnt); - virtual bool rx_config(rx_config_params_t* rxConfig, int8_t* datarate); + virtual bool rx_config(rx_config_params_t *rxConfig, int8_t *datarate); - virtual bool tx_config(tx_config_params_t* tx_config, int8_t* tx_power, - lorawan_time_t* tx_toa); + virtual bool tx_config(tx_config_params_t *tx_config, int8_t *tx_power, + lorawan_time_t *tx_toa); - virtual uint8_t link_ADR_request(adr_req_params_t* params, - int8_t* dr_out, int8_t* tx_power_out, - uint8_t* nb_rep_out, - uint8_t* nb_bytes_parsed); + virtual uint8_t link_ADR_request(adr_req_params_t *params, + int8_t *dr_out, int8_t *tx_power_out, + uint8_t *nb_rep_out, + uint8_t *nb_bytes_parsed); - virtual uint8_t accept_rx_param_setup_req(rx_param_setup_req_t* params); + virtual uint8_t accept_rx_param_setup_req(rx_param_setup_req_t *params); virtual int8_t get_alternate_DR(uint8_t nb_trials); - virtual bool set_next_channel(channel_selection_params_t* params, - uint8_t* channel, lorawan_time_t* time, - lorawan_time_t* aggregate_timeoff); + virtual bool set_next_channel(channel_selection_params_t *params, + uint8_t *channel, lorawan_time_t *time, + lorawan_time_t *aggregate_timeoff); - virtual void set_tx_cont_mode(cw_mode_params_t* continuousWave, + virtual void set_tx_cont_mode(cw_mode_params_t *continuousWave, uint32_t frequency = 0); virtual uint8_t apply_DR_offset(int8_t dr, int8_t dr_offset); private: int8_t limit_tx_power(int8_t tx_power, int8_t max_band_tx_power, int8_t datarate); - bool validate_channel_mask(uint16_t* channel_mask); - void reenable_500khz_channels(uint16_t mask, uint16_t* channel_mask); + bool validate_channel_mask(uint16_t *channel_mask); + void reenable_500khz_channels(uint16_t mask, uint16_t *channel_mask); /*! * LoRaMAC channels diff --git a/features/lorawan/lorastack/phy/lora_phy_ds.h b/features/lorawan/lorastack/phy/lora_phy_ds.h index ebcd0f6ae0d..7fe605e7746 100644 --- a/features/lorawan/lorastack/phy/lora_phy_ds.h +++ b/features/lorawan/lorastack/phy/lora_phy_ds.h @@ -527,8 +527,7 @@ /*! * Enumeration of PHY attributes. */ -typedef enum phy_attributes__e -{ +typedef enum phy_attributes__e { /*! * The minimum RX datarate. */ @@ -674,8 +673,7 @@ typedef enum phy_attributes__e * Keeps value in response to a call to * get_phy_params() API. */ -typedef union phy_param_u -{ +typedef union phy_param_u { /*! * A parameter value. */ @@ -687,18 +685,17 @@ typedef union phy_param_u /*! * A pointer to the channels mask. */ - uint16_t* channel_mask; + uint16_t *channel_mask; /*! * A pointer to the channels. */ - channel_params_t* channel_params; + channel_params_t *channel_params; } phy_param_t; /** * The parameter structure for the function RegionGetPhyParam. */ -typedef struct -{ +typedef struct { /** * Set up the parameter to get. */ @@ -715,8 +712,7 @@ typedef struct /** * The parameter structure for the function RegionSetBandTxDone. */ -typedef struct -{ +typedef struct { /** * The channel to update. */ @@ -734,8 +730,7 @@ typedef struct /** * The parameter verification structure. */ -typedef union -{ +typedef union { /** * The TX power to verify. */ @@ -758,12 +753,11 @@ typedef union /** * The parameter structure for the function RegionApplyCFList. */ -typedef struct -{ +typedef struct { /** * The payload containing the CF list. */ - uint8_t* payload; + uint8_t *payload; /** * The size of the payload. */ @@ -773,8 +767,7 @@ typedef struct /** * TX configuration parameters. */ -typedef struct -{ +typedef struct { /** * The TX channel. */ @@ -805,12 +798,11 @@ typedef struct * This structure contains parameters for ADR request coming from * network server. */ -typedef struct -{ +typedef struct { /*! * A pointer to the payload containing the MAC commands. */ - uint8_t* payload; + uint8_t *payload; /*! * The size of the payload. */ @@ -840,8 +832,7 @@ typedef struct /** * Structure containing data for local ADR settings */ -typedef struct link_adr_params_s -{ +typedef struct link_adr_params_s { /** * The number of repetitions. */ @@ -868,8 +859,7 @@ typedef struct link_adr_params_s * Structure used to store ADR values received from network * for verification (legality) purposes. */ -typedef struct verify_adr_params_s -{ +typedef struct verify_adr_params_s { /*! * The current status of the AdrLinkRequest. */ @@ -906,15 +896,14 @@ typedef struct verify_adr_params_s /*! * A pointer to the first element of the channels mask. */ - uint16_t* channel_mask; + uint16_t *channel_mask; } verify_adr_params_t; /** * Contains rx parameter setup request coming from * network server. */ -typedef struct rx_param_setup_req_s -{ +typedef struct rx_param_setup_req_s { /** * The datarate to set up. */ @@ -933,8 +922,7 @@ typedef struct rx_param_setup_req_s * Contains tx parameter setup request coming from * network server. */ -typedef struct tx_param_setup_req_s -{ +typedef struct tx_param_setup_req_s { /** * The uplink dwell time. */ @@ -953,12 +941,11 @@ typedef struct tx_param_setup_req_s * A structure that holds new channel parameters coming * from the network server. */ -typedef struct new_channel_req_params_s -{ +typedef struct new_channel_req_params_s { /** * A pointer to the new channel's parameters. */ - channel_params_t* new_channel; + channel_params_t *new_channel; /** * The channel ID. */ @@ -969,8 +956,7 @@ typedef struct new_channel_req_params_s /** * The parameter structure for the function RegionDlChannelReq. */ -typedef struct dl_channel_req_params_s -{ +typedef struct dl_channel_req_params_s { /** * The channel ID to add the frequency. */ @@ -984,8 +970,7 @@ typedef struct dl_channel_req_params_s /*! * The parameter structure for the function RegionCalcBackOff. */ -typedef struct backoff_params_s -{ +typedef struct backoff_params_s { /** * Set to true, if the node has already joined a network, otherwise false. */ @@ -1016,8 +1001,7 @@ typedef struct backoff_params_s /** * The parameter structure for the function RegionNextChannel. */ -typedef struct channel_selection_params_s -{ +typedef struct channel_selection_params_s { /** * The aggregated time-off time. */ @@ -1043,8 +1027,7 @@ typedef struct channel_selection_params_s /*! * The parameter structure for the function RegionContinuousWave. */ -typedef struct continuous_wave_mode_params_s -{ +typedef struct continuous_wave_mode_params_s { /*! * The current channel index. */ diff --git a/features/lorawan/system/LoRaWANTimer.cpp b/features/lorawan/system/LoRaWANTimer.cpp index 4497f75db28..1b98d55fd62 100644 --- a/features/lorawan/system/LoRaWANTimer.cpp +++ b/features/lorawan/system/LoRaWANTimer.cpp @@ -34,7 +34,7 @@ void LoRaWANTimeHandler::activate_timer_subsystem(events::EventQueue *queue) _queue = queue; } -lorawan_time_t LoRaWANTimeHandler::get_current_time( void ) +lorawan_time_t LoRaWANTimeHandler::get_current_time(void) { const uint32_t current_time = _queue->tick(); return (lorawan_time_t)current_time; diff --git a/features/lorawan/system/LoRaWANTimer.h b/features/lorawan/system/LoRaWANTimer.h index 2b5118eb674..5b74e8937d6 100644 --- a/features/lorawan/system/LoRaWANTimer.h +++ b/features/lorawan/system/LoRaWANTimer.h @@ -25,8 +25,7 @@ SPDX-License-Identifier: BSD-3-Clause #include "lorawan/system/lorawan_data_structures.h" #include "events/EventQueue.h" -class LoRaWANTimeHandler -{ +class LoRaWANTimeHandler { public: LoRaWANTimeHandler(); ~LoRaWANTimeHandler(); @@ -61,7 +60,7 @@ class LoRaWANTimeHandler * @param [in] obj The structure containing the timer object parameters. * @param [in] callback The function callback called at the end of the timeout. */ - void init(timer_event_t &obj, mbed::Callback callback); + void init(timer_event_t &obj, mbed::Callback callback); /** Starts and adds the timer object to the list of timer events. * diff --git a/features/lorawan/system/lorawan_data_structures.h b/features/lorawan/system/lorawan_data_structures.h index cc37cf01786..b2e3584f78d 100644 --- a/features/lorawan/system/lorawan_data_structures.h +++ b/features/lorawan/system/lorawan_data_structures.h @@ -125,8 +125,8 @@ typedef uint32_t lorawan_time_t; */ // reject if user tries to set more than MTU #if MBED_CONF_LORA_TX_MAX_SIZE > 255 - #warning "Cannot set TX Max size more than MTU=255" - #define MBED_CONF_LORA_TX_MAX_SIZE 255 +#warning "Cannot set TX Max size more than MTU=255" +#define MBED_CONF_LORA_TX_MAX_SIZE 255 #endif /*! @@ -166,15 +166,14 @@ typedef union { /*! * The structure to store the minimum and the maximum datarate. */ - struct sFields - { - /*! - * The minimum data rate. - * - * LoRaWAN Regional Parameters V1.0.2rB. - * - * The allowed ranges are region-specific. Please refer to \ref DR_0 to \ref DR_15 for details. - */ + struct sFields { + /*! + * The minimum data rate. + * + * LoRaWAN Regional Parameters V1.0.2rB. + * + * The allowed ranges are region-specific. Please refer to \ref DR_0 to \ref DR_15 for details. + */ int8_t min : 4; /*! * The maximum data rate. @@ -560,8 +559,7 @@ typedef union { /*! * The structure containing single access to header bits. */ - struct hdr_bits_s - { + struct hdr_bits_s { /*! * Major version. */ @@ -590,8 +588,7 @@ typedef union { /*! * The structure containing single access to bits. */ - struct ctrl_bits_s - { + struct ctrl_bits_s { /*! * Frame options length. */ @@ -691,8 +688,7 @@ typedef union { /*! * The structure containing single access to bits. */ - struct mac_flag_bits_s - { + struct mac_flag_bits_s { /*! * MCPS-Req pending */ @@ -841,8 +837,7 @@ typedef struct { /*! * MCPS-Request parameters. */ - union - { + union { /*! * MCPS-Request parameters for an unconfirmed frame. */ @@ -861,12 +856,12 @@ typedef struct { * * A pointer to the buffer of the frame payload. */ - void *f_buffer; - /** Payload size - * - * The size of the frame payload. - */ - uint16_t f_buffer_size; + void *f_buffer; + /** Payload size + * + * The size of the frame payload. + */ + uint16_t f_buffer_size; } loramac_mcps_req_t; @@ -1450,31 +1445,31 @@ typedef union { * * Related MIB type: \ref MIB_CHANNELS */ - channel_params_t* channel_list; - /*! - * Channel for the receive window 2 - * - * Related MIB type: \ref MIB_RX2_CHANNEL - */ + channel_params_t *channel_list; + /*! + * Channel for the receive window 2 + * + * Related MIB type: \ref MIB_RX2_CHANNEL + */ rx2_channel_params rx2_channel; - /*! - * Channel for the receive window 2 - * - * Related MIB type: \ref MIB_RX2_DEFAULT_CHANNEL - */ + /*! + * Channel for the receive window 2 + * + * Related MIB type: \ref MIB_RX2_DEFAULT_CHANNEL + */ rx2_channel_params default_rx2_channel; /*! * Channel mask * * Related MIB type: \ref MIB_CHANNELS_MASK */ - uint16_t* channel_mask; + uint16_t *channel_mask; /*! * Default channel mask * * Related MIB type: \ref MIB_CHANNELS_DEFAULT_MASK */ - uint16_t* default_channel_mask; + uint16_t *default_channel_mask; /*! * Number of frame repetitions * @@ -1552,7 +1547,7 @@ typedef union { * * Related MIB type: \ref MIB_MULTICAST_CHANNEL */ - multicast_params_t* multicast_list; + multicast_params_t *multicast_list; /*! * System overall timing error in milliseconds * @@ -1586,7 +1581,7 @@ typedef struct { * MLME-RequestConfirm parameters */ mib_params_t param; -}loramac_mib_req_confirm_t; +} loramac_mib_req_confirm_t; /*! * LoRaMAC TX information @@ -1639,29 +1634,29 @@ typedef struct { * * \param [OUT] MCPS-Confirm parameters. */ - mbed::Callback mcps_confirm; + mbed::Callback mcps_confirm; /*! * \brief MCPS-Indication primitive. * * \param [OUT] MCPS-Indication parameters. */ - mbed::Callback mcps_indication; + mbed::Callback mcps_indication; /*! * \brief MLME-Confirm primitive. * * \param [OUT] MLME-Confirm parameters. */ - mbed::Callback mlme_confirm; + mbed::Callback mlme_confirm; /*! * \brief MLME-Indication primitive * * \param [OUT] MLME-Indication parameters */ - mbed::Callback mlme_indication; -}loramac_primitives_t; + mbed::Callback mlme_indication; +} loramac_primitives_t; /** End-device states. * @@ -2057,7 +2052,7 @@ typedef struct { /*! * The RX window timeout */ - uint32_t window_timeout; + uint32_t window_timeout; /*! * The RX window offset */ @@ -2131,45 +2126,45 @@ typedef struct { } loramac_keys; typedef struct { - /*! - * Aggregated duty cycle management - */ - lorawan_time_t aggregated_last_tx_time; - lorawan_time_t aggregated_timeoff; - - /*! - * Stores the time at LoRaMac initialization. - * - * \remark Used for the BACKOFF_DC computation. - */ - lorawan_time_t mac_init_time; - - - /*! - * Last transmission time on air - */ - lorawan_time_t tx_toa; - - /*! - * LoRaMac timer used to check the LoRaMacState (runs every second) - */ - timer_event_t mac_state_check_timer; - - /*! - * LoRaMac duty cycle delayed Tx timer - */ - timer_event_t tx_delayed_timer; - - /*! - * LoRaMac reception windows timers - */ - timer_event_t rx_window1_timer; - timer_event_t rx_window2_timer; - - /*! - * Acknowledge timeout timer. Used for packet retransmissions. - */ - timer_event_t ack_timeout_timer; + /*! + * Aggregated duty cycle management + */ + lorawan_time_t aggregated_last_tx_time; + lorawan_time_t aggregated_timeoff; + + /*! + * Stores the time at LoRaMac initialization. + * + * \remark Used for the BACKOFF_DC computation. + */ + lorawan_time_t mac_init_time; + + + /*! + * Last transmission time on air + */ + lorawan_time_t tx_toa; + + /*! + * LoRaMac timer used to check the LoRaMacState (runs every second) + */ + timer_event_t mac_state_check_timer; + + /*! + * LoRaMac duty cycle delayed Tx timer + */ + timer_event_t tx_delayed_timer; + + /*! + * LoRaMac reception windows timers + */ + timer_event_t rx_window1_timer; + timer_event_t rx_window2_timer; + + /*! + * Acknowledge timeout timer. Used for packet retransmissions. + */ + timer_event_t ack_timeout_timer; } lorawan_timers; @@ -2183,7 +2178,7 @@ typedef struct { /*! * Holds the type of current Receive window slot */ - rx_slot_t rx_slot; + rx_slot_t rx_slot; /*! * Indicates if the node is connected to a private or public network @@ -2376,7 +2371,7 @@ typedef struct { * */ typedef enum lora_events { - CONNECTED=0, + CONNECTED = 0, DISCONNECTED, TX_DONE, TX_TIMEOUT, @@ -2390,21 +2385,21 @@ typedef enum lora_events { } lorawan_event_t; typedef struct { - // Mandatory. Event Callback must be provided - mbed::Callback events; - - // Rest are optional - // If the user do not assign these callbacks, these callbacks would return - // null if checked with bool operator - // link_check_resp callback and other such callbacks will be maped in - // future releases of Mbed-OS - mbed::Callback link_check_resp; - - // Battery level callback goes in the down direction, i.e., it informs - // the stack about the battery level by calling a function provided - // by the upper layers - mbed::Callback battery_level; - } lorawan_app_callbacks_t; + // Mandatory. Event Callback must be provided + mbed::Callback events; + + // Rest are optional + // If the user do not assign these callbacks, these callbacks would return + // null if checked with bool operator + // link_check_resp callback and other such callbacks will be maped in + // future releases of Mbed-OS + mbed::Callback link_check_resp; + + // Battery level callback goes in the down direction, i.e., it informs + // the stack about the battery level by calling a function provided + // by the upper layers + mbed::Callback battery_level; +} lorawan_app_callbacks_t; typedef struct lora_channelplan { uint8_t nb_channels; // number of channels diff --git a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/mbed-mesh-api/MeshInterfaceNanostack.h b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/mbed-mesh-api/MeshInterfaceNanostack.h index 59d8b477ced..60356394b8e 100644 --- a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/mbed-mesh-api/MeshInterfaceNanostack.h +++ b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/mbed-mesh-api/MeshInterfaceNanostack.h @@ -59,7 +59,10 @@ class MeshInterfaceNanostack : public MeshInterface { /** Get the interface ID /return Interface identifier */ - int8_t get_interface_id() const { return _network_interface_id; } + int8_t get_interface_id() const + { + return _network_interface_id; + } /** * \brief Callback from C-layer @@ -90,7 +93,7 @@ class MeshInterfaceNanostack : public MeshInterface { MeshInterfaceNanostack(); MeshInterfaceNanostack(NanostackPhy *phy); nsapi_error_t register_phy(); - virtual NetworkStack * get_stack(void); + virtual NetworkStack *get_stack(void); /** * \brief Read own global IP address diff --git a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/MeshInterfaceNanostack.cpp b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/MeshInterfaceNanostack.cpp index 355dc8f1ad7..177edb09f23 100644 --- a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/MeshInterfaceNanostack.cpp +++ b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/MeshInterfaceNanostack.cpp @@ -23,7 +23,7 @@ MeshInterfaceNanostack::MeshInterfaceNanostack() : phy(NULL), _network_interface_id(-1), _device_id(-1), _eui64(), - ip_addr_str(), mac_addr_str(), connect_semaphore(0), + ip_addr_str(), mac_addr_str(), connect_semaphore(0), _connection_status_cb(NULL), _connect_status(NSAPI_STATUS_DISCONNECTED), _blocking(true) { @@ -51,7 +51,7 @@ void MeshInterfaceNanostack::mesh_network_handler(mesh_connection_status_t statu nanostack_lock(); if ((status == MESH_CONNECTED || status == MESH_CONNECTED_LOCAL || - status == MESH_CONNECTED_GLOBAL) && _blocking) { + status == MESH_CONNECTED_GLOBAL) && _blocking) { connect_semaphore.release(); } @@ -65,10 +65,10 @@ void MeshInterfaceNanostack::mesh_network_handler(mesh_connection_status_t statu _connect_status = NSAPI_STATUS_LOCAL_UP; } if (arm_net_address_get(_network_interface_id, ADDR_IPV6_GP, temp_ipv6_global) == 0 - && (memcmp(temp_ipv6_global, temp_ipv6_local, 16) != 0)) { + && (memcmp(temp_ipv6_global, temp_ipv6_local, 16) != 0)) { _connect_status = NSAPI_STATUS_GLOBAL_UP; } - } else if (status == MESH_CONNECTED_LOCAL ) { + } else if (status == MESH_CONNECTED_LOCAL) { _connect_status = NSAPI_STATUS_LOCAL_UP; } else if (status == MESH_CONNECTED_GLOBAL) { _connect_status = NSAPI_STATUS_GLOBAL_UP; @@ -93,9 +93,9 @@ nsapi_error_t MeshInterfaceNanostack::register_phy() return -1; } // Read mac address after registering the device. - const uint8_t empty_eui64[8] = {0,0,0,0,0,0,0,0}; + const uint8_t empty_eui64[8] = {0, 0, 0, 0, 0, 0, 0, 0}; // if not set by application then read from rf driver - if(!memcmp(_eui64, empty_eui64,8)) { + if (!memcmp(_eui64, empty_eui64, 8)) { phy->get_mac_address(_eui64); } @@ -106,7 +106,7 @@ nsapi_error_t MeshInterfaceNanostack::register_phy() return 0; } -NetworkStack * MeshInterfaceNanostack::get_stack() +NetworkStack *MeshInterfaceNanostack::get_stack() { return NanostackInterface::get_stack(); } diff --git a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/NanostackEthernetInterface.cpp b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/NanostackEthernetInterface.cpp index 1a8e8d798ab..1bb3021af6f 100644 --- a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/NanostackEthernetInterface.cpp +++ b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/NanostackEthernetInterface.cpp @@ -21,8 +21,9 @@ nsapi_error_t NanostackEthernetInterface::initialize(NanostackEthernetPhy *phy) { nsapi_error_t err = MeshInterfaceNanostack::initialize(phy); - if (err != NSAPI_ERROR_OK) + if (err != NSAPI_ERROR_OK) { return err; + } nanostack_lock(); @@ -37,10 +38,11 @@ nsapi_error_t NanostackEthernetInterface::initialize(NanostackEthernetPhy *phy) nanostack_unlock(); - if (_network_interface_id < 0) + if (_network_interface_id < 0) { return MESH_ERROR_UNKNOWN; - else + } else { return MESH_ERROR_NONE; + } } int NanostackEthernetInterface::connect() @@ -75,7 +77,7 @@ int NanostackEthernetInterface::disconnect() bool NanostackEthernetInterface::getOwnIpAddress(char *address, int8_t len) { - return enet_tasklet_get_ip_address(address, len)?false:true; + return enet_tasklet_get_ip_address(address, len) ? false : true; } bool NanostackEthernetInterface::getRouterIpAddress(char *address, int8_t len) diff --git a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/ethernet_tasklet.c b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/ethernet_tasklet.c index 0385924f97d..54f7c1df9de 100644 --- a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/ethernet_tasklet.c +++ b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/ethernet_tasklet.c @@ -189,7 +189,7 @@ static void enet_tasklet_poll_network_status(void *param) memcpy(tasklet_data_ptr->ip, temp_ipv6, 16); uint8_t temp_ipv6_local[16]; if (arm_net_address_get(tasklet_data_ptr->network_interface_id, ADDR_IPV6_LL, temp_ipv6_local) == 0 - && (memcmp(temp_ipv6, temp_ipv6_local, 16) != 0)) { + && (memcmp(temp_ipv6, temp_ipv6_local, 16) != 0)) { enet_tasklet_network_state_changed(MESH_CONNECTED_GLOBAL); } else { enet_tasklet_network_state_changed(MESH_CONNECTED_LOCAL);; @@ -197,8 +197,9 @@ static void enet_tasklet_poll_network_status(void *param) } } else { if (tasklet_data_ptr->connection_status != MESH_DISCONNECTED && - tasklet_data_ptr->connection_status != MESH_BOOTSTRAP_STARTED) + tasklet_data_ptr->connection_status != MESH_BOOTSTRAP_STARTED) { enet_tasklet_network_state_changed(MESH_DISCONNECTED); + } } } @@ -256,7 +257,7 @@ int8_t enet_tasklet_connect(mesh_interface_cb callback, int8_t nwk_interface_id) if (re_connecting == false) { tasklet_data_ptr->tasklet = eventOS_event_handler_create(&enet_tasklet_main, - ARM_LIB_TASKLET_INIT_EVENT); + ARM_LIB_TASKLET_INIT_EVENT); if (tasklet_data_ptr->tasklet < 0) { // -1 handler already used by other tasklet // -2 memory allocation failure diff --git a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/mesh_system.c b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/mesh_system.c index c87d7d37729..66cac09fb98 100644 --- a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/mesh_system.c +++ b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/mesh_system.c @@ -62,7 +62,7 @@ void mesh_system_init(void) { if (mesh_initialized == false) { #if MBED_CONF_MBED_MESH_API_USE_MALLOC_FOR_HEAP - app_stack_heap = malloc(MBED_CONF_MBED_MESH_API_HEAP_SIZE+1); + app_stack_heap = malloc(MBED_CONF_MBED_MESH_API_HEAP_SIZE + 1); MBED_ASSERT(app_stack_heap); #endif ns_hal_init(app_stack_heap, MBED_CONF_MBED_MESH_API_HEAP_SIZE, diff --git a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/nd_tasklet.c b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/nd_tasklet.c index 1eaa785f090..4f6c2308208 100644 --- a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/nd_tasklet.c +++ b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/nd_tasklet.c @@ -268,15 +268,15 @@ void nd_tasklet_configure_and_connect_to_network(void) tasklet_data_ptr->network_interface_id, NULL); arm_nwk_6lowpan_link_panid_filter_for_nwk_scan( - tasklet_data_ptr->network_interface_id, - MBED_CONF_MBED_MESH_API_6LOWPAN_ND_PANID_FILTER); + tasklet_data_ptr->network_interface_id, + MBED_CONF_MBED_MESH_API_6LOWPAN_ND_PANID_FILTER); // Enable MPL by default - const uint8_t all_mpl_forwarders[16] = {0xff, 0x03, [15]=0xfc}; + const uint8_t all_mpl_forwarders[16] = {0xff, 0x03, [15] = 0xfc}; multicast_mpl_domain_subscribe(tasklet_data_ptr->network_interface_id, - all_mpl_forwarders, - MULTICAST_MPL_SEED_ID_DEFAULT, - NULL); + all_mpl_forwarders, + MULTICAST_MPL_SEED_ID_DEFAULT, + NULL); status = arm_nwk_interface_up(tasklet_data_ptr->network_interface_id); if (status >= 0) { @@ -327,7 +327,7 @@ void nd_tasklet_trace_bootstrap_info() tr_error("MAC Address read fail\n"); } else { uint8_t temp[2]; - common_write_16_bit(app_link_address_info.mac_short,temp); + common_write_16_bit(app_link_address_info.mac_short, temp); tr_debug("MAC 16-bit: %s", trace_array(temp, 2)); common_write_16_bit(app_link_address_info.PANId, temp); tr_debug("PAN ID: %s", trace_array(temp, 2)); @@ -392,7 +392,7 @@ int8_t nd_tasklet_connect(mesh_interface_cb callback, int8_t nwk_interface_id) if (re_connecting == false) { tasklet_data_ptr->tasklet = eventOS_event_handler_create(&nd_tasklet_main, - ARM_LIB_TASKLET_INIT_EVENT); + ARM_LIB_TASKLET_INIT_EVENT); if (tasklet_data_ptr->tasklet < 0) { // -1 handler already used by other tasklet // -2 memory allocation failure diff --git a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/thread_tasklet.c b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/thread_tasklet.c index d16271d13c1..0a8cc62355f 100644 --- a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/thread_tasklet.c +++ b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/thread_tasklet.c @@ -244,23 +244,25 @@ void thread_tasklet_poll_network_status(void *param) } } else { if (thread_tasklet_data_ptr->connection_status != MESH_DISCONNECTED && - thread_tasklet_data_ptr->connection_status != MESH_BOOTSTRAP_STARTED) + thread_tasklet_data_ptr->connection_status != MESH_BOOTSTRAP_STARTED) { thread_tasklet_network_state_changed(MESH_DISCONNECTED); + } } } -void read_link_configuration() { +void read_link_configuration() +{ thread_tasklet_data_ptr->link_config.panId = MBED_CONF_MBED_MESH_API_THREAD_CONFIG_PANID; TRACE_DETAIL("PANID %x", thread_tasklet_data_ptr->link_config.panId); thread_tasklet_data_ptr->link_config.rfChannel = MBED_CONF_MBED_MESH_API_THREAD_CONFIG_CHANNEL; TRACE_DETAIL("channel: %d", thread_tasklet_data_ptr->link_config.rfChannel); - + // Mesh prefix const uint8_t mesh_local_prefix[] = MBED_CONF_MBED_MESH_API_THREAD_CONFIG_ML_PREFIX; MBED_ASSERT(sizeof(mesh_local_prefix) == 8); - + memcpy(thread_tasklet_data_ptr->link_config.mesh_local_ula_prefix, mesh_local_prefix, 8); TRACE_DETAIL("Mesh prefix: %s", trace_array(mesh_local_prefix, 8)); @@ -277,14 +279,14 @@ void read_link_configuration() { thread_tasklet_data_ptr->link_config.key_rotation = 3600; thread_tasklet_data_ptr->link_config.key_sequence = 0; - thread_tasklet_data_ptr->link_config.securityPolicy = MBED_CONF_MBED_MESH_API_THREAD_SECURITY_POLICY; - + thread_tasklet_data_ptr->link_config.securityPolicy = MBED_CONF_MBED_MESH_API_THREAD_SECURITY_POLICY; + // network name MBED_ASSERT(strlen(MBED_CONF_MBED_MESH_API_THREAD_CONFIG_NETWORK_NAME) > 0 && strlen(MBED_CONF_MBED_MESH_API_THREAD_CONFIG_NETWORK_NAME) < 17); memcpy(thread_tasklet_data_ptr->link_config.name, MBED_CONF_MBED_MESH_API_THREAD_CONFIG_NETWORK_NAME, strlen(MBED_CONF_MBED_MESH_API_THREAD_CONFIG_NETWORK_NAME)); - + thread_tasklet_data_ptr->link_config.timestamp = MBED_CONF_MBED_MESH_API_THREAD_CONFIG_COMMISSIONING_DATASET_TIMESTAMP; - + // extended pan-id const uint8_t extented_panid[] = MBED_CONF_MBED_MESH_API_THREAD_CONFIG_EXTENDED_PANID; MBED_ASSERT(sizeof(extented_panid) == 8); @@ -298,13 +300,12 @@ void read_link_configuration() { void thread_tasklet_configure_and_connect_to_network(void) { int8_t status; - link_configuration_s* temp_link_config=NULL; + link_configuration_s *temp_link_config = NULL; if (MBED_CONF_MBED_MESH_API_THREAD_DEVICE_TYPE == MESH_DEVICE_TYPE_THREAD_MINIMAL_END_DEVICE) { - thread_tasklet_data_ptr->operating_mode = NET_6LOWPAN_HOST; - } - else if (MBED_CONF_MBED_MESH_API_THREAD_DEVICE_TYPE == MESH_DEVICE_TYPE_THREAD_SLEEPY_END_DEVICE) { + thread_tasklet_data_ptr->operating_mode = NET_6LOWPAN_HOST; + } else if (MBED_CONF_MBED_MESH_API_THREAD_DEVICE_TYPE == MESH_DEVICE_TYPE_THREAD_SLEEPY_END_DEVICE) { thread_tasklet_data_ptr->operating_mode = NET_6LOWPAN_SLEEPY_HOST; } else { thread_tasklet_data_ptr->operating_mode = NET_6LOWPAN_ROUTER; @@ -314,16 +315,16 @@ void thread_tasklet_configure_and_connect_to_network(void) thread_tasklet_data_ptr->nwk_if_id, thread_tasklet_data_ptr->operating_mode, NET_6LOWPAN_THREAD); - + thread_tasklet_data_ptr->channel_list.channel_page = (channel_page_e)MBED_CONF_MBED_MESH_API_THREAD_CONFIG_CHANNEL_PAGE; thread_tasklet_data_ptr->channel_list.channel_mask[0] = MBED_CONF_MBED_MESH_API_THREAD_CONFIG_CHANNEL_MASK; - + TRACE_DETAIL("channel page: %d", thread_tasklet_data_ptr->channel_list.channel_page); TRACE_DETAIL("channel mask: 0x%.8lx", thread_tasklet_data_ptr->channel_list.channel_mask[0]); // PSKd const char PSKd[] = MBED_CONF_MBED_MESH_API_THREAD_PSKD; - if(device_configuration.PSKd_len==0) { + if (device_configuration.PSKd_len == 0) { int ret = thread_tasklet_device_pskd_set(PSKd); MBED_ASSERT(!ret); } @@ -332,11 +333,11 @@ void thread_tasklet_configure_and_connect_to_network(void) read_link_configuration(); temp_link_config = &thread_tasklet_data_ptr->link_config; } - + thread_management_node_init(thread_tasklet_data_ptr->nwk_if_id, - &thread_tasklet_data_ptr->channel_list, - &device_configuration, - temp_link_config); + &thread_tasklet_data_ptr->channel_list, + &device_configuration, + temp_link_config); status = arm_nwk_interface_up(thread_tasklet_data_ptr->nwk_if_id); @@ -380,7 +381,7 @@ void thread_tasklet_trace_bootstrap_info() tr_error("MAC Address read fail\n"); } else { uint8_t temp[2]; - common_write_16_bit(app_link_address_info.mac_short,temp); + common_write_16_bit(app_link_address_info.mac_short, temp); tr_debug("MAC 16-bit: %s", trace_array(temp, 2)); common_write_16_bit(app_link_address_info.PANId, temp); tr_debug("PAN ID: %s", trace_array(temp, 2)); @@ -426,7 +427,7 @@ int8_t thread_tasklet_connect(mesh_interface_cb callback, int8_t nwk_interface_i if (re_connecting == false) { thread_tasklet_data_ptr->tasklet = eventOS_event_handler_create(&thread_tasklet_main, - ARM_LIB_TASKLET_INIT_EVENT); + ARM_LIB_TASKLET_INIT_EVENT); if (thread_tasklet_data_ptr->tasklet < 0) { // -1 handler already used by other tasklet // -2 memory allocation failure @@ -493,16 +494,16 @@ void thread_tasklet_device_eui64_set(const uint8_t *eui64) uint8_t thread_tasklet_device_pskd_set(const char *pskd) { int len = strlen(pskd); - if(len < 6 || len > 32) { + if (len < 6 || len > 32) { return MESH_ERROR_PARAM; } - char *dyn_buf = ns_dyn_mem_alloc(strlen(pskd)+1); + char *dyn_buf = ns_dyn_mem_alloc(strlen(pskd) + 1); if (!dyn_buf) { return MESH_ERROR_MEMORY; } strcpy(dyn_buf, pskd); ns_dyn_mem_free(device_configuration.PSKd_ptr); - device_configuration.PSKd_ptr = (uint8_t*)dyn_buf; + device_configuration.PSKd_ptr = (uint8_t *)dyn_buf; device_configuration.PSKd_len = strlen(pskd); return 0; } diff --git a/features/nanostack/FEATURE_NANOSTACK/nanostack-interface/NanostackInterface.cpp b/features/nanostack/FEATURE_NANOSTACK/nanostack-interface/NanostackInterface.cpp index c85cfca2a95..49d6655799e 100644 --- a/features/nanostack/FEATURE_NANOSTACK/nanostack-interface/NanostackInterface.cpp +++ b/features/nanostack/FEATURE_NANOSTACK/nanostack-interface/NanostackInterface.cpp @@ -61,15 +61,18 @@ enum socket_mode_t { class NanostackSocket { public: static void socket_callback(void *cb); - static void* operator new(std::size_t sz); - static void operator delete(void* ptr); + static void *operator new (std::size_t sz); + static void operator delete (void *ptr); NanostackSocket(int8_t protocol); ~NanostackSocket(void); bool open(void); int accept(NanostackSocket *accepted_socket, ns_address_t *addr); void close(void); - bool closed(void) {return SOCKET_MODE_CLOSED == mode;} + bool closed(void) + { + return SOCKET_MODE_CLOSED == mode; + } bool is_connecting(void); void set_connecting(ns_address_t *addr); bool is_connected(void); @@ -101,21 +104,26 @@ class NanostackSocket { socket_mode_t mode; }; -static NanostackSocket * socket_tbl[NS_INTERFACE_SOCKETS_MAX]; +static NanostackSocket *socket_tbl[NS_INTERFACE_SOCKETS_MAX]; nsapi_error_t map_mesh_error(mesh_error_t err) { switch (err) { - case MESH_ERROR_NONE: return 0; - case MESH_ERROR_MEMORY: return NSAPI_ERROR_NO_MEMORY; - case MESH_ERROR_PARAM: return NSAPI_ERROR_UNSUPPORTED; - case MESH_ERROR_STATE: return NSAPI_ERROR_DEVICE_ERROR; - default: return NSAPI_ERROR_DEVICE_ERROR; + case MESH_ERROR_NONE: + return 0; + case MESH_ERROR_MEMORY: + return NSAPI_ERROR_NO_MEMORY; + case MESH_ERROR_PARAM: + return NSAPI_ERROR_UNSUPPORTED; + case MESH_ERROR_STATE: + return NSAPI_ERROR_DEVICE_ERROR; + default: + return NSAPI_ERROR_DEVICE_ERROR; } } static void convert_mbed_addr_to_ns(ns_address_t *ns_addr, - const SocketAddress *s_addr) + const SocketAddress *s_addr) { ns_addr->type = ADDRESS_IPV6; ns_addr->identifier = s_addr->get_port(); @@ -142,10 +150,12 @@ static int8_t find_interface_by_address(const uint8_t target_addr[16]) return -1; } -void* NanostackSocket::operator new(std::size_t sz) { +void *NanostackSocket::operator new (std::size_t sz) +{ return MALLOC(sz); } -void NanostackSocket::operator delete(void* ptr) { +void NanostackSocket::operator delete (void *ptr) +{ FREE(ptr); } @@ -296,7 +306,8 @@ void NanostackSocket::signal_event() } } -void NanostackSocket::socket_callback(void *cb) { +void NanostackSocket::socket_callback(void *cb) +{ nanostack_assert_locked(); socket_callback_t *sock_cb = (socket_callback_t *) cb; @@ -304,7 +315,7 @@ void NanostackSocket::socket_callback(void *cb) { MBED_ASSERT(socket != NULL); tr_debug("socket_callback() sock=%d, event=%d, interface=%d, data len=%d", - sock_cb->socket_id, sock_cb->event_type, sock_cb->interface_id, sock_cb->d_len); + sock_cb->socket_id, sock_cb->event_type, sock_cb->interface_id, sock_cb->d_len); switch (sock_cb->event_type) { case SOCKET_DATA: @@ -457,7 +468,7 @@ NanostackInterface *NanostackInterface::get_stack() return _ns_interface; } -const char * NanostackInterface::get_ip_address() +const char *NanostackInterface::get_ip_address() { NanostackLockGuard lock; @@ -490,11 +501,11 @@ nsapi_error_t NanostackInterface::socket_open(void **handle, nsapi_protocol_t pr MBED_ASSERT(false); return NSAPI_ERROR_UNSUPPORTED; } - *handle = (void*)NULL; + *handle = (void *)NULL; NanostackLockGuard lock; - NanostackSocket * socket = new NanostackSocket(ns_proto); + NanostackSocket *socket = new NanostackSocket(ns_proto); if (socket == NULL) { tr_debug("socket_open() ret=%i", NSAPI_ERROR_NO_MEMORY); return NSAPI_ERROR_NO_MEMORY; @@ -504,7 +515,7 @@ nsapi_error_t NanostackInterface::socket_open(void **handle, nsapi_protocol_t pr tr_debug("socket_open() ret=%i", NSAPI_ERROR_DEVICE_ERROR); return NSAPI_ERROR_DEVICE_ERROR; } - *handle = (void*)socket; + *handle = (void *)socket; tr_debug("socket_open() socket=%p, sock_id=%d, ret=0", socket, socket->socket_id); @@ -515,7 +526,7 @@ nsapi_error_t NanostackInterface::socket_close(void *handle) { NanostackLockGuard lock; // Validate parameters - NanostackSocket * socket = static_cast(handle); + NanostackSocket *socket = static_cast(handle); if (NULL == handle) { MBED_ASSERT(false); return NSAPI_ERROR_NO_SOCKET; @@ -531,7 +542,7 @@ nsapi_error_t NanostackInterface::socket_close(void *handle) nsapi_size_or_error_t NanostackInterface::do_sendto(void *handle, const ns_address_t *address, const void *data, nsapi_size_t size) { // Validate parameters - NanostackSocket * socket = static_cast(handle); + NanostackSocket *socket = static_cast(handle); if (handle == NULL) { MBED_ASSERT(false); return NSAPI_ERROR_NO_SOCKET; @@ -555,7 +566,7 @@ nsapi_size_or_error_t NanostackInterface::do_sendto(void *handle, const ns_addre int retcode; #if 0 retcode = ::socket_sendto(socket->socket_id, address, - data, size); + data, size); #else // Use sendmsg purely to get the new return style // of returning data written rather than 0 on success, @@ -567,7 +578,7 @@ nsapi_size_or_error_t NanostackInterface::do_sendto(void *handle, const ns_addre iov.iov_base = const_cast(data); iov.iov_len = size; msg.msg_name = const_cast(address); - msg.msg_namelen = address ? sizeof *address : 0; + msg.msg_namelen = address ? sizeof * address : 0; msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = NULL; @@ -715,32 +726,32 @@ nsapi_error_t NanostackInterface::setsockopt(void *handle, int level, int optnam switch (optname) { case NSAPI_ADD_MEMBERSHIP: case NSAPI_DROP_MEMBERSHIP: { - if (optlen != sizeof(nsapi_ip_mreq_t)) { - return NSAPI_ERROR_PARAMETER; + if (optlen != sizeof(nsapi_ip_mreq_t)) { + return NSAPI_ERROR_PARAMETER; + } + const nsapi_ip_mreq_t *imr = static_cast(optval); + + /* Check address types are IPv6, or unspecified for interface */ + if (imr->imr_multiaddr.version != NSAPI_IPv6 || + (imr->imr_interface.version != NSAPI_UNSPEC && imr->imr_interface.version != NSAPI_IPv6)) { + return NSAPI_ERROR_PARAMETER; + } + + /* Convert all parameters to Nanostack native, and proceed with setsockopt */ + memcpy(ns_mreq.ipv6mr_multiaddr, imr->imr_multiaddr.bytes, 16); + if (imr->imr_interface.version == NSAPI_UNSPEC || memcmp(imr->imr_interface.bytes, ns_in6addr_any, 16) == 0) { + ns_mreq.ipv6mr_interface = 0; + } else { + // If this fails, Nanostack will itself fault the invalid -1 interface ID + ns_mreq.ipv6mr_interface = find_interface_by_address(imr->imr_interface.bytes); + } + + level = SOCKET_IPPROTO_IPV6; + optname = optname == NSAPI_ADD_MEMBERSHIP ? SOCKET_IPV6_JOIN_GROUP : SOCKET_IPV6_LEAVE_GROUP; + optval = &ns_mreq; + optlen = sizeof ns_mreq; + break; } - const nsapi_ip_mreq_t *imr = static_cast(optval); - - /* Check address types are IPv6, or unspecified for interface */ - if (imr->imr_multiaddr.version != NSAPI_IPv6 || - (imr->imr_interface.version != NSAPI_UNSPEC && imr->imr_interface.version != NSAPI_IPv6)) { - return NSAPI_ERROR_PARAMETER; - } - - /* Convert all parameters to Nanostack native, and proceed with setsockopt */ - memcpy(ns_mreq.ipv6mr_multiaddr, imr->imr_multiaddr.bytes, 16); - if (imr->imr_interface.version == NSAPI_UNSPEC || memcmp(imr->imr_interface.bytes, ns_in6addr_any, 16) == 0) { - ns_mreq.ipv6mr_interface = 0; - } else { - // If this fails, Nanostack will itself fault the invalid -1 interface ID - ns_mreq.ipv6mr_interface = find_interface_by_address(imr->imr_interface.bytes); - } - - level = SOCKET_IPPROTO_IPV6; - optname = optname == NSAPI_ADD_MEMBERSHIP ? SOCKET_IPV6_JOIN_GROUP : SOCKET_IPV6_LEAVE_GROUP; - optval = &ns_mreq; - optlen = sizeof ns_mreq; - break; - } default: return NSAPI_ERROR_PARAMETER; } @@ -789,7 +800,7 @@ nsapi_error_t NanostackInterface::socket_listen(void *handle, int backlog) NanostackLockGuard lock; - if(::socket_listen(socket->socket_id, backlog) < 0) { + if (::socket_listen(socket->socket_id, backlog) < 0) { ret = NSAPI_ERROR_PARAMETER; } else { socket->set_listening(); @@ -852,7 +863,7 @@ nsapi_error_t NanostackInterface::socket_connect(void *handle, const SocketAddre nsapi_error_t NanostackInterface::socket_accept(void *server, void **handle, SocketAddress *address) { - NanostackSocket * socket = static_cast(server); + NanostackSocket *socket = static_cast(server); NanostackSocket *accepted_sock = NULL; nsapi_error_t ret; @@ -913,7 +924,7 @@ nsapi_size_or_error_t NanostackInterface::socket_recv(void *handle, void *data, void NanostackInterface::socket_attach(void *handle, void (*callback)(void *), void *id) { // Validate parameters - NanostackSocket * socket = static_cast(handle); + NanostackSocket *socket = static_cast(handle); if (handle == NULL) { MBED_ASSERT(false); return; diff --git a/features/nanostack/FEATURE_NANOSTACK/nanostack-interface/NanostackInterface.h b/features/nanostack/FEATURE_NANOSTACK/nanostack-interface/NanostackInterface.h index 453efa14aee..1e70a0e31bb 100644 --- a/features/nanostack/FEATURE_NANOSTACK/nanostack-interface/NanostackInterface.h +++ b/features/nanostack/FEATURE_NANOSTACK/nanostack-interface/NanostackInterface.h @@ -234,7 +234,7 @@ class NanostackInterface : public NetworkStack { private: nsapi_size_or_error_t do_sendto(void *handle, const struct ns_address *address, const void *data, nsapi_size_t size); char text_ip_address[40]; - static NanostackInterface * _ns_interface; + static NanostackInterface *_ns_interface; }; nsapi_error_t map_mesh_error(mesh_error_t err); diff --git a/features/nanostack/FEATURE_NANOSTACK/nanostack-interface/NanostackLockGuard.h b/features/nanostack/FEATURE_NANOSTACK/nanostack-interface/NanostackLockGuard.h index ec1a249a14d..9a064f82d77 100644 --- a/features/nanostack/FEATURE_NANOSTACK/nanostack-interface/NanostackLockGuard.h +++ b/features/nanostack/FEATURE_NANOSTACK/nanostack-interface/NanostackLockGuard.h @@ -27,17 +27,19 @@ class NanostackLockGuard { public: - NanostackLockGuard() { + NanostackLockGuard() + { eventOS_scheduler_mutex_wait(); } - ~NanostackLockGuard() { + ~NanostackLockGuard() + { eventOS_scheduler_mutex_release(); } private: - NanostackLockGuard(const NanostackLockGuard&); - NanostackLockGuard& operator=(const NanostackLockGuard&); + NanostackLockGuard(const NanostackLockGuard &); + NanostackLockGuard &operator=(const NanostackLockGuard &); }; #endif /* NANOSTACK_LOCK_GUARD_H_ */ diff --git a/features/nanostack/FEATURE_NANOSTACK/nanostack-interface/NanostackRfPhy.h b/features/nanostack/FEATURE_NANOSTACK/nanostack-interface/NanostackRfPhy.h index ac65de92b59..852d8606597 100644 --- a/features/nanostack/FEATURE_NANOSTACK/nanostack-interface/NanostackRfPhy.h +++ b/features/nanostack/FEATURE_NANOSTACK/nanostack-interface/NanostackRfPhy.h @@ -40,12 +40,18 @@ class NanostackRfPhy : public NanostackPhy { * @return Device driver ID or a negative error * code on failure */ - virtual int8_t phy_register() { return rf_register();} + virtual int8_t phy_register() + { + return rf_register(); + } /** Unregister this physical interface * */ - virtual void unregister() { rf_unregister(); } + virtual void unregister() + { + rf_unregister(); + } }; #endif /* NANOSTACK_RF_PHY_H_ */ diff --git a/features/netsocket/CellularInterface.h b/features/netsocket/CellularInterface.h index 8851a2ac6c0..d431804ccae 100644 --- a/features/netsocket/CellularInterface.h +++ b/features/netsocket/CellularInterface.h @@ -25,8 +25,7 @@ * Common interface that is shared between ethernet hardware * @addtogroup netsocket */ -class CellularInterface : public NetworkInterface -{ +class CellularInterface : public NetworkInterface { public: /** CellularInterface lifetime */ @@ -40,7 +39,7 @@ class CellularInterface : public NetworkInterface * @return 0 on success, negative error code on failure */ virtual nsapi_error_t set_credentials(const char *apn, - const char *username = 0, const char *password = 0) = 0; + const char *username = 0, const char *password = 0) = 0; /** Start the interface * @@ -50,7 +49,7 @@ class CellularInterface : public NetworkInterface * @return 0 on success, negative error code on failure */ virtual nsapi_error_t connect(const char *apn, - const char *username = 0, const char *password = 0) = 0; + const char *username = 0, const char *password = 0) = 0; /** Start the interface * diff --git a/features/netsocket/EthInterface.h b/features/netsocket/EthInterface.h index 6d4ee9ad24b..b884ce7ea12 100644 --- a/features/netsocket/EthInterface.h +++ b/features/netsocket/EthInterface.h @@ -27,8 +27,7 @@ * * Common interface that is shared between ethernet hardware. */ -class EthInterface : public NetworkInterface -{ +class EthInterface : public NetworkInterface { }; diff --git a/features/netsocket/MeshInterface.h b/features/netsocket/MeshInterface.h index dcbd54a738f..2ef31b65fce 100644 --- a/features/netsocket/MeshInterface.h +++ b/features/netsocket/MeshInterface.h @@ -27,8 +27,7 @@ * * Common interface that is shared between mesh hardware */ -class MeshInterface : public NetworkInterface -{ +class MeshInterface : public NetworkInterface { }; diff --git a/features/netsocket/NetworkInterface.h b/features/netsocket/NetworkInterface.h index 3d5d8253702..126164e61d0 100644 --- a/features/netsocket/NetworkInterface.h +++ b/features/netsocket/NetworkInterface.h @@ -42,7 +42,7 @@ class NetworkInterface { * Provided MAC address is intended for info or debug purposes and * may not be provided if the underlying network interface does not * provide a MAC address - * + * * @return Null-terminated representation of the local MAC address * or null if no MAC address is available */ @@ -57,7 +57,7 @@ class NetworkInterface { /** Get the local network mask * - * @return Null-terminated representation of the local network mask + * @return Null-terminated representation of the local network mask * or null if no network mask has been recieved */ virtual const char *get_netmask(); @@ -81,7 +81,7 @@ class NetworkInterface { * @return 0 on success, negative error code on failure */ virtual nsapi_error_t set_network( - const char *ip_address, const char *netmask, const char *gateway); + const char *ip_address, const char *netmask, const char *gateway); /** Enable or disable DHCP on the network * @@ -121,7 +121,7 @@ class NetworkInterface { * @return 0 on success, negative error code on failure */ virtual nsapi_error_t gethostbyname(const char *host, - SocketAddress *address, nsapi_version_t version = NSAPI_UNSPEC); + SocketAddress *address, nsapi_version_t version = NSAPI_UNSPEC); /** Add a domain name server to list of servers to query * diff --git a/features/netsocket/NetworkStack.cpp b/features/netsocket/NetworkStack.cpp index cb02bbfce10..73d6862f12f 100644 --- a/features/netsocket/NetworkStack.cpp +++ b/features/netsocket/NetworkStack.cpp @@ -72,14 +72,13 @@ nsapi_error_t NetworkStack::getsockopt(void *handle, int level, int optname, voi // NetworkStackWrapper class for encapsulating the raw nsapi_stack structure -class NetworkStackWrapper : public NetworkStack -{ +class NetworkStackWrapper : public NetworkStack { private: inline nsapi_stack_t *_stack() { return reinterpret_cast( - reinterpret_cast(this) - - offsetof(nsapi_stack_t, _stack_buffer)); + reinterpret_cast(this) + - offsetof(nsapi_stack_t, _stack_buffer)); } inline const nsapi_stack_api_t *_stack_api() @@ -282,7 +281,7 @@ class NetworkStackWrapper : public NetworkStack NetworkStack *nsapi_create_stack(nsapi_stack_t *stack) { MBED_STATIC_ASSERT(sizeof stack->_stack_buffer >= sizeof(NetworkStackWrapper), - "The nsapi_stack_t stack buffer must fit a NetworkStackWrapper"); + "The nsapi_stack_t stack buffer must fit a NetworkStackWrapper"); return new (stack->_stack_buffer) NetworkStackWrapper; } diff --git a/features/netsocket/NetworkStack.h b/features/netsocket/NetworkStack.h index 27b9cc1f97c..c1d2b240ec8 100644 --- a/features/netsocket/NetworkStack.h +++ b/features/netsocket/NetworkStack.h @@ -31,8 +31,7 @@ * for instantiating network sockets. * @addtogroup netsocket */ -class NetworkStack -{ +class NetworkStack { public: virtual ~NetworkStack() {}; @@ -58,7 +57,7 @@ class NetworkStack * @return 0 on success, negative error code on failure */ virtual nsapi_error_t gethostbyname(const char *host, - SocketAddress *address, nsapi_version_t version = NSAPI_UNSPEC); + SocketAddress *address, nsapi_version_t version = NSAPI_UNSPEC); /** Add a domain name server to list of servers to query * @@ -181,7 +180,7 @@ class NetworkStack * @return 0 on success, negative error code on failure */ virtual nsapi_error_t socket_accept(nsapi_socket_t server, - nsapi_socket_t *handle, SocketAddress *address=0) = 0; + nsapi_socket_t *handle, SocketAddress *address = 0) = 0; /** Send data over a TCP socket * @@ -282,7 +281,7 @@ class NetworkStack * @return 0 on success, negative error code on failure */ virtual nsapi_error_t setsockopt(nsapi_socket_t handle, int level, - int optname, const void *optval, unsigned optlen); + int optname, const void *optval, unsigned optlen); /* Get stack-specific socket options * @@ -298,7 +297,7 @@ class NetworkStack * @return 0 on success, negative error code on failure */ virtual nsapi_error_t getsockopt(nsapi_socket_t handle, int level, - int optname, void *optval, unsigned *optlen); + int optname, void *optval, unsigned *optlen); }; diff --git a/features/netsocket/Socket.h b/features/netsocket/Socket.h index 4040abe5be7..58440340c6a 100644 --- a/features/netsocket/Socket.h +++ b/features/netsocket/Socket.h @@ -49,10 +49,11 @@ class Socket { nsapi_error_t open(NetworkStack *stack); template - nsapi_error_t open(S *stack) { + nsapi_error_t open(S *stack) + { return open(nsapi_create_stack(stack)); } - + /** Close the socket * * Closes any open connection and deallocates any memory associated @@ -61,7 +62,7 @@ class Socket { * @return 0 on success, negative error code on failure */ nsapi_error_t close(); - + /** Subscribes to an IP multicast group * * @param address Multicast group IP address @@ -106,7 +107,7 @@ class Socket { * @return 0 on success, negative error code on failure. */ nsapi_error_t bind(const SocketAddress &address); - + /** Set blocking or non-blocking mode of the socket * * Initially all sockets are in blocking mode. In non-blocking mode @@ -119,7 +120,7 @@ class Socket { * @param blocking true for blocking mode, false for non-blocking mode. */ void set_blocking(bool blocking); - + /** Set timeout on blocking socket operations * * Initially all sockets have unbounded timeouts. NSAPI_ERROR_WOULD_BLOCK @@ -148,7 +149,7 @@ class Socket { * @param optval Option value * @param optlen Length of the option value * @return 0 on success, negative error code on failure - */ + */ nsapi_error_t setsockopt(int level, int optname, const void *optval, unsigned optlen); /* Get socket options @@ -165,7 +166,7 @@ class Socket { * @param optval Destination for option value * @param optlen Length of the option value * @return 0 on success, negative error code on failure - */ + */ nsapi_error_t getsockopt(int level, int optname, void *optval, unsigned *optlen); /** Register a callback on state change of the socket @@ -194,8 +195,8 @@ class Socket { * mbed OS and has been known to cause confusion. Replaced by Socket::sigio. */ MBED_DEPRECATED_SINCE("mbed-os-5.4", - "The behaviour of Socket::attach differs from other attach functions in " - "mbed OS and has been known to cause confusion. Replaced by Socket::sigio.") + "The behaviour of Socket::attach differs from other attach functions in " + "mbed OS and has been known to cause confusion. Replaced by Socket::sigio.") void attach(mbed::Callback func); /** Register a callback on state change of the socket @@ -207,9 +208,10 @@ class Socket { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "The attach function does not support cv-qualifiers. Replaced by " - "attach(callback(obj, method)).") - void attach(T *obj, M method) { + "The attach function does not support cv-qualifiers. Replaced by " + "attach(callback(obj, method)).") + void attach(T *obj, M method) + { attach(mbed::callback(obj, method)); } diff --git a/features/netsocket/SocketAddress.cpp b/features/netsocket/SocketAddress.cpp index 8fc25952942..929831c8aab 100644 --- a/features/netsocket/SocketAddress.cpp +++ b/features/netsocket/SocketAddress.cpp @@ -33,7 +33,7 @@ static bool ipv4_is_valid(const char *addr) } // Ending with '.' garuntees host - if (i > 0 && addr[i-1] == '.') { + if (i > 0 && addr[i - 1] == '.') { return false; } @@ -47,9 +47,9 @@ static bool ipv6_is_valid(const char *addr) int colons = 0; for (int i = 0; addr[i]; i++) { if (!(addr[i] >= '0' && addr[i] <= '9') && - !(addr[i] >= 'a' && addr[i] <= 'f') && - !(addr[i] >= 'A' && addr[i] <= 'F') && - addr[i] != ':') { + !(addr[i] >= 'a' && addr[i] <= 'f') && + !(addr[i] >= 'A' && addr[i] <= 'F') && + addr[i] != ':') { return false; } if (addr[i] == ':') { @@ -84,11 +84,12 @@ static void ipv4_from_address(uint8_t *bytes, const char *addr) } } -static int ipv6_scan_chunk(uint16_t *shorts, const char *chunk) { +static int ipv6_scan_chunk(uint16_t *shorts, const char *chunk) +{ int count = 0; int i = 0; - for (; count < NSAPI_IPv6_BYTES/2; count++) { + for (; count < NSAPI_IPv6_BYTES / 2; count++) { unsigned short s; int scanned = sscanf(&chunk[i], "%hx", &s); if (scanned < 1) { @@ -99,7 +100,7 @@ static int ipv6_scan_chunk(uint16_t *shorts, const char *chunk) { for (; chunk[i] != ':'; i++) { if (!chunk[i]) { - return count+1; + return count + 1; } } @@ -112,30 +113,30 @@ static int ipv6_scan_chunk(uint16_t *shorts, const char *chunk) { static void ipv6_from_address(uint8_t *bytes, const char *addr) { // Start with zeroed address - uint16_t shorts[NSAPI_IPv6_BYTES/2]; + uint16_t shorts[NSAPI_IPv6_BYTES / 2]; int suffix = 0; // Find double colons and scan suffix for (int i = 0; addr[i]; i++) { - if (addr[i] == ':' && addr[i+1] == ':') { - suffix = ipv6_scan_chunk(shorts, &addr[i+2]); + if (addr[i] == ':' && addr[i + 1] == ':') { + suffix = ipv6_scan_chunk(shorts, &addr[i + 2]); break; } } // Move suffix to end - memmove(&shorts[NSAPI_IPv6_BYTES/2-suffix], &shorts[0], - suffix*sizeof(uint16_t)); + memmove(&shorts[NSAPI_IPv6_BYTES / 2 - suffix], &shorts[0], + suffix * sizeof(uint16_t)); memset(&shorts[0], 0, - (NSAPI_IPv6_BYTES/2-suffix)*sizeof(uint16_t)); + (NSAPI_IPv6_BYTES / 2 - suffix)*sizeof(uint16_t)); // Scan prefix ipv6_scan_chunk(shorts, &addr[0]); // Flip bytes - for (int i = 0; i < NSAPI_IPv6_BYTES/2; i++) { - bytes[2*i+0] = (uint8_t)(shorts[i] >> 8); - bytes[2*i+1] = (uint8_t)(shorts[i] >> 0); + for (int i = 0; i < NSAPI_IPv6_BYTES / 2; i++) { + bytes[2 * i + 0] = (uint8_t)(shorts[i] >> 8); + bytes[2 * i + 1] = (uint8_t)(shorts[i] >> 0); } } @@ -146,11 +147,11 @@ static void ipv4_to_address(char *addr, const uint8_t *bytes) static void ipv6_to_address(char *addr, const uint8_t *bytes) { - for (int i = 0; i < NSAPI_IPv6_BYTES/2; i++) { - sprintf(&addr[5*i], "%02x%02x", bytes[2*i], bytes[2*i+1]); - addr[5*i+4] = ':'; + for (int i = 0; i < NSAPI_IPv6_BYTES / 2; i++) { + sprintf(&addr[5 * i], "%02x%02x", bytes[2 * i], bytes[2 * i + 1]); + addr[5 * i + 4] = ':'; } - addr[NSAPI_IPv6_SIZE-1] = '\0'; + addr[NSAPI_IPv6_SIZE - 1] = '\0'; } diff --git a/features/netsocket/SocketAddress.h b/features/netsocket/SocketAddress.h index 42c5684e6f4..5383a6494a4 100644 --- a/features/netsocket/SocketAddress.h +++ b/features/netsocket/SocketAddress.h @@ -28,7 +28,7 @@ class NetworkInterface; /** SocketAddress class * - * Representation of an IP address and port pair. + * Representation of an IP address and port pair. * @addtogroup netsocket */ class SocketAddress { @@ -49,8 +49,8 @@ class SocketAddress { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1.3", - "Constructors hide possible errors. Replaced by " - "NetworkInterface::gethostbyname.") + "Constructors hide possible errors. Replaced by " + "NetworkInterface::gethostbyname.") SocketAddress(S *stack, const char *host, uint16_t port = 0) { _SocketAddress(nsapi_create_stack(stack), host, port); @@ -83,7 +83,7 @@ class SocketAddress { * @param addr SocketAddress to copy */ SocketAddress(const SocketAddress &addr); - + /** Set the IP address * * @param addr Null-terminated represention of the IP address @@ -110,7 +110,7 @@ class SocketAddress { * @param port 16-bit port */ void set_port(uint16_t port); - + /** Get the IP address * * @return Null-terminated representation of the IP Address @@ -134,7 +134,7 @@ class SocketAddress { * @return Raw IP address */ nsapi_addr_t get_addr() const; - + /** Get the port * * @return The 16-bit port diff --git a/features/netsocket/TCPServer.cpp b/features/netsocket/TCPServer.cpp index 85f3249341c..09c508a01ce 100644 --- a/features/netsocket/TCPServer.cpp +++ b/features/netsocket/TCPServer.cpp @@ -56,7 +56,7 @@ nsapi_error_t TCPServer::accept(TCPSocket *connection, SocketAddress *address) if (!_socket) { ret = NSAPI_ERROR_NO_SOCKET; break; - } + } _pending = 0; void *socket; diff --git a/features/netsocket/TCPServer.h b/features/netsocket/TCPServer.h index af9a4e66e34..b125532a783 100644 --- a/features/netsocket/TCPServer.h +++ b/features/netsocket/TCPServer.h @@ -66,7 +66,7 @@ class TCPServer : public Socket { * @return 0 on success, negative error code on failure */ nsapi_error_t listen(int backlog = 1); - + /** Accepts a connection on a TCP socket * * The server socket must be bound and set to listen for connections. diff --git a/features/netsocket/TCPSocket.cpp b/features/netsocket/TCPSocket.cpp index 7897f8accaf..b570be8a2a4 100644 --- a/features/netsocket/TCPSocket.cpp +++ b/features/netsocket/TCPSocket.cpp @@ -208,7 +208,7 @@ nsapi_size_or_error_t TCPSocket::recv(void *data, nsapi_size_t size) void TCPSocket::event() { - _event_flag.set(READ_FLAG|WRITE_FLAG); + _event_flag.set(READ_FLAG | WRITE_FLAG); _pending += 1; if (_callback && _pending == 1) { diff --git a/features/netsocket/TCPSocket.h b/features/netsocket/TCPSocket.h index 39c547d7afa..f73a8b87564 100644 --- a/features/netsocket/TCPSocket.h +++ b/features/netsocket/TCPSocket.h @@ -57,10 +57,13 @@ class TCPSocket : public Socket { */ virtual ~TCPSocket(); - /** Override multicast functions to return error for TCP - * - */ - int join_multicast_group(const SocketAddress &address) { return NSAPI_ERROR_UNSUPPORTED; } + /** Override multicast functions to return error for TCP + * + */ + int join_multicast_group(const SocketAddress &address) + { + return NSAPI_ERROR_UNSUPPORTED; + } /** Connects TCP socket to a remote host * @@ -82,7 +85,7 @@ class TCPSocket : public Socket { * @return 0 on success, negative error code on failure */ nsapi_error_t connect(const SocketAddress &address); - + /** Send data over a TCP socket * * The socket must be connected to a remote host. Returns the number of @@ -98,7 +101,7 @@ class TCPSocket : public Socket { * code on failure */ nsapi_size_or_error_t send(const void *data, nsapi_size_t size); - + /** Receive data over a TCP socket * * The socket must be connected to a remote host. Returns the number of diff --git a/features/netsocket/UDPSocket.cpp b/features/netsocket/UDPSocket.cpp index cb6fbd67ce1..3260760cd72 100644 --- a/features/netsocket/UDPSocket.cpp +++ b/features/netsocket/UDPSocket.cpp @@ -128,7 +128,7 @@ nsapi_size_or_error_t UDPSocket::recvfrom(SocketAddress *address, void *buffer, void UDPSocket::event() { - _event_flag.set(READ_FLAG|WRITE_FLAG); + _event_flag.set(READ_FLAG | WRITE_FLAG); _pending += 1; if (_callback && _pending == 1) { diff --git a/features/netsocket/UDPSocket.h b/features/netsocket/UDPSocket.h index a4570fa80e5..55d1d5520c1 100644 --- a/features/netsocket/UDPSocket.h +++ b/features/netsocket/UDPSocket.h @@ -74,7 +74,7 @@ class UDPSocket : public Socket { * code on failure */ nsapi_size_or_error_t sendto(const char *host, uint16_t port, - const void *data, nsapi_size_t size); + const void *data, nsapi_size_t size); /** Send a packet over a UDP socket * @@ -92,7 +92,7 @@ class UDPSocket : public Socket { * code on failure */ nsapi_size_or_error_t sendto(const SocketAddress &address, - const void *data, nsapi_size_t size); + const void *data, nsapi_size_t size); /** Receive a datagram over a UDP socket * @@ -111,7 +111,7 @@ class UDPSocket : public Socket { * code on failure */ nsapi_size_or_error_t recvfrom(SocketAddress *address, - void *data, nsapi_size_t size); + void *data, nsapi_size_t size); protected: virtual nsapi_protocol_t get_proto(); diff --git a/features/netsocket/WiFiAccessPoint.h b/features/netsocket/WiFiAccessPoint.h index b590c45aa26..e74cf700560 100644 --- a/features/netsocket/WiFiAccessPoint.h +++ b/features/netsocket/WiFiAccessPoint.h @@ -25,8 +25,7 @@ * Class that represents a WiFi Access Point * Common interface that is shared between WiFi devices */ -class WiFiAccessPoint -{ +class WiFiAccessPoint { /** WiFiAccessPoint lifetime */ public: diff --git a/features/netsocket/WiFiInterface.h b/features/netsocket/WiFiInterface.h index 9f248495409..37645921441 100644 --- a/features/netsocket/WiFiInterface.h +++ b/features/netsocket/WiFiInterface.h @@ -27,8 +27,7 @@ * Common interface that is shared between WiFi devices * @addtogroup netsocket */ -class WiFiInterface: public NetworkInterface -{ +class WiFiInterface: public NetworkInterface { public: /** WiFiInterface lifetime */ @@ -43,7 +42,7 @@ class WiFiInterface: public NetworkInterface * @return 0 on success, or error code on failure */ virtual nsapi_error_t set_credentials(const char *ssid, const char *pass, - nsapi_security_t security = NSAPI_SECURITY_NONE) = 0; + nsapi_security_t security = NSAPI_SECURITY_NONE) = 0; /** Set the WiFi network channel * @@ -70,7 +69,7 @@ class WiFiInterface: public NetworkInterface * @return 0 on success, or error code on failure */ virtual nsapi_error_t connect(const char *ssid, const char *pass, - nsapi_security_t security = NSAPI_SECURITY_NONE, uint8_t channel = 0) = 0; + nsapi_security_t security = NSAPI_SECURITY_NONE, uint8_t channel = 0) = 0; /** Start the interface * diff --git a/features/netsocket/cellular/generic_modem_driver/OnboardCellularInterface.cpp b/features/netsocket/cellular/generic_modem_driver/OnboardCellularInterface.cpp index fbd111eff7a..d8c5af726ec 100644 --- a/features/netsocket/cellular/generic_modem_driver/OnboardCellularInterface.cpp +++ b/features/netsocket/cellular/generic_modem_driver/OnboardCellularInterface.cpp @@ -25,9 +25,9 @@ * OnboardCellularInterface is an on-board specific implementation. */ OnboardCellularInterface::OnboardCellularInterface(bool debug) : - UARTCellularInterface(MDMTXD, MDMRXD, MDMDCD, MDMRTS, - MDMCTS, MDMRI, MDMDTR, MDMDSR, - MBED_CONF_PPP_CELL_IFACE_BAUD_RATE, MDM_PIN_POLARITY, debug) + UARTCellularInterface(MDMTXD, MDMRXD, MDMDCD, MDMRTS, + MDMCTS, MDMRI, MDMDTR, MDMDSR, + MBED_CONF_PPP_CELL_IFACE_BAUD_RATE, MDM_PIN_POLARITY, debug) { } diff --git a/features/netsocket/cellular/generic_modem_driver/PPPCellularInterface.cpp b/features/netsocket/cellular/generic_modem_driver/PPPCellularInterface.cpp index 4d22eb2b8b2..70c885f89e5 100644 --- a/features/netsocket/cellular/generic_modem_driver/PPPCellularInterface.cpp +++ b/features/netsocket/cellular/generic_modem_driver/PPPCellularInterface.cpp @@ -91,7 +91,7 @@ static bool get_MEID(ATCmdParser *at) { // Mobile equipment identifier bool success = at->send("AT+GSN") - && at->recv("%18[^\n]\nOK\n", dev_info.meid); + && at->recv("%18[^\n]\nOK\n", dev_info.meid); tr_debug("DevInfo: MEID=%s", dev_info.meid); return success; } @@ -156,10 +156,12 @@ static nsapi_error_t do_sim_pin_check(ATCmdParser *at, const char *pin) success = at->send("AT+CLCK=\"SC\",1,\"%s\"", pin) && at->recv("OK"); } else { /* use the SIM unlocked */ - success = at->send("AT+CLCK=\"SC\",0,\"%s\"",pin) && at->recv("OK"); + success = at->send("AT+CLCK=\"SC\",0,\"%s\"", pin) && at->recv("OK"); } - if (success) return NSAPI_ERROR_OK; + if (success) { + return NSAPI_ERROR_OK; + } return NSAPI_ERROR_AUTH_FAILURE; } @@ -170,12 +172,12 @@ static nsapi_error_t do_sim_pin_check(ATCmdParser *at, const char *pin) static nsapi_error_t do_change_sim_pin(ATCmdParser *at, const char *old_pin, const char *new_pin) { /* changes the SIM pin */ - bool success = at->send("AT+CPWD=\"SC\",\"%s\",\"%s\"", old_pin, new_pin) && at->recv("OK"); - if (success) { - return NSAPI_ERROR_OK; - } + bool success = at->send("AT+CPWD=\"SC\",\"%s\",\"%s\"", old_pin, new_pin) && at->recv("OK"); + if (success) { + return NSAPI_ERROR_OK; + } - return NSAPI_ERROR_AUTH_FAILURE; + return NSAPI_ERROR_AUTH_FAILURE; } static void set_nwk_reg_status_csd(unsigned int status) @@ -240,15 +242,15 @@ static void set_nwk_reg_status_psd(unsigned int status) static bool is_registered_csd() { - return (dev_info.reg_status_csd == CSD_REGISTERED) || - (dev_info.reg_status_csd == CSD_REGISTERED_ROAMING) || - (dev_info.reg_status_csd == CSD_CSFB_NOT_PREFERRED); + return (dev_info.reg_status_csd == CSD_REGISTERED) || + (dev_info.reg_status_csd == CSD_REGISTERED_ROAMING) || + (dev_info.reg_status_csd == CSD_CSFB_NOT_PREFERRED); } static bool is_registered_psd() { return (dev_info.reg_status_psd == PSD_REGISTERED) || - (dev_info.reg_status_psd == PSD_REGISTERED_ROAMING); + (dev_info.reg_status_psd == PSD_REGISTERED_ROAMING); } PPPCellularInterface::PPPCellularInterface(FileHandle *fh, bool debug) @@ -335,70 +337,70 @@ void PPPCellularInterface::set_new_sim_pin(const char *new_pin) bool PPPCellularInterface::nwk_registration(uint8_t nwk_type) { bool success = false; - bool registered = false; - - char str[35]; - int retcode; - int retry_counter = 0; - unsigned int reg_status; - - success = nwk_type == PACKET_SWITCHED ? - _at->send("AT+CGREG=0") : - _at->send("AT+CREG=0") && _at->recv("OK\n"); - - success = _at->send("AT+COPS=0") //initiate auto-registration - && _at->recv("OK"); - if (!success) { - tr_error("Modem not responding."); - return false; - } - - //Network search - //If not registered after 60 attempts, i.e., 30 seconds wait, give up - tr_debug("Searching Network ..."); - - while (!registered) { - - if (retry_counter > 60) { - success = false; - goto give_up; - } - - success = nwk_type == PACKET_SWITCHED ? - _at->send("AT+CGREG?") - && _at->recv("+CGREG: %34[^\n]\n", str) - && _at->recv("OK\n") : - _at->send("AT+CREG?") - && _at->recv("+CREG: %34[^\n]\n", str) - && _at->recv("OK\n"); - - retcode = sscanf(str, "%*u,%u", ®_status); - - if (retcode >= 1) { - if (nwk_type == PACKET_SWITCHED) { - set_nwk_reg_status_psd(reg_status); - if (is_registered_psd()) { - registered = true; - } - } else if (nwk_type == CIRCUIT_SWITCHED) { - set_nwk_reg_status_csd(reg_status); - if (is_registered_csd()) { - registered = true; - } - } - } - - if (registered) { - break; - } else { - wait_ms(500); - } - - retry_counter++; - } - - give_up: - return registered; + bool registered = false; + + char str[35]; + int retcode; + int retry_counter = 0; + unsigned int reg_status; + + success = nwk_type == PACKET_SWITCHED ? + _at->send("AT+CGREG=0") : + _at->send("AT+CREG=0") && _at->recv("OK\n"); + + success = _at->send("AT+COPS=0") //initiate auto-registration + && _at->recv("OK"); + if (!success) { + tr_error("Modem not responding."); + return false; + } + + //Network search + //If not registered after 60 attempts, i.e., 30 seconds wait, give up + tr_debug("Searching Network ..."); + + while (!registered) { + + if (retry_counter > 60) { + success = false; + goto give_up; + } + + success = nwk_type == PACKET_SWITCHED ? + _at->send("AT+CGREG?") + && _at->recv("+CGREG: %34[^\n]\n", str) + && _at->recv("OK\n") : + _at->send("AT+CREG?") + && _at->recv("+CREG: %34[^\n]\n", str) + && _at->recv("OK\n"); + + retcode = sscanf(str, "%*u,%u", ®_status); + + if (retcode >= 1) { + if (nwk_type == PACKET_SWITCHED) { + set_nwk_reg_status_psd(reg_status); + if (is_registered_psd()) { + registered = true; + } + } else if (nwk_type == CIRCUIT_SWITCHED) { + set_nwk_reg_status_csd(reg_status); + if (is_registered_csd()) { + registered = true; + } + } + } + + if (registered) { + break; + } else { + wait_ms(500); + } + + retry_counter++; + } + +give_up: + return registered; } bool PPPCellularInterface::is_connected() @@ -444,7 +446,8 @@ nsapi_error_t PPPCellularInterface::initialize_sim_card() return nsapi_error; } -void PPPCellularInterface::set_sim_pin(const char *pin) { +void PPPCellularInterface::set_sim_pin(const char *pin) +{ /* overwrite the default pin by user provided pin */ _pin = pin; } @@ -473,11 +476,11 @@ nsapi_error_t PPPCellularInterface::setup_context_and_credentials() retry_without_dual_stack: #endif success = _at->send("AT" - "+FCLASS=0;" // set to connection (ATD) to data mode - "+CGDCONT=" CTX ",\"%s\",\"%s%s\"", - pdp_type, auth, _apn - ) - && _at->recv("OK"); + "+FCLASS=0;" // set to connection (ATD) to data mode + "+CGDCONT=" CTX ",\"%s\",\"%s%s\"", + pdp_type, auth, _apn + ) + && _at->recv("OK"); #if NSAPI_PPP_IPV4_AVAILABLE && NSAPI_PPP_IPV6_AVAILABLE if (_stack == IPV4V6_STACK) { @@ -499,7 +502,7 @@ nsapi_error_t PPPCellularInterface::setup_context_and_credentials() } void PPPCellularInterface::set_credentials(const char *apn, const char *uname, - const char *pwd) + const char *pwd) { _apn = apn; _uname = uname; @@ -513,7 +516,7 @@ void PPPCellularInterface::setup_at_parser() } _at = new ATCmdParser(_fh, OUTPUT_ENTER_KEY, AT_PARSER_BUFFER_SIZE, AT_PARSER_TIMEOUT, - _debug_trace_on ? true : false); + _debug_trace_on ? true : false); /* Error cases, out of band handling */ _at->oob("ERROR", callback(parser_abort, _at)); @@ -570,12 +573,12 @@ nsapi_error_t PPPCellularInterface::connect() user_specified_apn = true; #endif } - + if (is_connected()) { return NSAPI_ERROR_IS_CONNECTED; } else if (_connect_status == NSAPI_STATUS_CONNECTING) { return NSAPI_ERROR_ALREADY; - } + } _connect_status = NSAPI_STATUS_CONNECTING; if (_connection_status_cb) { @@ -583,7 +586,8 @@ nsapi_error_t PPPCellularInterface::connect() } do { - retry_init: +retry_init: + retcode = NSAPI_ERROR_OK; @@ -608,12 +612,12 @@ nsapi_error_t PPPCellularInterface::connect() } success = nwk_registration(PACKET_SWITCHED) //perform network registration - && get_CCID(_at)//get integrated circuit ID of the SIM - && get_IMSI(_at)//get international mobile subscriber information - && get_IMEI(_at)//get international mobile equipment identifier - && get_MEID(_at)//its same as IMEI - && set_CMGF(_at)//set message format for SMS - && set_CNMI(_at);//set new SMS indication + && get_CCID(_at)//get integrated circuit ID of the SIM + && get_IMSI(_at)//get international mobile subscriber information + && get_IMEI(_at)//get international mobile equipment identifier + && get_MEID(_at)//its same as IMEI + && set_CMGF(_at)//set message format for SMS + && set_CNMI(_at);//set new SMS indication if (!success) { retcode = NSAPI_ERROR_NO_CONNECTION; @@ -677,7 +681,7 @@ nsapi_error_t PPPCellularInterface::connect() } tr_info("The APN being used is %s.\n", _apn); - + /* Attempt to enter data mode */ success = set_atd(_at); //enter into Data mode with the modem if (!success) { @@ -712,7 +716,7 @@ nsapi_error_t PPPCellularInterface::connect() _connect_status = NSAPI_STATUS_GLOBAL_UP; } } while ((_connect_status == NSAPI_STATUS_CONNECTING && _connect_is_blocking) && - apn_config && *apn_config); + apn_config && *apn_config); if (retcode != NSAPI_ERROR_OK) { diff --git a/features/netsocket/cellular/generic_modem_driver/PPPCellularInterface.h b/features/netsocket/cellular/generic_modem_driver/PPPCellularInterface.h index 80cee234b37..23d58385e06 100644 --- a/features/netsocket/cellular/generic_modem_driver/PPPCellularInterface.h +++ b/features/netsocket/cellular/generic_modem_driver/PPPCellularInterface.h @@ -30,14 +30,14 @@ class NetworkStack; * UBX-13001820 - AT Commands Example Application Note (Section 4.1.4.5) */ typedef enum { - GSM=0, - COMPACT_GSM=1, - UTRAN=2, - EDGE=3, - HSDPA=4, - HSUPA=5, - HSDPA_HSUPA=6, - LTE=7 + GSM = 0, + COMPACT_GSM = 1, + UTRAN = 2, + EDGE = 3, + HSDPA = 4, + HSUPA = 5, + HSDPA_HSUPA = 6, + LTE = 7 } radio_access_nwk_type; /** @@ -45,7 +45,7 @@ typedef enum { * to connect. */ typedef enum { - CIRCUIT_SWITCHED=0, + CIRCUIT_SWITCHED = 0, PACKET_SWITCHED } nwk_type; @@ -54,15 +54,15 @@ typedef enum { * UBX-13001820 - AT Commands Example Application Note (Section 7.10.3) */ typedef enum { - CSD_NOT_REGISTERED_NOT_SEARCHING=0, - CSD_REGISTERED=1, - CSD_NOT_REGISTERED_SEARCHING=2, - CSD_REGISTRATION_DENIED=3, - CSD_UNKNOWN_COVERAGE=4, - CSD_REGISTERED_ROAMING=5, - CSD_SMS_ONLY=6, - CSD_SMS_ONLY_ROAMING=7, - CSD_CSFB_NOT_PREFERRED=9 + CSD_NOT_REGISTERED_NOT_SEARCHING = 0, + CSD_REGISTERED = 1, + CSD_NOT_REGISTERED_SEARCHING = 2, + CSD_REGISTRATION_DENIED = 3, + CSD_UNKNOWN_COVERAGE = 4, + CSD_REGISTERED_ROAMING = 5, + CSD_SMS_ONLY = 6, + CSD_SMS_ONLY_ROAMING = 7, + CSD_CSFB_NOT_PREFERRED = 9 } nwk_registration_status_csd; /** @@ -70,20 +70,20 @@ typedef enum { * UBX-13001820 - AT Commands Example Application Note (Section 18.27.3) */ typedef enum { - PSD_NOT_REGISTERED_NOT_SEARCHING=0, - PSD_REGISTERED=1, - PSD_NOT_REGISTERED_SEARCHING=2, - PSD_REGISTRATION_DENIED=3, - PSD_UNKNOWN_COVERAGE=4, - PSD_REGISTERED_ROAMING=5, - PSD_EMERGENCY_SERVICES_ONLY=8 + PSD_NOT_REGISTERED_NOT_SEARCHING = 0, + PSD_REGISTERED = 1, + PSD_NOT_REGISTERED_SEARCHING = 2, + PSD_REGISTRATION_DENIED = 3, + PSD_UNKNOWN_COVERAGE = 4, + PSD_REGISTERED_ROAMING = 5, + PSD_EMERGENCY_SERVICES_ONLY = 8 } nwk_registration_status_psd; typedef struct { - char ccid[20+1]; //!< Integrated Circuit Card ID - char imsi[15+1]; //!< International Mobile Station Identity - char imei[15+1]; //!< International Mobile Equipment Identity - char meid[18+1]; //!< Mobile Equipment IDentifier + char ccid[20 + 1]; //!< Integrated Circuit Card ID + char imsi[15 + 1]; //!< International Mobile Station Identity + char imei[15 + 1]; //!< International Mobile Equipment Identity + char meid[18 + 1]; //!< Mobile Equipment IDentifier int flags; radio_access_nwk_type rat; nwk_registration_status_csd reg_status_csd; @@ -121,7 +121,7 @@ class PPPCellularInterface : public CellularBase { * @param pwd optionally, password */ virtual void set_credentials(const char *apn, const char *uname = 0, - const char *pwd = 0); + const char *pwd = 0); /** Set the pin code for SIM card * @@ -274,7 +274,7 @@ class PPPCellularInterface : public CellularBase { nsapi_error_t initialize_sim_card(); nsapi_error_t setup_context_and_credentials(); bool power_up(); - void power_down(); + void power_down(); void ppp_status_cb(nsapi_event_t, intptr_t); protected: @@ -351,7 +351,7 @@ class PPPCellularInterface : public CellularBase { * * @return true if registration is successful */ - bool nwk_registration(uint8_t nwk_type=PACKET_SWITCHED); + bool nwk_registration(uint8_t nwk_type = PACKET_SWITCHED); }; diff --git a/features/netsocket/cellular/generic_modem_driver/TESTS/unit_tests/default/main.cpp b/features/netsocket/cellular/generic_modem_driver/TESTS/unit_tests/default/main.cpp index 037c692963f..c2db87a5433 100644 --- a/features/netsocket/cellular/generic_modem_driver/TESTS/unit_tests/default/main.cpp +++ b/features/netsocket/cellular/generic_modem_driver/TESTS/unit_tests/default/main.cpp @@ -86,10 +86,10 @@ static void unlock(); * Verification tests for a successful porting * These tests must pass: * - * test_udp_echo() - * test_tcp_echo_async - * test_connect_credentials - * test_connect_preset_credentials + * test_udp_echo() + * test_tcp_echo_async + * test_connect_credentials + * test_connect_preset_credentials */ /** @@ -148,7 +148,7 @@ void test_tcp_echo_async() TEST_ASSERT(do_connect(&driver) == 0); TEST_ASSERT( - driver.gethostbyname(MBED_CONF_APP_ECHO_SERVER, &host_address) == 0); + driver.gethostbyname(MBED_CONF_APP_ECHO_SERVER, &host_address) == 0); host_address.set_port(MBED_CONF_APP_ECHO_TCP_PORT); tr_debug("TCP: Server %s address: %s on port %d.", @@ -172,7 +172,7 @@ void test_tcp_echo_async() drop_connection(&driver); tr_debug("TCP packets of size up to %d byte(s) echoed asynchronously and successfully.", - MBED_CONF_APP_TCP_MAX_PACKET_SIZE); + MBED_CONF_APP_TCP_MAX_PACKET_SIZE); } /** @@ -196,7 +196,7 @@ void test_connect_preset_credentials() driver.disconnect(); driver.set_sim_pin(MBED_CONF_APP_DEFAULT_PIN); driver.set_credentials(MBED_CONF_APP_APN, MBED_CONF_APP_USERNAME, - MBED_CONF_APP_PASSWORD); + MBED_CONF_APP_PASSWORD); int num_retries = 0; nsapi_error_t err = NSAPI_ERROR_OK; while (!driver.is_connected()) { @@ -226,10 +226,11 @@ utest::v1::status_t test_setup(const size_t number_of_cases) */ Case cases[] = { Case("UDP echo test", test_udp_echo), #if MBED_CONF_LWIP_TCP_ENABLED - Case("TCP async echo test", test_tcp_echo_async), + Case("TCP async echo test", test_tcp_echo_async), #endif - Case("Connect with credentials", test_connect_credentials), - Case("Connect with preset credentials", test_connect_preset_credentials) }; + Case("Connect with credentials", test_connect_credentials), + Case("Connect with preset credentials", test_connect_preset_credentials) + }; Specification specification(test_setup, cases); @@ -255,7 +256,7 @@ static nsapi_error_t do_connect(OnboardCellularInterface *iface) nsapi_error_t err = NSAPI_ERROR_OK; while (!iface->is_connected()) { err = driver.connect(MBED_CONF_APP_DEFAULT_PIN, MBED_CONF_APP_APN, - MBED_CONF_APP_USERNAME, MBED_CONF_APP_PASSWORD); + MBED_CONF_APP_USERNAME, MBED_CONF_APP_PASSWORD); if (err == NSAPI_ERROR_OK || num_retries > MBED_CONF_APP_MAX_RETRIES) { break; } @@ -284,14 +285,14 @@ static int fix(int size, int limit) static void do_udp_echo(UDPSocket *sock, SocketAddress *host_address, int size) { bool success = false; - void * recv_data = malloc(size); + void *recv_data = malloc(size); TEST_ASSERT(recv_data != NULL); // Retry this a few times, don't want to fail due to a flaky link for (int x = 0; !success && (x < NUM_UDP_RETRIES); x++) { tr_debug("Echo testing UDP packet size %d byte(s), try %d.", size, x + 1); - if ((sock->sendto(*host_address, (void*) test_data, size) == size) - && (sock->recvfrom(host_address, recv_data, size) == size)) { + if ((sock->sendto(*host_address, (void *) test_data, size) == size) + && (sock->recvfrom(host_address, recv_data, size) == size)) { TEST_ASSERT(memcmp(test_data, recv_data, size) == 0); success = true; } @@ -340,7 +341,7 @@ static void async_cb(bool *callback_triggered) static void do_tcp_echo_async(TCPSocket *sock, int size, bool *callback_triggered) { - void * recv_data = malloc(size); + void *recv_data = malloc(size); int recv_size = 0; int remaining_size; int x, y; @@ -370,7 +371,7 @@ static void do_tcp_echo_async(TCPSocket *sock, int size, y = memcmp(test_data, recv_data, size); if (y != 0) { tr_debug("Sent %d, |%*.*s|", size, size, size, test_data); - tr_debug("Rcvd %d, |%*.*s|", size, size, size, (char * ) recv_data); + tr_debug("Rcvd %d, |%*.*s|", size, size, size, (char *) recv_data); // We do not assert a failure here because ublox TCP echo server doesn't send // back original data. It actually constructs a ublox message string. They need to fix it as // at the minute in case of TCP, their server is not behaving like a echo TCP server. @@ -386,9 +387,9 @@ static void do_tcp_echo_async(TCPSocket *sock, int size, */ static void use_connection(OnboardCellularInterface *driver) { - const char * ip_address = driver->get_ip_address(); - const char * net_mask = driver->get_netmask(); - const char * gateway = driver->get_gateway(); + const char *ip_address = driver->get_ip_address(); + const char *net_mask = driver->get_netmask(); + const char *gateway = driver->get_gateway(); TEST_ASSERT(driver->is_connected()); diff --git a/features/netsocket/cellular/generic_modem_driver/UARTCellularInterface.cpp b/features/netsocket/cellular/generic_modem_driver/UARTCellularInterface.cpp index e1ee6388767..be692a5eb0b 100644 --- a/features/netsocket/cellular/generic_modem_driver/UARTCellularInterface.cpp +++ b/features/netsocket/cellular/generic_modem_driver/UARTCellularInterface.cpp @@ -17,9 +17,9 @@ #if NSAPI_PPP_AVAILABLE UARTCellularInterface::UARTCellularInterface(PinName txd, PinName rxd, PinName dcd, PinName rts, PinName cts, PinName ri, - PinName dtr, PinName dsr, int baud, bool active_high, bool debug) : - PPPCellularInterface(&_serial, debug), - _serial(txd, rxd, baud) + PinName dtr, PinName dsr, int baud, bool active_high, bool debug) : + PPPCellularInterface(&_serial, debug), + _serial(txd, rxd, baud) { _dcd_pin = dcd; _active_high = active_high; diff --git a/features/netsocket/cellular/generic_modem_driver/UARTCellularInterface.h b/features/netsocket/cellular/generic_modem_driver/UARTCellularInterface.h index e86d5862c69..4e5f8ba8482 100644 --- a/features/netsocket/cellular/generic_modem_driver/UARTCellularInterface.h +++ b/features/netsocket/cellular/generic_modem_driver/UARTCellularInterface.h @@ -34,9 +34,9 @@ class UARTCellularInterface : public PPPCellularInterface { public: UARTCellularInterface(PinName tx, PinName rx, PinName dcd = NC, PinName rts = NC, PinName cts = NC, PinName ri = NC, - PinName dtr = NC, PinName dsr = NC, int baud = MBED_CONF_PPP_CELL_IFACE_BAUD_RATE, - bool active_high = false, - bool debug = false); + PinName dtr = NC, PinName dsr = NC, int baud = MBED_CONF_PPP_CELL_IFACE_BAUD_RATE, + bool active_high = false, + bool debug = false); virtual ~UARTCellularInterface(); diff --git a/features/netsocket/cellular/utils/APN_db.h b/features/netsocket/cellular/utils/APN_db.h index 040cb2bf422..1056192b6af 100644 --- a/features/netsocket/cellular/utils/APN_db.h +++ b/features/netsocket/cellular/utils/APN_db.h @@ -16,17 +16,17 @@ /* ---------------------------------------------------------------- APN stands for Access Point Name, a setting on your modem or phone - that identifies an external network your phone can access for data - (e.g. 3G or 4G Internet service on your phone). - + that identifies an external network your phone can access for data + (e.g. 3G or 4G Internet service on your phone). + The APN settings can be forced when calling the join function. - Below is a list of known APNs that us used if no apn config + Below is a list of known APNs that us used if no apn config is forced. This list could be extended by other settings. - + For further reading: wiki apn: http://en.wikipedia.org/wiki/Access_Point_Name wiki mcc/mnc: http://en.wikipedia.org/wiki/Mobile_country_code - google: https://www.google.de/search?q=APN+list + google: https://www.google.de/search?q=APN+list ---------------------------------------------------------------- */ /** @@ -44,15 +44,15 @@ /** * APN lookup struct */ -typedef struct { - const char* mccmnc; /**< mobile country code (MCC) and mobile network code MNC */ - const char* cfg; /**< APN configuartion string, use _APN macro to generate */ +typedef struct { + const char *mccmnc; /**< mobile country code (MCC) and mobile network code MNC */ + const char *cfg; /**< APN configuartion string, use _APN macro to generate */ } APN_t; /** * Default APN settings used by many networks */ -static const char* apndef = _APN("internet",,); +static const char *apndef = _APN("internet",,); /** * List of special APNs for different network operators. @@ -73,14 +73,17 @@ static const APN_t apnlut[] = { // 460 China - CN { /* CN Mobile */"460-00", _APN("cmnet",,) - _APN("cmwap",,) }, + _APN("cmwap",,) + }, { /* Unicom */ "460-01", _APN("3gnet",,) - _APN("uninet","uninet","uninet") }, - + _APN("uninet", "uninet", "uninet") + }, + // 262 Germany - DE - { /* T-Mobile */ "262-01", _APN("internet.t-mobile","t-mobile","tm") }, - { /* T-Mobile */ "262-02,06", - _APN("m2m.business",,) }, + { /* T-Mobile */ "262-01", _APN("internet.t-mobile", "t-mobile", "tm") }, + { /* T-Mobile */ "262-02,06", + _APN("m2m.business",,) + }, // 222 Italy - IT { /* TIM */ "222-01", _APN("ibox.tim.it",,) }, @@ -89,15 +92,17 @@ static const APN_t apnlut[] = { // 440 Japan - JP { /* Softbank */ "440-04,06,20,40,41,42,43,44,45,46,47,48,90,91,92,93,94,95" - ",96,97,98" - _APN("open.softbank.ne.jp","opensoftbank","ebMNuX1FIHg9d3DA") - _APN("smile.world","dna1trop","so2t3k3m2a") }, + ",96,97,98" + _APN("open.softbank.ne.jp", "opensoftbank", "ebMNuX1FIHg9d3DA") + _APN("smile.world", "dna1trop", "so2t3k3m2a") + }, { /* NTTDoCoMo */"440-09,10,11,12,13,14,15,16,17,18,19,21,22,23,24,25,26,27," - "28,29,30,31,32,33,34,35,36,37,38,39,58,59,60,61,62,63," - "64,65,66,67,68,69,87,99", - _APN("bmobilewap",,) /*BMobile*/ - _APN("mpr2.bizho.net","Mopera U",) /* DoCoMo */ - _APN("bmobile.ne.jp","bmobile@wifi2","bmobile") /*BMobile*/ }, + "28,29,30,31,32,33,34,35,36,37,38,39,58,59,60,61,62,63," + "64,65,66,67,68,69,87,99", + _APN("bmobilewap",,) /*BMobile*/ + _APN("mpr2.bizho.net", "Mopera U",) /* DoCoMo */ + _APN("bmobile.ne.jp", "bmobile@wifi2", "bmobile") /*BMobile*/ + }, // 204 Netherlands - NL { /* Vodafone */ "204-04", _APN("public4.m2minternet.com",,) }, @@ -106,38 +111,44 @@ static const APN_t apnlut[] = { { /* Si.mobil */ "293-40", _APN("internet.simobil.si",,) }, { /* Tusmobil */ "293-70", _APN("internet.tusmobil.si",,) }, -// 240 Sweden SE +// 240 Sweden SE { /* Telia */ "240-01", _APN("online.telia.se",,) }, { /* Telenor */ "240-06,08", - _APN("services.telenor.se",,) }, + _APN("services.telenor.se",,) + }, { /* Tele2 */ "240-07", _APN("mobileinternet.tele2.se",,) }, - + // 228 Switzerland - CH { /* Swisscom */ "228-01", _APN("gprs.swisscom.ch",,) }, { /* Orange */ "228-03", _APN("internet",,) /* contract */ - _APN("click",,) /* pre-pay */ }, + _APN("click",,) /* pre-pay */ + }, // 234 United Kingdom - GB { /* O2 */ "234-02,10,11", - _APN("mobile.o2.co.uk","faster","web") /* contract */ - _APN("mobile.o2.co.uk","bypass","web") /* pre-pay */ - _APN("payandgo.o2.co.uk","payandgo","payandgo") }, - { /* Vodafone */ "234-15", _APN("internet","web","web") /* contract */ - _APN("pp.vodafone.co.uk","wap","wap") /* pre-pay */ }, + _APN("mobile.o2.co.uk", "faster", "web") /* contract */ + _APN("mobile.o2.co.uk", "bypass", "web") /* pre-pay */ + _APN("payandgo.o2.co.uk", "payandgo", "payandgo") + }, + { /* Vodafone */ "234-15", _APN("internet", "web", "web") /* contract */ + _APN("pp.vodafone.co.uk", "wap", "wap") /* pre-pay */ + }, { /* Three */ "234-20", _APN("three.co.uk",,) }, { /* Jersey */ "234-50", _APN("jtm2m",,) /* as used on u-blox C030 U201 boards */ }, // 310 United States of America - US { /* T-Mobile */ "310-026,260,490", - _APN("epc.tmobile.com",,) - _APN("fast.tmobile.com",,) /* LTE */ }, + _APN("epc.tmobile.com",,) + _APN("fast.tmobile.com",,) /* LTE */ + }, { /* AT&T */ "310-030,150,170,260,410,560,680", - _APN("phone",,) - _APN("wap.cingular","WAP@CINGULARGPRS.COM","CINGULAR1") - _APN("isp.cingular","ISP@CINGULARGPRS.COM","CINGULAR1") }, + _APN("phone",,) + _APN("wap.cingular", "WAP@CINGULARGPRS.COM", "CINGULAR1") + _APN("isp.cingular", "ISP@CINGULARGPRS.COM", "CINGULAR1") + }, // 901 International - INT - { /* Transatel */ "901-37", _APN("netgprs.com","tsl","tsl") }, + { /* Transatel */ "901-37", _APN("netgprs.com", "tsl", "tsl") }, }; /** @@ -145,26 +156,27 @@ static const APN_t apnlut[] = { * * @param imsi strinf containing IMSI */ -inline const char* apnconfig(const char* imsi) +inline const char *apnconfig(const char *imsi) { - const char* config = NULL; + const char *config = NULL; if (imsi && *imsi) { // many carriers use internet without username and password, os use this as default // now try to lookup the setting for our table - for (size_t i = 0; i < sizeof(apnlut)/sizeof(*apnlut) && !config; i ++) { - const char* p = apnlut[i].mccmnc; + for (size_t i = 0; i < sizeof(apnlut) / sizeof(*apnlut) && !config; i ++) { + const char *p = apnlut[i].mccmnc; // check the MCC if ((0 == memcmp(imsi, p, 3))) { p += 3; // check all the MNC, MNC length can be 2 or 3 digits - while (((p[0] == '-') || (p[0] == ',')) && - (p[1] >= '0') && (p[1] <= '9') && + while (((p[0] == '-') || (p[0] == ',')) && + (p[1] >= '0') && (p[1] <= '9') && (p[2] >= '0') && (p[2] <= '9') && !config) { int l = ((p[3] >= '0') && (p[3] <= '9')) ? 3 : 2; - if (0 == memcmp(imsi+3,p+1,l)) + if (0 == memcmp(imsi + 3, p + 1, l)) { config = apnlut[i].cfg; + } p += 1 + l; - } + } } } } diff --git a/features/netsocket/emac_stack_mem.h b/features/netsocket/emac_stack_mem.h index d3e0e4dd14f..fe651333813 100644 --- a/features/netsocket/emac_stack_mem.h +++ b/features/netsocket/emac_stack_mem.h @@ -39,7 +39,7 @@ typedef void emac_stack_t; * @param align Memory alignment requirements * @return Allocated memory struct, or NULL in case of error */ -emac_stack_mem_t *emac_stack_mem_alloc(emac_stack_t* stack, uint32_t size, uint32_t align); +emac_stack_mem_t *emac_stack_mem_alloc(emac_stack_t *stack, uint32_t size, uint32_t align); /** * Free memory allocated using @a stack_mem_alloc @@ -47,7 +47,7 @@ emac_stack_mem_t *emac_stack_mem_alloc(emac_stack_t* stack, uint32_t size, uint3 * @param stack Emac stack context * @param mem Memory to be freed */ -void emac_stack_mem_free(emac_stack_t* stack, emac_stack_mem_t *mem); +void emac_stack_mem_free(emac_stack_t *stack, emac_stack_mem_t *mem); /** * Copy memory @@ -56,7 +56,7 @@ void emac_stack_mem_free(emac_stack_t* stack, emac_stack_mem_t *mem); * @param to Memory to copy to * @param from Memory to copy from */ -void emac_stack_mem_copy(emac_stack_t* stack, emac_stack_mem_t *to, emac_stack_mem_t *from); +void emac_stack_mem_copy(emac_stack_t *stack, emac_stack_mem_t *to, emac_stack_mem_t *from); /** * Return pointer to the payload @@ -65,7 +65,7 @@ void emac_stack_mem_copy(emac_stack_t* stack, emac_stack_mem_t *to, emac_stack_m * @param mem Memory structure * @return Pointer to the payload */ -void *emac_stack_mem_ptr(emac_stack_t* stack, emac_stack_mem_t *mem); +void *emac_stack_mem_ptr(emac_stack_t *stack, emac_stack_mem_t *mem); /** * Return actual payload size @@ -74,7 +74,7 @@ void *emac_stack_mem_ptr(emac_stack_t* stack, emac_stack_mem_t *mem); * @param mem Memory structure * @return Size in bytes */ -uint32_t emac_stack_mem_len(emac_stack_t* stack, emac_stack_mem_t *mem); +uint32_t emac_stack_mem_len(emac_stack_t *stack, emac_stack_mem_t *mem); /** * Sets the actual payload size (the allocated payload size will not change) @@ -83,7 +83,7 @@ uint32_t emac_stack_mem_len(emac_stack_t* stack, emac_stack_mem_t *mem); * @param mem Memory structure * @param len Actual payload size */ -void emac_stack_mem_set_len(emac_stack_t* stack, emac_stack_mem_t *mem, uint32_t len); +void emac_stack_mem_set_len(emac_stack_t *stack, emac_stack_mem_t *mem, uint32_t len); /** * Returns first memory structure from the list and move the head to point to the next node @@ -92,7 +92,7 @@ void emac_stack_mem_set_len(emac_stack_t* stack, emac_stack_mem_t *mem, uint32_t * @param chain Pointer to the list * @return First memory structure from the list */ -emac_stack_mem_t *emac_stack_mem_chain_dequeue(emac_stack_t* stack, emac_stack_mem_chain_t **chain); +emac_stack_mem_t *emac_stack_mem_chain_dequeue(emac_stack_t *stack, emac_stack_mem_chain_t **chain); /** * Return total length of the memory chain @@ -101,7 +101,7 @@ emac_stack_mem_t *emac_stack_mem_chain_dequeue(emac_stack_t* stack, emac_stack_m * @param chain Memory chain * @return Chain length */ -uint32_t emac_stack_mem_chain_len(emac_stack_t* stack, emac_stack_mem_chain_t *chain); +uint32_t emac_stack_mem_chain_len(emac_stack_t *stack, emac_stack_mem_chain_t *chain); /** * Increases the reference counter for the memory @@ -109,7 +109,7 @@ uint32_t emac_stack_mem_chain_len(emac_stack_t* stack, emac_stack_mem_chain_t *c * @param stack Emac stack context * @param mem Memory structure */ -void emac_stack_mem_ref(emac_stack_t* stack, emac_stack_mem_t *mem); +void emac_stack_mem_ref(emac_stack_t *stack, emac_stack_mem_t *mem); #endif /* DEVICE_EMAC */ diff --git a/features/netsocket/nsapi_dns.cpp b/features/netsocket/nsapi_dns.cpp index 0c270bb17c8..ccad32047a7 100644 --- a/features/netsocket/nsapi_dns.cpp +++ b/features/netsocket/nsapi_dns.cpp @@ -34,17 +34,25 @@ nsapi_addr_t dns_servers[DNS_SERVERS_SIZE] = { {NSAPI_IPv4, {8, 8, 8, 8}}, // Google {NSAPI_IPv4, {209, 244, 0, 3}}, // Level 3 {NSAPI_IPv4, {84, 200, 69, 80}}, // DNS.WATCH - {NSAPI_IPv6, {0x20,0x01, 0x48,0x60, 0x48,0x60, 0,0, // Google - 0,0, 0,0, 0,0, 0x88,0x88}}, - {NSAPI_IPv6, {0x20,0x01, 0x16,0x08, 0,0x10, 0,0x25, // DNS.WATCH - 0,0, 0,0, 0x1c,0x04, 0xb1,0x2f}}, + { + NSAPI_IPv6, { + 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0, 0, // Google + 0, 0, 0, 0, 0, 0, 0x88, 0x88 + } + }, + { + NSAPI_IPv6, { + 0x20, 0x01, 0x16, 0x08, 0, 0x10, 0, 0x25, // DNS.WATCH + 0, 0, 0, 0, 0x1c, 0x04, 0xb1, 0x2f + } + }, }; // DNS server configuration extern "C" nsapi_error_t nsapi_dns_add_server(nsapi_addr_t addr) { memmove(&dns_servers[1], &dns_servers[0], - (DNS_SERVERS_SIZE-1)*sizeof(nsapi_addr_t)); + (DNS_SERVERS_SIZE - 1)*sizeof(nsapi_addr_t)); dns_servers[0] = addr; return NSAPI_ERROR_OK; @@ -214,7 +222,7 @@ static nsapi_size_or_error_t nsapi_dns_query_multiple(NetworkStack *stack, const socket.set_timeout(DNS_TIMEOUT); // create network packet - uint8_t * const packet = (uint8_t *)malloc(DNS_BUFFER_SIZE); + uint8_t *const packet = (uint8_t *)malloc(DNS_BUFFER_SIZE); if (!packet) { return NSAPI_ERROR_NO_MEMORY; } @@ -298,7 +306,7 @@ extern "C" nsapi_error_t nsapi_dns_query(nsapi_stack_t *stack, const char *host, } nsapi_error_t nsapi_dns_query(NetworkStack *stack, const char *host, - SocketAddress *address, nsapi_version_t version) + SocketAddress *address, nsapi_version_t version) { nsapi_addr_t addr; nsapi_size_or_error_t result = nsapi_dns_query_multiple(stack, host, &addr, 1, version); diff --git a/features/netsocket/nsapi_dns.h b/features/netsocket/nsapi_dns.h index 0575ae35f94..a7c69c230fd 100644 --- a/features/netsocket/nsapi_dns.h +++ b/features/netsocket/nsapi_dns.h @@ -38,7 +38,7 @@ * NSAPI_ERROR_DNS_FAILURE indicates the host could not be found */ nsapi_error_t nsapi_dns_query(nsapi_stack_t *stack, const char *host, - nsapi_addr_t *addr, nsapi_version_t version); + nsapi_addr_t *addr, nsapi_version_t version); /** Query a domain name server for multiple IP address of a given hostname * @@ -74,7 +74,7 @@ nsapi_error_t nsapi_dns_add_server(nsapi_addr_t addr); * NSAPI_ERROR_DNS_FAILURE indicates the host could not be found */ nsapi_error_t nsapi_dns_query(NetworkStack *stack, const char *host, - SocketAddress *addr, nsapi_version_t version = NSAPI_IPv4); + SocketAddress *addr, nsapi_version_t version = NSAPI_IPv4); /** Query a domain name server for an IP address of a given hostname * @@ -99,7 +99,7 @@ extern "C" nsapi_error_t nsapi_dns_query(nsapi_stack_t *stack, const char *host, */ template nsapi_error_t nsapi_dns_query(S *stack, const char *host, - SocketAddress *addr, nsapi_version_t version = NSAPI_IPv4) + SocketAddress *addr, nsapi_version_t version = NSAPI_IPv4) { return nsapi_dns_query(nsapi_create_stack(stack), host, addr, version); } @@ -145,7 +145,7 @@ nsapi_size_or_error_t nsapi_dns_query_multiple(S *stack, const char *host, SocketAddress *addr, nsapi_size_t addr_count, nsapi_version_t version = NSAPI_IPv4) { return nsapi_dns_query_multiple(nsapi_create_stack(stack), - host, addr, addr_count, version); + host, addr, addr_count, version); } /** Add a domain name server to list of servers to query diff --git a/features/netsocket/nsapi_ppp.h b/features/netsocket/nsapi_ppp.h index 4e3a284c4d3..8d47dffe6ae 100644 --- a/features/netsocket/nsapi_ppp.h +++ b/features/netsocket/nsapi_ppp.h @@ -47,7 +47,7 @@ nsapi_error_t nsapi_ppp_set_blocking(bool blocking); * * @return 0 on success, negative error code on failure */ -nsapi_error_t nsapi_ppp_connect(FileHandle *stream, Callback status_cb=0, const char *uname=0, const char *pwd=0, const nsapi_ip_stack_t stack=DEFAULT_STACK); +nsapi_error_t nsapi_ppp_connect(FileHandle *stream, Callback status_cb = 0, const char *uname = 0, const char *pwd = 0, const nsapi_ip_stack_t stack = DEFAULT_STACK); /** Close a PPP connection * diff --git a/features/netsocket/nsapi_types.h b/features/netsocket/nsapi_types.h index b6b789d04c7..c10c75e1458 100644 --- a/features/netsocket/nsapi_types.h +++ b/features/netsocket/nsapi_types.h @@ -63,7 +63,7 @@ enum nsapi_error { * * @enum nsapi_connection_status */ - typedef enum nsapi_connection_status { +typedef enum nsapi_connection_status { NSAPI_STATUS_LOCAL_UP = 0, /*!< local IP address set */ NSAPI_STATUS_GLOBAL_UP = 1, /*!< global IP address set */ NSAPI_STATUS_DISCONNECTED = 2, /*!< no connection to network */ @@ -73,12 +73,12 @@ enum nsapi_error { /** Enum of event types - * + * * Event callbacks are accompanied with an event-dependent parameter passed as an intptr_t. * * @enum nsapi_event */ - typedef enum nsapi_event { +typedef enum nsapi_event { NSAPI_EVENT_CONNECTION_STATUS_CHANGE = 0 /*!< network connection status has changed, the parameter = new status (nsapi_connection_status_t) */ } nsapi_event_t; @@ -191,8 +191,8 @@ typedef void *nsapi_socket_t; * @enum nsapi_protocol */ typedef enum nsapi_protocol { - NSAPI_TCP, /*!< Socket is of TCP type */ - NSAPI_UDP, /*!< Socket is of UDP type */ + NSAPI_TCP, /*!< Socket is of TCP type */ + NSAPI_UDP, /*!< Socket is of UDP type */ } nsapi_protocol_t; /** Enum of standardized stack option levels @@ -310,8 +310,7 @@ typedef struct nsapi_ip_mreq { * * Unsupported operations can be left as null pointers. */ -typedef struct nsapi_stack_api -{ +typedef struct nsapi_stack_api { /** Get the local IP address * * @param stack Stack handle @@ -356,7 +355,7 @@ typedef struct nsapi_stack_api * @return 0 on success, negative error code on failure */ nsapi_error_t (*setstackopt)(nsapi_stack_t *stack, int level, - int optname, const void *optval, unsigned optlen); + int optname, const void *optval, unsigned optlen); /* Get stack-specific stack options * @@ -372,7 +371,7 @@ typedef struct nsapi_stack_api * @return 0 on success, negative error code on failure */ nsapi_error_t (*getstackopt)(nsapi_stack_t *stack, int level, - int optname, void *optval, unsigned *optlen); + int optname, void *optval, unsigned *optlen); /** Opens a socket * @@ -388,7 +387,7 @@ typedef struct nsapi_stack_api * @return 0 on success, negative error code on failure */ nsapi_error_t (*socket_open)(nsapi_stack_t *stack, nsapi_socket_t *socket, - nsapi_protocol_t proto); + nsapi_protocol_t proto); /** Close the socket * @@ -413,7 +412,7 @@ typedef struct nsapi_stack_api * @return 0 on success, negative error code on failure. */ nsapi_error_t (*socket_bind)(nsapi_stack_t *stack, nsapi_socket_t socket, - nsapi_addr_t addr, uint16_t port); + nsapi_addr_t addr, uint16_t port); /** Listen for connections on a TCP socket * @@ -440,7 +439,7 @@ typedef struct nsapi_stack_api * @return 0 on success, negative error code on failure */ nsapi_error_t (*socket_connect)(nsapi_stack_t *stack, nsapi_socket_t socket, - nsapi_addr_t addr, uint16_t port); + nsapi_addr_t addr, uint16_t port); /** Accepts a connection on a TCP socket * @@ -463,7 +462,7 @@ typedef struct nsapi_stack_api * @return 0 on success, negative error code on failure */ nsapi_error_t (*socket_accept)(nsapi_stack_t *stack, nsapi_socket_t server, - nsapi_socket_t *socket, nsapi_addr_t *addr, uint16_t *port); + nsapi_socket_t *socket, nsapi_addr_t *addr, uint16_t *port); /** Send data over a TCP socket * @@ -481,7 +480,7 @@ typedef struct nsapi_stack_api * code on failure */ nsapi_size_or_error_t (*socket_send)(nsapi_stack_t *stack, nsapi_socket_t socket, - const void *data, nsapi_size_t size); + const void *data, nsapi_size_t size); /** Receive data over a TCP socket * @@ -499,7 +498,7 @@ typedef struct nsapi_stack_api * code on failure */ nsapi_size_or_error_t (*socket_recv)(nsapi_stack_t *stack, nsapi_socket_t socket, - void *data, nsapi_size_t size); + void *data, nsapi_size_t size); /** Send a packet over a UDP socket * @@ -519,7 +518,7 @@ typedef struct nsapi_stack_api * code on failure */ nsapi_size_or_error_t (*socket_sendto)(nsapi_stack_t *stack, nsapi_socket_t socket, - nsapi_addr_t addr, uint16_t port, const void *data, nsapi_size_t size); + nsapi_addr_t addr, uint16_t port, const void *data, nsapi_size_t size); /** Receive a packet over a UDP socket * @@ -556,7 +555,7 @@ typedef struct nsapi_stack_api * @param data Argument to pass to callback */ void (*socket_attach)(nsapi_stack_t *stack, nsapi_socket_t socket, - void (*callback)(void *), void *data); + void (*callback)(void *), void *data); /* Set stack-specific socket options * @@ -573,7 +572,7 @@ typedef struct nsapi_stack_api * @return 0 on success, negative error code on failure */ nsapi_error_t (*setsockopt)(nsapi_stack_t *stack, nsapi_socket_t socket, int level, - int optname, const void *optval, unsigned optlen); + int optname, const void *optval, unsigned optlen); /* Get stack-specific socket options * @@ -590,7 +589,7 @@ typedef struct nsapi_stack_api * @return 0 on success, negative error code on failure */ nsapi_error_t (*getsockopt)(nsapi_stack_t *stack, nsapi_socket_t socket, int level, - int optname, void *optval, unsigned *optlen); + int optname, void *optval, unsigned *optlen); } nsapi_stack_api_t; diff --git a/features/nvstore/TESTS/nvstore/functionality/main.cpp b/features/nvstore/TESTS/nvstore/functionality/main.cpp index 32923c359bf..e9d982ecada 100644 --- a/features/nvstore/TESTS/nvstore/functionality/main.cpp +++ b/features/nvstore/TESTS/nvstore/functionality/main.cpp @@ -359,7 +359,7 @@ static void thread_test_check_key(uint16_t key) if (key == thr_test_data->last_key) { if ((thr_test_data->sizes[key][thr_test_data->last_ind] == actual_len_bytes) && - (!memcmp(thr_test_data->buffs[key][thr_test_data->last_ind], get_buff, actual_len_bytes))) { + (!memcmp(thr_test_data->buffs[key][thr_test_data->last_ind], get_buff, actual_len_bytes))) { return; } } @@ -428,7 +428,7 @@ static void nvstore_multi_thread_test() } for (i = 0; i < num_threads; i++) { - threads[i] = new rtos::Thread((osPriority_t)((int)osPriorityBelowNormal-num_threads+i), thr_test_stack_size); + threads[i] = new rtos::Thread((osPriority_t)((int)osPriorityBelowNormal - num_threads + i), thr_test_stack_size); threads[i]->start(callback(thread_test_worker)); } @@ -529,7 +529,8 @@ static void nvstore_race_test() -utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) { +utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) +{ greentea_case_failure_abort_handler(source, reason); return STATUS_CONTINUE; } diff --git a/features/nvstore/source/nvstore.cpp b/features/nvstore/source/nvstore.cpp index 13d5f5d1fae..21dc4c4977d 100644 --- a/features/nvstore/source/nvstore.cpp +++ b/features/nvstore/source/nvstore.cpp @@ -39,8 +39,7 @@ static const uint16_t master_record_key = 0xFFE; static const uint16_t no_key = 0xFFF; static const uint16_t last_reserved_key = master_record_key; -typedef struct -{ +typedef struct { uint16_t key_and_flags; uint16_t size; uint32_t crc; @@ -79,10 +78,12 @@ static const uint8_t blank_flash_val = 0xFF; #endif NVStore::nvstore_area_data_t NVStore::initial_area_params[] = {{NVSTORE_AREA_1_ADDRESS, NVSTORE_AREA_1_SIZE}, - {NVSTORE_AREA_2_ADDRESS, NVSTORE_AREA_2_SIZE}}; + {NVSTORE_AREA_2_ADDRESS, NVSTORE_AREA_2_SIZE} +}; #else NVStore::nvstore_area_data_t NVStore::initial_area_params[] = {{0, 0}, - {0, 0}}; + {0, 0} +}; #endif typedef enum { @@ -121,18 +122,18 @@ static uint32_t crc32(uint32_t init_crc, uint32_t data_size, uint8_t *data_buf) crc = init_crc; for (i = 0; i < data_size; i++) { - crc = crc ^ (uint32_t) (data_buf[i]); + crc = crc ^ (uint32_t)(data_buf[i]); for (j = 0; j < 8; j++) { - mask = -(crc & 1); - crc = (crc >> 1) ^ (0xEDB88320 & mask); + mask = -(crc & 1); + crc = (crc >> 1) ^ (0xEDB88320 & mask); } } return crc; } NVStore::NVStore() : _init_done(0), _init_attempts(0), _active_area(0), _max_keys(NVSTORE_MAX_KEYS), - _active_area_version(0), _free_space_offset(0), _size(0), _mutex(0), _offset_by_key(0), _flash(0), - _min_prog_size(0), _page_buf(0) + _active_area_version(0), _free_space_offset(0), _size(0), _mutex(0), _offset_by_key(0), _flash(0), + _min_prog_size(0), _page_buf(0) { } @@ -261,7 +262,7 @@ void NVStore::calc_validate_area_params() _flash_area_params[area].size = 0; int i; for (i = num_sectors - 1; i >= 0; i--) { - sector_size = sector_map[i+1] - sector_map[i]; + sector_size = sector_map[i + 1] - sector_map[i]; _flash_area_params[area].size += sector_size; if (_flash_area_params[area].size >= min_area_size) { _flash_area_params[area].address = sector_map[i]; @@ -524,7 +525,7 @@ int NVStore::garbage_collection(uint16_t key, uint16_t flags, uint16_t buf_size, return ret; } _offset_by_key[key] = new_area_offset | (1 - _active_area) << offs_by_key_area_bit_pos | - (((flags & set_once_flag) != 0) << offs_by_key_set_once_bit_pos); + (((flags & set_once_flag) != 0) << offs_by_key_set_once_bit_pos); new_area_offset = next_offset; } diff --git a/features/nvstore/source/nvstore.h b/features/nvstore/source/nvstore.h index 42725794024..a3ef3680f6b 100644 --- a/features/nvstore/source/nvstore.h +++ b/features/nvstore/source/nvstore.h @@ -61,7 +61,7 @@ class NVStore : private mbed::NonCopyable { * * @returns Singleton instance reference. */ - static NVStore& get_instance() + static NVStore &get_instance() { // Use this implementation of singleton (Meyer's) rather than the one that allocates // the instance on the heap because it ensures destruction at program end (preventing warnings diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/add_del/add_del.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/add_del/add_del.cpp index 91035333242..e7e2b0e2af6 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/add_del/add_del.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/add_del/add_del.cpp @@ -60,8 +60,8 @@ UVISOR_SET_MODE_ACL(UVISOR_ENABLED, cfstore_acl_uvisor_box_add_del_g); #endif /* YOTTA_CFG_CFSTORE_UVISOR */ static cfstore_kv_data_t cfstore_add_del_test_07_data[] = { - CFSTORE_INIT_1_TABLE_MID_NODE, - { NULL, NULL}, + CFSTORE_INIT_1_TABLE_MID_NODE, + { NULL, NULL}, }; @@ -91,7 +91,7 @@ control_t cfstore_add_del_test_01_end(const size_t call_count) bool bfound = false; int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE len = 0; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_KEYDESC kdesc; ARM_CFSTORE_HANDLE_INIT(hkey); ARM_CFSTORE_FMODE flags; @@ -104,7 +104,7 @@ control_t cfstore_add_del_test_01_end(const size_t call_count) kdesc.drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE; len = strlen(cfstore_add_del_test_07_data[0].value); - ret = cfstore_test_create(cfstore_add_del_test_07_data[0].key_name, (char*) cfstore_add_del_test_07_data[0].value, &len, &kdesc); + ret = cfstore_test_create(cfstore_add_del_test_07_data[0].key_name, (char *) cfstore_add_del_test_07_data[0].value, &len, &kdesc); CFSTORE_TEST_UTEST_MESSAGE(cfstore_add_del_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to create KV in store (ret=%d).\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_add_del_utest_msg_g); @@ -113,7 +113,7 @@ control_t cfstore_add_del_test_01_end(const size_t call_count) CFSTORE_TEST_UTEST_MESSAGE(cfstore_add_del_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to Open() (ret=%d).\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_add_del_utest_msg_g); - if(hkey != NULL){ + if (hkey != NULL) { ret = drv->Delete(hkey); drv->Close(hkey); hkey = NULL; @@ -136,10 +136,10 @@ control_t cfstore_add_del_test_01_end(const size_t call_count) static cfstore_kv_data_t cfstore_add_del_test_08_data[] = { - CFSTORE_INIT_1_TABLE_HEAD, - CFSTORE_INIT_1_TABLE_MID_NODE, - CFSTORE_INIT_1_TABLE_TAIL, - { NULL, NULL}, + CFSTORE_INIT_1_TABLE_HEAD, + CFSTORE_INIT_1_TABLE_MID_NODE, + CFSTORE_INIT_1_TABLE_TAIL, + { NULL, NULL}, }; @@ -159,8 +159,8 @@ control_t cfstore_add_del_test_02_end(const size_t call_count) int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE len = 0; ARM_CFSTORE_KEYDESC kdesc; - cfstore_kv_data_t* node = NULL; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + cfstore_kv_data_t *node = NULL; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; CFSTORE_FENTRYLOG("%s:entered\n", __func__); (void) call_count; @@ -169,10 +169,9 @@ control_t cfstore_add_del_test_02_end(const size_t call_count) /* create */ kdesc.drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE; node = cfstore_add_del_test_08_data; - while(node->key_name != NULL) - { + while (node->key_name != NULL) { len = strlen(node->value); - ret = cfstore_test_create(node->key_name, (char*) node->value, &len, &kdesc); + ret = cfstore_test_create(node->key_name, (char *) node->value, &len, &kdesc); CFSTORE_TEST_UTEST_MESSAGE(cfstore_add_del_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to create kv (key_name=%s.\n", __func__, node->key_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_add_del_utest_msg_g); /* revert CFSTORE_LOG for more trace */ @@ -187,8 +186,7 @@ control_t cfstore_add_del_test_02_end(const size_t call_count) /* check there are no KVs present as expected */ node = cfstore_add_del_test_08_data; - while(node->key_name != NULL) - { + while (node->key_name != NULL) { ret = cfstore_test_kv_is_found(node->key_name, &bResult); CFSTORE_TEST_UTEST_MESSAGE(cfstore_add_del_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: found key when should not be present.\n", __func__); TEST_ASSERT_MESSAGE(ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND && bResult == false, cfstore_add_del_utest_msg_g); @@ -215,7 +213,7 @@ control_t cfstore_add_del_test_03_end(const size_t call_count) int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_FMODE flags; cfstore_kv_data_t *node; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; CFSTORE_FENTRYLOG("%s:entered\n", __func__); (void) call_count; @@ -227,8 +225,7 @@ control_t cfstore_add_del_test_03_end(const size_t call_count) /* delete some keys */ node = cfstore_add_del_test_08_data; - while(node->key_name != NULL) - { + while (node->key_name != NULL) { CFSTORE_DBGLOG("%s:about to delete key (key_name=%s).\n", __func__, node->key_name); cfstore_test_delete(node->key_name); CFSTORE_TEST_UTEST_MESSAGE(cfstore_add_del_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error failed to delete a key (ret=%d).\n", __func__, (int) ret); @@ -239,8 +236,7 @@ control_t cfstore_add_del_test_03_end(const size_t call_count) } /* check the keys have been deleted */ node = cfstore_add_del_test_08_data; - while(node->key_name != NULL) - { + while (node->key_name != NULL) { ret = cfstore_test_kv_is_found(node->key_name, &bfound); CFSTORE_TEST_UTEST_MESSAGE(cfstore_add_del_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to delete a key (ret=%d).\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND, cfstore_add_del_utest_msg_g); @@ -381,18 +377,18 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("ADD_DEL_test_00", cfstore_add_del_test_00), - Case("ADD_DEL_test_01_start", cfstore_utest_default_start), - Case("ADD_DEL_test_01_end", cfstore_add_del_test_01_end), - Case("ADD_DEL_test_02_start", cfstore_utest_default_start), - Case("ADD_DEL_test_02_end", cfstore_add_del_test_02_end), - Case("ADD_DEL_test_03_start", cfstore_utest_default_start), - Case("ADD_DEL_test_03_end", cfstore_add_del_test_03_end), - Case("ADD_DEL_test_04", cfstore_add_del_test_04), - Case("ADD_DEL_test_05_start", cfstore_utest_default_start), - Case("ADD_DEL_test_05_end", cfstore_add_del_test_05_end), + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("ADD_DEL_test_00", cfstore_add_del_test_00), + Case("ADD_DEL_test_01_start", cfstore_utest_default_start), + Case("ADD_DEL_test_01_end", cfstore_add_del_test_01_end), + Case("ADD_DEL_test_02_start", cfstore_utest_default_start), + Case("ADD_DEL_test_02_end", cfstore_add_del_test_02_end), + Case("ADD_DEL_test_03_start", cfstore_utest_default_start), + Case("ADD_DEL_test_03_end", cfstore_add_del_test_03_end), + Case("ADD_DEL_test_04", cfstore_add_del_test_04), + Case("ADD_DEL_test_05_start", cfstore_utest_default_start), + Case("ADD_DEL_test_05_end", cfstore_add_del_test_05_end), }; diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/close/close.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/close/close.cpp index 5d64b3e3a55..df59a095205 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/close/close.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/close/close.cpp @@ -52,9 +52,9 @@ UVISOR_BOX_CONFIG(cfstore_close_box1, UVISOR_BOX_STACK_SIZE); /* KV data for test_01 */ static cfstore_kv_data_t cfstore_close_test_01_kv_data[] = { - { "yotta.hello-world.animal{wobbly-dog}{foot}frontLeft", "first_data_"}, - { "yotta.hello-world.animal{wobbly-dog}{foot}frontLeft", "second_data"}, - { NULL, NULL}, + { "yotta.hello-world.animal{wobbly-dog}{foot}frontLeft", "first_data_"}, + { "yotta.hello-world.animal{wobbly-dog}{foot}frontLeft", "second_data"}, + { NULL, NULL}, }; @@ -95,7 +95,7 @@ control_t cfstore_close_test_01_end(const size_t call_count) char read_buf[CFSTORE_KEY_NAME_MAX_LENGTH]; int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE len = 0; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_KEYDESC kdesc; ARM_CFSTORE_HANDLE_INIT(hkey1); ARM_CFSTORE_HANDLE_INIT(hkey2); @@ -119,7 +119,7 @@ control_t cfstore_close_test_01_end(const size_t call_count) /* step 02 */ len = strlen(node->value); - ret = drv->Write(hkey1, (char*) node->value, &len); + ret = drv->Write(hkey1, (char *) node->value, &len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_close_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to write key (key_name=\"%s\", value=\"%s\")(ret=%d)\n", __func__, node->key_name, node->value, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_close_utest_msg_g); @@ -150,7 +150,7 @@ control_t cfstore_close_test_01_end(const size_t call_count) /* step 05 write new data using hkey2 */ node = &cfstore_close_test_01_kv_data[1]; len = strlen(node->value); - ret = drv->Write(hkey2, (char*) node->value, &len); + ret = drv->Write(hkey2, (char *) node->value, &len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_close_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to write key with 2nd handle (key_name=\"%s\", value=\"%s\")(ret=%d)\n", __func__, node->key_name, node->value, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_close_utest_msg_g); @@ -206,7 +206,7 @@ control_t cfstore_close_test_01_end(const size_t call_count) CFSTORE_DBGLOG("%s:length of KV=%d (key_name=\"%s\", value=\"%s\")\n", __func__, (int) len, node->key_name, node->value); len = strlen(node->value); - ret = drv->Write(hkey1, (char*) node->value, &len); + ret = drv->Write(hkey1, (char *) node->value, &len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_close_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to write key (key_name=\"%s\", value=\"%s\")(ret=%d)\n", __func__, node->key_name, node->value, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_close_utest_msg_g); @@ -231,11 +231,11 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("CLOSE_test_00", cfstore_close_test_00), - Case("CLOSE_test_01_start", cfstore_utest_default_start), - Case("CLOSE_test_01_end", cfstore_close_test_01_end) + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("CLOSE_test_00", cfstore_close_test_00), + Case("CLOSE_test_01_start", cfstore_utest_default_start), + Case("CLOSE_test_01_end", cfstore_close_test_01_end) }; diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/create/create.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/create/create.cpp index 981f6c85904..bc54e2f23c8 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/create/create.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/create/create.cpp @@ -76,68 +76,68 @@ UVISOR_BOX_CONFIG(cfstore_create_box1, UVISOR_BOX_STACK_SIZE); #define CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_04 { "There.is.in.the.worst.of.fortune.the.best.of.chances.for.a.happy.change", "Iphigenia.in.Tauris"} static cfstore_kv_data_t cfstore_create_test_01_data[] = { - CFSTORE_CREATE_TEST_01_TABLE_MID_ENTRY_01, - CFSTORE_CREATE_TEST_01_TABLE_MID_ENTRY_02, - CFSTORE_CREATE_TEST_01_TABLE_MID_ENTRY_03, - { NULL, NULL}, + CFSTORE_CREATE_TEST_01_TABLE_MID_ENTRY_01, + CFSTORE_CREATE_TEST_01_TABLE_MID_ENTRY_02, + CFSTORE_CREATE_TEST_01_TABLE_MID_ENTRY_03, + { NULL, NULL}, }; /* table 1: to initialise cfstore with CFSTORE_CREATE_TEST_01_TABLE_MID_ENTRY_01 */ static cfstore_kv_data_t cfstore_create_test_01_data_step_01[] = { - CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_01, - CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_02, - CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_03, - CFSTORE_CREATE_TEST_01_TABLE_MID_ENTRY_01, - CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_01, - CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_02, - CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_03, - CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_04, - { NULL, NULL}, + CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_01, + CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_02, + CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_03, + CFSTORE_CREATE_TEST_01_TABLE_MID_ENTRY_01, + CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_01, + CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_02, + CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_03, + CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_04, + { NULL, NULL}, }; /* table 2: to CFSTORE_CREATE_TEST_01_TABLE_MID_ENTRY_01 grown to CFSTORE_CREATE_TEST_01_TABLE_MID_ENTRY_02 */ static cfstore_kv_data_t cfstore_create_test_01_data_step_02[] = { - CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_01, - CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_02, - CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_03, - CFSTORE_CREATE_TEST_01_TABLE_MID_ENTRY_02, - CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_01, - CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_02, - CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_03, - CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_04, - { NULL, NULL}, + CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_01, + CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_02, + CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_03, + CFSTORE_CREATE_TEST_01_TABLE_MID_ENTRY_02, + CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_01, + CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_02, + CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_03, + CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_04, + { NULL, NULL}, }; /* table 3: to CFSTORE_CREATE_TEST_01_TABLE_MID_ENTRY_02 shrunk to CFSTORE_CREATE_TEST_01_TABLE_MID_ENTRY_03 */ static cfstore_kv_data_t cfstore_create_test_01_data_step_03[] = { - CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_01, - CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_02, - CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_03, - CFSTORE_CREATE_TEST_01_TABLE_MID_ENTRY_03, - CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_01, - CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_02, - CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_03, - CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_04, - { NULL, NULL}, + CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_01, + CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_02, + CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_03, + CFSTORE_CREATE_TEST_01_TABLE_MID_ENTRY_03, + CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_01, + CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_02, + CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_03, + CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_04, + { NULL, NULL}, }; /* table 3: CFSTORE_CREATE_TEST_01_TABLE_MID_ENTRY_03 deleted */ static cfstore_kv_data_t cfstore_create_test_01_data_step_04[] = { - CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_01, - CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_02, - CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_03, - CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_01, - CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_02, - CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_03, - CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_04, - { NULL, NULL}, + CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_01, + CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_02, + CFSTORE_CREATE_TEST_01_TABLE_HEAD_ENTRY_03, + CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_01, + CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_02, + CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_03, + CFSTORE_CREATE_TEST_01_TABLE_TAIL_ENTRY_04, + { NULL, NULL}, }; /// @endcond /* support functions */ /* @brief support function for generating value blob data */ -static int32_t cfstore_create_kv_value_gen(char* value, const size_t len) +static int32_t cfstore_create_kv_value_gen(char *value, const size_t len) { size_t i = 0; size_t cpy_size = 0; @@ -146,8 +146,7 @@ static int32_t cfstore_create_kv_value_gen(char* value, const size_t len) CFSTORE_TEST_UTEST_MESSAGE(cfstore_create_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: value pointer is null.\n", __func__); TEST_ASSERT_MESSAGE(value != NULL, cfstore_create_utest_msg_g); - while(i < len) - { + while (i < len) { cpy_size = len - i > CFSTORE_TEST_BYTE_DATA_TABLE_SIZE ? CFSTORE_TEST_BYTE_DATA_TABLE_SIZE : len - i; memcpy(value + i, cfstore_test_byte_data_table, cpy_size); i += cpy_size; @@ -156,7 +155,7 @@ static int32_t cfstore_create_kv_value_gen(char* value, const size_t len) } -static char* CFSTORE_CREATE_KV_CREATE_NO_TAG = NULL; +static char *CFSTORE_CREATE_KV_CREATE_NO_TAG = NULL; /** @brief * @@ -170,31 +169,31 @@ static char* CFSTORE_CREATE_KV_CREATE_NO_TAG = NULL; * @param value_len the length of the value to generate * */ -static int32_t cfstore_create_kv_create(size_t name_len, char* name_tag, char* value_buf, size_t value_len) +static int32_t cfstore_create_kv_create(size_t name_len, char *name_tag, char *value_buf, size_t value_len) { int32_t ret = ARM_DRIVER_OK; size_t name_len_ex = name_len; - char kv_name[CFSTORE_KEY_NAME_MAX_LENGTH+1]; /* extra char for terminating null */ + char kv_name[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; /* extra char for terminating null */ ARM_CFSTORE_KEYDESC kdesc; CFSTORE_FENTRYLOG("%s:entered\n", __func__); - memset(kv_name, 0, CFSTORE_KEY_NAME_MAX_LENGTH+1); + memset(kv_name, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); memset(&kdesc, 0, sizeof(kdesc)); kdesc.drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE; name_len_ex = name_len; - if(name_tag){ + if (name_tag) { name_len_ex += strlen(name_tag); } CFSTORE_TEST_UTEST_MESSAGE(cfstore_create_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: max supported KV name length for testing exceeded.\n", __func__); - TEST_ASSERT_MESSAGE(name_len_ex < CFSTORE_KEY_NAME_MAX_LENGTH+1, cfstore_create_utest_msg_g); + TEST_ASSERT_MESSAGE(name_len_ex < CFSTORE_KEY_NAME_MAX_LENGTH + 1, cfstore_create_utest_msg_g); ret = cfstore_test_kv_name_gen(kv_name, name_len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_create_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: unable to generate kv_name.\n", __func__); - TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK , cfstore_create_utest_msg_g); + TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_create_utest_msg_g); /* append name tag */ - if(name_tag){ + if (name_tag) { strncat(kv_name, name_tag, CFSTORE_KEY_NAME_MAX_LENGTH); } @@ -203,11 +202,11 @@ static int32_t cfstore_create_kv_create(size_t name_len, char* name_tag, char* v ret = cfstore_create_kv_value_gen(value_buf, value_len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_create_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: unable to generate kv_name.\n", __func__); - TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK , cfstore_create_utest_msg_g); + TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_create_utest_msg_g); ret = cfstore_test_create(kv_name, value_buf, &value_len, &kdesc); - if(ret == ARM_CFSTORE_DRIVER_ERROR_OUT_OF_MEMORY){ + if (ret == ARM_CFSTORE_DRIVER_ERROR_OUT_OF_MEMORY) { CFSTORE_ERRLOG("%s: Error: out of memory\n", __func__); return ret; } @@ -220,11 +219,11 @@ static int32_t cfstore_create_kv_create(size_t name_len, char* name_tag, char* v /* @brief cfstore_create_test_01() support function change the size of a value blob in the cfstore */ -static int32_t cfstore_create_test_KV_change(const cfstore_kv_data_t* old_node, const cfstore_kv_data_t* new_node ) +static int32_t cfstore_create_test_KV_change(const cfstore_kv_data_t *old_node, const cfstore_kv_data_t *new_node) { int32_t ret = ARM_DRIVER_ERROR; size_t len = 0; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_HANDLE_INIT(hkey); ARM_CFSTORE_FMODE flags; ARM_CFSTORE_KEYDESC kdesc; @@ -234,24 +233,24 @@ static int32_t cfstore_create_test_KV_change(const cfstore_kv_data_t* old_node, memset(&kdesc, 0, sizeof(kdesc)); /* check node key_names are identical */ - if(strncmp(old_node->key_name, new_node->key_name, strlen(old_node->key_name)) != 0){ + if (strncmp(old_node->key_name, new_node->key_name, strlen(old_node->key_name)) != 0) { CFSTORE_ERRLOG("%s:old and new entries so not have the same key_name (old_key_name=%s, new_key_name=%s).\n", __func__, old_node->key_name, new_node->key_name); return ret; } len = strlen(new_node->value); /* supply NULL key descriptor to open a pre-existing key for increasing the blob size */ ret = drv->Create(new_node->key_name, len, NULL, hkey); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to change size of KV (key_name=%s)(ret=%d).\n", __func__, new_node->key_name, (int) ret); goto out1; } len = strlen(new_node->value); ret = drv->Write(hkey, new_node->value, &len); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to write KV (key_name=%s)(ret=%d).\n", __func__, new_node->key_name, (int) ret); goto out2; } - if(len != strlen(new_node->value)){ + if (len != strlen(new_node->value)) { CFSTORE_DBGLOG("%s:Failed wrote (%d) rather than the correct number of bytes (%d).\n", __func__, (int) len, (int) strlen(cfstore_create_test_01_data[1].value)); goto out2; } @@ -291,8 +290,8 @@ control_t cfstore_create_test_01_end(const size_t call_count) { int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_FMODE flags; - cfstore_kv_data_t* node = NULL; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + cfstore_kv_data_t *node = NULL; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; CFSTORE_FENTRYLOG("%s:entered\n", __func__); (void) call_count; @@ -309,8 +308,7 @@ control_t cfstore_create_test_01_end(const size_t call_count) /* Now check that the KVs are all present and correct */ node = cfstore_create_test_01_data_step_02; - while(node->key_name != NULL) - { + while (node->key_name != NULL) { ret = cfstore_test_check_node_correct(node); CFSTORE_TEST_UTEST_MESSAGE(cfstore_create_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:node (key_name=\"%s\", value=\"%s\") not correct in cfstore\n", __func__, node->key_name, node->value); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_create_utest_msg_g); @@ -325,8 +323,7 @@ control_t cfstore_create_test_01_end(const size_t call_count) /* Now check that the KVs are all present and correct */ node = cfstore_create_test_01_data_step_03; - while(node->key_name != NULL) - { + while (node->key_name != NULL) { ret = cfstore_test_check_node_correct(node); CFSTORE_TEST_UTEST_MESSAGE(cfstore_create_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:node (key_name=\"%s\", value=\"%s\") not correct in cfstore\n", __func__, node->key_name, node->value); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_create_utest_msg_g); @@ -342,8 +339,7 @@ control_t cfstore_create_test_01_end(const size_t call_count) /* Now check that the KVs are all present and correct */ node = cfstore_create_test_01_data_step_04; - while(node->key_name != NULL) - { + while (node->key_name != NULL) { ret = cfstore_test_check_node_correct(node); CFSTORE_TEST_UTEST_MESSAGE(cfstore_create_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:node (key_name=\"%s\", value=\"%s\") not correct in cfstore\n", __func__, node->key_name, node->value); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_create_utest_msg_g); @@ -364,21 +360,20 @@ static int32_t cfstore_create_test_02_core(const size_t call_count) const uint32_t max_num_kvs_create = 10; const size_t kv_name_min_len = CFSTORE_KEY_NAME_MAX_LENGTH - max_num_kvs_create; const size_t kv_value_min_len = CFSTORE_TEST_BYTE_DATA_TABLE_SIZE; - const size_t max_value_buf_size = kv_value_min_len * (max_num_kvs_create +1); + const size_t max_value_buf_size = kv_value_min_len * (max_num_kvs_create + 1); char value_buf[max_value_buf_size]; CFSTORE_FENTRYLOG("%s:entered\n", __func__); (void) call_count; memset(value_buf, 0, max_value_buf_size); - for(i = 0; i < max_num_kvs_create; i++) - { + for (i = 0; i < max_num_kvs_create; i++) { memset(value_buf, 0, max_value_buf_size); - ret = cfstore_create_kv_create(kv_name_min_len +i, CFSTORE_CREATE_KV_CREATE_NO_TAG, value_buf, kv_value_min_len * (i+1)); + ret = cfstore_create_kv_create(kv_name_min_len + i, CFSTORE_CREATE_KV_CREATE_NO_TAG, value_buf, kv_value_min_len * (i + 1)); bytes_stored += kv_name_min_len + i; /* kv_name */ - bytes_stored += kv_value_min_len * (i+1); /* kv value blob */ + bytes_stored += kv_value_min_len * (i + 1); /* kv value blob */ bytes_stored += 8; /* kv overhead */ - if(ret == ARM_CFSTORE_DRIVER_ERROR_OUT_OF_MEMORY){ + if (ret == ARM_CFSTORE_DRIVER_ERROR_OUT_OF_MEMORY) { CFSTORE_ERRLOG("Out of memory on %d-th KV, trying to allocate memory totalling %d.\n", (int) i, (int) bytes_stored); break; } @@ -405,7 +400,7 @@ static int32_t cfstore_create_test_02_core(const size_t call_count) control_t cfstore_create_test_02_end(const size_t call_count) { int32_t ret; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; CFSTORE_FENTRYLOG("%s:entered\n", __func__); (void) call_count; @@ -430,11 +425,10 @@ control_t cfstore_create_test_03_end(const size_t call_count) { int32_t i = 0; int32_t ret; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; CFSTORE_FENTRYLOG("%s:entered\n", __func__); - for(i = 0; i < 100; i++) - { + for (i = 0; i < 100; i++) { ret = cfstore_create_test_02_core(call_count); CFSTORE_TEST_UTEST_MESSAGE(cfstore_create_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: something went wrong (ret=%d).\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_create_utest_msg_g); @@ -463,9 +457,9 @@ control_t cfstore_create_test_04_end(const size_t call_count) const uint32_t max_num_kvs_create = 100; const size_t kv_name_min_len = CFSTORE_KEY_NAME_MAX_LENGTH - max_num_kvs_create; const size_t kv_value_min_len = CFSTORE_TEST_BYTE_DATA_TABLE_SIZE; - const size_t max_value_buf_size = kv_value_min_len/8 * (max_num_kvs_create +1); - char* value_buf = NULL; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + const size_t max_value_buf_size = kv_value_min_len / 8 * (max_num_kvs_create + 1); + char *value_buf = NULL; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; CFSTORE_FENTRYLOG("%s:entered\n", __func__); (void) call_count; @@ -475,18 +469,17 @@ control_t cfstore_create_test_04_end(const size_t call_count) CFSTORE_TEST_UTEST_MESSAGE(cfstore_create_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: D.1.1 cfstore_test_dump failed (ret=%d).\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_create_utest_msg_g); - value_buf = (char*) malloc(max_value_buf_size); + value_buf = (char *) malloc(max_value_buf_size); CFSTORE_TEST_UTEST_MESSAGE(cfstore_create_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: out of memory.\n", __func__); TEST_ASSERT_MESSAGE(value_buf != NULL, cfstore_create_utest_msg_g); - for(i = 0; i < max_num_kvs_create; i++) - { + for (i = 0; i < max_num_kvs_create; i++) { memset(value_buf, 0, max_value_buf_size); - ret = cfstore_create_kv_create(kv_name_min_len +i, CFSTORE_CREATE_KV_CREATE_NO_TAG, value_buf, kv_value_min_len/8 * (i+1)); + ret = cfstore_create_kv_create(kv_name_min_len + i, CFSTORE_CREATE_KV_CREATE_NO_TAG, value_buf, kv_value_min_len / 8 * (i + 1)); bytes_stored += kv_name_min_len + i; /* kv_name */ - bytes_stored += kv_value_min_len/8 * (i+1); /* kv value blob */ + bytes_stored += kv_value_min_len / 8 * (i + 1); /* kv value blob */ bytes_stored += 8; /* kv overhead */ - if(ret == ARM_CFSTORE_DRIVER_ERROR_OUT_OF_MEMORY){ + if (ret == ARM_CFSTORE_DRIVER_ERROR_OUT_OF_MEMORY) { CFSTORE_ERRLOG("Out of memory on %d-th KV, trying to allocate memory totalling %d.\n", (int) i, (int) bytes_stored); break; } @@ -516,26 +509,25 @@ int32_t cfstore_create_test_05_core(const size_t call_count) const size_t kv_name_tag_len = 3; const size_t kv_name_min_len = 10; const size_t kv_value_min_len = CFSTORE_TEST_BYTE_DATA_TABLE_SIZE; - const size_t max_value_buf_size = kv_value_min_len/64 * (max_num_kvs_create+1); - char kv_name_tag_buf[kv_name_tag_len+1]; - char* value_buf = NULL; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + const size_t max_value_buf_size = kv_value_min_len / 64 * (max_num_kvs_create + 1); + char kv_name_tag_buf[kv_name_tag_len + 1]; + char *value_buf = NULL; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; CFSTORE_FENTRYLOG("%s:entered\n", __func__); /* Initialize() */ cfstore_utest_default_start(call_count); - value_buf = (char*) malloc(max_value_buf_size); + value_buf = (char *) malloc(max_value_buf_size); CFSTORE_TEST_UTEST_MESSAGE(cfstore_create_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: out of memory.\n", __func__); TEST_ASSERT_MESSAGE(value_buf != NULL, cfstore_create_utest_msg_g); - for(i = 0; i < max_num_kvs_create; i++) - { + for (i = 0; i < max_num_kvs_create; i++) { memset(value_buf, 0, max_value_buf_size); - snprintf(kv_name_tag_buf, kv_name_tag_len+1, "%0d", (int) i); - ret = cfstore_create_kv_create(kv_name_min_len, kv_name_tag_buf, value_buf, kv_value_min_len/64 * (i+1)); - if(ret == ARM_CFSTORE_DRIVER_ERROR_OUT_OF_MEMORY){ + snprintf(kv_name_tag_buf, kv_name_tag_len + 1, "%0d", (int) i); + ret = cfstore_create_kv_create(kv_name_min_len, kv_name_tag_buf, value_buf, kv_value_min_len / 64 * (i + 1)); + if (ret == ARM_CFSTORE_DRIVER_ERROR_OUT_OF_MEMORY) { CFSTORE_ERRLOG("Out of memory on %d-th KV.\n", (int) i); break; } @@ -577,14 +569,14 @@ control_t cfstore_create_test_05(const size_t call_count) mbed_stats_heap_get(&stats_before); CFSTORE_FENTRYLOG("%s:entered\n", __func__); - for(i = 0; i < max_loops; i++) { + for (i = 0; i < max_loops; i++) { ret = cfstore_create_test_05_core(call_count); CFSTORE_TEST_UTEST_MESSAGE(cfstore_create_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: cfstore_create_test_05_core() failed (ret = %d.\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_create_utest_msg_g); mbed_stats_heap_get(&stats_after); - if(i > 1) { - CFSTORE_TEST_UTEST_MESSAGE(cfstore_create_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: memory leak: stored %d bytes on loop %d, but %d bytes on loop %d .\n", __func__, (int) stats_after.current_size, (int) i, (int) stats_before.current_size, (int) i-1); + if (i > 1) { + CFSTORE_TEST_UTEST_MESSAGE(cfstore_create_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: memory leak: stored %d bytes on loop %d, but %d bytes on loop %d .\n", __func__, (int) stats_after.current_size, (int) i, (int) stats_before.current_size, (int) i - 1); TEST_ASSERT_MESSAGE(stats_after.current_size == stats_before.current_size, cfstore_create_utest_msg_g); TEST_ASSERT(stats_after.alloc_fail_cnt > stats_before.alloc_fail_cnt); } @@ -597,26 +589,26 @@ control_t cfstore_create_test_05(const size_t call_count) /// @cond CFSTORE_DOXYGEN_DISABLE /* structure to encode test data */ typedef struct cfstore_create_key_name_validate_t { - const char* key_name; + const char *key_name; uint32_t f_allowed : 1; } cfstore_create_key_name_validate_t; /* data table encoding test data */ cfstore_create_key_name_validate_t cfstore_create_test_06_data[] = { - /* ruler for measuring text strings */ - /* 1 1 1 1 1 1 1 1 1 1 2 2 2 */ - /* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 */ - { "", false}, - { "abc.{1}.efg", true }, - { "abc.{1.efg", false }, - { "abc.1}.efg", false }, - { "abc.{{1}}.efg", false }, - { "abc.{}.efg", true }, - { "abc.}1{.efg", false }, - { ".piety.demands.us.to.honour.truth.above.our.friends", false }, - { "basement.medicine.pavement.government.trenchcoat.off.cough.off.kid.did.when.again.alleyway.friend.cap.pen.dollarbills.ten.foot.soot.put.but.anyway.say.May.DA.kid.did.toes.bows.those.hose.nose.clothes.man.blows.{100000000}", false }, - { NULL, false}, + /* ruler for measuring text strings */ + /* 1 1 1 1 1 1 1 1 1 1 2 2 2 */ + /* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 */ + { "", false}, + { "abc.{1}.efg", true }, + { "abc.{1.efg", false }, + { "abc.1}.efg", false }, + { "abc.{{1}}.efg", false }, + { "abc.{}.efg", true }, + { "abc.}1{.efg", false }, + { ".piety.demands.us.to.honour.truth.above.our.friends", false }, + { "basement.medicine.pavement.government.trenchcoat.off.cough.off.kid.did.when.again.alleyway.friend.cap.pen.dollarbills.ten.foot.soot.put.but.anyway.say.May.DA.kid.did.toes.bows.those.hose.nose.clothes.man.blows.{100000000}", false }, + { NULL, false}, }; /// @endcond @@ -624,17 +616,17 @@ cfstore_create_key_name_validate_t cfstore_create_test_06_data[] = { /** * @brief Test whether a key name can be created or not. * - * @param key_name - * name of the key to create in the store - * @param should_create - * if true, then create KV should succeed, otherwise should fail. + * @param key_name + * name of the key to create in the store + * @param should_create + * if true, then create KV should succeed, otherwise should fail. * * @return on success returns CaseNext to continue to next test case, otherwise will assert on errors. */ bool cfstore_create_key_name_validate(const char *key_name, bool should_create) { bool bret = false; - char* test_data = (char*) "test_data"; + char *test_data = (char *) "test_data"; int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE len = 0; ARM_CFSTORE_KEYDESC kdesc; @@ -645,26 +637,23 @@ bool cfstore_create_key_name_validate(const char *key_name, bool should_create) /* create */ kdesc.drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE; len = strlen(test_data); - ret = cfstore_test_create((const char*) key_name, test_data, &len, &kdesc); + ret = cfstore_test_create((const char *) key_name, test_data, &len, &kdesc); /* dont not use any functions that require finding the created item as they may not work, * depending on the construction of the test key_name & match strings */ - if(should_create == true) - { - if(ret < ARM_DRIVER_OK){ + if (should_create == true) { + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to create kv (key_name=%s.\r\n", __func__, key_name); return bret; } CFSTORE_DBGLOG("%s:Success: Create() behaved as expected.\r\n", __func__); /* delete using the actual name */ - ret = cfstore_test_delete((const char*) key_name); - if(ret < ARM_DRIVER_OK){ + ret = cfstore_test_delete((const char *) key_name); + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to delete kv (key_name=%s)(ret=%d).\r\n", __func__, key_name, (int)ret); } bret = true; - } - else - { - if(ret >= ARM_DRIVER_OK){ + } else { + if (ret >= ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: created kv (key_name=%s) when Create() should have failed.\r\n", __func__, key_name); return bret; } @@ -684,13 +673,12 @@ control_t cfstore_create_test_06_end(const size_t call_count) { bool ret = false; int32_t ret32 = ARM_DRIVER_ERROR; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; - cfstore_create_key_name_validate_t* node = cfstore_create_test_06_data; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; + cfstore_create_key_name_validate_t *node = cfstore_create_test_06_data; (void) call_count; - while(node->key_name != NULL) - { + while (node->key_name != NULL) { ret = cfstore_create_key_name_validate(node->key_name, node->f_allowed); CFSTORE_TEST_UTEST_MESSAGE(cfstore_create_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: test failed (ret=%d, key_name=%s, f_allowed=%d)\n", __func__, (int) ret, node->key_name, (int) node->f_allowed); TEST_ASSERT_MESSAGE(ret == true, cfstore_create_utest_msg_g); @@ -732,8 +720,8 @@ control_t cfstore_create_test_07_end(const size_t call_count) int32_t ret = ARM_DRIVER_ERROR; void *test_buf1 = NULL; ARM_CFSTORE_FMODE flags; - cfstore_kv_data_t* node = NULL; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + cfstore_kv_data_t *node = NULL; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; CFSTORE_FENTRYLOG("%s:entered\n", __func__); (void) call_count; @@ -756,8 +744,7 @@ control_t cfstore_create_test_07_end(const size_t call_count) /* step 4. Now check that the KVs are all present and correct */ node = cfstore_create_test_01_data_step_02; - while(node->key_name != NULL) - { + while (node->key_name != NULL) { ret = cfstore_test_check_node_correct(node); CFSTORE_TEST_UTEST_MESSAGE(cfstore_create_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:node (key_name=\"%s\", value=\"%s\") not correct in cfstore\n", __func__, node->key_name, node->value); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_create_utest_msg_g); @@ -773,8 +760,7 @@ control_t cfstore_create_test_07_end(const size_t call_count) /* Step 5. Now check that the KVs are all present and correct */ node = cfstore_create_test_01_data_step_03; - while(node->key_name != NULL) - { + while (node->key_name != NULL) { ret = cfstore_test_check_node_correct(node); CFSTORE_TEST_UTEST_MESSAGE(cfstore_create_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:node (key_name=\"%s\", value=\"%s\") not correct in cfstore\n", __func__, node->key_name, node->value); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_create_utest_msg_g); @@ -790,8 +776,7 @@ control_t cfstore_create_test_07_end(const size_t call_count) /* Now check that the KVs are all present and correct */ node = cfstore_create_test_01_data_step_04; - while(node->key_name != NULL) - { + while (node->key_name != NULL) { ret = cfstore_test_check_node_correct(node); CFSTORE_TEST_UTEST_MESSAGE(cfstore_create_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:node (key_name=\"%s\", value=\"%s\") not correct in cfstore\n", __func__, node->key_name, node->value); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_create_utest_msg_g); @@ -814,24 +799,24 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("CREATE_test_00", cfstore_create_test_00), - Case("CREATE_test_01_start", cfstore_utest_default_start), - Case("CREATE_test_01_end", cfstore_create_test_01_end), - Case("CREATE_test_02_start", cfstore_utest_default_start), - Case("CREATE_test_02_end", cfstore_create_test_02_end), - Case("CREATE_test_03_start", cfstore_utest_default_start), - Case("CREATE_test_03_end", cfstore_create_test_03_end), - Case("CREATE_test_04_start", cfstore_utest_default_start), - Case("CREATE_test_04_end", cfstore_create_test_04_end), + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("CREATE_test_00", cfstore_create_test_00), + Case("CREATE_test_01_start", cfstore_utest_default_start), + Case("CREATE_test_01_end", cfstore_create_test_01_end), + Case("CREATE_test_02_start", cfstore_utest_default_start), + Case("CREATE_test_02_end", cfstore_create_test_02_end), + Case("CREATE_test_03_start", cfstore_utest_default_start), + Case("CREATE_test_03_end", cfstore_create_test_03_end), + Case("CREATE_test_04_start", cfstore_utest_default_start), + Case("CREATE_test_04_end", cfstore_create_test_04_end), #if defined(MBED_HEAP_STATS_ENABLED) && MBED_HEAP_STATS_ENABLED && !defined(__ICCARM__) - Case("CREATE_test_05", cfstore_create_test_05), + Case("CREATE_test_05", cfstore_create_test_05), #endif - Case("CREATE_test_06_start", cfstore_utest_default_start), - Case("CREATE_test_06_end", cfstore_create_test_06_end), - Case("CREATE_test_07_start", cfstore_utest_default_start), - Case("CREATE_test_07_end", cfstore_create_test_07_end), + Case("CREATE_test_06_start", cfstore_utest_default_start), + Case("CREATE_test_06_end", cfstore_create_test_06_end), + Case("CREATE_test_07_start", cfstore_utest_default_start), + Case("CREATE_test_07_end", cfstore_create_test_07_end), }; diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/dump/dump.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/dump/dump.cpp index 48d0074d4b0..0e97054202e 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/dump/dump.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/dump/dump.cpp @@ -46,14 +46,14 @@ using namespace utest::v1; control_t cfstore_dump_test_01_end(const size_t call_count) { int32_t ret = ARM_DRIVER_ERROR; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ret = cfstore_test_dump(); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_LOG("Error: failed to dump CFSTORE contents%s", "\n"); } ret = drv->Uninitialize(); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_LOG("Error: failed to Uninitialize() CFSTORE%s", "\n"); } return CaseNext; @@ -68,10 +68,10 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("DUMP_test_01_start", cfstore_utest_default_start), - Case("DUMP_test_01_end", cfstore_dump_test_01_end), + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("DUMP_test_01_start", cfstore_utest_default_start), + Case("DUMP_test_01_end", cfstore_dump_test_01_end), }; diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/example1/example1.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/example1/example1.cpp index b7c4d0e05a3..9dbd7e2e1f7 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/example1/example1.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/example1/example1.cpp @@ -95,9 +95,9 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("EXAMPLE1_test_00", cfstore_example1_test_00), + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("EXAMPLE1_test_00", cfstore_example1_test_00), }; @@ -171,8 +171,7 @@ using namespace utest::v1; }while(0); -const char* cfstore_ex_opcode_str[] = -{ +const char *cfstore_ex_opcode_str[] = { "UNDEFINED", "CFSTORE_OPCODE_CLOSE", "CFSTORE_OPCODE_CREATE", @@ -193,8 +192,8 @@ const char* cfstore_ex_opcode_str[] = }; bool cfstore_example1_done = false; -const char* cfstore_ex_kv_name = "basement.medicine.pavement.government.trenchcoat.off.cough.off.kid.did.when.again.alleyway.friend.cap.pen.dollarbills.ten.foot.soot.put.but.anyway.say.May.DA.kid.did.toes.bows.those.hose.nose.clothes.man.blows.well.well"; -const char* cfstore_ex_kv_value = "TheRollingStone"; +const char *cfstore_ex_kv_name = "basement.medicine.pavement.government.trenchcoat.off.cough.off.kid.did.when.again.alleyway.friend.cap.pen.dollarbills.ten.foot.soot.put.but.anyway.say.May.DA.kid.did.toes.bows.those.hose.nose.clothes.man.blows.well.well"; +const char *cfstore_ex_kv_value = "TheRollingStone"; #define CFSTORE_EX1_RSEEK_OFFSET 10 /* offset to S of Stone */ typedef enum cfstore_ex_state_t { @@ -234,8 +233,7 @@ typedef enum cfstore_ex_state_t { CFSTORE_EX_STATE_UNINIT_DONE } cfstore_ex_state_t; -typedef struct cfstore_example1_ctx_t -{ +typedef struct cfstore_example1_ctx_t { ARM_CFSTORE_CAPABILITIES caps; uint8_t hkey[CFSTORE_HANDLE_BUFSIZE]; uint8_t hkey_next_buf[CFSTORE_HANDLE_BUFSIZE]; @@ -246,7 +244,7 @@ typedef struct cfstore_example1_ctx_t ARM_CFSTORE_SIZE len; ARM_CFSTORE_KEYDESC kdesc; ARM_CFSTORE_FMODE flags; - char value[CFSTORE_KEY_NAME_MAX_LENGTH+1]; + char value[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; /* callback attributes*/ int32_t callback_status; ARM_CFSTORE_HANDLE callback_handle; @@ -258,7 +256,7 @@ extern ARM_CFSTORE_DRIVER cfstore_driver; ARM_CFSTORE_DRIVER *cfstore_drv = &cfstore_driver; /* forward declarations */ -static void cfstore_ex_fms_update(cfstore_example1_ctx_t* ctx); +static void cfstore_ex_fms_update(cfstore_example1_ctx_t *ctx); /// @endcond @@ -274,8 +272,7 @@ typedef enum cfstore_ex_flash_state_t { CFSTORE_EX_FLASH_STATE_READY, } cfstore_ex_flash_state_t; -typedef struct cfstore_example1_flash_ctx_t -{ +typedef struct cfstore_example1_flash_ctx_t { volatile cfstore_ex_flash_state_t state; } cfstore_example1_flash_ctx_t; @@ -289,11 +286,11 @@ static void cfstore_ex_flash_journal_callback(int32_t status, FlashJournal_OpCod const ARM_DRIVER_STORAGE *drv = &ARM_Driver_Storage_MTD_K64F; - if(cmd_code == (FlashJournal_OpCode_t) CFSTORE_FLASH_START_FORMAT) { + if (cmd_code == (FlashJournal_OpCode_t) CFSTORE_FLASH_START_FORMAT) { CFSTORE_EX1_LOG("FORMATTING%s", "\n"); status = flashJournalStrategySequential_format(drv, 4, cfstore_ex_flash_journal_callback); CFSTORE_EX1_TEST_ASSERT_MSG(status >= JOURNAL_STATUS_OK, "%s:Error: FlashJournal_format() failed (status=%d)\r\n", __func__, (int) status); - if(status == 0) { + if (status == 0) { /* async completion pending */ return; } @@ -301,40 +298,39 @@ static void cfstore_ex_flash_journal_callback(int32_t status, FlashJournal_OpCod * intentional fall through */ } - switch(cmd_code) - { - case FLASH_JOURNAL_OPCODE_FORMAT: - /* format done */ - CFSTORE_EX1_TEST_ASSERT_MSG(status > JOURNAL_STATUS_OK, "%s:Error: FlashJournal_format() failed (status=%d)\r\n", __func__, (int) status); - cfstore_example1_flash_ctx_g.state = CFSTORE_EX_FLASH_STATE_INITIALIZING; - - CFSTORE_EX1_LOG("FLASH INITIALIZING%s", "\n"); - status = FlashJournal_initialize(&jrnl, drv, &FLASH_JOURNAL_STRATEGY_SEQUENTIAL, NULL); - CFSTORE_EX1_TEST_ASSERT_MSG(status >= JOURNAL_STATUS_OK, "%s:Error: FlashJournal_initialize() failed (status=%d)\r\n", __func__, (int) status); - if(status == 0) { - /* async completion pending */ - break; - } + switch (cmd_code) { + case FLASH_JOURNAL_OPCODE_FORMAT: + /* format done */ + CFSTORE_EX1_TEST_ASSERT_MSG(status > JOURNAL_STATUS_OK, "%s:Error: FlashJournal_format() failed (status=%d)\r\n", __func__, (int) status); + cfstore_example1_flash_ctx_g.state = CFSTORE_EX_FLASH_STATE_INITIALIZING; + + CFSTORE_EX1_LOG("FLASH INITIALIZING%s", "\n"); + status = FlashJournal_initialize(&jrnl, drv, &FLASH_JOURNAL_STRATEGY_SEQUENTIAL, NULL); + CFSTORE_EX1_TEST_ASSERT_MSG(status >= JOURNAL_STATUS_OK, "%s:Error: FlashJournal_initialize() failed (status=%d)\r\n", __func__, (int) status); + if (status == 0) { + /* async completion pending */ + break; + } /* status > 0 implies operation completed synchronously * intentional fall through */ - case FLASH_JOURNAL_OPCODE_INITIALIZE: - /* initialize done */ - CFSTORE_EX1_TEST_ASSERT_MSG(status > JOURNAL_STATUS_OK, "%s:Error: FlashJournal_initialize() failed (status=%d)\r\n", __func__, (int) status); - cfstore_example1_flash_ctx_g.state = CFSTORE_EX_FLASH_STATE_RESETTING; - - CFSTORE_EX1_LOG("FLASH RESETTING%s", "\n"); - status = FlashJournal_reset(&jrnl); - CFSTORE_EX1_TEST_ASSERT_MSG(status >= JOURNAL_STATUS_OK, "%s:Error: FlashJournal_reset() failed (status=%d)\r\n", __func__, (int) status); + case FLASH_JOURNAL_OPCODE_INITIALIZE: + /* initialize done */ + CFSTORE_EX1_TEST_ASSERT_MSG(status > JOURNAL_STATUS_OK, "%s:Error: FlashJournal_initialize() failed (status=%d)\r\n", __func__, (int) status); + cfstore_example1_flash_ctx_g.state = CFSTORE_EX_FLASH_STATE_RESETTING; + + CFSTORE_EX1_LOG("FLASH RESETTING%s", "\n"); + status = FlashJournal_reset(&jrnl); + CFSTORE_EX1_TEST_ASSERT_MSG(status >= JOURNAL_STATUS_OK, "%s:Error: FlashJournal_reset() failed (status=%d)\r\n", __func__, (int) status); /* intentional fall through */ - case FLASH_JOURNAL_OPCODE_RESET: - /* reset done */ - CFSTORE_EX1_LOG("FLASH RESET DONE%s", "\n"); - cfstore_example1_flash_ctx_g.state = CFSTORE_EX_FLASH_STATE_READY; - break; - - default: - CFSTORE_EX1_LOG("%s:Error: notification of unsupported cmd_code event (status=%d, cmd_code=%d)\n", __func__, (int) status, (int) cmd_code); - return; + case FLASH_JOURNAL_OPCODE_RESET: + /* reset done */ + CFSTORE_EX1_LOG("FLASH RESET DONE%s", "\n"); + cfstore_example1_flash_ctx_g.state = CFSTORE_EX_FLASH_STATE_READY; + break; + + default: + CFSTORE_EX1_LOG("%s:Error: notification of unsupported cmd_code event (status=%d, cmd_code=%d)\n", __func__, (int) status, (int) cmd_code); + return; } return; } @@ -354,7 +350,7 @@ static int32_t cfstore_test_startup(void) memset(&cfstore_example1_flash_ctx_g, 0, sizeof(cfstore_example1_flash_ctx_g)); cfstore_example1_flash_ctx_g.state = CFSTORE_EX_FLASH_STATE_STARTING; cfstore_ex_flash_journal_callback(JOURNAL_STATUS_OK, (FlashJournal_OpCode_t) CFSTORE_FLASH_START_FORMAT); - while(cfstore_example1_flash_ctx_g.state != CFSTORE_EX_FLASH_STATE_READY) { + while (cfstore_example1_flash_ctx_g.state != CFSTORE_EX_FLASH_STATE_READY) { /* spin */ } @@ -368,109 +364,104 @@ static void cfstore_ex_callback(int32_t status, ARM_CFSTORE_OPCODE cmd_code, voi { (void) handle; - cfstore_example1_ctx_t* ctx = (cfstore_example1_ctx_t*) client_context; + cfstore_example1_ctx_t *ctx = (cfstore_example1_ctx_t *) client_context; /* CFSTORE_EX1_LOG("%s:entered: status=%d, cmd_code=%d (%s) handle=%p\r\n", __func__, (int) status, (int) cmd_code, cfstore_ex_opcode_str[cmd_code], handle); */ - switch(cmd_code) - { - case CFSTORE_OPCODE_INITIALIZE: - ctx->state = CFSTORE_EX_STATE_INIT_DONE; - break; - case CFSTORE_OPCODE_CREATE: - ctx->state = CFSTORE_EX_STATE_CREATE_DONE; - break; - case CFSTORE_OPCODE_WRITE: - ctx->state = CFSTORE_EX_STATE_WRITE_DONE; - break; - case CFSTORE_OPCODE_CLOSE: - switch(ctx->state) - { - case(CFSTORE_EX_STATE_CLOSING1): - ctx->state = CFSTORE_EX_STATE_CLOSE_DONE1; + switch (cmd_code) { + case CFSTORE_OPCODE_INITIALIZE: + ctx->state = CFSTORE_EX_STATE_INIT_DONE; break; - case(CFSTORE_EX_STATE_CLOSING2): - ctx->state = CFSTORE_EX_STATE_CLOSE_DONE2; + case CFSTORE_OPCODE_CREATE: + ctx->state = CFSTORE_EX_STATE_CREATE_DONE; break; - default: - CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown Close() error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ - } - break; - case CFSTORE_OPCODE_FLUSH: - switch(ctx->state) - { - case(CFSTORE_EX_STATE_FLUSHING1): - ctx->state = CFSTORE_EX_STATE_FLUSH_DONE1; - break; - case(CFSTORE_EX_STATE_FLUSHING2): - ctx->state = CFSTORE_EX_STATE_FLUSH_DONE2; - break; - default: - CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown Find() error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ - } - break; - case CFSTORE_OPCODE_OPEN: - ctx->state = CFSTORE_EX_STATE_OPEN_DONE; - break; - case CFSTORE_OPCODE_FIND: - switch(ctx->state) - { - case(CFSTORE_EX_STATE_FINDING1): - ctx->state = CFSTORE_EX_STATE_FIND_DONE1; + case CFSTORE_OPCODE_WRITE: + ctx->state = CFSTORE_EX_STATE_WRITE_DONE; break; - case(CFSTORE_EX_STATE_FINDING2): - ctx->state = CFSTORE_EX_STATE_FIND_DONE2; + case CFSTORE_OPCODE_CLOSE: + switch (ctx->state) { + case (CFSTORE_EX_STATE_CLOSING1): + ctx->state = CFSTORE_EX_STATE_CLOSE_DONE1; + break; + case (CFSTORE_EX_STATE_CLOSING2): + ctx->state = CFSTORE_EX_STATE_CLOSE_DONE2; + break; + default: + CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown Close() error (line=%u)\r\n", __func__, __LINE__); + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ + } break; - default: - CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown Find() error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ - } - break; - case CFSTORE_OPCODE_GET_KEY_NAME: - ctx->state = CFSTORE_EX_STATE_GET_KEY_NAME_DONE; - break; - case CFSTORE_OPCODE_GET_VALUE_LEN: - ctx->state = CFSTORE_EX_STATE_GET_VALUE_LEN_DONE; - break; - case CFSTORE_OPCODE_READ: - switch(ctx->state) - { - case(CFSTORE_EX_STATE_READING1): - ctx->state = CFSTORE_EX_STATE_READ_DONE1; + case CFSTORE_OPCODE_FLUSH: + switch (ctx->state) { + case (CFSTORE_EX_STATE_FLUSHING1): + ctx->state = CFSTORE_EX_STATE_FLUSH_DONE1; + break; + case (CFSTORE_EX_STATE_FLUSHING2): + ctx->state = CFSTORE_EX_STATE_FLUSH_DONE2; + break; + default: + CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown Find() error (line=%u)\r\n", __func__, __LINE__); + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ + } + break; + case CFSTORE_OPCODE_OPEN: + ctx->state = CFSTORE_EX_STATE_OPEN_DONE; + break; + case CFSTORE_OPCODE_FIND: + switch (ctx->state) { + case (CFSTORE_EX_STATE_FINDING1): + ctx->state = CFSTORE_EX_STATE_FIND_DONE1; + break; + case (CFSTORE_EX_STATE_FINDING2): + ctx->state = CFSTORE_EX_STATE_FIND_DONE2; + break; + default: + CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown Find() error (line=%u)\r\n", __func__, __LINE__); + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ + } + break; + case CFSTORE_OPCODE_GET_KEY_NAME: + ctx->state = CFSTORE_EX_STATE_GET_KEY_NAME_DONE; + break; + case CFSTORE_OPCODE_GET_VALUE_LEN: + ctx->state = CFSTORE_EX_STATE_GET_VALUE_LEN_DONE; + break; + case CFSTORE_OPCODE_READ: + switch (ctx->state) { + case (CFSTORE_EX_STATE_READING1): + ctx->state = CFSTORE_EX_STATE_READ_DONE1; + break; + case (CFSTORE_EX_STATE_READING2): + ctx->state = CFSTORE_EX_STATE_READ_DONE2; + break; + default: + CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown Read() error (line=%u)\r\n", __func__, __LINE__); + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ + } break; - case(CFSTORE_EX_STATE_READING2): - ctx->state = CFSTORE_EX_STATE_READ_DONE2; + case CFSTORE_OPCODE_RSEEK: + ctx->state = CFSTORE_EX_STATE_RSEEK_DONE; break; + case CFSTORE_OPCODE_DELETE: + ctx->state = CFSTORE_EX_STATE_DELETE_DONE; + break; + case CFSTORE_OPCODE_UNINITIALIZE: + ctx->state = CFSTORE_EX_STATE_UNINIT_DONE; + break; + case CFSTORE_OPCODE_GET_STATUS: + case CFSTORE_OPCODE_POWER_CONTROL: default: - CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown Read() error (line=%u)\r\n", __func__, __LINE__); + CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: received asynchronous notification for opcode=%d (%s)\r\b", __func__, cmd_code, cmd_code < CFSTORE_OPCODE_MAX ? cfstore_ex_opcode_str[cmd_code] : "unknown"); /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning * and hence is commented out. Re-instate if previous assert is removed. * break; */ - } - break; - case CFSTORE_OPCODE_RSEEK: - ctx->state = CFSTORE_EX_STATE_RSEEK_DONE; - break; - case CFSTORE_OPCODE_DELETE: - ctx->state = CFSTORE_EX_STATE_DELETE_DONE; - break; - case CFSTORE_OPCODE_UNINITIALIZE: - ctx->state = CFSTORE_EX_STATE_UNINIT_DONE; - break; - case CFSTORE_OPCODE_GET_STATUS: - case CFSTORE_OPCODE_POWER_CONTROL: - default: - CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: received asynchronous notification for opcode=%d (%s)\r\b", __func__, cmd_code, cmd_code < CFSTORE_OPCODE_MAX ? cfstore_ex_opcode_str[cmd_code] : "unknown"); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ } ctx->callback_status = status; ctx->callback_handle = handle; @@ -478,35 +469,34 @@ static void cfstore_ex_callback(int32_t status, ARM_CFSTORE_OPCODE cmd_code, voi return; } -static void cfstore_ex_fms_update(cfstore_example1_ctx_t* ctx) +static void cfstore_ex_fms_update(cfstore_example1_ctx_t *ctx) { int32_t ret; - switch (ctx->state) - { + switch (ctx->state) { case CFSTORE_EX_STATE_INITIALIZING: CFSTORE_EX1_LOG("INITIALIZING%s", "\r\n"); // note that cfstore_ex_callback() for cmd_code==CFSTORE_OPCODE_INITIALIZE can be invoked before Initialize() has returned ret = cfstore_drv->Initialize(cfstore_ex_callback, ctx); CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Initialize() should return ret >= 0 for async/synch modes(ret=%ld)\r\n", __func__, ret); - if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { + if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { ctx->state = CFSTORE_EX_STATE_INIT_DONE; break; - } else if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { + } else if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { // await pending notification of completion. break; } CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ case CFSTORE_EX_STATE_INIT_DONE: CFSTORE_EX1_LOG("INIT_DONE%s", "\r\n"); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_status >= ARM_DRIVER_OK, "%s:Error: Initialize() completion failed (status=%ld)\r\n", __func__, ctx->callback_status); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_handle == NULL, "%s:Error: the cfstore_ex_callback(cmd_code==CFSTORE_OPCODE_INITIALIZE) received non-NULL handle (%p)\r\n", __func__, ctx->callback_handle); ctx->state = CFSTORE_EX_STATE_CREATING; - // intentional fall-through + // intentional fall-through case CFSTORE_EX_STATE_CREATING: CFSTORE_EX1_LOG("CREATING%s", "\r\n"); @@ -516,24 +506,24 @@ static void cfstore_ex_fms_update(cfstore_example1_ctx_t* ctx) // note that cfstore_ex_callback() for cmd_code==CFSTORE_OPCODE_CREATE can be invoked before Create() has returned ret = cfstore_drv->Create(cfstore_ex_kv_name, ctx->len, &ctx->kdesc, ctx->hkey); CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Create() failed (ret=%ld)\r\n", __func__, ret); - if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { + if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { ctx->state = CFSTORE_EX_STATE_CREATE_DONE; break; - } else if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { + } else if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { // await pending notification of completion. break; } CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ case CFSTORE_EX_STATE_CREATE_DONE: CFSTORE_EX1_LOG("CREATE_DONE%s", "\r\n"); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_status >= ARM_DRIVER_OK, "%s:Error: Create() completion failed (status=%ld)\r\n", __func__, ctx->callback_status); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_handle == ctx->hkey, "%s:Error: the cfstore_ex_callback(cmd_code==CFSTORE_OPCODE_CREATE) received handle (%p) is not the hkey supplied to Create()(%p)\r\n", __func__, ctx->callback_handle, ctx->hkey); ctx->state = CFSTORE_EX_STATE_WRITING; - // intentional fall-through + // intentional fall-through case CFSTORE_EX_STATE_WRITING: CFSTORE_EX1_LOG("WRITING%s", "\r\n"); @@ -541,17 +531,17 @@ static void cfstore_ex_fms_update(cfstore_example1_ctx_t* ctx) // note that cfstore_ex_callback() for cmd_code==CFSTORE_OPCODE_WRITE can be invoked before Write() has returned ret = cfstore_drv->Write(ctx->hkey, cfstore_ex_kv_value, &ctx->len); CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Write() failed (ret=%ld)\r\n", __func__, ret); - if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { + if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { ctx->state = CFSTORE_EX_STATE_WRITE_DONE; break; - } else if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { + } else if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { // await pending notification of completion. break; } CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ case CFSTORE_EX_STATE_WRITE_DONE: CFSTORE_EX1_LOG("WRITE_DONE%s", "\r\n"); @@ -560,55 +550,55 @@ static void cfstore_ex_fms_update(cfstore_example1_ctx_t* ctx) CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_status == (int32_t) ctx->len, "%s:Error: Write() number of octets written (i.e. completion status (%ld)) != updated value of len parameter (%ld)\r\n", __func__, ctx->callback_status, (int32_t) ctx->len); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_handle == ctx->hkey, "%s:Error: the cfstore_ex_callback(cmd_code==CFSTORE_OPCODE_WRITE) received handle (%p) is not the hkey supplied to Write()(%p)\r\n", __func__, ctx->callback_handle, ctx->hkey); ctx->state = CFSTORE_EX_STATE_CLOSING1; - // intentional fall-through + // intentional fall-through case CFSTORE_EX_STATE_CLOSING1: CFSTORE_EX1_LOG("CLOSING1%s", "\r\n"); // note that cfstore_ex_callback() for cmd_code==CFSTORE_OPCODE_CLOSE can be invoked before Close() has returned ret = cfstore_drv->Close(ctx->hkey); CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Close() failed (ret=%ld)\r\n", __func__, ret); - if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { + if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { ctx->state = CFSTORE_EX_STATE_CLOSE_DONE1; break; - } else if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { + } else if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { // await pending notification of completion. break; } CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ case CFSTORE_EX_STATE_CLOSE_DONE1: CFSTORE_EX1_LOG("CLOSE_DONE1%s", "\r\n"); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_status >= ARM_DRIVER_OK, "%s:Error: Close() completion failed (status=%ld)\r\n", __func__, ctx->callback_status); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_handle == NULL, "%s:Error: the cfstore_ex_callback(cmd_code==CFSTORE_OPCODE_CLOSE) received non-NULL handle (%p)\r\n", __func__, ctx->callback_handle); ctx->state = CFSTORE_EX_STATE_FLUSHING1; - // intentional fall-through + // intentional fall-through case CFSTORE_EX_STATE_FLUSHING1: CFSTORE_EX1_LOG("FLUSHING1%s", "\r\n"); // note that cfstore_ex_callback() for cmd_code==CFSTORE_OPCODE_FLUSH can be invoked before Flush() has returned ret = cfstore_drv->Flush(); CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Flush() failed (ret=%ld)\r\n", __func__, ret); - if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { + if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { ctx->state = CFSTORE_EX_STATE_FLUSH_DONE1; break; - } else if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { + } else if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { // await pending notification of completion. break; } CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ case CFSTORE_EX_STATE_FLUSH_DONE1: CFSTORE_EX1_LOG("FLUSH_DONE1%s", "\r\n"); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_status >= ARM_DRIVER_OK, "%s:Error: Flush() completion failed (status=%ld)\r\n", __func__, ctx->callback_status); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_handle == NULL, "%s:Error: the cfstore_ex_callback(cmd_code==CFSTORE_OPCODE_FLUSH) received non-NULL handle (%p)\r\n", __func__, ctx->callback_handle); ctx->state = CFSTORE_EX_STATE_OPENING; - // intentional fall-through + // intentional fall-through case CFSTORE_EX_STATE_OPENING: CFSTORE_EX1_LOG("OPENING%s", "\r\n"); @@ -617,43 +607,43 @@ static void cfstore_ex_fms_update(cfstore_example1_ctx_t* ctx) // note that cfstore_ex_callback() for cmd_code==CFSTORE_OPCODE_OPEN can be invoked before Open() has returned ret = cfstore_drv->Open(cfstore_ex_kv_name, ctx->flags, ctx->hkey); CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Open() failed (ret=%ld)\r\n", __func__, ret); - if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { + if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { ctx->state = CFSTORE_EX_STATE_OPEN_DONE; break; - } else if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { + } else if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { // await pending notification of completion. break; } CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ case CFSTORE_EX_STATE_OPEN_DONE: CFSTORE_EX1_LOG("OPEN_DONE%s", "\r\n"); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_status >= ARM_DRIVER_OK, "%s:Error: Open() completion failed (status=%ld)\r\n", __func__, ctx->callback_status); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_handle == ctx->hkey, "%s:Error: the cfstore_ex_callback(cmd_code==CFSTORE_OPCODE_OPEN) received handle (%p) is not the hkey supplied to Open()(%p)\r\n", __func__, ctx->callback_handle, ctx->hkey); ctx->state = CFSTORE_EX_STATE_READING1; - // intentional fall-through + // intentional fall-through case CFSTORE_EX_STATE_READING1: CFSTORE_EX1_LOG("READING1%s", "\r\n"); ctx->len = CFSTORE_KEY_NAME_MAX_LENGTH; - memset(ctx->value, 0, CFSTORE_KEY_NAME_MAX_LENGTH+1); + memset(ctx->value, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); // note that cfstore_ex_callback() for cmd_code==CFSTORE_OPCODE_READ can be invoked before Read() has returned ret = cfstore_drv->Read(ctx->hkey, ctx->value, &ctx->len); CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Read() failed (ret=%ld)\r\n", __func__, ret); - if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { + if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { ctx->state = CFSTORE_EX_STATE_READ_DONE1; break; - } else if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { + } else if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { // await pending notification of completion. break; } CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ case CFSTORE_EX_STATE_READ_DONE1: CFSTORE_EX1_LOG("READ_DONE1%s", "\r\n"); @@ -663,50 +653,50 @@ static void cfstore_ex_fms_update(cfstore_example1_ctx_t* ctx) CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_handle == ctx->hkey, "%s:Error: the cfstore_ex_callback(cmd_code==CFSTORE_OPCODE_READ) received handle (%p) is not the hkey supplied to Read()(%p)\r\n", __func__, ctx->callback_handle, ctx->hkey); CFSTORE_EX1_TEST_ASSERT_MSG(strncmp(ctx->value, cfstore_ex_kv_value, strlen(cfstore_ex_kv_value)) == 0, "%s:Error: the read value (%s) is not as expected (%s)\r\n", __func__, ctx->value, cfstore_ex_kv_value); ctx->state = CFSTORE_EX_STATE_RSEEKING; - // intentional fall-through + // intentional fall-through case CFSTORE_EX_STATE_RSEEKING: CFSTORE_EX1_LOG("RSEEKING%s", "\r\n"); // note that cfstore_ex_callback() for cmd_code==CFSTORE_OPCODE_READ can be invoked before Read() has returned ret = cfstore_drv->Rseek(ctx->hkey, CFSTORE_EX1_RSEEK_OFFSET); CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Rseek() failed (ret=%ld)\r\n", __func__, ret); - if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { + if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { ctx->state = CFSTORE_EX_STATE_RSEEK_DONE; break; - } else if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { + } else if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { // await pending notification of completion. break; } CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ case CFSTORE_EX_STATE_RSEEK_DONE: CFSTORE_EX1_LOG("RSEEK_DONE%s", "\r\n"); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_status >= ARM_DRIVER_OK, "%s:Error: Read() completion failed (status=%ld)\r\n", __func__, ctx->callback_status); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_handle == ctx->hkey, "%s:Error: the cfstore_ex_callback(cmd_code==CFSTORE_OPCODE_RSEEK) received handle (%p) is not the hkey supplied to Read()(%p)\r\n", __func__, ctx->callback_handle, ctx->hkey); ctx->state = CFSTORE_EX_STATE_READING2; - // intentional fall-through + // intentional fall-through case CFSTORE_EX_STATE_READING2: CFSTORE_EX1_LOG("READING2%s", "\r\n"); ctx->len = CFSTORE_KEY_NAME_MAX_LENGTH; - memset(ctx->value, 0, CFSTORE_KEY_NAME_MAX_LENGTH+1); + memset(ctx->value, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); // note that cfstore_ex_callback() for cmd_code==CFSTORE_OPCODE_READ can be invoked before Read() has returned ret = cfstore_drv->Read(ctx->hkey, ctx->value, &ctx->len); CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Read() failed (ret=%ld)\r\n", __func__, ret); - if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { + if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { ctx->state = CFSTORE_EX_STATE_READ_DONE2; break; - } else if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { + } else if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { // await pending notification of completion. break; } CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ case CFSTORE_EX_STATE_READ_DONE2: CFSTORE_EX1_LOG("READ_DONE2%s", "\r\n"); @@ -717,83 +707,83 @@ static void cfstore_ex_fms_update(cfstore_example1_ctx_t* ctx) CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_handle == ctx->hkey, "%s:Error: the cfstore_ex_callback(cmd_code==CFSTORE_OPCODE_READ) received handle (%p) is not the hkey supplied to Read()(%p)\r\n", __func__, ctx->callback_handle, ctx->hkey); CFSTORE_EX1_TEST_ASSERT_MSG(strncmp(ctx->value, &cfstore_ex_kv_value[CFSTORE_EX1_RSEEK_OFFSET], strlen(&cfstore_ex_kv_value[CFSTORE_EX1_RSEEK_OFFSET])) == 0, "%s:Error: the read value (%s) is not as expected (%s)\r\n", __func__, ctx->value, &cfstore_ex_kv_value[CFSTORE_EX1_RSEEK_OFFSET]); ctx->state = CFSTORE_EX_STATE_CLOSING2; - // intentional fall-through + // intentional fall-through case CFSTORE_EX_STATE_CLOSING2: CFSTORE_EX1_LOG("CLOSING2%s", "\r\n"); // note that cfstore_ex_callback() for cmd_code==CFSTORE_OPCODE_CLOSE can be invoked before Close() has returned ret = cfstore_drv->Close(ctx->hkey); CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Close() failed (ret=%ld)\r\n", __func__, ret); - if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { + if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { ctx->state = CFSTORE_EX_STATE_CLOSE_DONE2; break; - } else if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { + } else if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { // await pending notification of completion. break; } CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ case CFSTORE_EX_STATE_CLOSE_DONE2: CFSTORE_EX1_LOG("CLOSE_DONE2%s", "\r\n"); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_status >= ARM_DRIVER_OK, "%s:Error: Close() completion failed (status=%ld)\r\n", __func__, ctx->callback_status); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_handle == NULL, "%s:Error: the cfstore_ex_callback(cmd_code==CFSTORE_OPCODE_CLOSE) received non-NULL handle (%p)\r\n", __func__, ctx->callback_handle); ctx->state = CFSTORE_EX_STATE_FINDING1; - // intentional fall-through + // intentional fall-through case CFSTORE_EX_STATE_FINDING1: CFSTORE_EX1_LOG("FINDING1%s", "\r\n"); // note that cfstore_ex_callback() for cmd_code==CFSTORE_OPCODE_FIND can be invoked before Find() has returned ret = cfstore_drv->Find("*", ctx->hkey_next, ctx->hkey_prev); CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Find() failed (ret=%ld)\r\n", __func__, ret); - if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { + if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { ctx->state = CFSTORE_EX_STATE_FIND_DONE1; break; - } else if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { + } else if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { // await pending notification of completion. break; } CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ case CFSTORE_EX_STATE_FIND_DONE1: CFSTORE_EX1_LOG("FIND_DONE1%s", "\r\n"); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_status == ARM_DRIVER_OK, "%s:Error: Find() completion failed (status=%ld)\r\n", __func__, ctx->callback_status); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_handle == ctx->hkey_prev, "%s:Error: the cfstore_ex_callback(cmd_code==CFSTORE_OPCODE_FIND) received handle (%p) is not the hkey supplied to Find()(%p)\r\n", __func__, ctx->callback_handle, ctx->hkey_prev); ctx->state = CFSTORE_EX_STATE_GETTING_KEY_NAME; - // intentional fall-through + // intentional fall-through case CFSTORE_EX_STATE_GETTING_KEY_NAME: CFSTORE_EX1_LOG("GETTING_KEY_NAME%s", "\r\n"); ctx->len = CFSTORE_KEY_NAME_MAX_LENGTH; - memset(ctx->value, 0, CFSTORE_KEY_NAME_MAX_LENGTH+1); + memset(ctx->value, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); // note that cfstore_ex_callback() for cmd_code==CFSTORE_OPCODE_GET_KEY_NAME can be invoked before GetKeyName() has returned - ret = cfstore_drv->GetKeyName(ctx->hkey_prev, ctx->value, (uint8_t*) &ctx->len); + ret = cfstore_drv->GetKeyName(ctx->hkey_prev, ctx->value, (uint8_t *) &ctx->len); CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: GetKeyName() failed (ret=%ld)\r\n", __func__, ret); - if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { + if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { ctx->state = CFSTORE_EX_STATE_GET_KEY_NAME_DONE; break; - } else if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { + } else if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { // await pending notification of completion. break; } CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ case CFSTORE_EX_STATE_GET_KEY_NAME_DONE: CFSTORE_EX1_LOG("GET_KEY_NAME_DONE%s", "\r\n"); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_status >= ARM_DRIVER_OK, "%s:Error: GetKeyName() completion failed (status=%ld)\r\n", __func__, ctx->callback_status); - CFSTORE_EX1_TEST_ASSERT_MSG( ((int32_t) ctx->len == ((int32_t) strlen(cfstore_ex_kv_name)+1)), "%s:Error: GetKeyName() updated value of len parameter (%ld) != strlen(cfstore_ex_kv_name) (%ld) (\r\n", __func__, (int32_t) ctx->len, (int32_t) strlen(cfstore_ex_kv_name)); + CFSTORE_EX1_TEST_ASSERT_MSG(((int32_t) ctx->len == ((int32_t) strlen(cfstore_ex_kv_name) + 1)), "%s:Error: GetKeyName() updated value of len parameter (%ld) != strlen(cfstore_ex_kv_name) (%ld) (\r\n", __func__, (int32_t) ctx->len, (int32_t) strlen(cfstore_ex_kv_name)); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_handle == ctx->hkey_prev, "%s:Error: the cfstore_ex_callback(cmd_code==CFSTORE_OPCODE_GET_KEY_NAME) received handle (%p) is not the hkey supplied to GetKeyName()(%p)\r\n", __func__, ctx->callback_handle, ctx->hkey_prev); CFSTORE_EX1_TEST_ASSERT_MSG(strncmp(ctx->value, cfstore_ex_kv_name, strlen(cfstore_ex_kv_name)) == 0, "%s:Error: the key name (%s) is not as expected (%s)\r\n", __func__, ctx->value, cfstore_ex_kv_name); ctx->state = CFSTORE_EX_STATE_GETTING_VALUE_LEN; - // intentional fall-through + // intentional fall-through case CFSTORE_EX_STATE_GETTING_VALUE_LEN: CFSTORE_EX1_LOG("GETTING_VALUE_LEN%s", "\r\n"); @@ -801,17 +791,17 @@ static void cfstore_ex_fms_update(cfstore_example1_ctx_t* ctx) // note that cfstore_ex_callback() for cmd_code==CFSTORE_OPCODE_GET_VALUE_LEN can be invoked before GetValueLen() has returned ret = cfstore_drv->GetValueLen(ctx->hkey_prev, &ctx->len); CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: GetValueLen() failed (ret=%ld)\r\n", __func__, ret); - if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { + if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { ctx->state = CFSTORE_EX_STATE_GET_VALUE_LEN_DONE; break; - } else if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { + } else if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { // await pending notification of completion. break; } CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ case CFSTORE_EX_STATE_GET_VALUE_LEN_DONE: CFSTORE_EX1_LOG("GET_VALUE_LEN_DONE%s", "\r\n"); @@ -819,24 +809,24 @@ static void cfstore_ex_fms_update(cfstore_example1_ctx_t* ctx) CFSTORE_EX1_TEST_ASSERT_MSG((int32_t) ctx->len == (int32_t) strlen(cfstore_ex_kv_value), "%s:Error: GetValueLen() updated value of len parameter (%ld) != strlen(cfstore_ex_kv_value)(%ld) \r\n", __func__, (int32_t) ctx->len, (int32_t) strlen(cfstore_ex_kv_value)); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_handle == ctx->hkey_prev, "%s:Error: the cfstore_ex_callback(cmd_code==CFSTORE_OPCODE_GET_VALUE_LEN) received handle (%p) is not the hkey supplied to GetValueLen()(%p)\r\n", __func__, ctx->callback_handle, ctx->hkey_prev); ctx->state = CFSTORE_EX_STATE_DELETING; - // intentional fall-through + // intentional fall-through case CFSTORE_EX_STATE_DELETING: CFSTORE_EX1_LOG("DELETING%s", "\r\n"); // note that cfstore_ex_callback() for cmd_code==CFSTORE_OPCODE_DELETE can be invoked before Delete() has returned ret = cfstore_drv->Delete(ctx->callback_handle); CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Close() failed (ret=%ld)\r\n", __func__, ret); - if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { + if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { ctx->state = CFSTORE_EX_STATE_DELETE_DONE; break; - } else if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { + } else if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { // await pending notification of completion. break; } CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ case CFSTORE_EX_STATE_DELETE_DONE: CFSTORE_EX1_LOG("DELETE_DONE%s", "\r\n"); @@ -844,70 +834,70 @@ static void cfstore_ex_fms_update(cfstore_example1_ctx_t* ctx) CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_handle == NULL, "%s:Error: the cfstore_ex_callback(cmd_code==CFSTORE_OPCODE_DELETE) received non-NULL handle (%p)\r\n", __func__, ctx->callback_handle); CFSTORE_HANDLE_SWAP(ctx->hkey_prev, ctx->hkey_next); ctx->state = CFSTORE_EX_STATE_FINDING2; - // intentional fall-through + // intentional fall-through case CFSTORE_EX_STATE_FINDING2: CFSTORE_EX1_LOG("FINDING2%s", "\r\n"); // note that cfstore_ex_callback() for cmd_code==CFSTORE_OPCODE_FIND can be invoked before Find() has returned ret = cfstore_drv->Find("*", ctx->hkey_next, ctx->hkey_prev); CFSTORE_EX1_TEST_ASSERT_MSG(ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND, "%s:Error: Find() failed to return expected value of ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND (ret=%ld)\r\n", __func__, ret); - if(ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND && ctx->caps.asynchronous_ops == false) { + if (ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND && ctx->caps.asynchronous_ops == false) { ctx->state = CFSTORE_EX_STATE_FIND_DONE2; break; - } else if(ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND && ctx->caps.asynchronous_ops == true) { + } else if (ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND && ctx->caps.asynchronous_ops == true) { // await pending notification of completion. break; } CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ case CFSTORE_EX_STATE_FIND_DONE2: CFSTORE_EX1_LOG("FIND_DONE2%s", "\r\n"); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_status == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND, "%s:Error: Find() completion should have been ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND (status=%ld)\r\n", __func__, ctx->callback_status); ctx->state = CFSTORE_EX_STATE_FLUSHING2; - // intentional fall-through + // intentional fall-through case CFSTORE_EX_STATE_FLUSHING2: CFSTORE_EX1_LOG("FLUSHING2%s", "\r\n"); // note that cfstore_ex_callback() for cmd_code==CFSTORE_OPCODE_FLUSH can be invoked before Flush() has returned ret = cfstore_drv->Flush(); CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error:2: Flush() failed (ret=%ld)\r\n", __func__, ret); - if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { + if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { ctx->state = CFSTORE_EX_STATE_FLUSH_DONE2; break; - } else if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { + } else if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { // await pending notification of completion. break; } CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ case CFSTORE_EX_STATE_FLUSH_DONE2: CFSTORE_EX1_LOG("FLUSH_DONE2%s", "\r\n"); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_status >= ARM_DRIVER_OK, "%s:Error: Flush() completion failed (status=%ld)\r\n", __func__, ctx->callback_status); CFSTORE_EX1_TEST_ASSERT_MSG(ctx->callback_handle == NULL, "%s:Error: the cfstore_ex_callback(cmd_code==CFSTORE_OPCODE_FLUSH) received non-NULL handle (%p)\r\n", __func__, ctx->callback_handle); ctx->state = CFSTORE_EX_STATE_UNINITIALIZING; - // intentional fall-through + // intentional fall-through case CFSTORE_EX_STATE_UNINITIALIZING: CFSTORE_EX1_LOG("UNINITIALIZING%s", "\r\n"); ret = cfstore_drv->Uninitialize(); CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Uninitialize() should return ret >= 0 for async/synch modes(ret=%ld)\r\n", __func__, ret); - if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { + if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == false) { ctx->state = CFSTORE_EX_STATE_UNINIT_DONE; break; - } else if(ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { + } else if (ret >= ARM_DRIVER_OK && ctx->caps.asynchronous_ops == true) { // await pending notification of completion. break; } CFSTORE_EX1_TEST_ASSERT_MSG(false, "%s:Error: unknown error (line=%u)\r\n", __func__, __LINE__); - /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning - * and hence is commented out. Re-instate if previous assert is removed. - * break; */ + /* The following 'break' statement generates ARMCC #111-D: statement is unreachable warning + * and hence is commented out. Re-instate if previous assert is removed. + * break; */ case CFSTORE_EX_STATE_UNINIT_DONE: CFSTORE_EX1_LOG("UNINIT_DONE%s", "\r\n"); @@ -922,7 +912,7 @@ static void cfstore_ex_fms_update(cfstore_example1_ctx_t* ctx) static control_t cfstore_example1_app_start(const size_t call_count) { - cfstore_example1_ctx_t* ctx = &cfstore_example1_ctx_g; + cfstore_example1_ctx_t *ctx = &cfstore_example1_ctx_g; (void) call_count; @@ -937,8 +927,7 @@ static control_t cfstore_example1_app_start(const size_t call_count) cfstore_ex_fms_update(ctx); /* main application worker loop */ - while (!cfstore_example1_done) - { + while (!cfstore_example1_done) { // do some work CFSTORE_EX1_LOG("%s: going to sleep!\r\n", __func__); @@ -978,10 +967,10 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("EXAMPLE1_test_00", cfstore_example1_test_00), - Case("EXAMPLE1_test_01_start", cfstore_example1_app_start), + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("EXAMPLE1_test_00", cfstore_example1_test_00), + Case("EXAMPLE1_test_01_start", cfstore_example1_app_start), }; @@ -998,7 +987,7 @@ int main() #else // CFSTORE_EXAMPLE1_APP // stand alone Configuration-Store-Example -void app_start(int argc __unused, char** argv __unused) +void app_start(int argc __unused, char **argv __unused) { cfstore_example1_app_start(0); } diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/example2/example2.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/example2/example2.cpp index 978d0340c32..d7266dfb05e 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/example2/example2.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/example2/example2.cpp @@ -79,29 +79,29 @@ ARM_CFSTORE_DRIVER *drv = &cfstore_driver; static int32_t CreateKeyValueStore( - const char *keyName, - const char *data, - ARM_CFSTORE_SIZE *dataLength, - ARM_CFSTORE_KEYDESC *keyDesc) + const char *keyName, + const char *data, + ARM_CFSTORE_SIZE *dataLength, + ARM_CFSTORE_KEYDESC *keyDesc) { - int32_t cfsStatus = ARM_DRIVER_ERROR; - ARM_CFSTORE_SIZE valueLength = 0; - ARM_CFSTORE_HANDLE_INIT(hkey); - - valueLength = *dataLength; - cfsStatus = drv->Create(keyName, valueLength, keyDesc, hkey); - TEST_ASSERT_EQUAL(ARM_DRIVER_OK, cfsStatus); - - valueLength = *dataLength; - cfsStatus = drv->Write(hkey, data, &valueLength); - /* - * (1) Note the following: - * - if cfsStatus > 0 then Write() has completed synchronously and returned the number of bytes written (irrespective of the caps.asynchronous_ops attribute). - * - if cfsStatus == ARM_DRIVER_OK then: + int32_t cfsStatus = ARM_DRIVER_ERROR; + ARM_CFSTORE_SIZE valueLength = 0; + ARM_CFSTORE_HANDLE_INIT(hkey); + + valueLength = *dataLength; + cfsStatus = drv->Create(keyName, valueLength, keyDesc, hkey); + TEST_ASSERT_EQUAL(ARM_DRIVER_OK, cfsStatus); + + valueLength = *dataLength; + cfsStatus = drv->Write(hkey, data, &valueLength); + /* + * (1) Note the following: + * - if cfsStatus > 0 then Write() has completed synchronously and returned the number of bytes written (irrespective of the caps.asynchronous_ops attribute). + * - if cfsStatus == ARM_DRIVER_OK then: * - if caps.asynchronous_ops == true then the operation will be completed with registered client callback passed to Initialize(). * - if caps.asynchronous_ops == false then the operation has completed synchronously and no bytes were written. * - if cfsStatus < ARM_DRIVER_OK then an error has occurred - */ + */ CFSTORE_TEST_UTEST_MESSAGE(cfstore_example2_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to write key (rc=%d)\n", __func__, (int) cfsStatus); TEST_ASSERT_MESSAGE(cfsStatus >= ARM_DRIVER_OK, cfstore_example2_utest_msg_g); @@ -111,71 +111,71 @@ static int32_t CreateKeyValueStore( CFSTORE_TEST_UTEST_MESSAGE(cfstore_example2_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%sError: Write() return value cfsStatus(%d) does not match the expected dataLength(%d)\n", __func__, (int) cfsStatus, (int) *dataLength); TEST_ASSERT_MESSAGE((int32_t) *dataLength == cfsStatus, cfstore_example2_utest_msg_g); - drv->Close(hkey); - /* CreateKeyValueStore() returns what was returned from Write(). See (1) above for description. */ - return cfsStatus; + drv->Close(hkey); + /* CreateKeyValueStore() returns what was returned from Write(). See (1) above for description. */ + return cfsStatus; } static control_t cfstore_example2_test_01(const size_t call_count) { - int32_t cfsStatus; - ARM_CFSTORE_HANDLE_INIT(hkey); - ARM_CFSTORE_HANDLE_INIT(updatedKeyH); - ARM_CFSTORE_FMODE flags; - ARM_CFSTORE_KEYDESC kdesc; - ARM_CFSTORE_SIZE valueLen; - char* ptr = NULL; - - const char key[] = "com.arm.mbed.spv.assets.asset2.payload"; - const char value[] = "Grumpy old man"; - - (void) call_count; - - // It must not exceed the value_len field specified when the Key-Value pair was created - const char newDataToWrite[] = "Grumpy man"; - - char readBuf[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; - ARM_CFSTORE_SIZE len = 0; - - // Write a key-value pair - - PvMemSet(&kdesc, 0, sizeof(kdesc)); - PvMemSet(&flags, 0, sizeof(flags)); - PvMemSet(readBuf, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); - - kdesc.drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE; - /* The length supplied to Write() is the number of octets to store in the blob. - * Specifying the following value for valueLen will store the terminating null to - * a string, for example. - */ - valueLen = PvStrLen(value) + 1; - - cfsStatus = drv->Initialize(NULL, NULL); + int32_t cfsStatus; + ARM_CFSTORE_HANDLE_INIT(hkey); + ARM_CFSTORE_HANDLE_INIT(updatedKeyH); + ARM_CFSTORE_FMODE flags; + ARM_CFSTORE_KEYDESC kdesc; + ARM_CFSTORE_SIZE valueLen; + char *ptr = NULL; + + const char key[] = "com.arm.mbed.spv.assets.asset2.payload"; + const char value[] = "Grumpy old man"; + + (void) call_count; + + // It must not exceed the value_len field specified when the Key-Value pair was created + const char newDataToWrite[] = "Grumpy man"; + + char readBuf[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; + ARM_CFSTORE_SIZE len = 0; + + // Write a key-value pair + + PvMemSet(&kdesc, 0, sizeof(kdesc)); + PvMemSet(&flags, 0, sizeof(flags)); + PvMemSet(readBuf, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); + + kdesc.drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE; + /* The length supplied to Write() is the number of octets to store in the blob. + * Specifying the following value for valueLen will store the terminating null to + * a string, for example. + */ + valueLen = PvStrLen(value) + 1; + + cfsStatus = drv->Initialize(NULL, NULL); CFSTORE_TEST_UTEST_MESSAGE(cfstore_example2_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Initialize() failed (cfsStatus=%d)\n", __func__, (int) cfsStatus); TEST_ASSERT_MESSAGE(cfsStatus >= ARM_DRIVER_OK, cfstore_example2_utest_msg_g); - cfsStatus = CreateKeyValueStore(key, value, &valueLen, &kdesc); + cfsStatus = CreateKeyValueStore(key, value, &valueLen, &kdesc); - /* CreateKeyValueStore() returns the number of characters written, which can vary between 0 and the supplied arg valueLen - * - in the case that this example is compiled for flash mode sync, CreateKeyValueStore(), on success should always return valueLen - * - in the case that this example is compiled for flash mode async, CreateKeyValueStore() on success may return a value 0 to valueLen - * with async notification of the completed transaction. - */ + /* CreateKeyValueStore() returns the number of characters written, which can vary between 0 and the supplied arg valueLen + * - in the case that this example is compiled for flash mode sync, CreateKeyValueStore(), on success should always return valueLen + * - in the case that this example is compiled for flash mode async, CreateKeyValueStore() on success may return a value 0 to valueLen + * with async notification of the completed transaction. + */ CFSTORE_TEST_UTEST_MESSAGE(cfstore_example2_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%sError: valueLen(%d) does not match the expected returned value from CreateKeyValueStore(%d)\n", __func__, (int) valueLen, (int) cfsStatus); TEST_ASSERT_MESSAGE(cfsStatus == (int32_t) valueLen, cfstore_example2_utest_msg_g); - // Read key-value pair with 'Write' permission + // Read key-value pair with 'Write' permission - flags.read = true; - flags.write = true; - cfsStatus = drv->Open(key, flags, hkey); - TEST_ASSERT_EQUAL(ARM_DRIVER_OK, cfsStatus); + flags.read = true; + flags.write = true; + cfsStatus = drv->Open(key, flags, hkey); + TEST_ASSERT_EQUAL(ARM_DRIVER_OK, cfsStatus); - len = sizeof(readBuf); - cfsStatus = drv->Read(hkey, readBuf, &len); + len = sizeof(readBuf); + cfsStatus = drv->Read(hkey, readBuf, &len); /* Read() returns the number of characters read, which can vary between 0 and the size of the value blob, and the size of the supplied buffer */ - CFSTORE_TEST_UTEST_MESSAGE(cfstore_example2_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Read() returned value (%d) does not match the created length of the value blob(%d)\n", __func__, (int) cfsStatus, (int) PvStrLen(value) + 1); - TEST_ASSERT_MESSAGE(cfsStatus == (int32_t) (PvStrLen(value) + 1), cfstore_example2_utest_msg_g); + CFSTORE_TEST_UTEST_MESSAGE(cfstore_example2_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Read() returned value (%d) does not match the created length of the value blob(%d)\n", __func__, (int) cfsStatus, (int) PvStrLen(value) + 1); + TEST_ASSERT_MESSAGE(cfsStatus == (int32_t)(PvStrLen(value) + 1), cfstore_example2_utest_msg_g); CFSTORE_TEST_UTEST_MESSAGE(cfstore_example2_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Read() returned len value (%d) does not match the created length of the value blob(%d)\n", __func__, (int) len, (int) PvStrLen(value) + 1); TEST_ASSERT_MESSAGE(len == PvStrLen(value) + 1, cfstore_example2_utest_msg_g); @@ -187,34 +187,33 @@ static control_t cfstore_example2_test_01(const size_t call_count) * - The new data is shorter that the old data so it will be accommodated in the value blob * - The size of the value blob will stay the same. */ - // Update the value and value length + // Update the value and value length /* note len set to sizeof(newDataToWrite) which includes the terminating null of the string */ - len = sizeof(newDataToWrite); - cfsStatus = drv->Write(hkey, newDataToWrite, &len); + len = sizeof(newDataToWrite); + cfsStatus = drv->Write(hkey, newDataToWrite, &len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_example2_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Write() returned cfsStatus value (%d) does not match the length of new data written(%d)\n", __func__, (int) cfsStatus, (int) sizeof(newDataToWrite)); TEST_ASSERT_MESSAGE(cfsStatus == (int32_t) sizeof(newDataToWrite), cfstore_example2_utest_msg_g); CFSTORE_TEST_UTEST_MESSAGE(cfstore_example2_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Write() returned len (%d) does not match the length of new data written(%d)\n", __func__, (int) len, (int) sizeof(newDataToWrite)); TEST_ASSERT_MESSAGE((int32_t) len == (int32_t) sizeof(newDataToWrite), cfstore_example2_utest_msg_g); - drv->Close(hkey); + drv->Close(hkey); - // Check that the value was updated - flags.write = false; - cfsStatus = drv->Open(key, flags, updatedKeyH); - TEST_ASSERT_EQUAL(ARM_DRIVER_OK, cfsStatus); + // Check that the value was updated + flags.write = false; + cfsStatus = drv->Open(key, flags, updatedKeyH); + TEST_ASSERT_EQUAL(ARM_DRIVER_OK, cfsStatus); - len = CFSTORE_KEY_NAME_MAX_LENGTH; - PvMemSet(readBuf, 0, len); - cfsStatus = drv->Read(updatedKeyH, readBuf, &len); + len = CFSTORE_KEY_NAME_MAX_LENGTH; + PvMemSet(readBuf, 0, len); + cfsStatus = drv->Read(updatedKeyH, readBuf, &len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_example2_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Read() returned value (%d) does not match the created length of the value blob(%d)\n", __func__, (int) cfsStatus, (int) PvStrLen(value) + 1); - TEST_ASSERT_MESSAGE(cfsStatus == (int32_t) (PvStrLen(value) + 1), cfstore_example2_utest_msg_g); + TEST_ASSERT_MESSAGE(cfsStatus == (int32_t)(PvStrLen(value) + 1), cfstore_example2_utest_msg_g); CFSTORE_TEST_UTEST_MESSAGE(cfstore_example2_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Read() returned len value (%d) does not match the created length of the value blob(%d)\n", __func__, (int) len, (int) PvStrLen(value) + 1); TEST_ASSERT_MESSAGE(len == (PvStrLen(value) + 1), cfstore_example2_utest_msg_g); /* convert any terminating nulls to '=' */ - while( (ptr = (char*) memchr(readBuf, 0, (PvStrLen(value) + 1))) != NULL) - { + while ((ptr = (char *) memchr(readBuf, 0, (PvStrLen(value) + 1))) != NULL) { *ptr = '='; } /* check the data is as expected */ @@ -224,13 +223,13 @@ static control_t cfstore_example2_test_01(const size_t call_count) /* revert to CFSTORE_LOG if more trace required */ CFSTORE_DBGLOG("Success: New value of KV (%s) value blob (with nulls converted to '=') = (%s)\n", key, readBuf); - drv->Close(updatedKeyH); + drv->Close(updatedKeyH); - cfsStatus = drv->Uninitialize(); + cfsStatus = drv->Uninitialize(); CFSTORE_TEST_UTEST_MESSAGE(cfstore_example2_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Uninitialize() failed (cfsStatus=%d)\n", __func__, (int) cfsStatus); TEST_ASSERT_MESSAGE(cfsStatus >= ARM_DRIVER_OK, cfstore_example2_utest_msg_g); - return CaseNext; + return CaseNext; } @@ -242,10 +241,10 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("EXAMPLE2_test_00", cfstore_example2_test_00), - Case("EXAMPLE2_test_01", cfstore_example2_test_01), + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("EXAMPLE2_test_00", cfstore_example2_test_00), + Case("EXAMPLE2_test_01", cfstore_example2_test_01), }; diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/example3/example3.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/example3/example3.cpp index f94f855f8f3..4155129d249 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/example3/example3.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/example3/example3.cpp @@ -106,8 +106,7 @@ using namespace utest::v1; }while(0); -const char* cfstore_ex3_opcode_str[] = -{ +const char *cfstore_ex3_opcode_str[] = { "UNDEFINED", "CFSTORE_OPCODE_CLOSE", "CFSTORE_OPCODE_CREATE", @@ -127,12 +126,11 @@ const char* cfstore_ex3_opcode_str[] = "CFSTORE_OPCODE_MAX" }; -const char* cfstore_ex3_kv_name = "basement.medicine.pavement.government.trenchcoat.off.cough.off.kid.did.when.again.alleyway.friend.cap.pen.dollarbills.ten.foot.soot.put.but.anyway.say.May.DA.kid.did.toes.bows.those.hose.nose.clothes.man.blows.well.well"; -const char* cfstore_ex3_kv_value = "TheRollingStone"; +const char *cfstore_ex3_kv_name = "basement.medicine.pavement.government.trenchcoat.off.cough.off.kid.did.when.again.alleyway.friend.cap.pen.dollarbills.ten.foot.soot.put.but.anyway.say.May.DA.kid.did.toes.bows.those.hose.nose.clothes.man.blows.well.well"; +const char *cfstore_ex3_kv_value = "TheRollingStone"; #define CFSTORE_EX1_RSEEK_OFFSET 10 /* offset to S of Stone */ -typedef struct cfstore_example3_ctx_t -{ +typedef struct cfstore_example3_ctx_t { ARM_CFSTORE_CAPABILITIES caps; uint8_t hkey[CFSTORE_HANDLE_BUFSIZE]; uint8_t hkey_next_buf[CFSTORE_HANDLE_BUFSIZE]; @@ -142,7 +140,7 @@ typedef struct cfstore_example3_ctx_t ARM_CFSTORE_SIZE len; ARM_CFSTORE_KEYDESC kdesc; ARM_CFSTORE_FMODE flags; - char value[CFSTORE_KEY_NAME_MAX_LENGTH+1]; + char value[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; } cfstore_example3_ctx_t; static cfstore_example3_ctx_t cfstore_example3_ctx_g; @@ -152,113 +150,113 @@ ARM_CFSTORE_DRIVER *cfstore_drv = &cfstore_driver; /// @endcond -static void cfstore_ex3_test_01(cfstore_example3_ctx_t* ctx) +static void cfstore_ex3_test_01(cfstore_example3_ctx_t *ctx) { int32_t ret; - CFSTORE_EX1_LOG("INITIALIZING%s", "\r\n"); - ret = cfstore_drv->Initialize(NULL, NULL); - CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Initialize() should return ret >= 0 for async/synch modes(ret=%ld)\r\n", __func__, ret); - - CFSTORE_EX1_LOG("CREATING%s", "\r\n"); - memset(&ctx->kdesc, 0, sizeof(ARM_CFSTORE_KEYDESC)); - ctx->kdesc.drl = ARM_RETENTION_NVM; - ctx->len = strlen(cfstore_ex3_kv_value); - ret = cfstore_drv->Create(cfstore_ex3_kv_name, ctx->len, &ctx->kdesc, ctx->hkey); - CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Create() failed (ret=%ld)\r\n", __func__, ret); - - CFSTORE_EX1_LOG("WRITING%s", "\r\n"); - ctx->len = strlen(cfstore_ex3_kv_value); - ret = cfstore_drv->Write(ctx->hkey, cfstore_ex3_kv_value, &ctx->len); - CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Write() failed (ret=%ld)\r\n", __func__, ret); - - CFSTORE_EX1_TEST_ASSERT_MSG(ret == (int32_t) strlen(cfstore_ex3_kv_value), "%s:Error: Write() number of octets written (i.e. completion status (%ld)) != strlen(ctx->value)(%ld)\r\n", __func__, ret, (int32_t) strlen(cfstore_ex3_kv_value)); - CFSTORE_EX1_TEST_ASSERT_MSG(ret == (int32_t) ctx->len, "%s:Error: Write() number of octets written (i.e. completion status (%ld)) != updated value of len parameter (%ld)\r\n", __func__, ret, (int32_t) ctx->len); - - CFSTORE_EX1_LOG("CLOSING1%s", "\r\n"); - ret = cfstore_drv->Close(ctx->hkey); - CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Close() failed (ret=%ld)\r\n", __func__, ret); - - CFSTORE_EX1_LOG("FLUSHING1%s", "\r\n"); - ret = cfstore_drv->Flush(); - CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Flush() failed (ret=%ld)\r\n", __func__, ret); - - CFSTORE_EX1_LOG("OPENING%s", "\r\n"); - memset(&ctx->flags, 0, sizeof(ctx->flags)); - memset(&ctx->hkey, 0, CFSTORE_HANDLE_BUFSIZE); - ret = cfstore_drv->Open(cfstore_ex3_kv_name, ctx->flags, ctx->hkey); - CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Open() failed (ret=%ld)\r\n", __func__, ret); - - CFSTORE_EX1_LOG("READING1%s", "\r\n"); - ctx->len = CFSTORE_KEY_NAME_MAX_LENGTH; - memset(ctx->value, 0, CFSTORE_KEY_NAME_MAX_LENGTH+1); - ret = cfstore_drv->Read(ctx->hkey, ctx->value, &ctx->len); - CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Read() failed (ret=%ld)\r\n", __func__, ret); - - CFSTORE_EX1_TEST_ASSERT_MSG(ret == (int32_t) strlen(cfstore_ex3_kv_value), "%s:Error: Read() number of octets read (i.e. completion status (%ld)) != strlen(ctx->value)(%ld)\r\n", __func__, ret, (int32_t) strlen(cfstore_ex3_kv_value)); - CFSTORE_EX1_TEST_ASSERT_MSG(ret == (int32_t) ctx->len, "%s:Error: Read() number of octets read (i.e. completion status (%ld)) != updated value of len parameter (%ld)\r\n", __func__, ret, (int32_t) ctx->len); - CFSTORE_EX1_TEST_ASSERT_MSG(strncmp(ctx->value, cfstore_ex3_kv_value, strlen(cfstore_ex3_kv_value)) == 0, "%s:Error: the read value (%s) is not as expected (%s)\r\n", __func__, ctx->value, cfstore_ex3_kv_value); - - CFSTORE_EX1_LOG("RSEEKING%s", "\r\n"); - ret = cfstore_drv->Rseek(ctx->hkey, CFSTORE_EX1_RSEEK_OFFSET); - CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Rseek() failed (ret=%ld)\r\n", __func__, ret); - - CFSTORE_EX1_LOG("READING2%s", "\r\n"); - ctx->len = CFSTORE_KEY_NAME_MAX_LENGTH; - memset(ctx->value, 0, CFSTORE_KEY_NAME_MAX_LENGTH+1); - ret = cfstore_drv->Read(ctx->hkey, ctx->value, &ctx->len); - CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Read() failed (ret=%ld)\r\n", __func__, ret); - CFSTORE_EX1_TEST_ASSERT_MSG(ret == (int32_t) strlen(&cfstore_ex3_kv_value[CFSTORE_EX1_RSEEK_OFFSET]), "%s:Error: Read() number of octets read (i.e. completion status (%ld)) != strlen(ctx->value)(%ld)\r\n", __func__, ret, (int32_t) strlen(&cfstore_ex3_kv_value[CFSTORE_EX1_RSEEK_OFFSET])); - CFSTORE_EX1_TEST_ASSERT_MSG(ret == (int32_t) ctx->len, "%s:Error: Read() number of octets read (i.e. completion status (%ld)) != updated value of len parameter (%ld)\r\n", __func__, ret, (int32_t) ctx->len); - CFSTORE_EX1_TEST_ASSERT_MSG(strncmp(ctx->value, &cfstore_ex3_kv_value[CFSTORE_EX1_RSEEK_OFFSET], strlen(&cfstore_ex3_kv_value[CFSTORE_EX1_RSEEK_OFFSET])) == 0, "%s:Error: the read value (%s) is not as expected (%s)\r\n", __func__, ctx->value, &cfstore_ex3_kv_value[CFSTORE_EX1_RSEEK_OFFSET]); - - CFSTORE_EX1_LOG("CLOSING2%s", "\r\n"); - ret = cfstore_drv->Close(ctx->hkey); - CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Close() failed (ret=%ld)\r\n", __func__, ret); - - CFSTORE_EX1_LOG("FINDING1%s", "\r\n"); - ret = cfstore_drv->Find("*", ctx->hkey_next, ctx->hkey_prev); - CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Find() failed (ret=%ld)\r\n", __func__, ret); - - CFSTORE_EX1_LOG("GETTING_KEY_NAME%s", "\r\n"); - ctx->len = CFSTORE_KEY_NAME_MAX_LENGTH; - memset(ctx->value, 0, CFSTORE_KEY_NAME_MAX_LENGTH+1); - ret = cfstore_drv->GetKeyName(ctx->hkey_prev, ctx->value, (uint8_t*) &ctx->len); - CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: GetKeyName() failed (ret=%ld)\r\n", __func__, ret); - CFSTORE_EX1_TEST_ASSERT_MSG( ((int32_t) ctx->len == ((int32_t) strlen(cfstore_ex3_kv_name)+1)), "%s:Error: GetKeyName() updated value of len parameter (%ld) != strlen(cfstore_ex3_kv_name) (%ld) (\r\n", __func__, (int32_t) ctx->len, (int32_t) strlen(cfstore_ex3_kv_name)); - CFSTORE_EX1_TEST_ASSERT_MSG(strncmp(ctx->value, cfstore_ex3_kv_name, strlen(cfstore_ex3_kv_name)) == 0, "%s:Error: the key name (%s) is not as expected (%s)\r\n", __func__, ctx->value, cfstore_ex3_kv_name); - - CFSTORE_EX1_LOG("GETTING_VALUE_LEN%s", "\r\n"); - ctx->len = CFSTORE_KEY_NAME_MAX_LENGTH; - ret = cfstore_drv->GetValueLen(ctx->hkey_prev, &ctx->len); - CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: GetValueLen() failed (ret=%ld)\r\n", __func__, ret); - CFSTORE_EX1_TEST_ASSERT_MSG((int32_t) ctx->len == (int32_t) strlen(cfstore_ex3_kv_value), "%s:Error: GetValueLen() updated value of len parameter (%ld) != strlen(cfstore_ex3_kv_value)(%ld) \r\n", __func__, (int32_t) ctx->len, (int32_t) strlen(cfstore_ex3_kv_value)); - - CFSTORE_EX1_LOG("DELETING%s", "\r\n"); - ret = cfstore_drv->Delete(ctx->hkey_prev); - CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Close() failed (ret=%ld)\r\n", __func__, ret); - CFSTORE_HANDLE_SWAP(ctx->hkey_prev, ctx->hkey_next); - - CFSTORE_EX1_LOG("FINDING2%s", "\r\n"); - ret = cfstore_drv->Find("*", ctx->hkey_next, ctx->hkey_prev); - CFSTORE_EX1_TEST_ASSERT_MSG(ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND, "%s:Error: Find() failed to return expected value of ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND (ret=%ld)\r\n", __func__, ret); - - CFSTORE_EX1_LOG("FLUSHING2%s", "\r\n"); - ret = cfstore_drv->Flush(); - CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error:2: Flush() failed (ret=%ld)\r\n", __func__, ret); - - CFSTORE_EX1_LOG("UNINITIALIZING%s", "\r\n"); - ret = cfstore_drv->Uninitialize(); - CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Uninitialize() should return ret >= 0 for synch mode(ret=%ld)\r\n", __func__, ret); - CFSTORE_EX1_LOG("***************%s", "\r\n"); - CFSTORE_EX1_LOG("*** SUCCESS ***%s", "\r\n"); - CFSTORE_EX1_LOG("***************%s", "\r\n"); - return; + CFSTORE_EX1_LOG("INITIALIZING%s", "\r\n"); + ret = cfstore_drv->Initialize(NULL, NULL); + CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Initialize() should return ret >= 0 for async/synch modes(ret=%ld)\r\n", __func__, ret); + + CFSTORE_EX1_LOG("CREATING%s", "\r\n"); + memset(&ctx->kdesc, 0, sizeof(ARM_CFSTORE_KEYDESC)); + ctx->kdesc.drl = ARM_RETENTION_NVM; + ctx->len = strlen(cfstore_ex3_kv_value); + ret = cfstore_drv->Create(cfstore_ex3_kv_name, ctx->len, &ctx->kdesc, ctx->hkey); + CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Create() failed (ret=%ld)\r\n", __func__, ret); + + CFSTORE_EX1_LOG("WRITING%s", "\r\n"); + ctx->len = strlen(cfstore_ex3_kv_value); + ret = cfstore_drv->Write(ctx->hkey, cfstore_ex3_kv_value, &ctx->len); + CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Write() failed (ret=%ld)\r\n", __func__, ret); + + CFSTORE_EX1_TEST_ASSERT_MSG(ret == (int32_t) strlen(cfstore_ex3_kv_value), "%s:Error: Write() number of octets written (i.e. completion status (%ld)) != strlen(ctx->value)(%ld)\r\n", __func__, ret, (int32_t) strlen(cfstore_ex3_kv_value)); + CFSTORE_EX1_TEST_ASSERT_MSG(ret == (int32_t) ctx->len, "%s:Error: Write() number of octets written (i.e. completion status (%ld)) != updated value of len parameter (%ld)\r\n", __func__, ret, (int32_t) ctx->len); + + CFSTORE_EX1_LOG("CLOSING1%s", "\r\n"); + ret = cfstore_drv->Close(ctx->hkey); + CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Close() failed (ret=%ld)\r\n", __func__, ret); + + CFSTORE_EX1_LOG("FLUSHING1%s", "\r\n"); + ret = cfstore_drv->Flush(); + CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Flush() failed (ret=%ld)\r\n", __func__, ret); + + CFSTORE_EX1_LOG("OPENING%s", "\r\n"); + memset(&ctx->flags, 0, sizeof(ctx->flags)); + memset(&ctx->hkey, 0, CFSTORE_HANDLE_BUFSIZE); + ret = cfstore_drv->Open(cfstore_ex3_kv_name, ctx->flags, ctx->hkey); + CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Open() failed (ret=%ld)\r\n", __func__, ret); + + CFSTORE_EX1_LOG("READING1%s", "\r\n"); + ctx->len = CFSTORE_KEY_NAME_MAX_LENGTH; + memset(ctx->value, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); + ret = cfstore_drv->Read(ctx->hkey, ctx->value, &ctx->len); + CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Read() failed (ret=%ld)\r\n", __func__, ret); + + CFSTORE_EX1_TEST_ASSERT_MSG(ret == (int32_t) strlen(cfstore_ex3_kv_value), "%s:Error: Read() number of octets read (i.e. completion status (%ld)) != strlen(ctx->value)(%ld)\r\n", __func__, ret, (int32_t) strlen(cfstore_ex3_kv_value)); + CFSTORE_EX1_TEST_ASSERT_MSG(ret == (int32_t) ctx->len, "%s:Error: Read() number of octets read (i.e. completion status (%ld)) != updated value of len parameter (%ld)\r\n", __func__, ret, (int32_t) ctx->len); + CFSTORE_EX1_TEST_ASSERT_MSG(strncmp(ctx->value, cfstore_ex3_kv_value, strlen(cfstore_ex3_kv_value)) == 0, "%s:Error: the read value (%s) is not as expected (%s)\r\n", __func__, ctx->value, cfstore_ex3_kv_value); + + CFSTORE_EX1_LOG("RSEEKING%s", "\r\n"); + ret = cfstore_drv->Rseek(ctx->hkey, CFSTORE_EX1_RSEEK_OFFSET); + CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Rseek() failed (ret=%ld)\r\n", __func__, ret); + + CFSTORE_EX1_LOG("READING2%s", "\r\n"); + ctx->len = CFSTORE_KEY_NAME_MAX_LENGTH; + memset(ctx->value, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); + ret = cfstore_drv->Read(ctx->hkey, ctx->value, &ctx->len); + CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Read() failed (ret=%ld)\r\n", __func__, ret); + CFSTORE_EX1_TEST_ASSERT_MSG(ret == (int32_t) strlen(&cfstore_ex3_kv_value[CFSTORE_EX1_RSEEK_OFFSET]), "%s:Error: Read() number of octets read (i.e. completion status (%ld)) != strlen(ctx->value)(%ld)\r\n", __func__, ret, (int32_t) strlen(&cfstore_ex3_kv_value[CFSTORE_EX1_RSEEK_OFFSET])); + CFSTORE_EX1_TEST_ASSERT_MSG(ret == (int32_t) ctx->len, "%s:Error: Read() number of octets read (i.e. completion status (%ld)) != updated value of len parameter (%ld)\r\n", __func__, ret, (int32_t) ctx->len); + CFSTORE_EX1_TEST_ASSERT_MSG(strncmp(ctx->value, &cfstore_ex3_kv_value[CFSTORE_EX1_RSEEK_OFFSET], strlen(&cfstore_ex3_kv_value[CFSTORE_EX1_RSEEK_OFFSET])) == 0, "%s:Error: the read value (%s) is not as expected (%s)\r\n", __func__, ctx->value, &cfstore_ex3_kv_value[CFSTORE_EX1_RSEEK_OFFSET]); + + CFSTORE_EX1_LOG("CLOSING2%s", "\r\n"); + ret = cfstore_drv->Close(ctx->hkey); + CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Close() failed (ret=%ld)\r\n", __func__, ret); + + CFSTORE_EX1_LOG("FINDING1%s", "\r\n"); + ret = cfstore_drv->Find("*", ctx->hkey_next, ctx->hkey_prev); + CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Find() failed (ret=%ld)\r\n", __func__, ret); + + CFSTORE_EX1_LOG("GETTING_KEY_NAME%s", "\r\n"); + ctx->len = CFSTORE_KEY_NAME_MAX_LENGTH; + memset(ctx->value, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); + ret = cfstore_drv->GetKeyName(ctx->hkey_prev, ctx->value, (uint8_t *) &ctx->len); + CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: GetKeyName() failed (ret=%ld)\r\n", __func__, ret); + CFSTORE_EX1_TEST_ASSERT_MSG(((int32_t) ctx->len == ((int32_t) strlen(cfstore_ex3_kv_name) + 1)), "%s:Error: GetKeyName() updated value of len parameter (%ld) != strlen(cfstore_ex3_kv_name) (%ld) (\r\n", __func__, (int32_t) ctx->len, (int32_t) strlen(cfstore_ex3_kv_name)); + CFSTORE_EX1_TEST_ASSERT_MSG(strncmp(ctx->value, cfstore_ex3_kv_name, strlen(cfstore_ex3_kv_name)) == 0, "%s:Error: the key name (%s) is not as expected (%s)\r\n", __func__, ctx->value, cfstore_ex3_kv_name); + + CFSTORE_EX1_LOG("GETTING_VALUE_LEN%s", "\r\n"); + ctx->len = CFSTORE_KEY_NAME_MAX_LENGTH; + ret = cfstore_drv->GetValueLen(ctx->hkey_prev, &ctx->len); + CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: GetValueLen() failed (ret=%ld)\r\n", __func__, ret); + CFSTORE_EX1_TEST_ASSERT_MSG((int32_t) ctx->len == (int32_t) strlen(cfstore_ex3_kv_value), "%s:Error: GetValueLen() updated value of len parameter (%ld) != strlen(cfstore_ex3_kv_value)(%ld) \r\n", __func__, (int32_t) ctx->len, (int32_t) strlen(cfstore_ex3_kv_value)); + + CFSTORE_EX1_LOG("DELETING%s", "\r\n"); + ret = cfstore_drv->Delete(ctx->hkey_prev); + CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Close() failed (ret=%ld)\r\n", __func__, ret); + CFSTORE_HANDLE_SWAP(ctx->hkey_prev, ctx->hkey_next); + + CFSTORE_EX1_LOG("FINDING2%s", "\r\n"); + ret = cfstore_drv->Find("*", ctx->hkey_next, ctx->hkey_prev); + CFSTORE_EX1_TEST_ASSERT_MSG(ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND, "%s:Error: Find() failed to return expected value of ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND (ret=%ld)\r\n", __func__, ret); + + CFSTORE_EX1_LOG("FLUSHING2%s", "\r\n"); + ret = cfstore_drv->Flush(); + CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error:2: Flush() failed (ret=%ld)\r\n", __func__, ret); + + CFSTORE_EX1_LOG("UNINITIALIZING%s", "\r\n"); + ret = cfstore_drv->Uninitialize(); + CFSTORE_EX1_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Uninitialize() should return ret >= 0 for synch mode(ret=%ld)\r\n", __func__, ret); + CFSTORE_EX1_LOG("***************%s", "\r\n"); + CFSTORE_EX1_LOG("*** SUCCESS ***%s", "\r\n"); + CFSTORE_EX1_LOG("***************%s", "\r\n"); + return; } static control_t cfstore_example3_app_start(const size_t call_count) { - cfstore_example3_ctx_t* ctx = &cfstore_example3_ctx_g; + cfstore_example3_ctx_t *ctx = &cfstore_example3_ctx_g; (void) call_count; @@ -268,9 +266,9 @@ static control_t cfstore_example3_app_start(const size_t call_count) ctx->hkey_prev = ctx->hkey_prev_buf; ctx->caps = cfstore_drv->GetCapabilities(); CFSTORE_EX1_LOG("%s:INITIALIZING: caps.asynchronous_ops=%lu\n", __func__, ctx->caps.asynchronous_ops); - if(ctx->caps.asynchronous_ops == 1){ - /* This is a sync mode only test. If this test is not built for sync mode, then skip testing return true - * This means the test will conveniently pass when run in CI as part of async mode testing */ + if (ctx->caps.asynchronous_ops == 1) { + /* This is a sync mode only test. If this test is not built for sync mode, then skip testing return true + * This means the test will conveniently pass when run in CI as part of async mode testing */ CFSTORE_EX1_LOG("*** Skipping test as binary built for flash journal async mode, and this test is sync-only%s", "\n"); return CaseNext; } @@ -300,10 +298,10 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("EXAMPLE3_test_00", cfstore_example3_test_00), - Case("EXAMPLE3_test_01_start", cfstore_example3_app_start), + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("EXAMPLE3_test_00", cfstore_example3_test_00), + Case("EXAMPLE3_test_01_start", cfstore_example3_app_start), }; @@ -320,7 +318,7 @@ int main() #else // CFSTORE_EXAMPLE3_APP // stand alone Configuration-Store-Example -void app_start(int argc __unused, char** argv __unused) +void app_start(int argc __unused, char **argv __unused) { cfstore_example3_app_start(0); } diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/example4/example4.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/example4/example4.cpp index 2466dd4cab8..faa1fce58f8 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/example4/example4.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/example4/example4.cpp @@ -74,9 +74,9 @@ static control_t cfstore_example4_test_00(const size_t call_count) /* initialise the context */ caps = gCfStoreDriver->GetCapabilities(); CFSTORE_LOG("%s:INITIALIZING: caps.asynchronous_ops=%lu\n", __func__, caps.asynchronous_ops); - if(caps.asynchronous_ops == 1){ - /* This is a sync mode only test. If this test is not built for sync mode, then skip testing return true - * This means the test will conveniently pass when run in CI as part of async mode testing */ + if (caps.asynchronous_ops == 1) { + /* This is a sync mode only test. If this test is not built for sync mode, then skip testing return true + * This means the test will conveniently pass when run in CI as part of async mode testing */ CFSTORE_LOG("*** Skipping test as binary built for flash journal async mode, and this test is sync-only%s", "\n"); return CaseNext; } @@ -99,32 +99,32 @@ static const PvKeyValue_t testDataKeyValue[] = { static int32_t CreateKeyValueStore( - const char *keyName, - const char *data, - ARM_CFSTORE_SIZE *dataLength, - ARM_CFSTORE_KEYDESC *keyDesc) + const char *keyName, + const char *data, + ARM_CFSTORE_SIZE *dataLength, + ARM_CFSTORE_KEYDESC *keyDesc) { - int32_t cfsStatus = ARM_DRIVER_ERROR; - ARM_CFSTORE_SIZE valueLength = 0; - ARM_CFSTORE_HANDLE_INIT(hkey); + int32_t cfsStatus = ARM_DRIVER_ERROR; + ARM_CFSTORE_SIZE valueLength = 0; + ARM_CFSTORE_HANDLE_INIT(hkey); - valueLength = *dataLength; - cfsStatus = gCfStoreDriver->Create(keyName, valueLength, keyDesc, hkey); + valueLength = *dataLength; + cfsStatus = gCfStoreDriver->Create(keyName, valueLength, keyDesc, hkey); CFSTORE_TEST_UTEST_MESSAGE(cfstore_example4_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Create() failed (cfsStatus=%d)\n", __func__, (int) cfsStatus); TEST_ASSERT_MESSAGE(cfsStatus >= ARM_DRIVER_OK, cfstore_example4_utest_msg_g); - valueLength = *dataLength; - cfsStatus = gCfStoreDriver->Write(hkey, data, &valueLength); + valueLength = *dataLength; + cfsStatus = gCfStoreDriver->Write(hkey, data, &valueLength); CFSTORE_TEST_UTEST_MESSAGE(cfstore_example4_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Write() failed (cfsStatus=%d)\n", __func__, (int) cfsStatus); TEST_ASSERT_MESSAGE(cfsStatus >= ARM_DRIVER_OK, cfstore_example4_utest_msg_g); CFSTORE_TEST_UTEST_MESSAGE(cfstore_example4_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: valueLength != *dataLength\n", __func__); TEST_ASSERT_MESSAGE(valueLength == *dataLength, cfstore_example4_utest_msg_g); - cfsStatus = gCfStoreDriver->Close(hkey); + cfsStatus = gCfStoreDriver->Close(hkey); CFSTORE_TEST_UTEST_MESSAGE(cfstore_example4_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Close() failed (cfsStatus=%d)\n", __func__, (int) cfsStatus); TEST_ASSERT_MESSAGE(cfsStatus >= ARM_DRIVER_OK, cfstore_example4_utest_msg_g); - cfsStatus = gCfStoreDriver->Flush(); + cfsStatus = gCfStoreDriver->Flush(); CFSTORE_TEST_UTEST_MESSAGE(cfstore_example4_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Flush() failed (cfsStatus=%d)\n", __func__, (int) cfsStatus); TEST_ASSERT_MESSAGE(cfsStatus >= ARM_DRIVER_OK, cfstore_example4_utest_msg_g); @@ -134,49 +134,49 @@ static int32_t CreateKeyValueStore( static control_t cfstore_example4_test_01(const size_t call_count) { - int32_t cfsStatus = ARM_DRIVER_ERROR; - ARM_CFSTORE_KEYDESC kdesc; - ARM_CFSTORE_SIZE valueLen; - ARM_CFSTORE_FMODE flags; - ARM_CFSTORE_HANDLE_INIT(hkey); + int32_t cfsStatus = ARM_DRIVER_ERROR; + ARM_CFSTORE_KEYDESC kdesc; + ARM_CFSTORE_SIZE valueLen; + ARM_CFSTORE_FMODE flags; + ARM_CFSTORE_HANDLE_INIT(hkey); - (void) call_count; - PvMemSet(&kdesc, 0, sizeof(kdesc)); + (void) call_count; + PvMemSet(&kdesc, 0, sizeof(kdesc)); - kdesc.drl = ARM_RETENTION_NVM; - valueLen = PvStrLen(testDataKeyValue[0].value); + kdesc.drl = ARM_RETENTION_NVM; + valueLen = PvStrLen(testDataKeyValue[0].value); - cfsStatus = gCfStoreDriver->Initialize(NULL, NULL); + cfsStatus = gCfStoreDriver->Initialize(NULL, NULL); CFSTORE_TEST_UTEST_MESSAGE(cfstore_example4_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Initialize() failed (cfsStatus=%d)\n", __func__, (int) cfsStatus); TEST_ASSERT_MESSAGE(cfsStatus >= ARM_DRIVER_OK, cfstore_example4_utest_msg_g); - cfsStatus = CreateKeyValueStore(testDataKeyValue[0].key_name, testDataKeyValue[0].value, &valueLen, &kdesc); + cfsStatus = CreateKeyValueStore(testDataKeyValue[0].key_name, testDataKeyValue[0].value, &valueLen, &kdesc); CFSTORE_TEST_UTEST_MESSAGE(cfstore_example4_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: CreateKeyValueStore() failed (cfsStatus=%d)\n", __func__, (int) cfsStatus); TEST_ASSERT_MESSAGE(cfsStatus >= ARM_DRIVER_OK, cfstore_example4_utest_msg_g); - PvMemSet(&flags, 0, sizeof(flags)); + PvMemSet(&flags, 0, sizeof(flags)); - cfsStatus = gCfStoreDriver->Open(testDataKeyValue[0].key_name, flags, hkey); + cfsStatus = gCfStoreDriver->Open(testDataKeyValue[0].key_name, flags, hkey); CFSTORE_TEST_UTEST_MESSAGE(cfstore_example4_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Open() failed (cfsStatus=%d)\n", __func__, (int) cfsStatus); TEST_ASSERT_MESSAGE(cfsStatus >= ARM_DRIVER_OK, cfstore_example4_utest_msg_g); - cfsStatus = gCfStoreDriver->Delete(hkey); + cfsStatus = gCfStoreDriver->Delete(hkey); CFSTORE_TEST_UTEST_MESSAGE(cfstore_example4_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Delete() failed (cfsStatus=%d)\n", __func__, (int) cfsStatus); TEST_ASSERT_MESSAGE(cfsStatus >= ARM_DRIVER_OK, cfstore_example4_utest_msg_g); - cfsStatus = gCfStoreDriver->Close(hkey); + cfsStatus = gCfStoreDriver->Close(hkey); CFSTORE_TEST_UTEST_MESSAGE(cfstore_example4_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Close() failed (cfsStatus=%d)\n", __func__, (int) cfsStatus); TEST_ASSERT_MESSAGE(cfsStatus >= ARM_DRIVER_OK, cfstore_example4_utest_msg_g); - cfsStatus = gCfStoreDriver->Flush(); + cfsStatus = gCfStoreDriver->Flush(); CFSTORE_TEST_UTEST_MESSAGE(cfstore_example4_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Flush() failed (cfsStatus=%d)\n", __func__, (int) cfsStatus); TEST_ASSERT_MESSAGE(cfsStatus >= ARM_DRIVER_OK, cfstore_example4_utest_msg_g); - cfsStatus = gCfStoreDriver->Uninitialize(); + cfsStatus = gCfStoreDriver->Uninitialize(); CFSTORE_TEST_UTEST_MESSAGE(cfstore_example4_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Uninitialize() failed (cfsStatus=%d)\n", __func__, (int) cfsStatus); TEST_ASSERT_MESSAGE(cfsStatus >= ARM_DRIVER_OK, cfstore_example4_utest_msg_g); - return CaseNext; + return CaseNext; } #endif // STORAGE_DRIVER_CONFIG_HARDWARE_MTD_ASYNC_OPS @@ -189,11 +189,11 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("EXAMPLE4_test_00", cfstore_example4_test_00), + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("EXAMPLE4_test_00", cfstore_example4_test_00), #if defined STORAGE_DRIVER_CONFIG_HARDWARE_MTD_ASYNC_OPS && STORAGE_DRIVER_CONFIG_HARDWARE_MTD_ASYNC_OPS==0 - Case("EXAMPLE4_test_01", cfstore_example4_test_01), + Case("EXAMPLE4_test_01", cfstore_example4_test_01), #endif // STORAGE_DRIVER_CONFIG_HARDWARE_MTD_ASYNC_OPS }; diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/example5/example5.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/example5/example5.cpp index 267b15acfed..95a6d6bf698 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/example5/example5.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/example5/example5.cpp @@ -110,8 +110,7 @@ using namespace utest::v1; }while(0); -const char* cfstore_ex5_opcode_str[] = -{ +const char *cfstore_ex5_opcode_str[] = { "UNDEFINED", "CFSTORE_OPCODE_CLOSE", "CFSTORE_OPCODE_CREATE", @@ -131,13 +130,12 @@ const char* cfstore_ex5_opcode_str[] = "CFSTORE_OPCODE_MAX" }; -const char* cfstore_ex5_kv_name = "basement.medicine.pavement.government.trenchcoat.off.cough.off.kid.did.when.again.alleyway.friend.cap.pen.dollarbills.ten.foot.soot.put.but.anyway.say.May.DA.kid.did.toes.bows.those.hose.nose.clothes.man.blows.well.well"; -const char* cfstore_ex5_kv_value = "TheRollingStone"; +const char *cfstore_ex5_kv_name = "basement.medicine.pavement.government.trenchcoat.off.cough.off.kid.did.when.again.alleyway.friend.cap.pen.dollarbills.ten.foot.soot.put.but.anyway.say.May.DA.kid.did.toes.bows.those.hose.nose.clothes.man.blows.well.well"; +const char *cfstore_ex5_kv_value = "TheRollingStone"; #define CFSTORE_EX5_RSEEK_OFFSET 10 /* offset to S of Stone */ /// @cond CFSTORE_DOXYGEN_DISABLE -typedef struct cfstore_EXAMPLE5_ctx_t -{ +typedef struct cfstore_EXAMPLE5_ctx_t { ARM_CFSTORE_CAPABILITIES caps; uint8_t hkey[CFSTORE_HANDLE_BUFSIZE]; uint8_t hkey_next_buf[CFSTORE_HANDLE_BUFSIZE]; @@ -147,7 +145,7 @@ typedef struct cfstore_EXAMPLE5_ctx_t ARM_CFSTORE_SIZE len; ARM_CFSTORE_KEYDESC kdesc; ARM_CFSTORE_FMODE flags; - char value[CFSTORE_KEY_NAME_MAX_LENGTH+1]; + char value[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; } cfstore_EXAMPLE5_ctx_t; static cfstore_EXAMPLE5_ctx_t cfstore_EXAMPLE5_ctx_g; @@ -181,94 +179,94 @@ int32_t cfstore_test_startup(void) } -static void cfstore_ex5_test_01(cfstore_EXAMPLE5_ctx_t* ctx) +static void cfstore_ex5_test_01(cfstore_EXAMPLE5_ctx_t *ctx) { int32_t ret; - CFSTORE_EX5_LOG("INITIALIZING1%s", "\r\n"); - ret = cfstore_drv->Initialize(NULL, NULL); - CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Initialize() should return ret >= 0 for async/synch modes(ret=%ld)\r\n", __func__, ret); + CFSTORE_EX5_LOG("INITIALIZING1%s", "\r\n"); + ret = cfstore_drv->Initialize(NULL, NULL); + CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Initialize() should return ret >= 0 for async/synch modes(ret=%ld)\r\n", __func__, ret); - CFSTORE_EX5_LOG("CREATING%s", "\r\n"); - memset(&ctx->kdesc, 0, sizeof(ARM_CFSTORE_KEYDESC)); - ctx->kdesc.drl = ARM_RETENTION_NVM; - ctx->len = strlen(cfstore_ex5_kv_value); - ret = cfstore_drv->Create(cfstore_ex5_kv_name, ctx->len, &ctx->kdesc, ctx->hkey); - CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Create() failed (ret=%ld)\r\n", __func__, ret); + CFSTORE_EX5_LOG("CREATING%s", "\r\n"); + memset(&ctx->kdesc, 0, sizeof(ARM_CFSTORE_KEYDESC)); + ctx->kdesc.drl = ARM_RETENTION_NVM; + ctx->len = strlen(cfstore_ex5_kv_value); + ret = cfstore_drv->Create(cfstore_ex5_kv_name, ctx->len, &ctx->kdesc, ctx->hkey); + CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Create() failed (ret=%ld)\r\n", __func__, ret); - CFSTORE_EX5_LOG("WRITING%s", "\r\n"); - ctx->len = strlen(cfstore_ex5_kv_value); - ret = cfstore_drv->Write(ctx->hkey, cfstore_ex5_kv_value, &ctx->len); - CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Write() failed (ret=%ld)\r\n", __func__, ret); + CFSTORE_EX5_LOG("WRITING%s", "\r\n"); + ctx->len = strlen(cfstore_ex5_kv_value); + ret = cfstore_drv->Write(ctx->hkey, cfstore_ex5_kv_value, &ctx->len); + CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Write() failed (ret=%ld)\r\n", __func__, ret); - CFSTORE_EX5_TEST_ASSERT_MSG(ret == (int32_t) strlen(cfstore_ex5_kv_value), "%s:Error: Write() number of octets written (i.e. completion status (%ld)) != strlen(ctx->value)(%ld)\r\n", __func__, ret, (int32_t) strlen(cfstore_ex5_kv_value)); - CFSTORE_EX5_TEST_ASSERT_MSG(ret == (int32_t) ctx->len, "%s:Error: Write() number of octets written (i.e. completion status (%ld)) != updated value of len parameter (%ld)\r\n", __func__, ret, (int32_t) ctx->len); + CFSTORE_EX5_TEST_ASSERT_MSG(ret == (int32_t) strlen(cfstore_ex5_kv_value), "%s:Error: Write() number of octets written (i.e. completion status (%ld)) != strlen(ctx->value)(%ld)\r\n", __func__, ret, (int32_t) strlen(cfstore_ex5_kv_value)); + CFSTORE_EX5_TEST_ASSERT_MSG(ret == (int32_t) ctx->len, "%s:Error: Write() number of octets written (i.e. completion status (%ld)) != updated value of len parameter (%ld)\r\n", __func__, ret, (int32_t) ctx->len); - CFSTORE_EX5_LOG("CLOSING1%s", "\r\n"); - ret = cfstore_drv->Close(ctx->hkey); - CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Close() failed (ret=%ld)\r\n", __func__, ret); + CFSTORE_EX5_LOG("CLOSING1%s", "\r\n"); + ret = cfstore_drv->Close(ctx->hkey); + CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Close() failed (ret=%ld)\r\n", __func__, ret); - CFSTORE_EX5_LOG("FLUSHING1%s", "\r\n"); - ret = cfstore_drv->Flush(); - CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Flush() failed (ret=%ld)\r\n", __func__, ret); + CFSTORE_EX5_LOG("FLUSHING1%s", "\r\n"); + ret = cfstore_drv->Flush(); + CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Flush() failed (ret=%ld)\r\n", __func__, ret); #ifdef CFSTORE_CONFIG_BACKEND_FLASH_ENABLED - /* CFSTORE_CONFIG_BACKEND_FLASH_ENABLED => flash storage support present. - * if this was not the case (i.e. cfstore running SRAM in memory mode) then - * we dont compile in the Uninitialize()/Initialize() as the - * Uninitialize() clears the sram */ - CFSTORE_EX5_LOG("UNINITIALIZING1%s", "\r\n"); - ret = cfstore_drv->Uninitialize(); - CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Uninitialize() should return ret >= 0 for synch mode(ret=%ld)\r\n", __func__, ret); - - CFSTORE_EX5_LOG("INITIALIZING2%s", "\r\n"); - ret = cfstore_drv->Initialize(NULL, NULL); - CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Initialize() should return ret >= 0 for async/synch modes(ret=%ld)\r\n", __func__, ret); + /* CFSTORE_CONFIG_BACKEND_FLASH_ENABLED => flash storage support present. + * if this was not the case (i.e. cfstore running SRAM in memory mode) then + * we dont compile in the Uninitialize()/Initialize() as the + * Uninitialize() clears the sram */ + CFSTORE_EX5_LOG("UNINITIALIZING1%s", "\r\n"); + ret = cfstore_drv->Uninitialize(); + CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Uninitialize() should return ret >= 0 for synch mode(ret=%ld)\r\n", __func__, ret); + + CFSTORE_EX5_LOG("INITIALIZING2%s", "\r\n"); + ret = cfstore_drv->Initialize(NULL, NULL); + CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Initialize() should return ret >= 0 for async/synch modes(ret=%ld)\r\n", __func__, ret); #endif - CFSTORE_EX5_LOG("OPENING%s", "\r\n"); - memset(&ctx->flags, 0, sizeof(ctx->flags)); - memset(&ctx->hkey, 0, CFSTORE_HANDLE_BUFSIZE); - ret = cfstore_drv->Open(cfstore_ex5_kv_name, ctx->flags, ctx->hkey); - CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Open() failed (ret=%ld)\r\n", __func__, ret); - - CFSTORE_EX5_LOG("DELETE1%s", "\r\n"); - ctx->len = CFSTORE_KEY_NAME_MAX_LENGTH; - memset(ctx->value, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); - ret = cfstore_drv->Delete(ctx->hkey); - CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Delete() failed (ret=%ld)\r\n", __func__, ret); - - CFSTORE_EX5_LOG("CLOSING2%s", "\r\n"); - ret = cfstore_drv->Close(ctx->hkey); - CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Close() failed (ret=%ld)\r\n", __func__, ret); - - CFSTORE_EX5_LOG("FLUSHING3%s", "\r\n"); - ret = cfstore_drv->Flush(); - CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Flush() failed (ret=%ld)\r\n", __func__, ret); - - CFSTORE_EX5_LOG("OPEN2 %s", "\r\n"); - memset(&ctx->flags, 0, sizeof(ctx->flags)); - memset(&ctx->hkey, 0, CFSTORE_HANDLE_BUFSIZE); - ret = cfstore_drv->Open(cfstore_ex5_kv_name, ctx->flags, ctx->hkey); - CFSTORE_EX5_TEST_ASSERT_MSG(ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND, "%s:Error: Find() failed to return expected value of ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND (ret=%ld)\r\n", __func__, ret); - - CFSTORE_EX5_LOG("FLUSHING2%s", "\r\n"); - ret = cfstore_drv->Flush(); - CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error:2: Flush() failed (ret=%ld)\r\n", __func__, ret); - - CFSTORE_EX5_LOG("UNINITIALIZING3%s", "\r\n"); - ret = cfstore_drv->Uninitialize(); - CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Uninitialize() should return ret >= 0 for synch mode(ret=%ld)\r\n", __func__, ret); - CFSTORE_EX5_LOG("***************%s", "\r\n"); - CFSTORE_EX5_LOG("*** SUCCESS ***%s", "\r\n"); - CFSTORE_EX5_LOG("***************%s", "\r\n"); - return; + CFSTORE_EX5_LOG("OPENING%s", "\r\n"); + memset(&ctx->flags, 0, sizeof(ctx->flags)); + memset(&ctx->hkey, 0, CFSTORE_HANDLE_BUFSIZE); + ret = cfstore_drv->Open(cfstore_ex5_kv_name, ctx->flags, ctx->hkey); + CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Open() failed (ret=%ld)\r\n", __func__, ret); + + CFSTORE_EX5_LOG("DELETE1%s", "\r\n"); + ctx->len = CFSTORE_KEY_NAME_MAX_LENGTH; + memset(ctx->value, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); + ret = cfstore_drv->Delete(ctx->hkey); + CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Delete() failed (ret=%ld)\r\n", __func__, ret); + + CFSTORE_EX5_LOG("CLOSING2%s", "\r\n"); + ret = cfstore_drv->Close(ctx->hkey); + CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Close() failed (ret=%ld)\r\n", __func__, ret); + + CFSTORE_EX5_LOG("FLUSHING3%s", "\r\n"); + ret = cfstore_drv->Flush(); + CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Flush() failed (ret=%ld)\r\n", __func__, ret); + + CFSTORE_EX5_LOG("OPEN2 %s", "\r\n"); + memset(&ctx->flags, 0, sizeof(ctx->flags)); + memset(&ctx->hkey, 0, CFSTORE_HANDLE_BUFSIZE); + ret = cfstore_drv->Open(cfstore_ex5_kv_name, ctx->flags, ctx->hkey); + CFSTORE_EX5_TEST_ASSERT_MSG(ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND, "%s:Error: Find() failed to return expected value of ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND (ret=%ld)\r\n", __func__, ret); + + CFSTORE_EX5_LOG("FLUSHING2%s", "\r\n"); + ret = cfstore_drv->Flush(); + CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error:2: Flush() failed (ret=%ld)\r\n", __func__, ret); + + CFSTORE_EX5_LOG("UNINITIALIZING3%s", "\r\n"); + ret = cfstore_drv->Uninitialize(); + CFSTORE_EX5_TEST_ASSERT_MSG(ret >= ARM_DRIVER_OK, "%s:Error: Uninitialize() should return ret >= 0 for synch mode(ret=%ld)\r\n", __func__, ret); + CFSTORE_EX5_LOG("***************%s", "\r\n"); + CFSTORE_EX5_LOG("*** SUCCESS ***%s", "\r\n"); + CFSTORE_EX5_LOG("***************%s", "\r\n"); + return; } static control_t cfstore_EXAMPLE5_app_start(const size_t call_count) { int32_t ret = ARM_DRIVER_ERROR; - cfstore_EXAMPLE5_ctx_t* ctx = &cfstore_EXAMPLE5_ctx_g; + cfstore_EXAMPLE5_ctx_t *ctx = &cfstore_EXAMPLE5_ctx_g; (void) call_count; @@ -278,9 +276,9 @@ static control_t cfstore_EXAMPLE5_app_start(const size_t call_count) ctx->hkey_prev = ctx->hkey_prev_buf; ctx->caps = cfstore_drv->GetCapabilities(); CFSTORE_EX5_LOG("%s:INITIALIZING: caps.asynchronous_ops=%lu\n", __func__, ctx->caps.asynchronous_ops); - if(ctx->caps.asynchronous_ops){ - /* This is a sync mode only test. If this test is not built for sync mode, then skip testing return true - * This means the test will conveniently pass when run in CI as part of async mode testing */ + if (ctx->caps.asynchronous_ops) { + /* This is a sync mode only test. If this test is not built for sync mode, then skip testing return true + * This means the test will conveniently pass when run in CI as part of async mode testing */ CFSTORE_EX5_LOG("*** Skipping test as binary built for flash journal async mode, and this test is sync-only%s", "\n"); return CaseNext; } @@ -301,9 +299,9 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("EXAMPLE5_test_01_start", cfstore_EXAMPLE5_app_start), + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("EXAMPLE5_test_01_start", cfstore_EXAMPLE5_app_start), }; @@ -321,7 +319,7 @@ int main() #else // CFSTORE_EXAMPLE5_APP // stand alone Configuration-Store-Example -void app_start(int argc __unused, char** argv __unused) +void app_start(int argc __unused, char **argv __unused) { cfstore_EXAMPLE5_app_start(0); } diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/find/find.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/find/find.cpp index 7ef3075de9c..b91c6f54448 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/find/find.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/find/find.cpp @@ -81,8 +81,8 @@ control_t cfstore_find_test_01(const size_t call_count) } -/** @brief test to call cfstore_find() with key_name that in includes - * illegal characters +/** @brief test to call cfstore_find() with key_name that in includes + * illegal characters * - the character can be at the beginning of the key_name * - the character can be at the end of the key_name * - the character can be somewhere within the key_name string @@ -120,15 +120,15 @@ control_t cfstore_find_test_02(const size_t call_count) */ control_t cfstore_find_test_03_end(const size_t call_count) { - char* read_buf = NULL; - const uint8_t key_name_max_len = CFSTORE_KEY_NAME_MAX_LENGTH+1; + char *read_buf = NULL; + const uint8_t key_name_max_len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; char key_name_buf[key_name_max_len]; int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE len = 0; ARM_CFSTORE_SIZE max_len = 0; - cfstore_kv_data_t* node; - cfstore_kv_data_t* client_node = cfstore_test_init_1_data; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + cfstore_kv_data_t *node; + cfstore_kv_data_t *client_node = cfstore_test_init_1_data; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_KEYDESC kdesc; ARM_CFSTORE_HANDLE_INIT(prev); ARM_CFSTORE_HANDLE_INIT(next); @@ -136,20 +136,19 @@ control_t cfstore_find_test_03_end(const size_t call_count) CFSTORE_DBGLOG("%s:entered\r\n", __func__); (void) call_count; memset(&kdesc, 0, sizeof(kdesc)); - memset(key_name_buf, 0, CFSTORE_KEY_NAME_MAX_LENGTH+1); + memset(key_name_buf, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); /*scan for max length of value blob*/ node = client_node; - while(node->key_name != NULL) - { + while (node->key_name != NULL) { len = strlen(node->value); - if(len > max_len){ + if (len > max_len) { max_len = len; } node++; } max_len++; /* space for a terminating null, if required */ - read_buf = (char*) malloc(max_len); + read_buf = (char *) malloc(max_len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_find_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Failed to allocated read buffer \r\n", __func__); TEST_ASSERT_MESSAGE(read_buf != NULL, cfstore_find_utest_msg_g); @@ -160,8 +159,7 @@ control_t cfstore_find_test_03_end(const size_t call_count) /* now find and read back the key values */ ret = ARM_DRIVER_ERROR; node = client_node; - while(node->key_name != NULL) - { + while (node->key_name != NULL) { CFSTORE_DBGLOG("%s:About to find node (key_name=\"%s\", value=\"%s\")\r\n", __func__, node->key_name, node->value); ret = drv->Find(node->key_name, prev, next); CFSTORE_TEST_UTEST_MESSAGE(cfstore_find_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Failed to find node (key_name=\"%s\", value=\"%s\")\r\n", __func__, node->key_name, node->value); @@ -174,7 +172,7 @@ control_t cfstore_find_test_03_end(const size_t call_count) CFSTORE_TEST_UTEST_MESSAGE(cfstore_find_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to write key (key_name=\"%s\", value=\"%s\")\r\n", __func__, node->key_name, node->value); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_find_utest_msg_g); - if(len > 0) { + if (len > 0) { ret = drv->Read(next, read_buf, &len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_find_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to read value (key_name=\"%s\", value=\"%s\")\r\n", __func__, node->key_name, node->value); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_find_utest_msg_g); @@ -227,15 +225,15 @@ control_t cfstore_find_test_04(const size_t call_count) /** * @brief function to test whether a key name is valid, can be added to the - * cfstore and found by a wildcard string + * cfstore and found by a wildcard string * - * @param key_name - * name of the key to create in the store - * @param match - * string to use to try and find key_name in the cfstore - * @param should_find - * if true, then 'match' should find 'key_name' in the store - * if false, then 'match' should not find 'key_name' in the store + * @param key_name + * name of the key to create in the store + * @param match + * string to use to try and find key_name in the cfstore + * @param should_find + * if true, then 'match' should find 'key_name' in the store + * if false, then 'match' should not find 'key_name' in the store * * @return status code * ARM_DRIVER_OK, the test passed successfully @@ -246,7 +244,7 @@ static bool cfstore_find_key_name_validate(const char *key_name, const char *mat { bool bret = true; bool btest_status = false; - char* test_data = (char*) "test_data"; + char *test_data = (char *) "test_data"; int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE len = 0; ARM_CFSTORE_KEYDESC kdesc; @@ -257,30 +255,27 @@ static bool cfstore_find_key_name_validate(const char *key_name, const char *mat /* create */ kdesc.drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE; len = strlen(test_data); - ret = cfstore_test_create((const char*) key_name, test_data, &len, &kdesc); - if(ret < ARM_DRIVER_OK){ + ret = cfstore_test_create((const char *) key_name, test_data, &len, &kdesc); + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to create kv (key_name=%s.\r\n", "cfstore_find_test_05_ex", key_name); return ret; } ret = cfstore_test_kv_is_found(match, &bret); - if(ret < ARM_DRIVER_OK && ret != ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND){ + if (ret < ARM_DRIVER_OK && ret != ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { CFSTORE_ERRLOG("%s:Error: cfstore_test_kv_is_found() failed.\r\n", "cfstore_find_test_05_ex"); return ret; } /* dont not use any functions that require finding the created item as they may not work, * depending on the construction of the test key_name & match strings */ - if(should_find == bret) - { + if (should_find == bret) { CFSTORE_DBGLOG("%s:Success: Find() behaved as expected.\r\n", "cfstore_find_test_05_ex"); btest_status = true; - } - else - { + } else { CFSTORE_ERRLOG("cfstore_find_test_05_ex: Failed match on %s vs. %s\n", key_name, match); } /*delete using the actual name */ - ret = cfstore_test_delete((const char*) key_name); - if(ret < ARM_DRIVER_OK){ + ret = cfstore_test_delete((const char *) key_name); + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to delete kv (key_name=%s)(ret=%d).\r\n", "cfstore_find_test_05_ex", key_name, (int)ret); } return btest_status; @@ -289,23 +284,23 @@ static bool cfstore_find_key_name_validate(const char *key_name, const char *mat /// @cond CFSTORE_DOXYGEN_DISABLE typedef struct cfstore_find_key_name_validate_t { - const char* key_name; - const char* match; + const char *key_name; + const char *match; uint32_t f_allowed : 1; } cfstore_find_key_name_validate_t; cfstore_find_key_name_validate_t cfstore_find_test_05_data[] = { - { "yotta.hello-world.animal{wobbly-dog}{foot}backLeft", "yotta.hello-world.animal{*}{foot}backLeft", true}, - { "yotta.hello-world.animal{wobbly-dog}{foot}backLeft", "yotta.hello-world.animal{wobbly-dog}{*}backLeft", true}, - { "yotta.hello-world.animal{wobbly-dog}{foot}backLeft", "yotta.hello-world.animal{wobbly-dog}{*}*", true}, - { "yotta.hello-world.animal{1}{foot}backLeft", "yotta.hello-world.animal{?}{foot}backLeft", false}, - { "xyz", "xyz", true}, - { "xyzijkXYZ", "XYZ", false}, - { "xyzijkXYZ", "*XYZ", true}, - { "xyzijkXYZ", "xyz*XYZ", true}, - { "xyzijkXYZ", "*yz*XYZ", true}, - { "xyzijkXYZ", "*ijk*", true}, - { NULL, NULL, false}, + { "yotta.hello-world.animal{wobbly-dog}{foot}backLeft", "yotta.hello-world.animal{*}{foot}backLeft", true}, + { "yotta.hello-world.animal{wobbly-dog}{foot}backLeft", "yotta.hello-world.animal{wobbly-dog}{*}backLeft", true}, + { "yotta.hello-world.animal{wobbly-dog}{foot}backLeft", "yotta.hello-world.animal{wobbly-dog}{*}*", true}, + { "yotta.hello-world.animal{1}{foot}backLeft", "yotta.hello-world.animal{?}{foot}backLeft", false}, + { "xyz", "xyz", true}, + { "xyzijkXYZ", "XYZ", false}, + { "xyzijkXYZ", "*XYZ", true}, + { "xyzijkXYZ", "xyz*XYZ", true}, + { "xyzijkXYZ", "*yz*XYZ", true}, + { "xyzijkXYZ", "*ijk*", true}, + { NULL, NULL, false}, }; /// @endcond @@ -319,13 +314,12 @@ control_t cfstore_find_test_05_end(const size_t call_count) { bool ret = false; int32_t ret32 = ARM_DRIVER_ERROR; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; - cfstore_find_key_name_validate_t* node = cfstore_find_test_05_data; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; + cfstore_find_key_name_validate_t *node = cfstore_find_test_05_data; (void) call_count; - while(node->key_name != NULL) - { + while (node->key_name != NULL) { ret = cfstore_find_key_name_validate(node->key_name, node->match, node->f_allowed); CFSTORE_TEST_UTEST_MESSAGE(cfstore_find_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: test failed (ret=%d)\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret == true, cfstore_find_utest_msg_g); @@ -355,26 +349,26 @@ control_t cfstore_find_test_05_end(const size_t call_count) /* table 1: to initialise cfstore with CFSTORE_CREATE_TEST_01_TABLE_MID_ENTRY_01 */ static cfstore_kv_data_t cfstore_find_test_06_data[] = { - CFSTORE_FIND_TEST_06_ENTRY_NOMATCH_01, - CFSTORE_FIND_TEST_06_ENTRY_NOMATCH_02, - CFSTORE_FIND_TEST_06_ENTRY_MATCH_03, - CFSTORE_FIND_TEST_06_ENTRY_NOMATCH_04, - CFSTORE_FIND_TEST_06_ENTRY_MATCH_05, - CFSTORE_FIND_TEST_06_ENTRY_NOMATCH_06, - CFSTORE_FIND_TEST_06_ENTRY_MATCH_07, - CFSTORE_FIND_TEST_06_ENTRY_NOMATCH_08, - CFSTORE_FIND_TEST_06_ENTRY_MATCH_09, - CFSTORE_FIND_TEST_06_ENTRY_NOMATCH_10, - CFSTORE_FIND_TEST_06_ENTRY_NOMATCH_11, - { NULL, NULL}, + CFSTORE_FIND_TEST_06_ENTRY_NOMATCH_01, + CFSTORE_FIND_TEST_06_ENTRY_NOMATCH_02, + CFSTORE_FIND_TEST_06_ENTRY_MATCH_03, + CFSTORE_FIND_TEST_06_ENTRY_NOMATCH_04, + CFSTORE_FIND_TEST_06_ENTRY_MATCH_05, + CFSTORE_FIND_TEST_06_ENTRY_NOMATCH_06, + CFSTORE_FIND_TEST_06_ENTRY_MATCH_07, + CFSTORE_FIND_TEST_06_ENTRY_NOMATCH_08, + CFSTORE_FIND_TEST_06_ENTRY_MATCH_09, + CFSTORE_FIND_TEST_06_ENTRY_NOMATCH_10, + CFSTORE_FIND_TEST_06_ENTRY_NOMATCH_11, + { NULL, NULL}, }; static cfstore_kv_data_t cfstore_find_test_06_data_match_results[] = { - CFSTORE_FIND_TEST_06_ENTRY_MATCH_03, - CFSTORE_FIND_TEST_06_ENTRY_MATCH_05, - CFSTORE_FIND_TEST_06_ENTRY_MATCH_07, - CFSTORE_FIND_TEST_06_ENTRY_MATCH_09, - { NULL, NULL}, + CFSTORE_FIND_TEST_06_ENTRY_MATCH_03, + CFSTORE_FIND_TEST_06_ENTRY_MATCH_05, + CFSTORE_FIND_TEST_06_ENTRY_MATCH_07, + CFSTORE_FIND_TEST_06_ENTRY_MATCH_09, + { NULL, NULL}, }; /// @endcond @@ -388,32 +382,31 @@ static cfstore_kv_data_t cfstore_find_test_06_data_match_results[] = { */ control_t cfstore_find_test_06_end(const size_t call_count) { - const char* key_name_query = "0123456789abcdef0123456.y*"; - char key_name[CFSTORE_KEY_NAME_MAX_LENGTH+1]; - uint8_t len = CFSTORE_KEY_NAME_MAX_LENGTH+1; + const char *key_name_query = "0123456789abcdef0123456.y*"; + char key_name[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; + uint8_t len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; int32_t ret = ARM_DRIVER_ERROR; int32_t find_count = 0; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_HANDLE_INIT(next); ARM_CFSTORE_HANDLE_INIT(prev); - cfstore_kv_data_t* node = NULL; + cfstore_kv_data_t *node = NULL; ret = cfstore_test_create_table(cfstore_find_test_06_data); CFSTORE_TEST_UTEST_MESSAGE(cfstore_find_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Failed to add cfstore_find_test_06_data table data (ret=%d).\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_find_utest_msg_g); - while((ret = drv->Find(key_name_query, prev, next)) == ARM_DRIVER_OK) - { - len = CFSTORE_KEY_NAME_MAX_LENGTH+1; + while ((ret = drv->Find(key_name_query, prev, next)) == ARM_DRIVER_OK) { + len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; ret = drv->GetKeyName(next, key_name, &len); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("Error: failed to get key name%s", "\n"); break; } CFSTORE_LOG("%s:Found entry key_name=%s\n", __func__, key_name); node = cfstore_find_test_06_data_match_results; - while(node->key_name != NULL){ - if(strncmp(node->key_name, key_name, CFSTORE_KEY_NAME_MAX_LENGTH) == 0){ + while (node->key_name != NULL) { + if (strncmp(node->key_name, key_name, CFSTORE_KEY_NAME_MAX_LENGTH) == 0) { find_count++; break; } @@ -425,8 +418,8 @@ control_t cfstore_find_test_06_end(const size_t call_count) CFSTORE_HANDLE_SWAP(prev, next); } - CFSTORE_TEST_UTEST_MESSAGE(cfstore_find_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: find_count=%d doesnt match the number of entries in match table = %d.\n", __func__, (int) find_count, (int) (sizeof(cfstore_find_test_06_data_match_results)/sizeof(cfstore_kv_data_t))-1); - TEST_ASSERT_MESSAGE(find_count == (sizeof(cfstore_find_test_06_data_match_results)/sizeof(cfstore_kv_data_t))-1, cfstore_find_utest_msg_g); + CFSTORE_TEST_UTEST_MESSAGE(cfstore_find_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: find_count=%d doesnt match the number of entries in match table = %d.\n", __func__, (int) find_count, (int)(sizeof(cfstore_find_test_06_data_match_results) / sizeof(cfstore_kv_data_t)) - 1); + TEST_ASSERT_MESSAGE(find_count == (sizeof(cfstore_find_test_06_data_match_results) / sizeof(cfstore_kv_data_t)) - 1, cfstore_find_utest_msg_g); CFSTORE_TEST_UTEST_MESSAGE(cfstore_find_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: expected ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND, but ret = %d.\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND, cfstore_find_utest_msg_g); @@ -444,40 +437,39 @@ control_t cfstore_find_test_06_end(const size_t call_count) */ control_t cfstore_find_test_07_end(const size_t call_count) { - const char* key_name_query = "0123456789abcdef0123456.y*"; - char key_name[CFSTORE_KEY_NAME_MAX_LENGTH+1]; - uint8_t len = CFSTORE_KEY_NAME_MAX_LENGTH+1; + const char *key_name_query = "0123456789abcdef0123456.y*"; + char key_name[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; + uint8_t len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; int32_t ret = ARM_DRIVER_ERROR; int32_t find_count = 0; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_HANDLE_INIT(next); - cfstore_kv_data_t* node = NULL; + cfstore_kv_data_t *node = NULL; ret = cfstore_test_create_table(cfstore_find_test_06_data); CFSTORE_TEST_UTEST_MESSAGE(cfstore_find_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Failed to add cfstore_find_test_06_data table data (ret=%d).\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_find_utest_msg_g); - while(true) - { + while (true) { ret = drv->Find(key_name_query, NULL, next); - if(ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { + if (ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { /* no more attributes found matching search criteria.*/ - break; + break; } CFSTORE_TEST_UTEST_MESSAGE(cfstore_find_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Find() failed(ret=%d).\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_find_utest_msg_g); - len = CFSTORE_KEY_NAME_MAX_LENGTH+1; + len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; ret = drv->GetKeyName(next, key_name, &len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_find_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to get key name for next (ret=%d).\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_find_utest_msg_g); CFSTORE_LOG("%s:Found entry key_name=%s\n", __func__, key_name); node = cfstore_find_test_06_data_match_results; - while(node->key_name != NULL){ - if(strncmp(node->key_name, key_name, CFSTORE_KEY_NAME_MAX_LENGTH) == 0){ + while (node->key_name != NULL) { + if (strncmp(node->key_name, key_name, CFSTORE_KEY_NAME_MAX_LENGTH) == 0) { find_count++; break; } @@ -496,8 +488,8 @@ control_t cfstore_find_test_07_end(const size_t call_count) TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_find_utest_msg_g); } - CFSTORE_TEST_UTEST_MESSAGE(cfstore_find_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: find_count=%d doesnt match the number of entries in match table = %d.\n", __func__, (int) find_count, (int) (sizeof(cfstore_find_test_06_data_match_results)/sizeof(cfstore_kv_data_t))-1); - TEST_ASSERT_MESSAGE(find_count == (sizeof(cfstore_find_test_06_data_match_results)/sizeof(cfstore_kv_data_t))-1, cfstore_find_utest_msg_g); + CFSTORE_TEST_UTEST_MESSAGE(cfstore_find_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: find_count=%d doesnt match the number of entries in match table = %d.\n", __func__, (int) find_count, (int)(sizeof(cfstore_find_test_06_data_match_results) / sizeof(cfstore_kv_data_t)) - 1); + TEST_ASSERT_MESSAGE(find_count == (sizeof(cfstore_find_test_06_data_match_results) / sizeof(cfstore_kv_data_t)) - 1, cfstore_find_utest_msg_g); CFSTORE_TEST_UTEST_MESSAGE(cfstore_find_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: expected ret == ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND, but ret = %d.\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND, cfstore_find_utest_msg_g); @@ -517,20 +509,20 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("FIND_test_00", cfstore_find_test_00), - Case("FIND_test_01", cfstore_find_test_01), - Case("FIND_test_02", cfstore_find_test_02), - Case("FIND_test_03_start", cfstore_utest_default_start), - Case("FIND_test_03_end", cfstore_find_test_03_end), - Case("FIND_test_04", cfstore_find_test_04), - Case("FIND_test_05_start", cfstore_utest_default_start), - Case("FIND_test_05_end", cfstore_find_test_05_end), - Case("FIND_test_06_start", cfstore_utest_default_start), - Case("FIND_test_06_end", cfstore_find_test_06_end), - Case("FIND_test_07_start", cfstore_utest_default_start), - Case("FIND_test_07_end", cfstore_find_test_07_end), + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("FIND_test_00", cfstore_find_test_00), + Case("FIND_test_01", cfstore_find_test_01), + Case("FIND_test_02", cfstore_find_test_02), + Case("FIND_test_03_start", cfstore_utest_default_start), + Case("FIND_test_03_end", cfstore_find_test_03_end), + Case("FIND_test_04", cfstore_find_test_04), + Case("FIND_test_05_start", cfstore_utest_default_start), + Case("FIND_test_05_end", cfstore_find_test_05_end), + Case("FIND_test_06_start", cfstore_utest_default_start), + Case("FIND_test_06_end", cfstore_find_test_06_end), + Case("FIND_test_07_start", cfstore_utest_default_start), + Case("FIND_test_07_end", cfstore_find_test_07_end), }; diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/find2/find2.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/find2/find2.cpp index 640470fbbb5..792e03144d0 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/find2/find2.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/find2/find2.cpp @@ -86,71 +86,71 @@ static control_t cfstore_find2_test_00(const size_t call_count) static control_t cfstore_find2_test_01(const size_t call_count) { - char keyBuffer[128] = "com.arm.mbed.manifest-manager.root.AQAAAAAAAAA-.manifest"; - int32_t rc; - ARM_CFSTORE_HANDLE_INIT(hkey); - ARM_CFSTORE_HANDLE_INIT(prev); - - // Initialize the config store - (void) call_count; - cfstore_driver.Initialize(cfstore_find2_callback, NULL); - cfstore_driver.PowerControl(ARM_POWER_FULL); - - // Find the target key - rc = cfstore_driver.Find(keyBuffer, prev, hkey); - - // If the target key was not found - if (rc == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { - ARM_CFSTORE_KEYDESC kdesc = { - .acl = { - .perm_owner_read = 1, - .perm_owner_write = 1, - .perm_owner_execute = 0, - .perm_other_read = 1, - .perm_other_write = 0, - .perm_other_execute = 0, - /* added initialisers */ + char keyBuffer[128] = "com.arm.mbed.manifest-manager.root.AQAAAAAAAAA-.manifest"; + int32_t rc; + ARM_CFSTORE_HANDLE_INIT(hkey); + ARM_CFSTORE_HANDLE_INIT(prev); + + // Initialize the config store + (void) call_count; + cfstore_driver.Initialize(cfstore_find2_callback, NULL); + cfstore_driver.PowerControl(ARM_POWER_FULL); + + // Find the target key + rc = cfstore_driver.Find(keyBuffer, prev, hkey); + + // If the target key was not found + if (rc == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { + ARM_CFSTORE_KEYDESC kdesc = { + .acl = { + .perm_owner_read = 1, + .perm_owner_write = 1, + .perm_owner_execute = 0, + .perm_other_read = 1, + .perm_other_write = 0, + .perm_other_execute = 0, + /* added initialisers */ .reserved = 0 - }, .drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE, - .security = { - .acls = 1, - .rollback_protection = 0, - .tamper_proof = 0, - .internal_flash = 0, - /* added initialisers */ + }, .drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE, + .security = { + .acls = 1, + .rollback_protection = 0, + .tamper_proof = 0, + .internal_flash = 0, + /* added initialisers */ .reserved1 = 0, .software_attacks = 0, .board_level_attacks = 0, .chip_level_attacks = 0, .side_channel_attacks = 0, .reserved2 = 0 - }, - .flags = { - .continuous = 0, - .lazy_flush = 1, - .flush_on_close = 1, - .read = 0, - .write = 1, - .execute = 0, - .storage_detect = 1, + }, + .flags = { + .continuous = 0, + .lazy_flush = 1, + .flush_on_close = 1, + .read = 0, + .write = 1, + .execute = 0, + .storage_detect = 1, /* added initialisers */ .reserved = 0 - } - }; + } + }; - // Create the target key - rc = cfstore_driver.Create(keyBuffer, 191, &kdesc, hkey); - } - return CaseNext; + // Create the target key + rc = cfstore_driver.Create(keyBuffer, 191, &kdesc, hkey); + } + return CaseNext; } /* fixed version of brendans code */ static control_t cfstore_find2_test_02(const size_t call_count) { - char keyBuffer[128] = "com.arm.mbed.manifest-manager.root.AQAAAAAAAAA-.manifest"; + char keyBuffer[128] = "com.arm.mbed.manifest-manager.root.AQAAAAAAAAA-.manifest"; - int32_t rc; + int32_t rc; ARM_CFSTORE_HANDLE_INIT(hkey); ARM_CFSTORE_HANDLE_INIT(prev); ARM_CFSTORE_SIZE length; @@ -176,7 +176,7 @@ static control_t cfstore_find2_test_02(const size_t call_count) .perm_other_write = 0, .perm_other_execute = 0, .reserved = 0 - }, .drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE, /* DATA_RETENTION_NVM not supported for MBED_V_0_1_x */ + }, .drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE, /* DATA_RETENTION_NVM not supported for MBED_V_0_1_x */ .security = { .acls = 0, /* protection against internal software attacks using ACLs not supported for MBED_V_0_1_x */ .rollback_protection = 0, @@ -191,8 +191,8 @@ static control_t cfstore_find2_test_02(const size_t call_count) }, .flags = { .continuous = 0, - .lazy_flush = 0, /* lazy flush not supported for MBED_V_0_1_x */ - .flush_on_close = 0, /* flush on close not supported for MBED_V_0_1_x */ + .lazy_flush = 0, /* lazy flush not supported for MBED_V_0_1_x */ + .flush_on_close = 0, /* flush on close not supported for MBED_V_0_1_x */ .read = 0, .write = 1, .execute = 0, @@ -209,12 +209,12 @@ static control_t cfstore_find2_test_02(const size_t call_count) TEST_ASSERT_MESSAGE(rc >= ARM_DRIVER_OK, cfstore_find2_utest_msg_g); strncpy(value, "MyValueData", CFSTORE_FIND2_TEST_02_VALUE_SIZE); - length = strlen(value); - rc = cfstore_driver.Write(hkey, value, &length); + length = strlen(value); + rc = cfstore_driver.Write(hkey, value, &length); CFSTORE_TEST_UTEST_MESSAGE(cfstore_find2_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%sError: failed to write key\n", __func__); TEST_ASSERT_MESSAGE(rc >= ARM_DRIVER_OK, cfstore_find2_utest_msg_g); /* revert to CFSTORE_LOG if more trace required */ - CFSTORE_DBGLOG("Success!%s", "\n"); + CFSTORE_DBGLOG("Success!%s", "\n"); } return CaseNext; } @@ -227,11 +227,11 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("FIND2_test_00", cfstore_find2_test_00), - Case("FIND2_test_01", cfstore_find2_test_01), - Case("FIND2_test_02", cfstore_find2_test_02), + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("FIND2_test_00", cfstore_find2_test_00), + Case("FIND2_test_01", cfstore_find2_test_01), + Case("FIND2_test_02", cfstore_find2_test_02), }; diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/flash/flash.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/flash/flash.cpp index 26fd4bf219a..45d0ef614e2 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/flash/flash.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/flash/flash.cpp @@ -93,16 +93,15 @@ extern ARM_DRIVER_STORAGE ARM_Driver_Storage_MTD_K64F; /* KV data for test_01 */ static cfstore_kv_data_t cfstore_flush_test_01_kv_data[] = { - { CFSTORE_TEST_DATA_KEYNAME, CFSTORE_TEST_DATA_VALUE_INIT}, - { NULL, NULL}, + { CFSTORE_TEST_DATA_KEYNAME, CFSTORE_TEST_DATA_VALUE_INIT}, + { NULL, NULL}, }; /* @brief key value header structure defining key_name length, value length * @note * 8 bytes long */ -typedef struct cfstore_area_header_t -{ +typedef struct cfstore_area_header_t { uint32_t vlength; uint8_t klength; uint8_t perm_owner_read : 1; @@ -140,17 +139,17 @@ typedef struct cfstore_flash_data_blob_t { */ /* print key name string from area where key_name is not null terminated*/ -static void cfstore_dump_key_name(uint8_t* keyname, uint8_t len, const char* tag) +static void cfstore_dump_key_name(uint8_t *keyname, uint8_t len, const char *tag) { - char blob_data[CFSTORE_KEY_NAME_MAX_LENGTH]; - - (void) tag; - assert(keyname != NULL); - assert(tag != NULL); - assert(len > 0); - memcpy(blob_data, keyname, len); - blob_data[len] = '\0'; - CFSTORE_DBGLOG("%s:keyname=%s\r\n", tag, blob_data); + char blob_data[CFSTORE_KEY_NAME_MAX_LENGTH]; + + (void) tag; + assert(keyname != NULL); + assert(tag != NULL); + assert(len > 0); + memcpy(blob_data, keyname, len); + blob_data[len] = '\0'; + CFSTORE_DBGLOG("%s:keyname=%s\r\n", tag, blob_data); } /* @brief test fsm states and events */ @@ -171,18 +170,16 @@ typedef enum cfstore_flash_fsm_event_t { cfstore_flash_fsm_event_max, } cfstore_flash_fsm_event_t; -typedef void (*cfstore_flash_fsm_handler)(void* ctx); +typedef void (*cfstore_flash_fsm_handler)(void *ctx); -typedef struct cfstore_fsm_t -{ +typedef struct cfstore_fsm_t { cfstore_flash_fsm_state_t state; cfstore_flash_fsm_event_t event; } cfstore_fsm_t; -typedef struct cfstore_flash_ctx_t -{ - uint8_t* area_0_head; - uint8_t* area_0_tail; +typedef struct cfstore_flash_ctx_t { + uint8_t *area_0_head; + uint8_t *area_0_tail; FlashJournal_t jrnl; uint64_t expected_blob_size; cfstore_fsm_t fsm; @@ -195,8 +192,7 @@ typedef struct cfstore_flash_ctx_t * Globals */ static cfstore_flash_ctx_t cfstore_flash_ctx_g; -static const char* cfstore_flash_opcode_str[] = -{ +static const char *cfstore_flash_opcode_str[] = { "FLASH_JOURNAL_OPCODE_INITIALIZE", "FLASH_JOURNAL_OPCODE_GET_INFO", "FLASH_JOURNAL_OPCODE_READ_BLOB", @@ -206,8 +202,7 @@ static const char* cfstore_flash_opcode_str[] = }; #ifdef CFSTORE_DEBUG -static const char* cfstore_flash_state_str[] = -{ +static const char *cfstore_flash_state_str[] = { "initializing", "reading", "writing", @@ -215,8 +210,7 @@ static const char* cfstore_flash_state_str[] = "unknown" }; -static const char* cfstore_flash_event_str[] = -{ +static const char *cfstore_flash_event_str[] = { "init_done", "read_done", "write_done", @@ -228,15 +222,15 @@ static const char* cfstore_flash_event_str[] = /* * Forward decl */ -static void cfstore_fsm_state_handle_event(cfstore_fsm_t* fsm, cfstore_flash_fsm_event_t event, void* context); -static void cfstore_fsm_state_set(cfstore_fsm_t* fsm, cfstore_flash_fsm_state_t new_state, void* ctx); +static void cfstore_fsm_state_handle_event(cfstore_fsm_t *fsm, cfstore_flash_fsm_event_t event, void *context); +static void cfstore_fsm_state_set(cfstore_fsm_t *fsm, cfstore_flash_fsm_state_t new_state, void *ctx); /* * context related methods */ /* @brief get a pointer to the global context data structure */ -static cfstore_flash_ctx_t* cfstore_flash_ctx_get(void) +static cfstore_flash_ctx_t *cfstore_flash_ctx_get(void) { return &cfstore_flash_ctx_g; } @@ -245,45 +239,44 @@ static cfstore_flash_ctx_t* cfstore_flash_ctx_get(void) /* @brief flash journal asynchronous callback handler */ void cfstore_flash_test_01_callback(int32_t status, FlashJournal_OpCode_t cmd_code) { - cfstore_flash_ctx_t* ctx = cfstore_flash_ctx_get(); + cfstore_flash_ctx_t *ctx = cfstore_flash_ctx_get(); CFSTORE_FENTRYLOG("%s:entered: status=%d, cmd_code=%d (%s)\r\n", __func__, (int) status, (int) cmd_code, cfstore_flash_opcode_str[cmd_code]); - switch(cmd_code) - { - case FLASH_JOURNAL_OPCODE_INITIALIZE: - ctx->fsm.event = cfstore_flash_fsm_event_init_done; - break; - case FLASH_JOURNAL_OPCODE_READ_BLOB: - ctx->fsm.event = cfstore_flash_fsm_event_read_done; - break; - case FLASH_JOURNAL_OPCODE_LOG_BLOB: - ctx->fsm.event = cfstore_flash_fsm_event_write_done; - break; - case FLASH_JOURNAL_OPCODE_COMMIT: - ctx->fsm.event = cfstore_flash_fsm_event_commit_done; - break; - case FLASH_JOURNAL_OPCODE_GET_INFO: - case FLASH_JOURNAL_OPCODE_RESET: - default: - CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: received asynchronous notification for opcode=%d (%s) when api call should have been synchronous", __func__, cmd_code, cmd_code <= FLASH_JOURNAL_OPCODE_RESET ? cfstore_flash_opcode_str[cmd_code] : "unknown"); - TEST_ASSERT_MESSAGE(false, cfstore_flash_utest_msg_g) - return; + switch (cmd_code) { + case FLASH_JOURNAL_OPCODE_INITIALIZE: + ctx->fsm.event = cfstore_flash_fsm_event_init_done; + break; + case FLASH_JOURNAL_OPCODE_READ_BLOB: + ctx->fsm.event = cfstore_flash_fsm_event_read_done; + break; + case FLASH_JOURNAL_OPCODE_LOG_BLOB: + ctx->fsm.event = cfstore_flash_fsm_event_write_done; + break; + case FLASH_JOURNAL_OPCODE_COMMIT: + ctx->fsm.event = cfstore_flash_fsm_event_commit_done; + break; + case FLASH_JOURNAL_OPCODE_GET_INFO: + case FLASH_JOURNAL_OPCODE_RESET: + default: + CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: received asynchronous notification for opcode=%d (%s) when api call should have been synchronous", __func__, cmd_code, cmd_code <= FLASH_JOURNAL_OPCODE_RESET ? cfstore_flash_opcode_str[cmd_code] : "unknown"); + TEST_ASSERT_MESSAGE(false, cfstore_flash_utest_msg_g) + return; } ctx->status = status; ctx->cmd_code = cmd_code; - cfstore_fsm_state_handle_event(&ctx->fsm, ctx->fsm.event, (void*) ctx); + cfstore_fsm_state_handle_event(&ctx->fsm, ctx->fsm.event, (void *) ctx); return; } /* @brief fsm handler called on entry to initializing state */ -static void cfstore_flash_fsm_init_on_entry(void* context) +static void cfstore_flash_fsm_init_on_entry(void *context) { /* round up cfstore_flash_data_blob_t to nearest k64f program unit size */ const ARM_DRIVER_STORAGE *drv = &ARM_Driver_Storage_MTD_K64F; FlashJournal_Info_t info; FlashJournal_Status_t status = JOURNAL_STATUS_ERROR; - cfstore_flash_ctx_t* ctx = (cfstore_flash_ctx_t*) context; + cfstore_flash_ctx_t *ctx = (cfstore_flash_ctx_t *) context; /* check that the mtd is in synchronous mode */ CFSTORE_FENTRYLOG("%s:entered: \r\n", __func__); @@ -294,16 +287,16 @@ static void cfstore_flash_fsm_init_on_entry(void* context) CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: failed to initialize flash journaling layer (status=%d)\r\n", __func__, status); TEST_ASSERT_MESSAGE(status >= JOURNAL_STATUS_OK, cfstore_flash_utest_msg_g); /* if status > 0, expect async callback, otherwise initialisation has been completed */ - if(status > 0) { + if (status > 0) { cfstore_flash_test_01_callback(status, FLASH_JOURNAL_OPCODE_INITIALIZE); } return; } /* brief callback handler when in state initializing */ -static void cfstore_flash_fsm_initializing(void* context) +static void cfstore_flash_fsm_initializing(void *context) { - cfstore_flash_ctx_t* ctx = (cfstore_flash_ctx_t*) context; + cfstore_flash_ctx_t *ctx = (cfstore_flash_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered\r\n", __func__); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: entered handler(%s) but not in initializing state (fsm->state=%d)\r\n", __func__, __func__, (int) ctx->fsm.state); @@ -313,7 +306,7 @@ static void cfstore_flash_fsm_initializing(void* context) CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: status=%d\r\n", __func__, (int) ctx->status); TEST_ASSERT_MESSAGE(ctx->status >= JOURNAL_STATUS_OK, cfstore_flash_utest_msg_g); /* only change state if status > 0*/ - if(ctx->status > 0){ + if (ctx->status > 0) { cfstore_fsm_state_set(&ctx->fsm, cfstore_flash_fsm_state_reading, ctx); } } @@ -324,13 +317,13 @@ static void cfstore_flash_fsm_initializing(void* context) * note * flash journal has initialised successfully. now */ -static void cfstore_flash_fsm_read_on_entry(void* context) +static void cfstore_flash_fsm_read_on_entry(void *context) { - uint8_t* ptr = NULL; + uint8_t *ptr = NULL; int32_t ret = 0; FlashJournal_Info_t info; FlashJournal_Status_t status = JOURNAL_STATUS_ERROR; - cfstore_flash_ctx_t* ctx = (cfstore_flash_ctx_t*) context; + cfstore_flash_ctx_t *ctx = (cfstore_flash_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered\r\n", __func__); CFSTORE_ASSERT(ctx != NULL); @@ -340,12 +333,11 @@ static void cfstore_flash_fsm_read_on_entry(void* context) TEST_ASSERT_MESSAGE(status == JOURNAL_STATUS_OK, cfstore_flash_utest_msg_g); CFSTORE_DBGLOG("%s:FlashJournal_getInfo() done. info.sizeofJournaledBlob=%lu\r\n", __func__, (long unsigned int) info.sizeofJournaledBlob); - if(info.sizeofJournaledBlob > 0) - { + if (info.sizeofJournaledBlob > 0) { /* setup the expected blob size for writing * This is a multiple of program unit so the write doesnt fail due to unaligned log */ ctx->expected_blob_size = sizeof(cfstore_flash_data_blob_t); - if(ctx->expected_blob_size % CFSTORE_FLASH_K64F_CURRENT_PROGRAM_UNIT_SIZE > 0){ + if (ctx->expected_blob_size % CFSTORE_FLASH_K64F_CURRENT_PROGRAM_UNIT_SIZE > 0) { ctx->expected_blob_size += (CFSTORE_FLASH_K64F_CURRENT_PROGRAM_UNIT_SIZE - (sizeof(cfstore_flash_data_blob_t) % CFSTORE_FLASH_K64F_CURRENT_PROGRAM_UNIT_SIZE)); } /* test that a blob size is the expected size for flash data that has been written before */ @@ -353,22 +345,22 @@ static void cfstore_flash_fsm_read_on_entry(void* context) TEST_ASSERT_EQUAL_INT64_MESSAGE(ctx->expected_blob_size, info.sizeofJournaledBlob, cfstore_flash_utest_msg_g); /* grow the area by the size of the stored blob */ - ptr = (uint8_t*) CFSTORE_REALLOC((void*) ctx->area_0_head, ctx->expected_blob_size); + ptr = (uint8_t *) CFSTORE_REALLOC((void *) ctx->area_0_head, ctx->expected_blob_size); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:realloc failed flash blob (size=%d)\r\n", __func__, (int)info.sizeofJournaledBlob); TEST_ASSERT_MESSAGE(ptr != NULL, cfstore_flash_utest_msg_g); memset(ptr, 0, ctx->expected_blob_size); - if(ptr != ctx->area_0_head){ + if (ptr != ctx->area_0_head) { CFSTORE_DBGLOG("%s:cfstore_ctx_g.area_0_head pointer changed (cfstore_ctx_g.area_0_head=%p, ptr=%p)\r\n", __func__, ctx->area_0_head, ptr); ctx->area_0_head = ptr; ctx->area_0_tail = ctx->area_0_head + info.sizeofJournaledBlob; } - ret = FlashJournal_read(&ctx->jrnl, (void*) ctx->area_0_head, info.sizeofJournaledBlob); + ret = FlashJournal_read(&ctx->jrnl, (void *) ctx->area_0_head, info.sizeofJournaledBlob); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: unable to read flash journal (ret=%d. info.sizeofJournaledBlob=%d)\r\n", __func__, (int) ret, (int) info.sizeofJournaledBlob); TEST_ASSERT_MESSAGE(ret >= JOURNAL_STATUS_OK, cfstore_flash_utest_msg_g); - if(ret > 0){ + if (ret > 0) { /* read has completed synchronously*/ CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: unable to read all data from flash journal (expected size=%lu, read=%d)\r\n", __func__, (unsigned long int)info.sizeofJournaledBlob, (int) ret); - TEST_ASSERT_EQUAL_INT32_MESSAGE( (int32_t) info.sizeofJournaledBlob, ret, cfstore_flash_utest_msg_g); + TEST_ASSERT_EQUAL_INT32_MESSAGE((int32_t) info.sizeofJournaledBlob, ret, cfstore_flash_utest_msg_g); cfstore_flash_test_01_callback(ret, FLASH_JOURNAL_OPCODE_READ_BLOB); } } else { @@ -382,10 +374,10 @@ static void cfstore_flash_fsm_read_on_entry(void* context) } /* @brief fsm handler when in reading state */ -void cfstore_flash_fsm_reading(void* context) +void cfstore_flash_fsm_reading(void *context) { int32_t ret = 0; - cfstore_flash_ctx_t* ctx = (cfstore_flash_ctx_t*) context; + cfstore_flash_ctx_t *ctx = (cfstore_flash_ctx_t *) context; cfstore_flash_data_blob_t *blob = NULL; CFSTORE_FENTRYLOG("%s:entered\r\n", __func__); @@ -396,18 +388,15 @@ void cfstore_flash_fsm_reading(void* context) CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: status=%d\r\n", __func__, (int) ctx->status); TEST_ASSERT_MESSAGE(ctx->status >= JOURNAL_STATUS_OK, cfstore_flash_utest_msg_g); - if(ctx->status > 0) - { - if(ctx->status > (int32_t) CFSTORE_FLASH_AREA_SIZE_MIN) - { + if (ctx->status > 0) { + if (ctx->status > (int32_t) CFSTORE_FLASH_AREA_SIZE_MIN) { /* check the correct amount of data was read, which is the status code */ CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: unable to read all data from flash journal (expected size=%lu, read=%d)\r\n", __func__, (unsigned long int) ctx->expected_blob_size, (int) ctx->status); /* ctx->status contains the status of the read that was completed */ TEST_ASSERT_EQUAL_INT64_MESSAGE(ctx->expected_blob_size, (int32_t) ctx->status, cfstore_flash_utest_msg_g); - if(ctx->area_0_head != NULL) - { + if (ctx->area_0_head != NULL) { /* check the key_name read from flash is correct */ - blob = (cfstore_flash_data_blob_t*) ctx->area_0_head; + blob = (cfstore_flash_data_blob_t *) ctx->area_0_head; cfstore_dump_key_name(blob->data, CFSTORE_TEST_DATA_KEYNAME_SIZE, __func__); ret = memcmp(blob->data, cfstore_flush_test_01_kv_data[0].key_name, strlen(cfstore_flush_test_01_kv_data[0].key_name)); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: incorrect key_name read from flash (expected 0 from memcpy(keyname, flash_data), actual was non-zero)", __func__); @@ -421,56 +410,54 @@ void cfstore_flash_fsm_reading(void* context) /* void cfstore_flash_fsm_read_on_exit(void* context){ (void) context;} */ /* @brief on entry to writing state, update value */ -void cfstore_flash_fsm_write_on_entry(void* context) +void cfstore_flash_fsm_write_on_entry(void *context) { uint8_t value = 0; int32_t ret = 0; - cfstore_flash_ctx_t* ctx = (cfstore_flash_ctx_t*) context; + cfstore_flash_ctx_t *ctx = (cfstore_flash_ctx_t *) context; cfstore_flash_data_blob_t *blob = NULL; CFSTORE_FENTRYLOG("%s:entered:\r\n", __func__); /* allocate memory for data if not already done so */ - if(ctx->area_0_head == NULL) - { + if (ctx->area_0_head == NULL) { /* This is a multiple of program unit so the write doesnt fail due to unaligned log */ ctx->expected_blob_size = sizeof(cfstore_flash_data_blob_t); - if(ctx->expected_blob_size % CFSTORE_FLASH_K64F_CURRENT_PROGRAM_UNIT_SIZE > 0){ + if (ctx->expected_blob_size % CFSTORE_FLASH_K64F_CURRENT_PROGRAM_UNIT_SIZE > 0) { ctx->expected_blob_size += (CFSTORE_FLASH_K64F_CURRENT_PROGRAM_UNIT_SIZE - (sizeof(cfstore_flash_data_blob_t) % CFSTORE_FLASH_K64F_CURRENT_PROGRAM_UNIT_SIZE)); } - ctx->area_0_head = (uint8_t*) CFSTORE_REALLOC((void*) ctx->area_0_head, ctx->expected_blob_size); + ctx->area_0_head = (uint8_t *) CFSTORE_REALLOC((void *) ctx->area_0_head, ctx->expected_blob_size); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: unable to allocate memory for context\r\n", __func__); TEST_ASSERT_MESSAGE(ctx->area_0_head != NULL, cfstore_flash_utest_msg_g); ctx->area_0_tail = ctx->area_0_head + ctx->expected_blob_size; memset(ctx->area_0_head, 0, ctx->expected_blob_size); /* setup data to write to flash */ - blob = (cfstore_flash_data_blob_t*) ctx->area_0_head; + blob = (cfstore_flash_data_blob_t *) ctx->area_0_head; blob->hdr.klength = strlen(cfstore_flush_test_01_kv_data->key_name); - blob->hdr.vlength= 1; + blob->hdr.vlength = 1; blob->hdr.perm_owner_read = true; blob->hdr.perm_owner_write = true; blob->hdr.refcount = 1; - memcpy((void*) blob->data, (const void*) cfstore_flush_test_01_kv_data->key_name, strlen(cfstore_flush_test_01_kv_data->key_name)); - memcpy((void*) &blob->data[CFSTORE_TEST_DATA_KEYNAME_SIZE], (const void*) cfstore_flush_test_01_kv_data->value, strlen(cfstore_flush_test_01_kv_data->value)); + memcpy((void *) blob->data, (const void *) cfstore_flush_test_01_kv_data->key_name, strlen(cfstore_flush_test_01_kv_data->key_name)); + memcpy((void *) &blob->data[CFSTORE_TEST_DATA_KEYNAME_SIZE], (const void *) cfstore_flush_test_01_kv_data->value, strlen(cfstore_flush_test_01_kv_data->value)); } - if(ctx->area_0_head != NULL) - { + if (ctx->area_0_head != NULL) { /* data has been read */ /* check the key_name read from flash is correct */ - blob = (cfstore_flash_data_blob_t*) ctx->area_0_head; + blob = (cfstore_flash_data_blob_t *) ctx->area_0_head; value = (uint8_t) blob->data[CFSTORE_TEST_DATA_KEYNAME_SIZE]; CFSTORE_DBGLOG("INFO: value read from flash = %u\r\n", value); /* update the value */ value++; - memcpy((void*) &blob->data[CFSTORE_TEST_DATA_KEYNAME_SIZE], (const void*) &value, sizeof(uint8_t)); + memcpy((void *) &blob->data[CFSTORE_TEST_DATA_KEYNAME_SIZE], (const void *) &value, sizeof(uint8_t)); } - ret = FlashJournal_log(&ctx->jrnl, (const void*) ctx->area_0_head, ctx->expected_blob_size); + ret = FlashJournal_log(&ctx->jrnl, (const void *) ctx->area_0_head, ctx->expected_blob_size); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: ret = JOURNAL_STATUS_SMALL_LOG_REQUEST, bailing out.", __func__); TEST_ASSERT_MESSAGE(ret != (int32_t) JOURNAL_STATUS_SMALL_LOG_REQUEST, cfstore_flash_utest_msg_g); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: failed to perform log operation to flash journal (ret=%d)\r\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret >= 0, cfstore_flash_utest_msg_g); - if(ret > 0){ + if (ret > 0) { /* write has completed synchronously*/ CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: unable to write all data from flash journal (expected size=%lu, read=%d)\r\n", __func__, (unsigned long int) ctx->expected_blob_size, (int) ret); TEST_ASSERT_EQUAL_INT32_MESSAGE(ret, (int32_t) ctx->expected_blob_size, cfstore_flash_utest_msg_g); @@ -480,9 +467,9 @@ void cfstore_flash_fsm_write_on_entry(void* context) } /* @brief fsm handler when in reading state */ -void cfstore_flash_fsm_writing(void* context) +void cfstore_flash_fsm_writing(void *context) { - cfstore_flash_ctx_t* ctx = (cfstore_flash_ctx_t*) context; + cfstore_flash_ctx_t *ctx = (cfstore_flash_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered:\r\n", __func__); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: entered handler(%s) but not in writing state (fsm->state=%d)\r\n", __func__, __func__, (int) ctx->fsm.state); @@ -492,7 +479,7 @@ void cfstore_flash_fsm_writing(void* context) CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: status=%d\r\n", __func__, (int) ctx->status); TEST_ASSERT_MESSAGE(ctx->status >= JOURNAL_STATUS_OK, cfstore_flash_utest_msg_g); - if(ctx->status > 0){ + if (ctx->status > 0) { /* check the correct amount of data was written */ CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: unable to write all data from flash journal (expected size=%lu, read=%d)\r\n", __func__, (unsigned long int) ctx->expected_blob_size, (int) ctx->status); TEST_ASSERT_EQUAL_INT64_MESSAGE(ctx->expected_blob_size, ctx->status, cfstore_flash_utest_msg_g); @@ -504,17 +491,17 @@ void cfstore_flash_fsm_writing(void* context) /* void cfstore_flash_fsm_write_on_exit(void* ctx){(void) ctx;} */ /* @brief fsm handler when entering committing state */ -void cfstore_flash_fsm_commit_on_entry(void* context) +void cfstore_flash_fsm_commit_on_entry(void *context) { int32_t ret = 0; - cfstore_flash_ctx_t* ctx = (cfstore_flash_ctx_t*) context; + cfstore_flash_ctx_t *ctx = (cfstore_flash_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered:\r\n", __func__); ret = FlashJournal_commit(&ctx->jrnl); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: failed to perform commit operation to flash journal (ret=%d)\r\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret >= (int32_t) JOURNAL_STATUS_OK, cfstore_flash_utest_msg_g); /* for flash-journal-strategy-sequential version >0.4.0, commit() return no longer reports size of commit block */ - if(ret > 0){ + if (ret > 0) { Harness::validate_callback(); } /* wait for async completion handler*/ @@ -523,9 +510,9 @@ void cfstore_flash_fsm_commit_on_entry(void* context) /* @brief fsm handler when in committing state */ -void cfstore_flash_fsm_committing(void* context) +void cfstore_flash_fsm_committing(void *context) { - cfstore_flash_ctx_t* ctx = (cfstore_flash_ctx_t*) context; + cfstore_flash_ctx_t *ctx = (cfstore_flash_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered\r\n", __func__); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: entered handler(%s) but not in committing state (fsm->state=%d)\r\n", __func__, __func__, (int) ctx->fsm.state); @@ -541,35 +528,33 @@ void cfstore_flash_fsm_committing(void* context) } /* @brief fsm handler when exiting committing state */ -void cfstore_flash_fsm_commit_on_exit(void* context) +void cfstore_flash_fsm_commit_on_exit(void *context) { - cfstore_flash_ctx_t* ctx = (cfstore_flash_ctx_t*) context; + cfstore_flash_ctx_t *ctx = (cfstore_flash_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered\r\n", __func__); /* test done. clean up*/ - if(ctx->area_0_head){ + if (ctx->area_0_head) { CFSTORE_FREE(ctx->area_0_head); ctx->area_0_head = NULL; } Harness::validate_callback(); - } +} #define cfstore_flash_fsm_null NULL /* handler functions while in state */ -static cfstore_flash_fsm_handler cfstore_flash_fsm[cfstore_flash_fsm_state_max][cfstore_flash_fsm_event_max] = -{ -/* state\event: init_done read_done write_done commit_done */ -/* initialising */ {cfstore_flash_fsm_initializing, cfstore_flash_fsm_null, cfstore_flash_fsm_null, cfstore_flash_fsm_null }, -/* reading */ {cfstore_flash_fsm_null, cfstore_flash_fsm_reading, cfstore_flash_fsm_null, cfstore_flash_fsm_null }, -/* writing */ {cfstore_flash_fsm_null, cfstore_flash_fsm_null, cfstore_flash_fsm_writing, cfstore_flash_fsm_null }, -/* committing */ {cfstore_flash_fsm_null, cfstore_flash_fsm_null, cfstore_flash_fsm_null, cfstore_flash_fsm_committing }, +static cfstore_flash_fsm_handler cfstore_flash_fsm[cfstore_flash_fsm_state_max][cfstore_flash_fsm_event_max] = { + /* state\event: init_done read_done write_done commit_done */ + /* initialising */ {cfstore_flash_fsm_initializing, cfstore_flash_fsm_null, cfstore_flash_fsm_null, cfstore_flash_fsm_null }, + /* reading */ {cfstore_flash_fsm_null, cfstore_flash_fsm_reading, cfstore_flash_fsm_null, cfstore_flash_fsm_null }, + /* writing */ {cfstore_flash_fsm_null, cfstore_flash_fsm_null, cfstore_flash_fsm_writing, cfstore_flash_fsm_null }, + /* committing */ {cfstore_flash_fsm_null, cfstore_flash_fsm_null, cfstore_flash_fsm_null, cfstore_flash_fsm_committing }, }; /* handler functions for entering the state*/ -cfstore_flash_fsm_handler cfstore_flash_fsm_on_entry[cfstore_flash_fsm_state_max] = -{ +cfstore_flash_fsm_handler cfstore_flash_fsm_on_entry[cfstore_flash_fsm_state_max] = { cfstore_flash_fsm_init_on_entry, cfstore_flash_fsm_read_on_entry, cfstore_flash_fsm_write_on_entry, @@ -577,22 +562,21 @@ cfstore_flash_fsm_handler cfstore_flash_fsm_on_entry[cfstore_flash_fsm_state_max }; /* handler functions for exiting state, currently none used */ -cfstore_flash_fsm_handler cfstore_flash_fsm_on_exit[cfstore_flash_fsm_state_max] = -{ +cfstore_flash_fsm_handler cfstore_flash_fsm_on_exit[cfstore_flash_fsm_state_max] = { NULL, NULL, NULL, NULL, }; /* @brief inject event into fsm */ -static void cfstore_fsm_state_handle_event(cfstore_fsm_t* fsm, cfstore_flash_fsm_event_t event, void* context) +static void cfstore_fsm_state_handle_event(cfstore_fsm_t *fsm, cfstore_flash_fsm_event_t event, void *context) { - cfstore_flash_ctx_t* ctx = (cfstore_flash_ctx_t*) context; + cfstore_flash_ctx_t *ctx = (cfstore_flash_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered: fsm=%p, event=%d (%s), ctx=%p\r\n", __func__, fsm, (int) event, cfstore_flash_event_str[event], ctx); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flash_utest_msg_g, CFSTORE_FLASH_UTEST_MSG_BUF_SIZE, "%s:Error: invalid event (%d)\r\n", __func__, (int) event); TEST_ASSERT_MESSAGE(event < cfstore_flash_fsm_event_max, cfstore_flash_utest_msg_g); fsm->event = event; - if(cfstore_flash_fsm[fsm->state][fsm->event] != NULL){ + if (cfstore_flash_fsm[fsm->state][fsm->event] != NULL) { cfstore_flash_fsm[fsm->state][fsm->event](ctx); } @@ -606,7 +590,7 @@ static void cfstore_fsm_state_handle_event(cfstore_fsm_t* fsm, cfstore_flash_fsm /* @brief function to move to new fsm state, calling state exit function for old state and entry function for new state */ -static void cfstore_fsm_state_set(cfstore_fsm_t* fsm, cfstore_flash_fsm_state_t new_state, void* ctx) +static void cfstore_fsm_state_set(cfstore_fsm_t *fsm, cfstore_flash_fsm_state_t new_state, void *ctx) { CFSTORE_FENTRYLOG("%s:entered: fsm=%p, new_state=%d, ctx=%p\r\n", __func__, fsm, (int) new_state, ctx); CFSTORE_DBGLOG("%s:FSM:REQ RX:%s:%s\r\n", __func__, cfstore_flash_state_str[fsm->state], cfstore_flash_state_str[new_state]); @@ -615,11 +599,11 @@ static void cfstore_fsm_state_set(cfstore_fsm_t* fsm, cfstore_flash_fsm_state_t TEST_ASSERT_MESSAGE(ctx != NULL, "ctx is not a valid pointer"); TEST_ASSERT_MESSAGE(fsm->state < cfstore_flash_fsm_state_max, "fsm->state is not a valid state"); - if(cfstore_flash_fsm_on_exit[fsm->state] != NULL){ + if (cfstore_flash_fsm_on_exit[fsm->state] != NULL) { cfstore_flash_fsm_on_exit[fsm->state](ctx); } fsm->state = new_state; - if(cfstore_flash_fsm_on_entry[new_state] != NULL){ + if (cfstore_flash_fsm_on_entry[new_state] != NULL) { cfstore_flash_fsm_on_entry[new_state](ctx); } CFSTORE_DBGLOG("%s:FSM:REQ DONE:\r\n", __func__); @@ -627,7 +611,7 @@ static void cfstore_fsm_state_set(cfstore_fsm_t* fsm, cfstore_flash_fsm_state_t } /* @brief initialize global context data structure */ -static void cfstore_flash_ctx_init(cfstore_flash_ctx_t* ctx) +static void cfstore_flash_ctx_init(cfstore_flash_ctx_t *ctx) { TEST_ASSERT_MESSAGE(ctx != NULL, "ctx is NULL"); @@ -639,7 +623,7 @@ static void cfstore_flash_ctx_init(cfstore_flash_ctx_t* ctx) /* @brief asynchronous test 01 */ static control_t cfstore_flash_journal_async_test_01(void) { - cfstore_flash_ctx_t* ctx = cfstore_flash_ctx_get(); + cfstore_flash_ctx_t *ctx = cfstore_flash_ctx_get(); CFSTORE_FENTRYLOG("%s:entered: \r\n", __func__); cfstore_flash_mtd_async_ops_g = CFSTORE_FLASH_MTD_ASYNC_OPS_ON; @@ -672,9 +656,9 @@ static control_t cfstore_flash_test_00(const size_t call_count) /// @cond CFSTORE_DOXYGEN_DISABLE /* Specify all your test cases here */ Case cases[] = { - Case("flash_journal_async_test_00", cfstore_flash_test_00), + Case("flash_journal_async_test_00", cfstore_flash_test_00), #ifdef CFSTORE_CONFIG_BACKEND_FLASH_ENABLED - Case("flash_journal_async_test_01", cfstore_flash_journal_async_test_01), + Case("flash_journal_async_test_01", cfstore_flash_journal_async_test_01), #endif }; diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/flash_set/flash_set.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/flash_set/flash_set.cpp index 74119b49b10..39c089f7b15 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/flash_set/flash_set.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/flash_set/flash_set.cpp @@ -62,7 +62,7 @@ static control_t cfstore_flash_set_test_01_end(const size_t call_count) { int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_FMODE flags; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_CAPABILITIES caps = cfstore_driver.GetCapabilities(); CFSTORE_FENTRYLOG("%s:entered\n", __func__); @@ -71,21 +71,21 @@ static control_t cfstore_flash_set_test_01_end(const size_t call_count) CFSTORE_LOG("caps.asynchronous_ops : %d\n", (int) caps.asynchronous_ops); ret = cfstore_test_init_1(); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to write data to falsh.", __func__); } ret = drv->Flush(); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Flush() call failed (ret=%d).\r\n", __func__, (int) ret); } #ifdef CFSTORE_DEBUG ret = cfstore_test_dump(); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("Error: failed to dump CFSTORE contents%s", "\n"); } #endif /* CFSTORE_DEBUG */ ret = drv->Uninitialize(); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("Error: failed to Uninitialize() CFSTORE%s", "\n"); } return CaseNext; @@ -99,10 +99,10 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("FLASH_SET_test_01_start", cfstore_utest_default_start), - Case("FLASH_SET_test_01_end", cfstore_flash_set_test_01_end), + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("FLASH_SET_test_01_start", cfstore_utest_default_start), + Case("FLASH_SET_test_01_end", cfstore_flash_set_test_01_end), }; diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/flush/flush.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/flush/flush.cpp index c752f3a1bbf..02de0042c5c 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/flush/flush.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/flush/flush.cpp @@ -60,9 +60,9 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("FLUSH_test_00", cfstore_flush_test_00), + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("FLUSH_test_00", cfstore_flush_test_00), }; @@ -140,33 +140,33 @@ UVISOR_BOX_CONFIG(cfstore_flush_box1, UVISOR_BOX_STACK_SIZE); int32_t cfstore_flush_test_01_x86_sync(void) { int32_t ret = ARM_DRIVER_ERROR; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ret = drv->Initialize(NULL, NULL); - if(ret != ARM_DRIVER_OK){ + if (ret != ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Initialize() call failed (ret=%d).\r\n", __func__, (int) ret); goto out0; } ret = drv->Flush(); - if(ret != ARM_DRIVER_OK){ + if (ret != ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Flush() call failed (ret=%d).\r\n", __func__, (int) ret); } ret = drv->Uninitialize(); - if(ret != ARM_DRIVER_OK){ + if (ret != ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Initialize() call failed to Uninitialise(ret=%d).\r\n", __func__, (int) ret); goto out0; } - out0: +out0: return ret; } #endif /* TARGET_LIKE_X86_LINUX_NATIVE */ /* KV data for test_03 */ static cfstore_kv_data_t cfstore_flush_test_02_kv_data[] = { - { "com.arm.mbed.configurationstore.test.flush.cfstoreflushtest02", "1"}, - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - { NULL, NULL}, + { "com.arm.mbed.configurationstore.test.flush.cfstoreflushtest02", "1"}, + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + { NULL, NULL}, }; @@ -189,19 +189,17 @@ typedef enum cfstore_flush_fsm_event_t { cfstore_flush_fsm_event_max, } cfstore_flush_fsm_event_t; -typedef void (*cfstore_flush_fsm_handler)(void* ctx); +typedef void (*cfstore_flush_fsm_handler)(void *ctx); /// @cond CFSTORE_DOXYGEN_DISABLE -typedef struct cfstore_fsm_t -{ +typedef struct cfstore_fsm_t { cfstore_flush_fsm_state_t state; cfstore_flush_fsm_event_t event; } cfstore_fsm_t; /// @endcond /// @cond CFSTORE_DOXYGEN_DISABLE -typedef struct cfstore_flush_ctx_t -{ +typedef struct cfstore_flush_ctx_t { int32_t loops_done; cfstore_fsm_t fsm; int32_t status; @@ -216,8 +214,7 @@ typedef struct cfstore_flush_ctx_t static cfstore_flush_ctx_t cfstore_flush_ctx_g; #ifdef CFSTORE_DEBUG -static const char* cfstore_flush_state_str[] = -{ +static const char *cfstore_flush_state_str[] = { "stopped", "initializing", "flushing", @@ -225,8 +222,7 @@ static const char* cfstore_flush_state_str[] = "unknown" }; -static const char* cfstore_flush_event_str[] = -{ +static const char *cfstore_flush_event_str[] = { "init_done", "flush_done", "uninit_done", @@ -239,20 +235,20 @@ static const char* cfstore_flush_event_str[] = /* * Forward decl */ -static void cfstore_flush_fsm_state_handle_event(cfstore_fsm_t* fsm, cfstore_flush_fsm_event_t event, void* context); -static void cfstore_flush_fsm_state_set(cfstore_fsm_t* fsm, cfstore_flush_fsm_state_t new_state, void* ctx); +static void cfstore_flush_fsm_state_handle_event(cfstore_fsm_t *fsm, cfstore_flush_fsm_event_t event, void *context); +static void cfstore_flush_fsm_state_set(cfstore_fsm_t *fsm, cfstore_flush_fsm_state_t new_state, void *ctx); /* * context related methods */ /* @brief get a pointer to the global context data structure */ -static cfstore_flush_ctx_t* cfstore_flush_ctx_get(void) +static cfstore_flush_ctx_t *cfstore_flush_ctx_get(void) { return &cfstore_flush_ctx_g; } /* @brief initialize global context data structure */ -static void cfstore_flush_ctx_init(cfstore_flush_ctx_t* ctx) +static void cfstore_flush_ctx_init(cfstore_flush_ctx_t *ctx) { TEST_ASSERT_MESSAGE(ctx != NULL, "ctx is NULL"); @@ -264,38 +260,37 @@ static void cfstore_flush_ctx_init(cfstore_flush_ctx_t* ctx) /* @brief cfstore asynchronous callback handler */ void cfstore_flush_test_01_callback(int32_t status, ARM_CFSTORE_OPCODE cmd_code, void *client_context, ARM_CFSTORE_HANDLE handle) { - cfstore_flush_ctx_t* ctx = (cfstore_flush_ctx_t*) client_context; + cfstore_flush_ctx_t *ctx = (cfstore_flush_ctx_t *) client_context; CFSTORE_FENTRYLOG("%s:entered: status=%d, cmd_code=%d (%s) ctx=%p, handle=%p\r\n", __func__, (int) status, (int) cmd_code, cfstore_test_opcode_str[cmd_code], ctx, handle); (void) handle; - switch(cmd_code) - { - case CFSTORE_OPCODE_INITIALIZE: - ctx->fsm.event = cfstore_flush_fsm_event_init_done; - break; - case CFSTORE_OPCODE_FLUSH: - ctx->fsm.event = cfstore_flush_fsm_event_flush_done; - break; - case CFSTORE_OPCODE_UNINITIALIZE: - ctx->fsm.event = cfstore_flush_fsm_event_uninit_done; - break; - case CFSTORE_OPCODE_CLOSE: - case CFSTORE_OPCODE_CREATE: - case CFSTORE_OPCODE_DELETE: - case CFSTORE_OPCODE_FIND: - case CFSTORE_OPCODE_GET_KEY_NAME: - case CFSTORE_OPCODE_GET_STATUS: - case CFSTORE_OPCODE_GET_VALUE_LEN: - case CFSTORE_OPCODE_OPEN: - case CFSTORE_OPCODE_POWER_CONTROL: - case CFSTORE_OPCODE_READ: - case CFSTORE_OPCODE_RSEEK: - case CFSTORE_OPCODE_WRITE: - default: - CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush_utest_msg_g, CFSTORE_FLUSH_UTEST_MSG_BUF_SIZE, "%s:WARN: received asynchronous notification for opcode=%d (%s) when api call should have been synchronous", __func__, cmd_code, cmd_code < CFSTORE_OPCODE_MAX ? cfstore_test_opcode_str[cmd_code] : "unknown"); - CFSTORE_DBGLOG("%s:WARN: received asynchronous notification for opcode=%d (%s) when api call should have been synchronous", __func__, cmd_code, cmd_code < CFSTORE_OPCODE_MAX ? cfstore_test_opcode_str[cmd_code] : "unknown"); - /* TEST_ASSERT_MESSAGE(false, cfstore_flush_utest_msg_g) */ - return; + switch (cmd_code) { + case CFSTORE_OPCODE_INITIALIZE: + ctx->fsm.event = cfstore_flush_fsm_event_init_done; + break; + case CFSTORE_OPCODE_FLUSH: + ctx->fsm.event = cfstore_flush_fsm_event_flush_done; + break; + case CFSTORE_OPCODE_UNINITIALIZE: + ctx->fsm.event = cfstore_flush_fsm_event_uninit_done; + break; + case CFSTORE_OPCODE_CLOSE: + case CFSTORE_OPCODE_CREATE: + case CFSTORE_OPCODE_DELETE: + case CFSTORE_OPCODE_FIND: + case CFSTORE_OPCODE_GET_KEY_NAME: + case CFSTORE_OPCODE_GET_STATUS: + case CFSTORE_OPCODE_GET_VALUE_LEN: + case CFSTORE_OPCODE_OPEN: + case CFSTORE_OPCODE_POWER_CONTROL: + case CFSTORE_OPCODE_READ: + case CFSTORE_OPCODE_RSEEK: + case CFSTORE_OPCODE_WRITE: + default: + CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush_utest_msg_g, CFSTORE_FLUSH_UTEST_MSG_BUF_SIZE, "%s:WARN: received asynchronous notification for opcode=%d (%s) when api call should have been synchronous", __func__, cmd_code, cmd_code < CFSTORE_OPCODE_MAX ? cfstore_test_opcode_str[cmd_code] : "unknown"); + CFSTORE_DBGLOG("%s:WARN: received asynchronous notification for opcode=%d (%s) when api call should have been synchronous", __func__, cmd_code, cmd_code < CFSTORE_OPCODE_MAX ? cfstore_test_opcode_str[cmd_code] : "unknown"); + /* TEST_ASSERT_MESSAGE(false, cfstore_flush_utest_msg_g) */ + return; } ctx->status = status; ctx->cmd_code = cmd_code; @@ -304,7 +299,7 @@ void cfstore_flush_test_01_callback(int32_t status, ARM_CFSTORE_OPCODE cmd_code, } /* @brief fsm handler called on entry to stopping state */ -static void cfstore_flush_fsm_stop_on_entry(void* context) +static void cfstore_flush_fsm_stop_on_entry(void *context) { (void) context; CFSTORE_FENTRYLOG("%s:entered:\r\n", __func__); @@ -313,11 +308,11 @@ static void cfstore_flush_fsm_stop_on_entry(void* context) } /* @brief fsm handler called on entry to initializing state */ -static void cfstore_flush_fsm_init_on_entry(void* context) +static void cfstore_flush_fsm_init_on_entry(void *context) { int32_t ret = ARM_DRIVER_ERROR; - cfstore_flush_ctx_t* ctx = (cfstore_flush_ctx_t*) context; - const ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + cfstore_flush_ctx_t *ctx = (cfstore_flush_ctx_t *) context; + const ARM_CFSTORE_DRIVER *drv = &cfstore_driver; /* check that the mtd is in synchronous mode */ CFSTORE_FENTRYLOG("%s:entered: callback=%p, ctx=%p\r\n", __func__, cfstore_flush_test_01_callback, ctx); @@ -329,9 +324,9 @@ static void cfstore_flush_fsm_init_on_entry(void* context) } /* brief callback handler when in state initializing */ -static void cfstore_flush_fsm_initializing(void* context) +static void cfstore_flush_fsm_initializing(void *context) { - cfstore_flush_ctx_t* ctx = (cfstore_flush_ctx_t*) context; + cfstore_flush_ctx_t *ctx = (cfstore_flush_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered\r\n", __func__); CFSTORE_FENTRYLOG("%s:entered: status = %d\r\n", __func__, (int) ctx->status); @@ -342,7 +337,7 @@ static void cfstore_flush_fsm_initializing(void* context) CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush_utest_msg_g, CFSTORE_FLUSH_UTEST_MSG_BUF_SIZE, "%s:Error: status=%d\r\n", __func__, (int) ctx->status); TEST_ASSERT_MESSAGE(ctx->status >= ARM_DRIVER_OK, cfstore_flush_utest_msg_g); /* only change state if status >= 0*/ - if(ctx->status >= 0){ + if (ctx->status >= 0) { cfstore_flush_fsm_state_set(&ctx->fsm, cfstore_flush_fsm_state_flushing, ctx); } return; @@ -352,19 +347,19 @@ static void cfstore_flush_fsm_initializing(void* context) /* @brief fsm handler called on entry to flushing state */ -static void cfstore_flush_fsm_flush_on_entry(void* context) +static void cfstore_flush_fsm_flush_on_entry(void *context) { bool bfound = false; int32_t ivalue = 0; int32_t ret = ARM_DRIVER_ERROR; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; - const char* key_name_query = "*"; - char value[CFSTORE_KEY_NAME_MAX_LENGTH+1]; - ARM_CFSTORE_SIZE len = CFSTORE_KEY_NAME_MAX_LENGTH+1; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; + const char *key_name_query = "*"; + char value[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; + ARM_CFSTORE_SIZE len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; ARM_CFSTORE_HANDLE_INIT(next); ARM_CFSTORE_HANDLE_INIT(prev); ARM_CFSTORE_KEYDESC kdesc; - cfstore_flush_ctx_t* ctx = (cfstore_flush_ctx_t*) context; + cfstore_flush_ctx_t *ctx = (cfstore_flush_ctx_t *) context; /* check that the mtd is in synchronous mode */ CFSTORE_FENTRYLOG("%s:entered: \r\n", __func__); @@ -374,16 +369,14 @@ static void cfstore_flush_fsm_flush_on_entry(void* context) TEST_ASSERT_MESSAGE(ctx->fsm.state == cfstore_flush_fsm_state_flushing, cfstore_flush_utest_msg_g); /* try to read key; should not be found */ ret = cfstore_test_kv_is_found(cfstore_flush_test_02_kv_data->key_name, &bfound); - if(ret != ARM_DRIVER_OK && ret != ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND){ + if (ret != ARM_DRIVER_OK && ret != ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush_utest_msg_g, CFSTORE_FLUSH_UTEST_MSG_BUF_SIZE, "%s:Error: cfstore_test_kv_is_found() call failed (ret=%d).\r\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(false, cfstore_flush_utest_msg_g); } - if(!bfound) - { + if (!bfound) { /* first time start up. nothing is stored in cfstore flash. check this is the case */ - while(drv->Find(key_name_query, prev, next) == ARM_DRIVER_OK) - { + while (drv->Find(key_name_query, prev, next) == ARM_DRIVER_OK) { CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush_utest_msg_g, CFSTORE_FLUSH_UTEST_MSG_BUF_SIZE, "%s:Error: have found an entry in cfstore when none should be present", __func__); TEST_ASSERT_MESSAGE(false, cfstore_flush_utest_msg_g); } @@ -401,7 +394,7 @@ static void cfstore_flush_fsm_flush_on_entry(void* context) CFSTORE_DBGLOG("FLUSH: Success pending for new KV creation (name=%s, value=%s)\n", cfstore_flush_test_02_kv_data->key_name, cfstore_flush_test_02_kv_data->value); } else { /*read the value, increment by 1 and write value back */ - len = CFSTORE_KEY_NAME_MAX_LENGTH+1; + len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; ret = cfstore_test_read(cfstore_flush_test_02_kv_data->key_name, value, &len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush_utest_msg_g, CFSTORE_FLUSH_UTEST_MSG_BUF_SIZE, "%s:Error: failed to read kv data (ret=%d).\r\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush_utest_msg_g); @@ -411,7 +404,7 @@ static void cfstore_flush_fsm_flush_on_entry(void* context) CFSTORE_DBGLOG("FLUSH: Read KV from flash (name=%s, value=%d)\n", cfstore_flush_test_02_kv_data->key_name, (int) ivalue); /* increment value */ ++ivalue; - snprintf(value, CFSTORE_KEY_NAME_MAX_LENGTH+1, "%d", (int) ivalue); + snprintf(value, CFSTORE_KEY_NAME_MAX_LENGTH + 1, "%d", (int) ivalue); len = strlen(value); ret = cfstore_test_write(cfstore_flush_test_02_kv_data->key_name, value, &len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush_utest_msg_g, CFSTORE_FLUSH_UTEST_MSG_BUF_SIZE, "%s:Error: failed to write kv data (ret=%d).\r\n", __func__, (int) ret); @@ -429,9 +422,9 @@ static void cfstore_flush_fsm_flush_on_entry(void* context) /* brief callback handler when in state flushing */ -static void cfstore_flush_fsm_flushing(void* context) +static void cfstore_flush_fsm_flushing(void *context) { - cfstore_flush_ctx_t* ctx = (cfstore_flush_ctx_t*) context; + cfstore_flush_ctx_t *ctx = (cfstore_flush_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered\r\n", __func__); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush_utest_msg_g, CFSTORE_FLUSH_UTEST_MSG_BUF_SIZE, "%s:Error: entered handler(%s) but not in flushing state (fsm->state=%d)\r\n", __func__, __func__, (int) ctx->fsm.state); @@ -441,7 +434,7 @@ static void cfstore_flush_fsm_flushing(void* context) CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush_utest_msg_g, CFSTORE_FLUSH_UTEST_MSG_BUF_SIZE, "%s:Error: status=%d\r\n", __func__, (int) ctx->status); TEST_ASSERT_MESSAGE(ctx->status >= ARM_DRIVER_OK, cfstore_flush_utest_msg_g); /* only change state if status >= 0*/ - if(ctx->status >= 0){ + if (ctx->status >= 0) { /* revert to CFSTORE_LOG if more trace required */ CFSTORE_DBGLOG("FLUSH: Successfully flushed data to flash.%s", "\n"); cfstore_flush_fsm_state_set(&ctx->fsm, cfstore_flush_fsm_state_uninitializing, ctx); @@ -453,11 +446,11 @@ static void cfstore_flush_fsm_flushing(void* context) /* @brief fsm handler called on entry to uninitializing state */ -static void cfstore_flush_fsm_uninit_on_entry(void* context) +static void cfstore_flush_fsm_uninit_on_entry(void *context) { int32_t ret = ARM_DRIVER_ERROR; - cfstore_flush_ctx_t* ctx = (cfstore_flush_ctx_t*) context; - const ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + cfstore_flush_ctx_t *ctx = (cfstore_flush_ctx_t *) context; + const ARM_CFSTORE_DRIVER *drv = &cfstore_driver; /* check that the mtd is in synchronous mode */ CFSTORE_FENTRYLOG("%s:entered: \r\n", __func__); @@ -470,9 +463,9 @@ static void cfstore_flush_fsm_uninit_on_entry(void* context) } /* brief callback handler when in state uninitializing */ -static void cfstore_flush_fsm_uninitializing(void* context) +static void cfstore_flush_fsm_uninitializing(void *context) { - cfstore_flush_ctx_t* ctx = (cfstore_flush_ctx_t*) context; + cfstore_flush_ctx_t *ctx = (cfstore_flush_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered\r\n", __func__); CFSTORE_DBGLOG("%s:ctx->status=%d, ctx->loops_done=%d\r\n", __func__, (int) ctx->status, (int) ctx->loops_done); @@ -483,9 +476,9 @@ static void cfstore_flush_fsm_uninitializing(void* context) CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush_utest_msg_g, CFSTORE_FLUSH_UTEST_MSG_BUF_SIZE, "%s:Error: status=%d\r\n", __func__, (int) ctx->status); TEST_ASSERT_MESSAGE(ctx->status >= ARM_DRIVER_OK, cfstore_flush_utest_msg_g); /* only change state if status >= 0*/ - if(ctx->status >= ARM_DRIVER_OK){ + if (ctx->status >= ARM_DRIVER_OK) { ++ctx->loops_done; - if(ctx->loops_done < CFSTORE_FLUSH_FSM_LOOPS){ + if (ctx->loops_done < CFSTORE_FLUSH_FSM_LOOPS) { cfstore_flush_fsm_state_set(&ctx->fsm, cfstore_flush_fsm_state_initializing, ctx); } else { /* move to init state */ @@ -500,19 +493,17 @@ static void cfstore_flush_fsm_uninitializing(void* context) /* handler functions while in state */ -static cfstore_flush_fsm_handler cfstore_flush_fsm[cfstore_flush_fsm_state_max][cfstore_flush_fsm_event_max] = -{ -/* state\event: init_done flush_done unint_done */ -/* stopped */ {cfstore_flush_fsm_null, cfstore_flush_fsm_null, cfstore_flush_fsm_null }, -/* initialising */ {cfstore_flush_fsm_initializing, cfstore_flush_fsm_null, cfstore_flush_fsm_null }, -/* flushing */ {cfstore_flush_fsm_null, cfstore_flush_fsm_flushing, cfstore_flush_fsm_null }, -/* uninitializing */ {cfstore_flush_fsm_null, cfstore_flush_fsm_null, cfstore_flush_fsm_uninitializing } +static cfstore_flush_fsm_handler cfstore_flush_fsm[cfstore_flush_fsm_state_max][cfstore_flush_fsm_event_max] = { + /* state\event: init_done flush_done unint_done */ + /* stopped */ {cfstore_flush_fsm_null, cfstore_flush_fsm_null, cfstore_flush_fsm_null }, + /* initialising */ {cfstore_flush_fsm_initializing, cfstore_flush_fsm_null, cfstore_flush_fsm_null }, + /* flushing */ {cfstore_flush_fsm_null, cfstore_flush_fsm_flushing, cfstore_flush_fsm_null }, + /* uninitializing */ {cfstore_flush_fsm_null, cfstore_flush_fsm_null, cfstore_flush_fsm_uninitializing } }; /* handler functions for entering the state*/ -static cfstore_flush_fsm_handler cfstore_flush_fsm_on_entry[cfstore_flush_fsm_state_max] = -{ +static cfstore_flush_fsm_handler cfstore_flush_fsm_on_entry[cfstore_flush_fsm_state_max] = { cfstore_flush_fsm_stop_on_entry, cfstore_flush_fsm_init_on_entry, cfstore_flush_fsm_flush_on_entry, @@ -520,8 +511,7 @@ static cfstore_flush_fsm_handler cfstore_flush_fsm_on_entry[cfstore_flush_fsm_st }; /* handler functions for exiting state, currently none used */ -static cfstore_flush_fsm_handler cfstore_flush_fsm_on_exit[cfstore_flush_fsm_state_max] = -{ +static cfstore_flush_fsm_handler cfstore_flush_fsm_on_exit[cfstore_flush_fsm_state_max] = { cfstore_flush_fsm_null, cfstore_flush_fsm_null, cfstore_flush_fsm_null, @@ -530,15 +520,15 @@ static cfstore_flush_fsm_handler cfstore_flush_fsm_on_exit[cfstore_flush_fsm_sta /* @brief inject event into fsm */ -static void cfstore_flush_fsm_state_handle_event(cfstore_fsm_t* fsm, cfstore_flush_fsm_event_t event, void* context) +static void cfstore_flush_fsm_state_handle_event(cfstore_fsm_t *fsm, cfstore_flush_fsm_event_t event, void *context) { - cfstore_flush_ctx_t* ctx = (cfstore_flush_ctx_t*) context; + cfstore_flush_ctx_t *ctx = (cfstore_flush_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered: fsm=%p, state=(%s), event=%d (%s), ctx=%p\r\n", __func__, fsm, cfstore_flush_state_str[fsm->state], (int) event, cfstore_flush_event_str[event], ctx); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush_utest_msg_g, CFSTORE_FLUSH_UTEST_MSG_BUF_SIZE, "%s:Error: invalid event (%d)\r\n", __func__, (int) event); TEST_ASSERT_MESSAGE(event < cfstore_flush_fsm_event_max, cfstore_flush_utest_msg_g); fsm->event = event; - if(cfstore_flush_fsm[fsm->state][fsm->event] != NULL){ + if (cfstore_flush_fsm[fsm->state][fsm->event] != NULL) { cfstore_flush_fsm[fsm->state][fsm->event](ctx); } @@ -552,31 +542,31 @@ static void cfstore_flush_fsm_state_handle_event(cfstore_fsm_t* fsm, cfstore_flu /* @brief function to move to new fsm state, calling state exit function for old state and entry function for new state */ -static void cfstore_flush_fsm_state_set(cfstore_fsm_t* fsm, cfstore_flush_fsm_state_t new_state, void* ctx) +static void cfstore_flush_fsm_state_set(cfstore_fsm_t *fsm, cfstore_flush_fsm_state_t new_state, void *ctx) { - #ifdef CFSTORE_DEBUG +#ifdef CFSTORE_DEBUG cfstore_flush_fsm_state_t old_state = fsm->state; - #endif +#endif CFSTORE_FENTRYLOG("%s:entered: fsm=%p, ctx=%p\r\n", __func__, fsm, ctx); - #ifdef CFSTORE_DEBUG +#ifdef CFSTORE_DEBUG CFSTORE_DBGLOG("%s:FSM:REQ RX:%s:%s\r\n", __func__, cfstore_flush_state_str[fsm->state], cfstore_flush_state_str[new_state]); - #endif +#endif TEST_ASSERT_MESSAGE(fsm != NULL, "fsm is not a valid pointer"); TEST_ASSERT_MESSAGE(new_state < cfstore_flush_fsm_state_max, "new_state is not a valid state"); TEST_ASSERT_MESSAGE(ctx != NULL, "ctx is not a valid pointer"); TEST_ASSERT_MESSAGE(fsm->state < cfstore_flush_fsm_state_max, "fsm->state is not a valid state"); - if(cfstore_flush_fsm_on_exit[fsm->state] != NULL){ + if (cfstore_flush_fsm_on_exit[fsm->state] != NULL) { cfstore_flush_fsm_on_exit[fsm->state](ctx); } fsm->state = new_state; - if(cfstore_flush_fsm_on_entry[new_state] != NULL){ + if (cfstore_flush_fsm_on_entry[new_state] != NULL) { cfstore_flush_fsm_on_entry[new_state](ctx); } - #ifdef CFSTORE_DEBUG +#ifdef CFSTORE_DEBUG CFSTORE_DBGLOG("%s:FSM:REQ DONE fsm=%p, fsm->state (old_state)=%s, new_state=%s, ctx=%p\r\n", __func__, fsm, cfstore_flush_state_str[old_state], cfstore_flush_state_str[new_state], ctx); - #endif +#endif return; } @@ -584,14 +574,14 @@ static void cfstore_flush_fsm_state_set(cfstore_fsm_t* fsm, cfstore_flush_fsm_st /* @brief asynchronous test 01 */ static control_t cfstore_flush_test_02_k64f(void) { - cfstore_flush_ctx_t* ctx = cfstore_flush_ctx_get(); + cfstore_flush_ctx_t *ctx = cfstore_flush_ctx_get(); ARM_CFSTORE_CAPABILITIES caps; - const ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + const ARM_CFSTORE_DRIVER *drv = &cfstore_driver; CFSTORE_FENTRYLOG("%s:entered: \r\n", __func__); memset(&caps, 0, sizeof(caps)); caps = drv->GetCapabilities(); - if(caps.asynchronous_ops == false){ + if (caps.asynchronous_ops == false) { /* This is a async mode only test. If this test is not built for sync mode, then skip testing return true * This means the test will conveniently pass when run in CI as part of async mode testing */ CFSTORE_LOG("*** Skipping test as binary built for flash journal sync mode, and this test is async-only%s", "\n"); @@ -600,7 +590,7 @@ static control_t cfstore_flush_test_02_k64f(void) cfstore_flush_ctx_init(ctx); cfstore_flush_fsm_state_set(&ctx->fsm, cfstore_flush_fsm_state_initializing, ctx); - return CaseTimeout(CFSTORE_FLUSH_GREENTEA_TIMEOUT_S*1000); + return CaseTimeout(CFSTORE_FLUSH_GREENTEA_TIMEOUT_S * 1000); } /* report whether built/configured for flash sync or async mode */ @@ -623,8 +613,8 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - Case("FLUSH_test_00", cfstore_flush_test_00), - Case("FLUSH_test_01", cfstore_flush_test_02_k64f), + Case("FLUSH_test_00", cfstore_flush_test_00), + Case("FLUSH_test_01", cfstore_flush_test_02_k64f), }; diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/flush2/flush2.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/flush2/flush2.cpp index 3d1dd02fbd3..322817ff2f4 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/flush2/flush2.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/flush2/flush2.cpp @@ -66,16 +66,15 @@ static char cfstore_flush_utest_msg_g[CFSTORE_FLUSH_UTEST_MSG_BUF_SIZE]; /* KV data for test_03 */ static cfstore_kv_data_t cfstore_flush_test_02_kv_data[] = { - { "com.arm.mbed.configurationstore.test.flush.cfstoreflushtest02", "1"}, - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - { NULL, NULL}, + { "com.arm.mbed.configurationstore.test.flush.cfstoreflushtest02", "1"}, + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + { NULL, NULL}, }; /* async test version */ -typedef struct cfstore_flush_ctx_t -{ +typedef struct cfstore_flush_ctx_t { int32_t status; ARM_CFSTORE_OPCODE cmd_code; } cfstore_flush_ctx_t; @@ -91,13 +90,13 @@ static cfstore_flush_ctx_t cfstore_flush_ctx_g; */ /* @brief get a pointer to the global context data structure */ -static cfstore_flush_ctx_t* cfstore_flush_ctx_get(void) +static cfstore_flush_ctx_t *cfstore_flush_ctx_get(void) { return &cfstore_flush_ctx_g; } /* @brief initialize global context data structure */ -static void cfstore_flush_ctx_init(cfstore_flush_ctx_t* ctx) +static void cfstore_flush_ctx_init(cfstore_flush_ctx_t *ctx) { TEST_ASSERT_MESSAGE(ctx != NULL, "ctx is NULL"); @@ -127,8 +126,8 @@ static control_t cfstore_flush2_test_00(const size_t call_count) control_t cfstore_flush2_test_01_start(const size_t call_count) { int32_t ret = ARM_DRIVER_ERROR; - cfstore_flush_ctx_t* ctx = cfstore_flush_ctx_get(); - const ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + cfstore_flush_ctx_t *ctx = cfstore_flush_ctx_get(); + const ARM_CFSTORE_DRIVER *drv = &cfstore_driver; /* check that the mtd is in synchronous mode */ CFSTORE_FENTRYLOG("%s:entered:\r\n", __func__); @@ -153,10 +152,10 @@ control_t cfstore_flush2_test_01_mid(const size_t call_count) bool bfound = false; int32_t ivalue = 0; int32_t ret = ARM_DRIVER_ERROR; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; - const char* key_name_query = "*"; - char value[CFSTORE_KEY_NAME_MAX_LENGTH+1]; - ARM_CFSTORE_SIZE len = CFSTORE_KEY_NAME_MAX_LENGTH+1; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; + const char *key_name_query = "*"; + char value[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; + ARM_CFSTORE_SIZE len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; ARM_CFSTORE_HANDLE_INIT(next); ARM_CFSTORE_HANDLE_INIT(prev); ARM_CFSTORE_KEYDESC kdesc; @@ -168,16 +167,14 @@ control_t cfstore_flush2_test_01_mid(const size_t call_count) /* try to read key; should not be found */ ret = cfstore_test_kv_is_found(cfstore_flush_test_02_kv_data->key_name, &bfound); - if(ret != ARM_DRIVER_OK && ret != ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND){ + if (ret != ARM_DRIVER_OK && ret != ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush_utest_msg_g, CFSTORE_FLUSH_UTEST_MSG_BUF_SIZE, "%s:Error: cfstore_test_kv_is_found() call failed (ret=%d).\r\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(false, cfstore_flush_utest_msg_g); } - if(!bfound) - { + if (!bfound) { /* first time start up. nothing is stored in cfstore flash. check this is the case */ - while(drv->Find(key_name_query, prev, next) == ARM_DRIVER_OK) - { + while (drv->Find(key_name_query, prev, next) == ARM_DRIVER_OK) { CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush_utest_msg_g, CFSTORE_FLUSH_UTEST_MSG_BUF_SIZE, "%s:Error: have found an entry in cfstore when none should be present", __func__); TEST_ASSERT_MESSAGE(false, cfstore_flush_utest_msg_g); } @@ -194,7 +191,7 @@ control_t cfstore_flush2_test_01_mid(const size_t call_count) } else { /*read the value, increment by 1 and write value back */ - len = CFSTORE_KEY_NAME_MAX_LENGTH+1; + len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; ret = cfstore_test_read(cfstore_flush_test_02_kv_data->key_name, value, &len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush_utest_msg_g, CFSTORE_FLUSH_UTEST_MSG_BUF_SIZE, "%s:Error: failed to read kv data (ret=%d).\r\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush_utest_msg_g); @@ -202,7 +199,7 @@ control_t cfstore_flush2_test_01_mid(const size_t call_count) /* increment value */ ivalue = atoi(value); ++ivalue; - snprintf(value, CFSTORE_KEY_NAME_MAX_LENGTH+1, "%d", (int) ivalue); + snprintf(value, CFSTORE_KEY_NAME_MAX_LENGTH + 1, "%d", (int) ivalue); len = strlen(value); ret = cfstore_test_write(cfstore_flush_test_02_kv_data->key_name, value, &len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush_utest_msg_g, CFSTORE_FLUSH_UTEST_MSG_BUF_SIZE, "%s:Error: failed to write kv data (ret=%d).\r\n", __func__, (int) ret); @@ -224,7 +221,7 @@ control_t cfstore_flush2_test_01_mid(const size_t call_count) */ control_t cfstore_flush2_test_01_end(const size_t call_count) { - const ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + const ARM_CFSTORE_DRIVER *drv = &cfstore_driver; CFSTORE_FENTRYLOG("%s:entered:\r\n", __func__); (void) call_count; @@ -260,12 +257,12 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - Case("CFSTORE_FLUSH2_test_00", cfstore_flush2_test_00), - Case("CFSTORE_FLUSH2_test_01_start", cfstore_flush2_test_01_start), - Case("CFSTORE_FLUSH2_test_01_mid", cfstore_flush2_test_01_mid), - Case("CFSTORE_FLUSH2_test_01_end", cfstore_flush2_test_01_end), - Case("CFSTORE_FLUSH2_test_02_start", cfstore_utest_default_start), - Case("CFSTORE_FLUSH2_test_02_end", cfstore_flush2_test_02), + Case("CFSTORE_FLUSH2_test_00", cfstore_flush2_test_00), + Case("CFSTORE_FLUSH2_test_01_start", cfstore_flush2_test_01_start), + Case("CFSTORE_FLUSH2_test_01_mid", cfstore_flush2_test_01_mid), + Case("CFSTORE_FLUSH2_test_01_end", cfstore_flush2_test_01_end), + Case("CFSTORE_FLUSH2_test_02_start", cfstore_utest_default_start), + Case("CFSTORE_FLUSH2_test_02_end", cfstore_flush2_test_02), }; diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/flush3/flush3.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/flush3/flush3.cpp index 7e53a782093..d235c0b42b2 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/flush3/flush3.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/flush3/flush3.cpp @@ -83,7 +83,7 @@ int32_t cfstore_flush3_end(void) CFSTORE_DBGLOG("%s:IN\n", __func__); cfsStatus = cfstoreDriver->Uninitialize(); - if(cfsStatus < ARM_DRIVER_OK){ + if (cfsStatus < ARM_DRIVER_OK) { CFSTORE_DBGLOG("CFStore Finalization failed (err %ld)\n", cfsStatus); return ARM_DRIVER_ERROR; } @@ -120,26 +120,26 @@ int32_t cfstore_flush3_delete_file(const char *fileDir, size_t maxFilePathSize, CFSTORE_DBGLOG("%s: cfsStatus == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND. returning success\n", __func__); return ARM_DRIVER_OK; } - if(cfsStatus < ARM_DRIVER_OK){ + if (cfsStatus < ARM_DRIVER_OK) { CFSTORE_DBGLOG("Open failed (err %ld)\n", cfsStatus); return ARM_DRIVER_ERROR; } cfsStatus = cfstoreDriver->Delete(hkey); - if(cfsStatus < ARM_DRIVER_OK){ + if (cfsStatus < ARM_DRIVER_OK) { CFSTORE_DBGLOG("Failed deleting (%s) failed (err %ld)\n", fileName, cfsStatus); status = ARM_DRIVER_ERROR; goto out; } out: cfsStatus = cfstoreDriver->Close(hkey); - if(cfsStatus < ARM_DRIVER_OK){ + if (cfsStatus < ARM_DRIVER_OK) { CFSTORE_DBGLOG("Close failed (err %ld)\n", cfsStatus); return ARM_DRIVER_ERROR; } /* Flash-to-flash only on success */ if (status == ARM_DRIVER_OK) { cfsStatus = cfstoreDriver->Flush(); - if(cfsStatus < ARM_DRIVER_OK){ + if (cfsStatus < ARM_DRIVER_OK) { CFSTORE_DBGLOG("Flush to flash failed (err %ld)\n", cfsStatus); return ARM_DRIVER_ERROR; } @@ -151,18 +151,18 @@ int32_t cfstore_flush3_delete_file(const char *fileDir, size_t maxFilePathSize, int32_t cfstore_flush3_read_file(const char *fileDir, size_t maxFilePathSize, const char *fileName, uint8_t *buff, size_t buffSize) { - int32_t cfsStatus; - int32_t status = ARM_DRIVER_OK; + int32_t cfsStatus; + int32_t status = ARM_DRIVER_OK; - ARM_CFSTORE_DRIVER *cfstoreDriver = &cfstore_driver; - ARM_CFSTORE_FMODE flags; - ARM_CFSTORE_SIZE readCount = buffSize; - ARM_CFSTORE_HANDLE_INIT(hkey); + ARM_CFSTORE_DRIVER *cfstoreDriver = &cfstore_driver; + ARM_CFSTORE_FMODE flags; + ARM_CFSTORE_SIZE readCount = buffSize; + ARM_CFSTORE_HANDLE_INIT(hkey); - CFSTORE_DBGLOG("%s:IN. File name %s, buffer %p, buffsize %d\n", __func__, fileName, buff, buffSize); + CFSTORE_DBGLOG("%s:IN. File name %s, buffer %p, buffsize %d\n", __func__, fileName, buff, buffSize); - CFSTORE_UNUSED_PARAM(fileDir); - CFSTORE_UNUSED_PARAM(maxFilePathSize); + CFSTORE_UNUSED_PARAM(fileDir); + CFSTORE_UNUSED_PARAM(maxFilePathSize); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Uninitialize Cfstore\n", __func__); TEST_ASSERT_MESSAGE(cfstoreDriver != NULL, cfstore_flush3_utest_msg_g); @@ -173,51 +173,51 @@ int32_t cfstore_flush3_read_file(const char *fileDir, size_t maxFilePathSize, co CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Invalid buff\n", __func__); TEST_ASSERT_MESSAGE(buff != NULL, cfstore_flush3_utest_msg_g); - memset(&flags, 0, sizeof(flags)); - flags.read = true; + memset(&flags, 0, sizeof(flags)); + flags.read = true; - cfsStatus = cfstoreDriver->Open(fileName, flags, hkey); - if(cfsStatus == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND){ - CFSTORE_DBGLOG("File (%s) not found (err %ld)\n", fileName, cfsStatus); - return ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND; + cfsStatus = cfstoreDriver->Open(fileName, flags, hkey); + if (cfsStatus == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { + CFSTORE_DBGLOG("File (%s) not found (err %ld)\n", fileName, cfsStatus); + return ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND; - } - if(cfsStatus < ARM_DRIVER_OK){ + } + if (cfsStatus < ARM_DRIVER_OK) { CFSTORE_DBGLOG("Open failed (err %ld)\n", cfsStatus); return ARM_DRIVER_ERROR; } - cfsStatus = cfstoreDriver->Read(hkey, buff, &readCount); - if(cfsStatus < ARM_DRIVER_OK){ + cfsStatus = cfstoreDriver->Read(hkey, buff, &readCount); + if (cfsStatus < ARM_DRIVER_OK) { CFSTORE_DBGLOG("Read failed (err %ld)\n", cfsStatus); status = ARM_DRIVER_ERROR; goto out; } - if(readCount < buffSize){ + if (readCount < buffSize) { CFSTORE_DBGLOG("Read failed, amount is %zu while requested %zu\n", readCount, buffSize); status = ARM_DRIVER_ERROR; goto out; } out: - cfsStatus = cfstoreDriver->Close(hkey); - if(cfsStatus < ARM_DRIVER_OK){ + cfsStatus = cfstoreDriver->Close(hkey); + if (cfsStatus < ARM_DRIVER_OK) { CFSTORE_DBGLOG("Close failed (err %ld)\n", cfsStatus); return ARM_DRIVER_ERROR; } CFSTORE_DBGLOG("%s:OUT: status=%d\n", __func__, (int) status); - return status; + return status; } int32_t cfstore_flush3_write_file(const char *fileDir, size_t maxFilePathSize, const char *fileName, const uint8_t *buff, size_t buffSize) { - int32_t cfsStatus; - int32_t status = ARM_DRIVER_ERROR; + int32_t cfsStatus; + int32_t status = ARM_DRIVER_ERROR; - ARM_CFSTORE_DRIVER *cfstoreDriver = &cfstore_driver; - ARM_CFSTORE_SIZE writeCount = buffSize; - ARM_CFSTORE_KEYDESC keyDesc; - ARM_CFSTORE_HANDLE_INIT(hkey); + ARM_CFSTORE_DRIVER *cfstoreDriver = &cfstore_driver; + ARM_CFSTORE_SIZE writeCount = buffSize; + ARM_CFSTORE_KEYDESC keyDesc; + ARM_CFSTORE_HANDLE_INIT(hkey); - CFSTORE_DBGLOG("%s:IN. File name %s, buffer %p, buffsize %d\n", __func__, fileName, buff, buffSize); + CFSTORE_DBGLOG("%s:IN. File name %s, buffer %p, buffsize %d\n", __func__, fileName, buff, buffSize); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Uninitialize Cfstore\n", __func__); TEST_ASSERT_MESSAGE(cfstoreDriver != NULL, cfstore_flush3_utest_msg_g); @@ -228,104 +228,104 @@ int32_t cfstore_flush3_write_file(const char *fileDir, size_t maxFilePathSize, c CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Invalid buff\n", __func__); TEST_ASSERT_MESSAGE(buff != NULL, cfstore_flush3_utest_msg_g); - /* We always deleting the old file and recreating a new one to preserve simplicity */ - CFSTORE_DBGLOG("Before delete%s", "\n"); + /* We always deleting the old file and recreating a new one to preserve simplicity */ + CFSTORE_DBGLOG("Before delete%s", "\n"); - /* Delete the old file */ - status = cfstore_flush3_delete_file(fileDir, maxFilePathSize, fileName); - if(status != ARM_DRIVER_OK){ + /* Delete the old file */ + status = cfstore_flush3_delete_file(fileDir, maxFilePathSize, fileName); + if (status != ARM_DRIVER_OK) { CFSTORE_DBGLOG("Failed deleting (%s)\n", fileName); return status; } - CFSTORE_DBGLOG("After delete%s", "\n"); - /* Create a new file */ - memset(&keyDesc, 0, sizeof(keyDesc)); - keyDesc.drl = ARM_RETENTION_NVM; - keyDesc.flags.read = true; - keyDesc.flags.write = true; - cfsStatus = cfstoreDriver->Create(fileName, buffSize, &keyDesc, hkey); - if(cfsStatus < ARM_DRIVER_OK){ + CFSTORE_DBGLOG("After delete%s", "\n"); + /* Create a new file */ + memset(&keyDesc, 0, sizeof(keyDesc)); + keyDesc.drl = ARM_RETENTION_NVM; + keyDesc.flags.read = true; + keyDesc.flags.write = true; + cfsStatus = cfstoreDriver->Create(fileName, buffSize, &keyDesc, hkey); + if (cfsStatus < ARM_DRIVER_OK) { CFSTORE_DBGLOG("Fail creating (%s) key-store (%ld)\n", fileName, cfsStatus); return ARM_DRIVER_ERROR; } - CFSTORE_DBGLOG("After create%s", "\n"); - cfsStatus = cfstoreDriver->Write(hkey, (const char *)buff, &writeCount); - if(cfsStatus < ARM_DRIVER_OK){ + CFSTORE_DBGLOG("After create%s", "\n"); + cfsStatus = cfstoreDriver->Write(hkey, (const char *)buff, &writeCount); + if (cfsStatus < ARM_DRIVER_OK) { CFSTORE_DBGLOG("Write failed (err %ld)\n", cfsStatus); status = ARM_DRIVER_ERROR; goto out; } - if(writeCount != buffSize){ + if (writeCount != buffSize) { CFSTORE_DBGLOG("Write failed, amount is %d while requested is %d\n", (int)writeCount, (int)buffSize); status = ARM_DRIVER_ERROR; goto out; } - CFSTORE_DBGLOG("After write%s", "\n"); + CFSTORE_DBGLOG("After write%s", "\n"); out: - cfsStatus = cfstoreDriver->Close(hkey); - if(cfsStatus < ARM_DRIVER_OK){ + cfsStatus = cfstoreDriver->Close(hkey); + if (cfsStatus < ARM_DRIVER_OK) { CFSTORE_DBGLOG("Close failed (err %ld)\n", cfsStatus); return ARM_DRIVER_ERROR; } - CFSTORE_DBGLOG("After close%s", "\n"); - /* Flash-to-flash only on success */ - if (status == ARM_DRIVER_OK) { - cfsStatus = cfstoreDriver->Flush(); - if(cfsStatus < ARM_DRIVER_OK){ - CFSTORE_DBGLOG("Flush to flash failed(err %ld)\n", cfsStatus); - return ARM_DRIVER_ERROR; - } - CFSTORE_DBGLOG("After flush%s", "\n"); - } + CFSTORE_DBGLOG("After close%s", "\n"); + /* Flash-to-flash only on success */ + if (status == ARM_DRIVER_OK) { + cfsStatus = cfstoreDriver->Flush(); + if (cfsStatus < ARM_DRIVER_OK) { + CFSTORE_DBGLOG("Flush to flash failed(err %ld)\n", cfsStatus); + return ARM_DRIVER_ERROR; + } + CFSTORE_DBGLOG("After flush%s", "\n"); + } CFSTORE_DBGLOG("%s:OUT: status=%d\n", __func__, (int) status); - return status; + return status; } int32_t cfstore_flush3_start(void) { - int32_t status = ARM_DRIVER_OK; - int32_t cfsStatus; - ARM_CFSTORE_DRIVER *cfstoreDriver = &cfstore_driver; - ARM_CFSTORE_CAPABILITIES caps; + int32_t status = ARM_DRIVER_OK; + int32_t cfsStatus; + ARM_CFSTORE_DRIVER *cfstoreDriver = &cfstore_driver; + ARM_CFSTORE_CAPABILITIES caps; - CFSTORE_DBGLOG("%s:IN\n", __func__); + CFSTORE_DBGLOG("%s:IN\n", __func__); - /* Initialize configuration store */ - cfsStatus = cfstoreDriver->Initialize(NULL, NULL); - if(cfsStatus < ARM_DRIVER_OK){ + /* Initialize configuration store */ + cfsStatus = cfstoreDriver->Initialize(NULL, NULL); + if (cfsStatus < ARM_DRIVER_OK) { CFSTORE_DBGLOG("CFStore Initialization failed (err %lu)\n", cfsStatus); return ARM_DRIVER_ERROR; } - /* Get capabilities */ - memset(&caps, 0, sizeof(caps)); - caps = cfstoreDriver->GetCapabilities(); - if(caps.asynchronous_ops == true){ + /* Get capabilities */ + memset(&caps, 0, sizeof(caps)); + caps = cfstoreDriver->GetCapabilities(); + if (caps.asynchronous_ops == true) { CFSTORE_DBGLOG("%s:Please configure CFstore to work in synchronous mode. This can be change in config.json file.\n", __func__); status = ARM_DRIVER_ERROR; goto out; } - if(caps.uvisor_support_enabled == true){ + if (caps.uvisor_support_enabled == true) { CFSTORE_DBGLOG("%s:Please enable uvisor spv box.\n", __func__); status = ARM_DRIVER_ERROR; goto out; } - CFSTORE_DBGLOG("%s:OUT: returning ARM_DRIVER_OK\n", __func__); - return ARM_DRIVER_OK; /* init succeeded */ + CFSTORE_DBGLOG("%s:OUT: returning ARM_DRIVER_OK\n", __func__); + return ARM_DRIVER_OK; /* init succeeded */ out: - /* init failed */ - (void) cfstore_flush3_end(); + /* init failed */ + (void) cfstore_flush3_end(); CFSTORE_DBGLOG("%s:OUT: status=%d\n", __func__, (int) status); - return status; + return status; } -int32_t cfstore_flush3_check_data(uint8_t* data, int32_t len, uint8_t val) +int32_t cfstore_flush3_check_data(uint8_t *data, int32_t len, uint8_t val) { int i; - for(i = 0; i < len; i++) { - if(data[i] != val){ + for (i = 0; i < len; i++) { + if (data[i] != val) { /* found byte which doesnt have the expected data value */ return ARM_DRIVER_ERROR; } @@ -411,12 +411,12 @@ static control_t cfstore_flush3_test_01(const size_t call_count) { int32_t i; int32_t ret = ARM_DRIVER_ERROR; - const char* kv_name_root = "com.arm.mbed.spv.sst"; - const char* kv_name_node= "node"; - const char* kv_name_meta= "meta"; - char kv_name[CFSTORE_KEY_NAME_MAX_LENGTH+1]; + const char *kv_name_root = "com.arm.mbed.spv.sst"; + const char *kv_name_node = "node"; + const char *kv_name_meta = "meta"; + char kv_name[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; uint8_t data[CFSTORE_FLUSH3_TEST_DATA_BUF_LEN]; - void* heap_buf = NULL; + void *heap_buf = NULL; (void) call_count; heap_buf = malloc(CFSTORE_FLUSH3_TEST_HEAP_BUF_LEN); @@ -432,14 +432,14 @@ static control_t cfstore_flush3_test_01(const size_t call_count) CFSTORE_DBGLOG("%s: cfstore_flush3_write_file(com.arm.mbed.spv.sst.meta, len: 2280) to create KV\n", __func__); memset(data, CFSTORE_FLUSH3_TEST_DATA_CHAR, CFSTORE_FLUSH3_TEST_DATA_BUF_LEN); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char*) kv_name_root, kv_name_meta); - ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, (const uint8_t*) data, 2280); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char *) kv_name_root, kv_name_meta); + ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, (const uint8_t *) data, 2280); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: A.2 cfstore_flush3_write_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: cfstore_flush3_write_file(com.arm.mbed.spv.sst.node.0, len: 220) to create KV\n", __func__); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char*) kv_name_root, (char*) kv_name_node); - ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, (const uint8_t*) data, 220); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char *) kv_name_root, (char *) kv_name_node); + ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, (const uint8_t *) data, 220); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: A.3 cfstore_flush3_write_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); @@ -449,7 +449,7 @@ static control_t cfstore_flush3_test_01(const size_t call_count) TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: check for heap corruption\n", __func__); - ret = cfstore_flush3_check_data((uint8_t*) heap_buf, CFSTORE_FLUSH3_TEST_HEAP_BUF_LEN, CFSTORE_FLUSH3_HEAP_DATA_CHAR); + ret = cfstore_flush3_check_data((uint8_t *) heap_buf, CFSTORE_FLUSH3_TEST_HEAP_BUF_LEN, CFSTORE_FLUSH3_HEAP_DATA_CHAR); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: A.5 cfstore_flush3_check_data() failed for heap (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); @@ -461,8 +461,8 @@ static control_t cfstore_flush3_test_01(const size_t call_count) CFSTORE_DBGLOG("%s: cfstore_flush3_read_file(com.arm.mbed.spv.sst.meta). read 2280\n", __func__); memset(data, 0, CFSTORE_FLUSH3_TEST_DATA_BUF_LEN); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char*) kv_name_root, (char*) kv_name_meta); - ret = cfstore_flush3_read_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, data, 2280); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char *) kv_name_root, (char *) kv_name_meta); + ret = cfstore_flush3_read_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, data, 2280); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: B.2 cfstore_flush3_read_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); @@ -472,8 +472,8 @@ static control_t cfstore_flush3_test_01(const size_t call_count) CFSTORE_DBGLOG("%s: cfstore_flush3_read_file(com.arm.mbed.spv.sst.node.0). read 220\n", __func__); memset(data, 0, CFSTORE_FLUSH3_TEST_DATA_BUF_LEN); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char*) kv_name_root, (char*) kv_name_node); - ret = cfstore_flush3_read_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, data, 220); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char *) kv_name_root, (char *) kv_name_node); + ret = cfstore_flush3_read_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, data, 220); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: B.4 cfstore_flush3_read_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); @@ -487,7 +487,7 @@ static control_t cfstore_flush3_test_01(const size_t call_count) TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: check for heap corruption\n", __func__); - ret = cfstore_flush3_check_data((uint8_t*) heap_buf, CFSTORE_FLUSH3_TEST_HEAP_BUF_LEN, CFSTORE_FLUSH3_HEAP_DATA_CHAR); + ret = cfstore_flush3_check_data((uint8_t *) heap_buf, CFSTORE_FLUSH3_TEST_HEAP_BUF_LEN, CFSTORE_FLUSH3_HEAP_DATA_CHAR); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: B.7 cfstore_flush3_check_data() failed for heap (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); @@ -498,16 +498,16 @@ static control_t cfstore_flush3_test_01(const size_t call_count) TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: cfstore_flush3_delete_file(com.arm.mbed.spv.sst.node.0). this will work as the KV is present\n", __func__); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char*) kv_name_root, (char*) kv_name_node); - ret = cfstore_flush3_delete_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char *) kv_name_root, (char *) kv_name_node); + ret = cfstore_flush3_delete_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: C.2 cfstore_flush3_delete_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: cfstore_flush3_delete_file(com.arm.mbed.spv.sst.node.x) where x = {1..29}, each of which should fail\n", __func__); - for(i = 1; i <= 29; i++){ - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.%d", (char*) kv_name_root, (char*) kv_name_node, (int) i); - ret = cfstore_flush3_delete_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name); - CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: C.%d cfstore_flush3_delete_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) i+2, (int) ret, kv_name); + for (i = 1; i <= 29; i++) { + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.%d", (char *) kv_name_root, (char *) kv_name_node, (int) i); + ret = cfstore_flush3_delete_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name); + CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: C.%d cfstore_flush3_delete_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) i + 2, (int) ret, kv_name); /* The delete operations are expected to fail as the keys dont exist * but cfstore_flush3_delete_file() returns ARM_DRIVER_OK when key isnt found, so cant test the return code. */ @@ -515,8 +515,8 @@ static control_t cfstore_flush3_test_01(const size_t call_count) } CFSTORE_DBGLOG("%s: cfstore_flush3_delete_file(name com.arm.mbed.spv.sst.meta). this is expected to succeed as the KV is present\n", __func__); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char*) kv_name_root, (char*) kv_name_meta); - ret = cfstore_flush3_delete_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char *) kv_name_root, (char *) kv_name_meta); + ret = cfstore_flush3_delete_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: C.32 cfstore_flush3_delete_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); @@ -533,7 +533,7 @@ static control_t cfstore_flush3_test_01(const size_t call_count) TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: check for heap corruption\n", __func__); - ret = cfstore_flush3_check_data((uint8_t*) heap_buf, CFSTORE_FLUSH3_TEST_HEAP_BUF_LEN, CFSTORE_FLUSH3_HEAP_DATA_CHAR); + ret = cfstore_flush3_check_data((uint8_t *) heap_buf, CFSTORE_FLUSH3_TEST_HEAP_BUF_LEN, CFSTORE_FLUSH3_HEAP_DATA_CHAR); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: C.34 cfstore_flush3_check_data() failed for heap (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); @@ -552,22 +552,22 @@ static control_t cfstore_flush3_test_01(const size_t call_count) CFSTORE_DBGLOG("%s: cfstore_flush3_read_file(com.arm.mbed.spv.sst.meta). this should fail as the kv has been deleted.\n", __func__); memset(data, 0, CFSTORE_FLUSH3_TEST_DATA_BUF_LEN); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char*) kv_name_root, (char*) kv_name_meta); - ret = cfstore_flush3_read_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, data, 2280); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char *) kv_name_root, (char *) kv_name_meta); + ret = cfstore_flush3_read_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, data, 2280); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: D.2 cfstore_flush3_read_file() succeeded when expected to fail (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret < ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: cfstore_flush3_write_file(com.arm.mbed.spv.sst.node.0, len: 220) to create KV.\n", __func__); memset(data, CFSTORE_FLUSH3_TEST_DATA_CHAR, CFSTORE_FLUSH3_TEST_DATA_BUF_LEN); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char*) kv_name_root, (char*) kv_name_node); - ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, (const uint8_t*) data, 220); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char *) kv_name_root, (char *) kv_name_node); + ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, (const uint8_t *) data, 220); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: D.3 cfstore_flush3_write_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: cfstore_flush3_write_file(com.arm.mbed.spv.sst.meta, len: 2280) to create KV.\n", __func__); memset(data, CFSTORE_FLUSH3_TEST_DATA_CHAR, CFSTORE_FLUSH3_TEST_DATA_BUF_LEN); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char*) kv_name_root, (char*) kv_name_meta); - ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, (const uint8_t*) data, 2280); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char *) kv_name_root, (char *) kv_name_meta); + ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, (const uint8_t *) data, 2280); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: D.4 cfstore_flush3_write_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); @@ -577,7 +577,7 @@ static control_t cfstore_flush3_test_01(const size_t call_count) TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: check for heap corruption\n", __func__); - ret = cfstore_flush3_check_data((uint8_t*) heap_buf, CFSTORE_FLUSH3_TEST_HEAP_BUF_LEN, CFSTORE_FLUSH3_HEAP_DATA_CHAR); + ret = cfstore_flush3_check_data((uint8_t *) heap_buf, CFSTORE_FLUSH3_TEST_HEAP_BUF_LEN, CFSTORE_FLUSH3_HEAP_DATA_CHAR); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: D.6 cfstore_flush3_check_data() failed for heap (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); @@ -588,16 +588,16 @@ static control_t cfstore_flush3_test_01(const size_t call_count) TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: cfstore_flush3_delete_file(com.arm.mbed.spv.sst.node.0). this will work as the KV is present.\n", __func__); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char*) kv_name_root, (char*) kv_name_node); - ret = cfstore_flush3_delete_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char *) kv_name_root, (char *) kv_name_node); + ret = cfstore_flush3_delete_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: E.2 cfstore_flush3_delete_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: cfstore_flush3_delete_file(com.arm.mbed.spv.sst.node.x) where x = {1..29}, each of which should fail.\n", __func__); - for(i = 1; i <= 29; i++){ - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.%d", (char*) kv_name_root, (char*) kv_name_node, (int) i); - ret = cfstore_flush3_delete_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name); - CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: E.%d cfstore_flush3_delete_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) i+2, (int) ret, kv_name); + for (i = 1; i <= 29; i++) { + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.%d", (char *) kv_name_root, (char *) kv_name_node, (int) i); + ret = cfstore_flush3_delete_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name); + CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: E.%d cfstore_flush3_delete_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) i + 2, (int) ret, kv_name); /* The delete operations are expected to fail as the keys dont exist * but cfstore_flush3_delete_file() returns ARM_DRIVER_OK when key isnt found, so cant test the return code. */ @@ -605,8 +605,8 @@ static control_t cfstore_flush3_test_01(const size_t call_count) } CFSTORE_DBGLOG("%s: cfstore_flush3_delete_file(name com.arm.mbed.spv.sst.meta). this is expected to succeed as the KV is present.\n", __func__); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char*) kv_name_root, (char*) kv_name_meta); - ret = cfstore_flush3_delete_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char *) kv_name_root, (char *) kv_name_meta); + ret = cfstore_flush3_delete_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: E.32 cfstore_flush3_delete_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); @@ -616,7 +616,7 @@ static control_t cfstore_flush3_test_01(const size_t call_count) TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: check for heap corruption\n", __func__); - ret = cfstore_flush3_check_data((uint8_t*) heap_buf, CFSTORE_FLUSH3_TEST_HEAP_BUF_LEN, CFSTORE_FLUSH3_HEAP_DATA_CHAR); + ret = cfstore_flush3_check_data((uint8_t *) heap_buf, CFSTORE_FLUSH3_TEST_HEAP_BUF_LEN, CFSTORE_FLUSH3_HEAP_DATA_CHAR); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: E.34 cfstore_flush3_check_data() failed for heap (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); @@ -628,57 +628,57 @@ static control_t cfstore_flush3_test_01(const size_t call_count) CFSTORE_DBGLOG("%s: cfstore_flush3_read_file(com.arm.mbed.spv.sst.meta). this should fail as the kv has been deleted.\n", __func__); memset(data, 0, CFSTORE_FLUSH3_TEST_DATA_BUF_LEN); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char*) kv_name_root, (char*) kv_name_meta); - ret = cfstore_flush3_read_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, data, 2280); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char *) kv_name_root, (char *) kv_name_meta); + ret = cfstore_flush3_read_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, data, 2280); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: F.2 cfstore_flush3_read_file() succeeded when expected to fail (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret < ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); memset(data, CFSTORE_FLUSH3_TEST_DATA_CHAR, CFSTORE_FLUSH3_TEST_DATA_BUF_LEN); /* cfstore_flush3_write_file(com.arm.mbed.spv.sst.node.0, len: 220) to create KV */ - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char*) kv_name_root, (char*) kv_name_node); - ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, (const uint8_t*) data, 220); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char *) kv_name_root, (char *) kv_name_node); + ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, (const uint8_t *) data, 220); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: F.3 cfstore_flush3_write_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: cfstore_flush3_write_file(com.arm.mbed.spv.sst.meta, len: 2280) to create KV.\n", __func__); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char*) kv_name_root, (char*) kv_name_meta); - ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, (const uint8_t*) data, 2280); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char *) kv_name_root, (char *) kv_name_meta); + ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, (const uint8_t *) data, 2280); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: F.4 cfstore_flush3_write_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: cfstore_flush3_write_file(com.arm.mbed.spv.sst.node.0, len: 816) to create KV.\n", __func__); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char*) kv_name_root, (char*) kv_name_node); - ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, (const uint8_t*) data, 816); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char *) kv_name_root, (char *) kv_name_node); + ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, (const uint8_t *) data, 816); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: F.5 cfstore_flush3_write_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: cfstore_flush3_write_file(com.arm.mbed.spv.sst.meta, len: 2280) to create KV.\n", __func__); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char*) kv_name_root, (char*) kv_name_meta); - ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, (const uint8_t*) data, 2280); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char *) kv_name_root, (char *) kv_name_meta); + ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, (const uint8_t *) data, 2280); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: F.6 cfstore_flush3_write_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: cfstore_flush3_write_file(com.arm.mbed.spv.sst.node.1, len: 217) to create KV.\n", __func__); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.1", (char*) kv_name_root, (char*) kv_name_node); - ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, (const uint8_t*) data, 217); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.1", (char *) kv_name_root, (char *) kv_name_node); + ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, (const uint8_t *) data, 217); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: F.7 cfstore_flush3_write_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: cfstore_flush3_write_file(com.arm.mbed.spv.sst.meta, len: 2280) to create KV.\n", __func__); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char*) kv_name_root, (char*) kv_name_meta); - ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, (const uint8_t*) data, 2280); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char *) kv_name_root, (char *) kv_name_meta); + ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, (const uint8_t *) data, 2280); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: F.8 cfstore_flush3_write_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: cfstore_flush3_write_file(com.arm.mbed.spv.sst.node.0, len: 818) to create KV.\n", __func__); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char*) kv_name_root, (char*) kv_name_node); - ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, (const uint8_t*) data, 818); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char *) kv_name_root, (char *) kv_name_node); + ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, (const uint8_t *) data, 818); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: F.9 cfstore_flush3_write_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: cfstore_flush3_write_file(com.arm.mbed.spv.sst.meta, len: 2280) to create KV.\n", __func__); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char*) kv_name_root, (char*) kv_name_meta); - ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, (const uint8_t*) data, 2280); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char *) kv_name_root, (char *) kv_name_meta); + ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, (const uint8_t *) data, 2280); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: F.10 cfstore_flush3_write_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); @@ -688,7 +688,7 @@ static control_t cfstore_flush3_test_01(const size_t call_count) TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: check for heap corruption\n", __func__); - ret = cfstore_flush3_check_data((uint8_t*) heap_buf, CFSTORE_FLUSH3_TEST_HEAP_BUF_LEN, CFSTORE_FLUSH3_HEAP_DATA_CHAR); + ret = cfstore_flush3_check_data((uint8_t *) heap_buf, CFSTORE_FLUSH3_TEST_HEAP_BUF_LEN, CFSTORE_FLUSH3_HEAP_DATA_CHAR); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: F.12 cfstore_flush3_check_data() failed for heap (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); @@ -700,8 +700,8 @@ static control_t cfstore_flush3_test_01(const size_t call_count) CFSTORE_DBGLOG("%s: cfstore_flush3_read_file(com.arm.mbed.spv.sst.meta) 2280 bytes should be read.\n", __func__); memset(data, 0, CFSTORE_FLUSH3_TEST_DATA_BUF_LEN); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char*) kv_name_root, (char*) kv_name_meta); - ret = cfstore_flush3_read_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, data, 2280); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char *) kv_name_root, (char *) kv_name_meta); + ret = cfstore_flush3_read_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, data, 2280); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: G.2 cfstore_flush3_read_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); @@ -711,8 +711,8 @@ static control_t cfstore_flush3_test_01(const size_t call_count) CFSTORE_DBGLOG("%s: cfstore_flush3_read_file(com.arm.mbed.spv.sst.node.0) 818 bytes should be read.\n", __func__); memset(data, 0, CFSTORE_FLUSH3_TEST_DATA_BUF_LEN); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char*) kv_name_root, (char*) kv_name_node); - ret = cfstore_flush3_read_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, data, 818); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char *) kv_name_root, (char *) kv_name_node); + ret = cfstore_flush3_read_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, data, 818); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: G.4 cfstore_flush3_read_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); @@ -721,29 +721,29 @@ static control_t cfstore_flush3_test_01(const size_t call_count) TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: cfstore_flush3_read_file(com.arm.mbed.spv.sst.node.1) 217 bytes should be read. repeat 4 times.\n", __func__); - for(i = 0; i < 4; i++){ + for (i = 0; i < 4; i++) { memset(data, 0, CFSTORE_FLUSH3_TEST_DATA_BUF_LEN); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.1", (char*) kv_name_root, (char*) kv_name_node); - ret = cfstore_flush3_read_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, data, 217); - CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: G.%d.1 cfstore_flush3_read_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) i+6, (int) ret, kv_name); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.1", (char *) kv_name_root, (char *) kv_name_node); + ret = cfstore_flush3_read_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, data, 217); + CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: G.%d.1 cfstore_flush3_read_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) i + 6, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); ret = cfstore_flush3_check_data(data, 217, CFSTORE_FLUSH3_TEST_DATA_CHAR); - CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: G.%d.2 cfstore_flush3_check_data() failed (ret=%d, kv_name=%s).\n", __func__, (int) i+6, (int) ret, kv_name); + CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: G.%d.2 cfstore_flush3_check_data() failed (ret=%d, kv_name=%s).\n", __func__, (int) i + 6, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); } memset(data, CFSTORE_FLUSH3_TEST_DATA_CHAR, CFSTORE_FLUSH3_TEST_DATA_BUF_LEN); CFSTORE_DBGLOG("%s: cfstore_flush3_write_file(com.arm.mbed.spv.sst.node.2, len: 235) to create KV.\n", __func__); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char*) kv_name_root, (char*) kv_name_node); - ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, (const uint8_t*) data, 235); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s.0", (char *) kv_name_root, (char *) kv_name_node); + ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, (const uint8_t *) data, 235); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: F.3 cfstore_flush3_write_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: cfstore_flush3_write_file(com.arm.mbed.spv.sst.meta, len: 2280) to create KV.\n", __func__); memset(data, CFSTORE_FLUSH3_TEST_DATA_CHAR, CFSTORE_FLUSH3_TEST_DATA_BUF_LEN); - snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char*) kv_name_root, (char*) kv_name_meta); - ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char*) kv_name, (const uint8_t*) data, 2280); + snprintf(kv_name, CFSTORE_KEY_NAME_MAX_LENGTH, "%s.%s", (char *) kv_name_root, (char *) kv_name_meta); + ret = cfstore_flush3_write_file(NULL, CFSTORE_KEY_NAME_MAX_LENGTH, (const char *) kv_name, (const uint8_t *) data, 2280); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: A.2 cfstore_flush3_write_file() failed (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); @@ -753,11 +753,11 @@ static control_t cfstore_flush3_test_01(const size_t call_count) TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); CFSTORE_DBGLOG("%s: check for heap corruption\n", __func__); - ret = cfstore_flush3_check_data((uint8_t*) heap_buf, CFSTORE_FLUSH3_TEST_HEAP_BUF_LEN, CFSTORE_FLUSH3_HEAP_DATA_CHAR); + ret = cfstore_flush3_check_data((uint8_t *) heap_buf, CFSTORE_FLUSH3_TEST_HEAP_BUF_LEN, CFSTORE_FLUSH3_HEAP_DATA_CHAR); CFSTORE_TEST_UTEST_MESSAGE(cfstore_flush3_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: A.5 cfstore_flush3_check_data() failed for heap (ret=%d, kv_name=%s).\n", __func__, (int) ret, kv_name); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_flush3_utest_msg_g); - if(heap_buf){ + if (heap_buf) { free(heap_buf); } @@ -773,7 +773,7 @@ static control_t cfstore_flush3_test_02(const size_t call_count) ARM_CFSTORE_FMODE flags; ARM_CFSTORE_SIZE len = strlen("key0"); ARM_CFSTORE_HANDLE_INIT(hkey); - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; (void) call_count; memset(&kdesc, 0, sizeof(kdesc)); @@ -837,14 +837,14 @@ static control_t cfstore_flush3_test_00(const size_t call_count) { int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_CAPABILITIES caps;; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; (void) call_count; /* initialise the context */ caps = drv->GetCapabilities(); CFSTORE_LOG("%s:INITIALIZING: caps.asynchronous_ops=%lu\n", __func__, caps.asynchronous_ops); - if(caps.asynchronous_ops == 1){ + if (caps.asynchronous_ops == 1) { /* This is a sync mode only test. If this test is not built for sync mode, then skip testing return true * This means the test will conveniently pass when run in CI as part of async mode testing */ CFSTORE_LOG("*** Skipping test as binary built for flash journal async mode, and this test is sync-only%s", "\n"); @@ -864,12 +864,12 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("FLUSH3_test_00", cfstore_flush3_test_00), + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("FLUSH3_test_00", cfstore_flush3_test_00), #if defined STORAGE_DRIVER_CONFIG_HARDWARE_MTD_ASYNC_OPS && STORAGE_DRIVER_CONFIG_HARDWARE_MTD_ASYNC_OPS==0 - Case("FLUSH3_test_01", cfstore_flush3_test_01), - Case("FLUSH3_test_02", cfstore_flush3_test_02), + Case("FLUSH3_test_01", cfstore_flush3_test_01), + Case("FLUSH3_test_02", cfstore_flush3_test_02), #endif // STORAGE_DRIVER_CONFIG_HARDWARE_MTD_ASYNC_OPS }; diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/init/init.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/init/init.cpp index 025f1af9c06..be86ac39161 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/init/init.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/init/init.cpp @@ -44,8 +44,7 @@ using namespace utest::v1; static char cfstore_init_utest_msg_g[CFSTORE_UTEST_MSG_BUF_SIZE]; /// @cond CFSTORE_DOXYGEN_DISABLE -typedef struct cfstore_init_ctx_t -{ +typedef struct cfstore_init_ctx_t { ARM_CFSTORE_CAPABILITIES caps; } cfstore_init_ctx_t; @@ -67,35 +66,35 @@ static control_t cfstore_init_test_00(const size_t call_count) return CaseNext; } -static void cfstore_init_test_01(cfstore_init_ctx_t* ctx) +static void cfstore_init_test_01(cfstore_init_ctx_t *ctx) { int32_t ret; (void) ctx; - CFSTORE_DBGLOG("INITIALIZING%s", "\r\n"); - ret = cfstore_drv->Initialize(NULL, NULL); + CFSTORE_DBGLOG("INITIALIZING%s", "\r\n"); + ret = cfstore_drv->Initialize(NULL, NULL); CFSTORE_TEST_UTEST_MESSAGE(cfstore_init_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Initialize() should return ret >= 0 for async/synch modes(ret=%ld)\r\n", __func__, ret); - TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_init_utest_msg_g); + TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_init_utest_msg_g); - CFSTORE_DBGLOG("FLUSHING1%s", "\r\n"); - ret = cfstore_drv->Flush(); + CFSTORE_DBGLOG("FLUSHING1%s", "\r\n"); + ret = cfstore_drv->Flush(); CFSTORE_TEST_UTEST_MESSAGE(cfstore_init_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Flush() failed (ret=%ld)\r\n", __func__, ret); - TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_init_utest_msg_g); + TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_init_utest_msg_g); - CFSTORE_DBGLOG("UNINITIALIZING%s", "\r\n"); - ret = cfstore_drv->Uninitialize(); + CFSTORE_DBGLOG("UNINITIALIZING%s", "\r\n"); + ret = cfstore_drv->Uninitialize(); CFSTORE_TEST_UTEST_MESSAGE(cfstore_init_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Uninitialize() should return ret >= 0 for synch mode(ret=%ld)\r\n", __func__, ret); - TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_init_utest_msg_g); + TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_init_utest_msg_g); - CFSTORE_DBGLOG("***************%s", "\r\n"); - CFSTORE_DBGLOG("*** SUCCESS ***%s", "\r\n"); - CFSTORE_DBGLOG("***************%s", "\r\n"); - return; + CFSTORE_DBGLOG("***************%s", "\r\n"); + CFSTORE_DBGLOG("*** SUCCESS ***%s", "\r\n"); + CFSTORE_DBGLOG("***************%s", "\r\n"); + return; } static control_t cfstore_init_app_start(const size_t call_count) { - cfstore_init_ctx_t* ctx = &cfstore_init_ctx_g; + cfstore_init_ctx_t *ctx = &cfstore_init_ctx_g; (void) call_count; @@ -103,9 +102,9 @@ static control_t cfstore_init_app_start(const size_t call_count) memset(ctx, 0, sizeof(cfstore_init_ctx_t)); ctx->caps = cfstore_drv->GetCapabilities(); CFSTORE_LOG("%s:INITIALIZING: caps.asynchronous_ops=%lu\n", __func__, ctx->caps.asynchronous_ops); - if(ctx->caps.asynchronous_ops == 1){ - /* This is a sync mode only test. If this test is not built for sync mode, then skip testing return true - * This means the test will conveniently pass when run in CI as part of async mode testing */ + if (ctx->caps.asynchronous_ops == 1) { + /* This is a sync mode only test. If this test is not built for sync mode, then skip testing return true + * This means the test will conveniently pass when run in CI as part of async mode testing */ CFSTORE_LOG("*** Skipping test as binary built for flash journal async mode, and this test is sync-only%s", "\n"); return CaseNext; } @@ -126,10 +125,10 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("INIT_test_00", cfstore_init_test_00), - Case("INIT_test_01_start", cfstore_init_app_start), + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("INIT_test_00", cfstore_init_test_00), + Case("INIT_test_01_start", cfstore_init_app_start), }; @@ -147,7 +146,7 @@ int main() // stand alone Configuration-Store-Example -void app_start(int argc __unused, char** argv __unused) +void app_start(int argc __unused, char **argv __unused) { cfstore_init_app_start(0); } diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/misc/misc.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/misc/misc.cpp index 954ba204f24..dc741cd4310 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/misc/misc.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/misc/misc.cpp @@ -76,7 +76,7 @@ static control_t cfstore_misc_test_00(const size_t call_count) control_t cfstore_misc_test_00_start(const size_t call_count) { int32_t ret = ARM_DRIVER_ERROR; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_POWER_STATE state = ARM_POWER_OFF; CFSTORE_FENTRYLOG("%s:entered\n", __func__); @@ -96,21 +96,20 @@ control_t cfstore_misc_test_00_start(const size_t call_count) static control_t cfstore_misc_test_00_end(const size_t call_count) { int32_t ret = ARM_DRIVER_ERROR; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_POWER_STATE state = ARM_POWER_OFF; CFSTORE_FENTRYLOG("%s:entered\n", __func__); (void) call_count; - while(state <= ARM_POWER_FULL) - { + while (state <= ARM_POWER_FULL) { ret = drv->PowerControl(state); CFSTORE_TEST_UTEST_MESSAGE(cfstore_misc_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: PowerControl() call failed\r\n", __func__); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_misc_utest_msg_g); state = (ARM_POWER_STATE)((uint32_t) state + 1); } /*try invalid value which should fail*/ - ret = drv->PowerControl((ARM_POWER_STATE ) 0xffffffff); + ret = drv->PowerControl((ARM_POWER_STATE) 0xffffffff); CFSTORE_TEST_UTEST_MESSAGE(cfstore_misc_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:ERror: PowerControl() did not fail with bad value 0xffffffff (not as expected)\r\n", __func__); TEST_ASSERT_MESSAGE(ret < ARM_DRIVER_OK, cfstore_misc_utest_msg_g); @@ -126,7 +125,7 @@ static control_t cfstore_misc_test_00_end(const size_t call_count) */ control_t cfstore_misc_test_01(const size_t call_count) { - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_DRIVER_VERSION version; CFSTORE_FENTRYLOG("%s:entered\n", __func__); @@ -145,12 +144,12 @@ control_t cfstore_misc_test_01(const size_t call_count) /* KV data for test_03 */ static cfstore_kv_data_t cfstore_misc_test_03_kv_data[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - { "The.principles.of.least.action.in.quantum.mechanics", "DoctoralThesis"}, - { "Space.Time.Approach.to.Quantum.Electrodynamic", " PhysicalReview766)"}, - { "An.Operator.Calculus.Having.Applications.in.Quantum.Electrodynamics", "PhysicalReview84)"}, - { NULL, NULL}, + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + { "The.principles.of.least.action.in.quantum.mechanics", "DoctoralThesis"}, + { "Space.Time.Approach.to.Quantum.Electrodynamic", " PhysicalReview766)"}, + { "An.Operator.Calculus.Having.Applications.in.Quantum.Electrodynamics", "PhysicalReview84)"}, + { NULL, NULL}, }; @@ -161,16 +160,16 @@ static cfstore_kv_data_t cfstore_misc_test_03_kv_data[] = { control_t cfstore_misc_test_02_end(const size_t call_count) { uint8_t key_name_len = 0; - char key_name_buf[CFSTORE_KEY_NAME_MAX_LENGTH+1]; + char key_name_buf[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; int32_t ret = ARM_DRIVER_ERROR; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; - cfstore_kv_data_t* node = NULL; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; + cfstore_kv_data_t *node = NULL; ARM_CFSTORE_HANDLE_INIT(hkey); ARM_CFSTORE_FMODE flags; CFSTORE_FENTRYLOG("%s:entered\r\n", __func__); (void) call_count; - memset(key_name_buf, 0, CFSTORE_KEY_NAME_MAX_LENGTH+1); + memset(key_name_buf, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); /* dont set any flags to get default settings */ memset(&flags, 0, sizeof(flags)); @@ -179,18 +178,17 @@ control_t cfstore_misc_test_02_end(const size_t call_count) TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_misc_utest_msg_g); node = cfstore_misc_test_03_kv_data; - while(node->key_name != NULL) - { + while (node->key_name != NULL) { CFSTORE_DBGLOG("%s:About to open KV (key_name=\"%s\", value=\"%s\")\r\n", __func__, node->key_name, node->value); ret = drv->Open(node->key_name, flags, hkey); CFSTORE_TEST_UTEST_MESSAGE(cfstore_misc_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Failed to open node (key_name=\"%s\", value=\"%s\")(ret=%d)\r\n", __func__, node->key_name, node->value, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_misc_utest_msg_g); - key_name_len = CFSTORE_KEY_NAME_MAX_LENGTH+1; + key_name_len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; memset(key_name_buf, 0, key_name_len); drv->GetKeyName(hkey, key_name_buf, &key_name_len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_misc_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to GetKeyName() (key_name (expected)=\"%s\", key_name (returned)=\"%s\", value=\"%s\"), len return=%d, len expected=%d\r\n", __func__, node->key_name, key_name_buf, node->value, (int) key_name_len, (int) strlen(node->key_name)); - TEST_ASSERT_MESSAGE(key_name_len == strlen(node->key_name)+1, cfstore_misc_utest_msg_g); + TEST_ASSERT_MESSAGE(key_name_len == strlen(node->key_name) + 1, cfstore_misc_utest_msg_g); /* revert to CFSTORE_LOG if more trace required */ CFSTORE_DBGLOG("GetKeyName() successfully reported key_name (key_name=\"%s\")\r\n", key_name_buf); @@ -216,8 +214,8 @@ control_t cfstore_misc_test_03_end(const size_t call_count) { int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE len = 0; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; - cfstore_kv_data_t* node = NULL; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; + cfstore_kv_data_t *node = NULL; ARM_CFSTORE_HANDLE_INIT(hkey); ARM_CFSTORE_FMODE flags; @@ -231,8 +229,7 @@ control_t cfstore_misc_test_03_end(const size_t call_count) TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_misc_utest_msg_g); node = cfstore_misc_test_03_kv_data; - while(node->key_name != NULL) - { + while (node->key_name != NULL) { CFSTORE_DBGLOG("%s:About to open KV (key_name=\"%s\", value=\"%s\")\r\n", __func__, node->key_name, node->value); ret = drv->Open(node->key_name, flags, hkey); CFSTORE_TEST_UTEST_MESSAGE(cfstore_misc_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Failed to open node (key_name=\"%s\", value=\"%s\")(ret=%d)\r\n", __func__, node->key_name, node->value, (int) ret); @@ -265,7 +262,7 @@ control_t cfstore_misc_test_04_start(const size_t call_count) { int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_STATUS status; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; CFSTORE_FENTRYLOG("%s:entered\n", __func__); (void) call_count; @@ -287,7 +284,7 @@ control_t cfstore_misc_test_04_start(const size_t call_count) control_t cfstore_misc_test_04_end(const size_t call_count) { int32_t ret = ARM_DRIVER_ERROR; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_STATUS status; CFSTORE_FENTRYLOG("%s:entered\n", __func__); @@ -315,18 +312,18 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("MISC_test_00", cfstore_misc_test_00), - Case("MISC_test_00_start", cfstore_misc_test_00_start), - Case("MISC_test_00_end", cfstore_misc_test_00_end), - Case("MISC_test_01", cfstore_misc_test_01), - Case("MISC_test_02_start", cfstore_utest_default_start), - Case("MISC_test_02_end", cfstore_misc_test_02_end), - Case("MISC_test_03_start", cfstore_utest_default_start), - Case("MISC_test_03_end", cfstore_misc_test_03_end), - Case("MISC_test_04_start", cfstore_misc_test_04_start), - Case("MISC_test_05_end", cfstore_misc_test_04_end), + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("MISC_test_00", cfstore_misc_test_00), + Case("MISC_test_00_start", cfstore_misc_test_00_start), + Case("MISC_test_00_end", cfstore_misc_test_00_end), + Case("MISC_test_01", cfstore_misc_test_01), + Case("MISC_test_02_start", cfstore_utest_default_start), + Case("MISC_test_02_end", cfstore_misc_test_02_end), + Case("MISC_test_03_start", cfstore_utest_default_start), + Case("MISC_test_03_end", cfstore_misc_test_03_end), + Case("MISC_test_04_start", cfstore_misc_test_04_start), + Case("MISC_test_05_end", cfstore_misc_test_04_end), }; diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/open/open.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/open/open.cpp index d1158f4ff3b..5af2584cc41 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/open/open.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/open/open.cpp @@ -69,8 +69,8 @@ UVISOR_BOX_CONFIG(cfstore_open_box1, UVISOR_BOX_STACK_SIZE); /* KV data for test_01 */ static cfstore_kv_data_t cfstore_open_test_01_kv_data[] = { - { "yotta.hello-world.animal{wobbly-dog}{foot}frontLeft", "missing"}, - { NULL, NULL}, + { "yotta.hello-world.animal{wobbly-dog}{foot}frontLeft", "missing"}, + { NULL, NULL}, }; @@ -98,10 +98,10 @@ static control_t cfstore_open_test_00(const size_t call_count) */ control_t cfstore_open_test_01_end(const size_t call_count) { - char* read_buf; + char *read_buf; int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE len = 0; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_KEYDESC kdesc; ARM_CFSTORE_HANDLE_INIT(hkey); cfstore_kv_data_t *node; @@ -121,7 +121,7 @@ control_t cfstore_open_test_01_end(const size_t call_count) CFSTORE_DBGLOG("%s:length of KV=%d (key_name=\"%s\", value=\"%s\")\n", __func__, (int) len, node->key_name, node->value); len = strlen(node->value); - ret = drv->Write(hkey, (char*) node->value, &len); + ret = drv->Write(hkey, (char *) node->value, &len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to write key (key_name=\"%s\", value=\"%s\")(ret=%d)\n", __func__, node->key_name, node->value, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_open_utest_msg_g); @@ -139,7 +139,7 @@ control_t cfstore_open_test_01_end(const size_t call_count) TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_open_utest_msg_g); len = strlen(node->value) + 1; - read_buf = (char*) malloc(len); + read_buf = (char *) malloc(len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to allocated read buffer \n", __func__); TEST_ASSERT_MESSAGE(read_buf != NULL, cfstore_open_utest_msg_g); @@ -153,7 +153,7 @@ control_t cfstore_open_test_01_end(const size_t call_count) CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: read value data (%s) != KV value data (key_name=\"%s\", value=\"%s\")\n", __func__, read_buf, node->key_name, node->value); TEST_ASSERT_MESSAGE(strncmp(read_buf, node->value, strlen(node->value)) == 0, cfstore_open_utest_msg_g); - if(read_buf){ + if (read_buf) { free(read_buf); } CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Close() call failed.\n", __func__); @@ -166,8 +166,8 @@ control_t cfstore_open_test_01_end(const size_t call_count) } static cfstore_kv_data_t cfstore_open_test_02_data[] = { - CFSTORE_INIT_1_TABLE_MID_NODE, - { NULL, NULL}, + CFSTORE_INIT_1_TABLE_MID_NODE, + { NULL, NULL}, }; /** @@ -187,7 +187,7 @@ control_t cfstore_open_test_02_end(const size_t call_count) { int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE len = 0; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_KEYDESC kdesc; ARM_CFSTORE_HANDLE_INIT(hkey); ARM_CFSTORE_FMODE flags; @@ -199,7 +199,7 @@ control_t cfstore_open_test_02_end(const size_t call_count) memset(&flags, 0, sizeof(flags)); kdesc.drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE; len = strlen(cfstore_open_test_02_data[0].value); - ret = cfstore_test_create(cfstore_open_test_02_data[0].key_name, (char*) cfstore_open_test_02_data[0].value, &len, &kdesc); + ret = cfstore_test_create(cfstore_open_test_02_data[0].key_name, (char *) cfstore_open_test_02_data[0].value, &len, &kdesc); CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to create KV in store (ret=%d).\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_open_utest_msg_g); @@ -240,7 +240,7 @@ control_t cfstore_open_test_03_end(const size_t call_count) { int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE len = 0; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_KEYDESC kdesc; ARM_CFSTORE_HANDLE_INIT(hkey); ARM_CFSTORE_FMODE flags; @@ -252,7 +252,7 @@ control_t cfstore_open_test_03_end(const size_t call_count) memset(&flags, 0, sizeof(flags)); kdesc.drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE; len = strlen(cfstore_open_test_02_data[0].value); - ret = cfstore_test_create(cfstore_open_test_02_data[0].key_name, (char*) cfstore_open_test_02_data[0].value, &len, &kdesc); + ret = cfstore_test_create(cfstore_open_test_02_data[0].key_name, (char *) cfstore_open_test_02_data[0].value, &len, &kdesc); CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to create KV in store (ret=%d).\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_open_utest_msg_g); @@ -286,18 +286,18 @@ control_t cfstore_open_test_03_end(const size_t call_count) */ control_t cfstore_open_test_04_end(const size_t call_count) { - char kv_name_good[CFSTORE_KEY_NAME_MAX_LENGTH+1]; /* extra char for terminating null */ - char kv_name_bad[CFSTORE_KEY_NAME_MAX_LENGTH+2]; + char kv_name_good[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; /* extra char for terminating null */ + char kv_name_bad[CFSTORE_KEY_NAME_MAX_LENGTH + 2]; int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE len = 0; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_KEYDESC kdesc; ARM_CFSTORE_FMODE flags; CFSTORE_FENTRYLOG("%s:entered\n", __func__); (void) call_count; - memset(kv_name_good, 0, CFSTORE_KEY_NAME_MAX_LENGTH+1); - memset(kv_name_bad, 0, CFSTORE_KEY_NAME_MAX_LENGTH+2); + memset(kv_name_good, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); + memset(kv_name_bad, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 2); memset(&kdesc, 0, sizeof(kdesc)); /* dont set any flags to get default settings */ memset(&flags, 0, sizeof(flags)); @@ -305,7 +305,7 @@ control_t cfstore_open_test_04_end(const size_t call_count) len = CFSTORE_KEY_NAME_MAX_LENGTH; ret = cfstore_test_kv_name_gen(kv_name_good, len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: unable to generate kv_name_good.\n", __func__); - TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK , cfstore_open_utest_msg_g); + TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_open_utest_msg_g); CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: kv_name_good is not the correct length (len=%d, expected=%d).\n", __func__, (int) strlen(kv_name_good), (int) len); TEST_ASSERT_MESSAGE(strlen(kv_name_good) == CFSTORE_KEY_NAME_MAX_LENGTH, cfstore_open_utest_msg_g); @@ -314,13 +314,13 @@ control_t cfstore_open_test_04_end(const size_t call_count) CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to create KV in store for kv_name_good(ret=%d).\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_open_utest_msg_g); - len = CFSTORE_KEY_NAME_MAX_LENGTH+1; + len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; ret = cfstore_test_kv_name_gen(kv_name_bad, len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: unable to generate kv_name_bad.\n", __func__); - TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK , cfstore_open_utest_msg_g); + TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_open_utest_msg_g); CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: kv_name_bad is not the correct length (len=%d, expected=%d).\n", __func__, (int) strlen(kv_name_bad), (int) len); - TEST_ASSERT_MESSAGE(strlen(kv_name_bad) == CFSTORE_KEY_NAME_MAX_LENGTH+1, cfstore_open_utest_msg_g); + TEST_ASSERT_MESSAGE(strlen(kv_name_bad) == CFSTORE_KEY_NAME_MAX_LENGTH + 1, cfstore_open_utest_msg_g); memset(&kdesc, 0, sizeof(kdesc)); ret = cfstore_test_create(kv_name_bad, kv_name_bad, &len, &kdesc); @@ -344,23 +344,22 @@ typedef struct cfstore_open_kv_name_ascii_node { static const uint32_t cfstore_open_kv_name_ascii_table_code_sentinel_g = 256; /*@brief table recording ascii character codes permitted in kv names */ -static cfstore_open_kv_name_ascii_node cfstore_open_kv_name_ascii_table[] = -{ - {0, false}, /* codes 0-44 not allowed */ - {45, true}, /* codes 45-46 == [-.] allowed */ - {47, false}, /* code 47 not allowed */ - {48, true}, /* codes 48-57 not allowed */ - {58, false}, /* codes 46-64 not allowed */ - {64, true}, /* codes 64-91 allowed [@A-Z] */ - {91, false}, /* code 91-96 not allowed */ - {95, true}, /* code 95 allowed '_' */ - {96, false}, /* codes 96 not allowed */ - {97, true}, /* codes 65-90 allowed [A-Z] and {*/ - {123, false}, /* codes 123 '}' not allowed on its own*/ - {124, false}, /* codes 124 not allowed */ - {125, false}, /* code 125 '}' not allowed on its own*/ - {126, false}, /* codes 126-255 not allowed */ - {cfstore_open_kv_name_ascii_table_code_sentinel_g, false}, /* sentinel */ +static cfstore_open_kv_name_ascii_node cfstore_open_kv_name_ascii_table[] = { + {0, false}, /* codes 0-44 not allowed */ + {45, true}, /* codes 45-46 == [-.] allowed */ + {47, false}, /* code 47 not allowed */ + {48, true}, /* codes 48-57 not allowed */ + {58, false}, /* codes 46-64 not allowed */ + {64, true}, /* codes 64-91 allowed [@A-Z] */ + {91, false}, /* code 91-96 not allowed */ + {95, true}, /* code 95 allowed '_' */ + {96, false}, /* codes 96 not allowed */ + {97, true}, /* codes 65-90 allowed [A-Z] and {*/ + {123, false}, /* codes 123 '}' not allowed on its own*/ + {124, false}, /* codes 124 not allowed */ + {125, false}, /* code 125 '}' not allowed on its own*/ + {126, false}, /* codes 126-255 not allowed */ + {cfstore_open_kv_name_ascii_table_code_sentinel_g, false}, /* sentinel */ }; /// @cond CFSTORE_DOXYGEN_DISABLE @@ -385,108 +384,100 @@ enum cfstore_open_kv_name_pos { control_t cfstore_open_test_05_end(const size_t call_count) { bool f_allowed = false; - char kv_name[CFSTORE_KEY_NAME_MAX_LENGTH+1]; /* extra char for terminating null */ + char kv_name[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; /* extra char for terminating null */ uint32_t j = 0; int32_t ret = ARM_DRIVER_OK; size_t name_len = CFSTORE_KEY_NAME_MAX_LENGTH; ARM_CFSTORE_KEYDESC kdesc; - cfstore_open_kv_name_ascii_node* node = NULL; + cfstore_open_kv_name_ascii_node *node = NULL; uint32_t pos; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; CFSTORE_FENTRYLOG("%s:entered\n", __func__); (void) call_count; #ifdef CFSTORE_DEBUG /* symbol only used why debug is enabled */ - const char* pos_str = NULL; + const char *pos_str = NULL; #endif /* create bad keyname strings with invalid character code at start of keyname */ node = cfstore_open_kv_name_ascii_table; - while(node->code != cfstore_open_kv_name_ascii_table_code_sentinel_g) - { + while (node->code != cfstore_open_kv_name_ascii_table_code_sentinel_g) { /* loop over range */ - for(j = node->code; j < (node+1)->code; j++) - { + for (j = node->code; j < (node + 1)->code; j++) { /* set the start, mid, last character of the name to the test char code */ - for(pos = (uint32_t) cfstore_open_kv_name_pos_start; pos < (uint32_t) cfstore_open_kv_name_pos_max; pos++) - { + for (pos = (uint32_t) cfstore_open_kv_name_pos_start; pos < (uint32_t) cfstore_open_kv_name_pos_max; pos++) { name_len = CFSTORE_KEY_NAME_MAX_LENGTH; - memset(kv_name, 0, CFSTORE_KEY_NAME_MAX_LENGTH+1); + memset(kv_name, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); memset(&kdesc, 0, sizeof(kdesc)); kdesc.drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE; ret = cfstore_test_kv_name_gen(kv_name, name_len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: unable to generate kv_name.\n", __func__); - TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK , cfstore_open_utest_msg_g); + TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_open_utest_msg_g); CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: kv_name incorrect length (len=%d, expected= %d).\n", __func__, (int) strlen(kv_name), (int) name_len); TEST_ASSERT_MESSAGE(strlen(kv_name) == name_len, cfstore_open_utest_msg_g); /* overwrite a char at the pos start, mid, end of the kv_name with an ascii char code (both illegal and legal)*/ - switch(pos) - { - case cfstore_open_kv_name_pos_start: - kv_name[0] = (char) j; - break; - case cfstore_open_kv_name_pos_mid: - /* create bad keyname strings with invalid character code in the middle of keyname */ - kv_name[name_len/2] = (char) j; - break; - case cfstore_open_kv_name_pos_end: - /* create bad keyname strings with invalid character code at end of keyname */ - kv_name[name_len-1] = (char) j; - break; - default: - CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: unexpected value of pos (pos=%d).\n", __func__, (int) pos); - TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_open_utest_msg_g); - break; + switch (pos) { + case cfstore_open_kv_name_pos_start: + kv_name[0] = (char) j; + break; + case cfstore_open_kv_name_pos_mid: + /* create bad keyname strings with invalid character code in the middle of keyname */ + kv_name[name_len / 2] = (char) j; + break; + case cfstore_open_kv_name_pos_end: + /* create bad keyname strings with invalid character code at end of keyname */ + kv_name[name_len - 1] = (char) j; + break; + default: + CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: unexpected value of pos (pos=%d).\n", __func__, (int) pos); + TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_open_utest_msg_g); + break; } #ifdef CFSTORE_DEBUG /* processing only required when debug trace enabled */ - switch(pos) - { - case cfstore_open_kv_name_pos_start: - pos_str = "start"; - break; - case cfstore_open_kv_name_pos_mid: - pos_str = "middle"; - break; - case cfstore_open_kv_name_pos_end: - pos_str = "end"; - break; - default: - break; + switch (pos) { + case cfstore_open_kv_name_pos_start: + pos_str = "start"; + break; + case cfstore_open_kv_name_pos_mid: + pos_str = "middle"; + break; + case cfstore_open_kv_name_pos_end: + pos_str = "end"; + break; + default: + break; } #endif ret = cfstore_test_create(kv_name, kv_name, &name_len, &kdesc); /* special cases */ - switch(j) - { - case 0 : - case 46 : - switch(pos) - { - /* for code = 0 (null terminator). permitted at mid and end of string */ - /* for code = 46 ('.'). permitted at mid and end of string but not at start */ - case cfstore_open_kv_name_pos_start: - f_allowed = false; + switch (j) { + case 0 : + case 46 : + switch (pos) { + /* for code = 0 (null terminator). permitted at mid and end of string */ + /* for code = 46 ('.'). permitted at mid and end of string but not at start */ + case cfstore_open_kv_name_pos_start: + f_allowed = false; + break; + case cfstore_open_kv_name_pos_mid: + case cfstore_open_kv_name_pos_end: + default: + f_allowed = true; + break; + } break; - case cfstore_open_kv_name_pos_mid: - case cfstore_open_kv_name_pos_end: default: - f_allowed = true; + f_allowed = node->f_allowed; break; - } - break; - default: - f_allowed = node->f_allowed; - break; } - if(f_allowed == true) - { + if (f_allowed == true) { CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to create KV in store when kv_name contains valid characters (code=%d, ret=%d).\n", __func__, (int) j, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_open_utest_msg_g); /* revert CFSTORE_LOG for more trace */ @@ -496,9 +487,8 @@ control_t cfstore_open_test_05_end(const size_t call_count) ret = cfstore_test_delete(kv_name); CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to delete KV previously created (code=%d, ret=%d).\n", __func__, (int) j, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_open_utest_msg_g); - } - else - { /*node->f_allowed == false => not allowed to create kv name with ascii code */ + } else { + /*node->f_allowed == false => not allowed to create kv name with ascii code */ CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: created KV in store when kv_name contains an invalid character (code=%d, ret=%d).\n", __func__, (int) j, (int) ret); TEST_ASSERT_MESSAGE(ret < ARM_DRIVER_OK, cfstore_open_utest_msg_g); /* revert CFSTORE_LOG for more trace */ @@ -527,14 +517,14 @@ static const char cfstore_open_ascii_illegal_buf_g[] = "!\"�$%&'()*+,./:;<=>?@ */ control_t cfstore_open_test_06_end(const size_t call_count) { - char kv_name[CFSTORE_KEY_NAME_MAX_LENGTH+1]; /* extra char for terminating null */ + char kv_name[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; /* extra char for terminating null */ size_t i = 0; uint32_t pos = 0; int32_t ret = ARM_DRIVER_OK; size_t name_len = CFSTORE_KEY_NAME_MAX_LENGTH; ARM_CFSTORE_KEYDESC kdesc; size_t buf_data_max = 0; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; CFSTORE_FENTRYLOG("%s:entered\n", __func__); (void) call_count; @@ -542,13 +532,12 @@ control_t cfstore_open_test_06_end(const size_t call_count) /* create bad keyname strings with invalid character code at start of keyname */ buf_data_max = strlen(cfstore_open_ascii_illegal_buf_g); name_len = CFSTORE_KEY_NAME_MAX_LENGTH; - memset(kv_name, 0, CFSTORE_KEY_NAME_MAX_LENGTH+1); + memset(kv_name, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); kdesc.drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE; /* generate a kv name of illegal chars*/ - for(i = 0; i < name_len; i++) - { - pos = rand() % (buf_data_max+1); + for (i = 0; i < name_len; i++) { + pos = rand() % (buf_data_max + 1); kv_name[i] = cfstore_open_ascii_illegal_buf_g[pos]; } @@ -569,13 +558,13 @@ control_t cfstore_open_test_06_end(const size_t call_count) */ control_t cfstore_open_test_07_end(const size_t call_count) { - char kv_name[CFSTORE_KEY_NAME_MAX_LENGTH+1]; /* extra char for terminating null */ + char kv_name[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; /* extra char for terminating null */ size_t i = 0; int32_t ret = ARM_DRIVER_OK; size_t name_len = CFSTORE_KEY_NAME_MAX_LENGTH; ARM_CFSTORE_KEYDESC kdesc; size_t buf_data_max = 0; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; CFSTORE_FENTRYLOG("%s:entered\n", __func__); (void) call_count; @@ -583,16 +572,16 @@ control_t cfstore_open_test_07_end(const size_t call_count) /* create bad keyname strings with invalid character code at start of keyname */ buf_data_max = strlen(cfstore_open_ascii_illegal_buf_g); name_len = CFSTORE_KEY_NAME_MAX_LENGTH; - memset(kv_name, 0, CFSTORE_KEY_NAME_MAX_LENGTH+1); + memset(kv_name, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); kdesc.drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE; ret = cfstore_test_kv_name_gen(kv_name, name_len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: unable to generate kv_name.\n", __func__); - TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK , cfstore_open_utest_msg_g); + TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_open_utest_msg_g); /* pepper the illegal chars across the string*/ - for(i++; i < buf_data_max; i++){ - kv_name[rand() % (name_len+1)] = cfstore_open_ascii_illegal_buf_g[i]; + for (i++; i < buf_data_max; i++) { + kv_name[rand() % (name_len + 1)] = cfstore_open_ascii_illegal_buf_g[i]; } ret = cfstore_test_create(kv_name, kv_name, &name_len, &kdesc); CFSTORE_TEST_UTEST_MESSAGE(cfstore_open_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: created KV in store when kv_name contains invalid characters (ret=%d).\n", __func__, (int) ret); @@ -611,23 +600,23 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("OPEN_test_00", cfstore_open_test_00), - Case("OPEN_test_01_start", cfstore_utest_default_start), - Case("OPEN_test_01_end", cfstore_open_test_01_end), - Case("OPEN_test_02_start", cfstore_utest_default_start), - Case("OPEN_test_02_end", cfstore_open_test_02_end), - Case("OPEN_test_03_start", cfstore_utest_default_start), - Case("OPEN_test_03_end", cfstore_open_test_03_end), - Case("OPEN_test_04_start", cfstore_utest_default_start), - Case("OPEN_test_04_end", cfstore_open_test_04_end), - Case("OPEN_test_05_start", cfstore_utest_default_start), - Case("OPEN_test_05_end", cfstore_open_test_05_end), - Case("OPEN_test_06_start", cfstore_utest_default_start), - Case("OPEN_test_06_end", cfstore_open_test_06_end), - Case("OPEN_test_07_start", cfstore_utest_default_start), - Case("OPEN_test_07_end", cfstore_open_test_07_end), + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("OPEN_test_00", cfstore_open_test_00), + Case("OPEN_test_01_start", cfstore_utest_default_start), + Case("OPEN_test_01_end", cfstore_open_test_01_end), + Case("OPEN_test_02_start", cfstore_utest_default_start), + Case("OPEN_test_02_end", cfstore_open_test_02_end), + Case("OPEN_test_03_start", cfstore_utest_default_start), + Case("OPEN_test_03_end", cfstore_open_test_03_end), + Case("OPEN_test_04_start", cfstore_utest_default_start), + Case("OPEN_test_04_end", cfstore_open_test_04_end), + Case("OPEN_test_05_start", cfstore_utest_default_start), + Case("OPEN_test_05_end", cfstore_open_test_05_end), + Case("OPEN_test_06_start", cfstore_utest_default_start), + Case("OPEN_test_06_end", cfstore_open_test_06_end), + Case("OPEN_test_07_start", cfstore_utest_default_start), + Case("OPEN_test_07_end", cfstore_open_test_07_end), }; diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/read/read.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/read/read.cpp index 53f03af7182..36e70f834c1 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/read/read.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/read/read.cpp @@ -52,8 +52,8 @@ UVISOR_BOX_CONFIG(cfstore_read_box1, UVISOR_BOX_STACK_SIZE); /* KV data for test_01 */ static cfstore_kv_data_t cfstore_read_test_01_kv_data[] = { - CFSTORE_INIT_1_TABLE_MID_NODE, - { NULL, NULL}, + CFSTORE_INIT_1_TABLE_MID_NODE, + { NULL, NULL}, }; /* report whether built/configured for flash sync or async mode */ @@ -75,19 +75,19 @@ static int32_t cfstore_read_seek_test(ARM_CFSTORE_HANDLE hkey, uint32_t offset, ARM_CFSTORE_SIZE len = 1; char read_buf[1]; int32_t ret = ARM_DRIVER_ERROR; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ret = drv->Rseek(hkey, offset); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:failed to Rseek() to desired offset (offset=%d) (ret=%d).\n", __func__, (int) offset, (int) ret); goto out0; } ret = drv->Read(hkey, read_buf, &len); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:failed to Read() (offset=%d)(ret=%d).\n", __func__, (int) offset, (int) ret); goto out0; } - if(read_buf[0] != expected){ + if (read_buf[0] != expected) { ret = ARM_DRIVER_ERROR; goto out0; } @@ -103,7 +103,7 @@ control_t cfstore_read_test_01_end(const size_t call_count) { int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE len = 0; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_KEYDESC kdesc; ARM_CFSTORE_HANDLE_INIT(hkey); cfstore_test_rw_data_entry_t *node; @@ -117,7 +117,7 @@ control_t cfstore_read_test_01_end(const size_t call_count) /* create a key for reading */ kdesc.drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE; len = strlen(cfstore_read_test_01_kv_data[0].value); - ret = cfstore_test_create(cfstore_read_test_01_kv_data[0].key_name, (char*) cfstore_read_test_01_kv_data[0].value, &len, &kdesc); + ret = cfstore_test_create(cfstore_read_test_01_kv_data[0].key_name, (char *) cfstore_read_test_01_kv_data[0].value, &len, &kdesc); CFSTORE_TEST_UTEST_MESSAGE(cfstore_read_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to create KV in store (ret=%d).\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_read_utest_msg_g); @@ -128,8 +128,7 @@ control_t cfstore_read_test_01_end(const size_t call_count) /* seek back and forth in key and check the characters are as expected */ node = cfstore_test_rw_data_table; - while(node->offset != CFSTORE_TEST_RW_TABLE_SENTINEL) - { + while (node->offset != CFSTORE_TEST_RW_TABLE_SENTINEL) { ret = cfstore_read_seek_test(hkey, node->offset, node->rw_char); CFSTORE_TEST_UTEST_MESSAGE(cfstore_read_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Rseek() to offset (%d) didn't read expected char (\'%c\') (ret=%d)\n", __func__, (int) node->offset, node->rw_char, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_read_utest_msg_g); @@ -168,13 +167,13 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("READ_test_00", cfstore_read_test_00), - Case("READ_test_01_start", cfstore_utest_default_start), - Case("READ_test_01_end", cfstore_read_test_01_end), - Case("READ_test_02_start", cfstore_utest_default_start), - Case("READ_test_02_end", cfstore_read_test_02_end), + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("READ_test_00", cfstore_read_test_00), + Case("READ_test_01_start", cfstore_utest_default_start), + Case("READ_test_01_end", cfstore_read_test_01_end), + Case("READ_test_02_start", cfstore_utest_default_start), + Case("READ_test_02_end", cfstore_read_test_02_end), }; diff --git a/features/storage/FEATURE_STORAGE/TESTS/cfstore/write/write.cpp b/features/storage/FEATURE_STORAGE/TESTS/cfstore/write/write.cpp index 41b7a5f27c9..ae295907adc 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/cfstore/write/write.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/cfstore/write/write.cpp @@ -57,8 +57,8 @@ UVISOR_BOX_CONFIG(cfstore_write_box1, UVISOR_BOX_STACK_SIZE); /* KV data for test_01 */ static cfstore_kv_data_t cfstore_write_test_01_kv_data[] = { - CFSTORE_INIT_1_TABLE_MID_NODE, - { NULL, NULL}, + CFSTORE_INIT_1_TABLE_MID_NODE, + { NULL, NULL}, }; @@ -81,18 +81,18 @@ static control_t cfstore_write_test_00(const size_t call_count) */ control_t cfstore_write_test_01_end(const size_t call_count) { - char read_buf[CFSTORE_KEY_NAME_MAX_LENGTH+1]; + char read_buf[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; uint32_t i = 0; int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE len = 0; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_KEYDESC kdesc; ARM_CFSTORE_HANDLE_INIT(hkey); ARM_CFSTORE_FMODE flags; CFSTORE_DBGLOG("%s:entered\n", __func__); (void) call_count; - memset(read_buf, 0, CFSTORE_KEY_NAME_MAX_LENGTH+1); + memset(read_buf, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); memset(&kdesc, 0, sizeof(kdesc)); memset(&flags, 0, sizeof(flags)); @@ -109,15 +109,14 @@ control_t cfstore_write_test_01_end(const size_t call_count) CFSTORE_TEST_UTEST_MESSAGE(cfstore_write_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: failed to open node (key_name=\"%s\", value=\"%s\")(ret=%d)\n", __func__, cfstore_write_test_01_kv_data[0].key_name, cfstore_write_test_01_kv_data[0].value, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_write_utest_msg_g); - for(i = 0; i < strlen(cfstore_write_test_01_kv_data[0].value); i++) - { + for (i = 0; i < strlen(cfstore_write_test_01_kv_data[0].value); i++) { len = 1; ret = drv->Write(hkey, &cfstore_write_test_01_kv_data[0].value[i], &len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_write_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Write failed for char (\'%c\') (ret=%d)\n", __func__, cfstore_write_test_01_kv_data[0].value[i], (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_write_utest_msg_g); } /* check that the value created in the key is as expected*/ - len = CFSTORE_KEY_NAME_MAX_LENGTH+1; + len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; ret = drv->Read(hkey, read_buf, &len); CFSTORE_TEST_UTEST_MESSAGE(cfstore_write_utest_msg_g, CFSTORE_UTEST_MSG_BUF_SIZE, "%s:Error: Read failed (ret=%d)\n", __func__, (int) ret); TEST_ASSERT_MESSAGE(ret >= ARM_DRIVER_OK, cfstore_write_utest_msg_g); @@ -145,7 +144,7 @@ control_t cfstore_write_test_02_end(const size_t call_count) int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE len = 0; ARM_CFSTORE_KEYDESC kdesc; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; CFSTORE_DBGLOG("%s:entered\n", __func__); (void) call_count; @@ -173,13 +172,13 @@ utest::v1::status_t greentea_setup(const size_t number_of_cases) } Case cases[] = { - /* 1 2 3 4 5 6 7 */ - /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ - Case("WRITE_test_00", cfstore_write_test_00), - Case("WRITE_test_01_start", cfstore_utest_default_start), - Case("WRITE_test_01_end", cfstore_write_test_01_end), - Case("WRITE_test_02_start", cfstore_utest_default_start), - Case("WRITE_test_02_end", cfstore_write_test_02_end), + /* 1 2 3 4 5 6 7 */ + /* 1234567890123456789012345678901234567890123456789012345678901234567890 */ + Case("WRITE_test_00", cfstore_write_test_00), + Case("WRITE_test_01_start", cfstore_utest_default_start), + Case("WRITE_test_01_end", cfstore_write_test_01_end), + Case("WRITE_test_02_start", cfstore_utest_default_start), + Case("WRITE_test_02_end", cfstore_write_test_02_end), }; diff --git a/features/storage/FEATURE_STORAGE/TESTS/flash_journal/basicAPI/basicAPI.cpp b/features/storage/FEATURE_STORAGE/TESTS/flash_journal/basicAPI/basicAPI.cpp index cf42fc78312..d1bd31fa8db 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/flash_journal/basicAPI/basicAPI.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/flash_journal/basicAPI/basicAPI.cpp @@ -167,11 +167,11 @@ control_t test_resetAndInitialize(const size_t call_count) } TEST_ASSERT_EQUAL(1, rc); /* synchronous completion of reset() is expected to return 1 */ - /* fall through */ + /* fall through */ case NEEDS_INITIALIZE_FOLLOWING_RESET: /* ensure that the journal has been re-initialized */ TEST_ASSERT_EQUAL(0, sequentialJournal->nextSequenceNumber); - TEST_ASSERT_EQUAL((uint32_t)-1, sequentialJournal->currentBlobIndex); + TEST_ASSERT_EQUAL((uint32_t) -1, sequentialJournal->currentBlobIndex); TEST_ASSERT_EQUAL(SEQUENTIAL_JOURNAL_STATE_INITIALIZED, sequentialJournal->state); rc = FlashJournal_getInfo(&journal, &info); @@ -190,12 +190,12 @@ control_t test_resetAndInitialize(const size_t call_count) } TEST_ASSERT_EQUAL(1, rc); /* synchronous completion of initialize() is expected to return 1 */ - /* fall through */ + /* fall through */ case NEEDS_VERIFICATION_FOLLOWING_INITIALIZE: default: //printf("test_resetAndInitialize: verification\n"); TEST_ASSERT_EQUAL(0, sequentialJournal->nextSequenceNumber); - TEST_ASSERT_EQUAL((uint32_t)-1, sequentialJournal->currentBlobIndex); + TEST_ASSERT_EQUAL((uint32_t) -1, sequentialJournal->currentBlobIndex); TEST_ASSERT_EQUAL(SEQUENTIAL_JOURNAL_STATE_INITIALIZED, sequentialJournal->state); rc = FlashJournal_getInfo(&journal, &info); @@ -272,7 +272,7 @@ control_t test_logSmallWithoutCommit(const size_t call_count) TEST_ASSERT_EQUAL(1, drv->GetCapabilities().asynchronous_ops); return CaseTimeout(500) + CaseRepeatAll; } - /* else, fall through to synchronous verification */ + /* else, fall through to synchronous verification */ default: rc = FlashJournal_read(&journal, buffer, SIZEOF_SMALL_WRITE); @@ -297,7 +297,7 @@ control_t test_logSmallAndCommit(const size_t call_count) TEST_ASSERT_EQUAL(1, drv->GetCapabilities().asynchronous_ops); return CaseTimeout(500) + CaseRepeatAll; } - /* else, fall through to synchronous verification */ + /* else, fall through to synchronous verification */ case 2: rc = FlashJournal_commit(&journal); @@ -306,10 +306,9 @@ control_t test_logSmallAndCommit(const size_t call_count) TEST_ASSERT_EQUAL(1, drv->GetCapabilities().asynchronous_ops); return CaseTimeout(500) + CaseRepeatAll; } - /* else, fall through to synchronous verification */ + /* else, fall through to synchronous verification */ - case 3: - { + case 3: { FlashJournal_Info_t info; rc = FlashJournal_getInfo(&journal, &info); TEST_ASSERT_EQUAL(JOURNAL_STATUS_OK, rc); @@ -324,7 +323,7 @@ control_t test_logSmallAndCommit(const size_t call_count) } TEST_ASSERT_EQUAL(SIZEOF_SMALL_WRITE, rc); - /* intentional fall-through */ + /* intentional fall-through */ default: for (unsigned i = 0; i < SIZEOF_SMALL_WRITE; i++) { @@ -384,7 +383,7 @@ control_t test_logLargeWithoutCommit(const size_t call_count) TEST_ASSERT_EQUAL(1, drv->GetCapabilities().asynchronous_ops); return CaseTimeout(5000) + CaseRepeatAll; } - /* intentional fall-through */ + /* intentional fall-through */ case 3: default: @@ -410,7 +409,7 @@ control_t test_logLargeAndCommit(const size_t call_count) TEST_ASSERT_EQUAL(1, drv->GetCapabilities().asynchronous_ops); return CaseTimeout(500) + CaseRepeatAll; } - /* intentional fall-through */ + /* intentional fall-through */ case 2: rc = FlashJournal_commit(&journal); @@ -419,10 +418,9 @@ control_t test_logLargeAndCommit(const size_t call_count) TEST_ASSERT_EQUAL(1, drv->GetCapabilities().asynchronous_ops); return CaseTimeout(500) + CaseRepeatAll; } - /* intentional fall-through */ + /* intentional fall-through */ - case 3: - { + case 3: { FlashJournal_Info_t info; rc = FlashJournal_getInfo(&journal, &info); TEST_ASSERT_EQUAL(JOURNAL_STATUS_OK, rc); @@ -437,7 +435,7 @@ control_t test_logLargeAndCommit(const size_t call_count) } TEST_ASSERT_EQUAL(SIZEOF_LARGE_WRITE, rc); - /* intentional fall-through */ + /* intentional fall-through */ default: for (unsigned i = 0; i < SIZEOF_LARGE_WRITE; i++) { @@ -491,7 +489,7 @@ control_t test_logLargeAndReadSmallChunks(const size_t call_count) TEST_ASSERT_EQUAL(1, drv->GetCapabilities().asynchronous_ops); return CaseTimeout(500) + CaseRepeatAll; } - /* intentional fall-through */ + /* intentional fall-through */ case 2: rc = FlashJournal_commit(&journal); @@ -500,16 +498,15 @@ control_t test_logLargeAndReadSmallChunks(const size_t call_count) TEST_ASSERT_EQUAL(1, drv->GetCapabilities().asynchronous_ops); return CaseTimeout(500) + CaseRepeatAll; } - /* intentional fall-through */ + /* intentional fall-through */ - case 3: - { + case 3: { FlashJournal_Info_t info; rc = FlashJournal_getInfo(&journal, &info); TEST_ASSERT_EQUAL(JOURNAL_STATUS_OK, rc); TEST_ASSERT_EQUAL(SIZEOF_LARGE_WRITE, info.sizeofJournaledBlob); } - /* intentional fall-through */ + /* intentional fall-through */ default: break; @@ -624,8 +621,7 @@ control_t test_logPattern(size_t call_count) /* intentional fall-through */ call_count = 3; - case 3: - { + case 3: { FlashJournal_Info_t info; rc = FlashJournal_getInfo(&journal, &info); TEST_ASSERT_EQUAL(JOURNAL_STATUS_OK, rc); @@ -1030,25 +1026,40 @@ control_t test_failedSmallWriteFollowedByPaddedWrite(const size_t call_count) void test_crc32() { const unsigned char dummyMsg[] = "ahello world"; - flashJournalCrcReset(); TEST_ASSERT_EQUAL(0xe8b7be43, flashJournalCrcCummulative(dummyMsg, 1)); - flashJournalCrcReset(); TEST_ASSERT_EQUAL(0x7e56a173, flashJournalCrcCummulative(dummyMsg, 2)); - flashJournalCrcReset(); TEST_ASSERT_EQUAL(0x26a80c7d, flashJournalCrcCummulative(dummyMsg, 3)); - flashJournalCrcReset(); TEST_ASSERT_EQUAL(0xb8946773, flashJournalCrcCummulative(dummyMsg, 4)); - flashJournalCrcReset(); TEST_ASSERT_EQUAL(0x5fb2761f, flashJournalCrcCummulative(dummyMsg, 5)); - flashJournalCrcReset(); TEST_ASSERT_EQUAL(0x82582cc7, flashJournalCrcCummulative(dummyMsg, 6)); - flashJournalCrcReset(); TEST_ASSERT_EQUAL(0xeceec07a, flashJournalCrcCummulative(dummyMsg, 7)); - flashJournalCrcReset(); TEST_ASSERT_EQUAL(0xac5f7df0, flashJournalCrcCummulative(dummyMsg, 8)); - flashJournalCrcReset(); TEST_ASSERT_EQUAL(0xb21e3e25, flashJournalCrcCummulative(dummyMsg, 9)); - flashJournalCrcReset(); TEST_ASSERT_EQUAL(0x27bf35e4, flashJournalCrcCummulative(dummyMsg, 10)); - flashJournalCrcReset(); TEST_ASSERT_EQUAL(0x31465baa, flashJournalCrcCummulative(dummyMsg, 11)); - flashJournalCrcReset(); TEST_ASSERT_EQUAL(0xaeef4661, flashJournalCrcCummulative(dummyMsg, 12)); + flashJournalCrcReset(); + TEST_ASSERT_EQUAL(0xe8b7be43, flashJournalCrcCummulative(dummyMsg, 1)); + flashJournalCrcReset(); + TEST_ASSERT_EQUAL(0x7e56a173, flashJournalCrcCummulative(dummyMsg, 2)); + flashJournalCrcReset(); + TEST_ASSERT_EQUAL(0x26a80c7d, flashJournalCrcCummulative(dummyMsg, 3)); + flashJournalCrcReset(); + TEST_ASSERT_EQUAL(0xb8946773, flashJournalCrcCummulative(dummyMsg, 4)); + flashJournalCrcReset(); + TEST_ASSERT_EQUAL(0x5fb2761f, flashJournalCrcCummulative(dummyMsg, 5)); + flashJournalCrcReset(); + TEST_ASSERT_EQUAL(0x82582cc7, flashJournalCrcCummulative(dummyMsg, 6)); + flashJournalCrcReset(); + TEST_ASSERT_EQUAL(0xeceec07a, flashJournalCrcCummulative(dummyMsg, 7)); + flashJournalCrcReset(); + TEST_ASSERT_EQUAL(0xac5f7df0, flashJournalCrcCummulative(dummyMsg, 8)); + flashJournalCrcReset(); + TEST_ASSERT_EQUAL(0xb21e3e25, flashJournalCrcCummulative(dummyMsg, 9)); + flashJournalCrcReset(); + TEST_ASSERT_EQUAL(0x27bf35e4, flashJournalCrcCummulative(dummyMsg, 10)); + flashJournalCrcReset(); + TEST_ASSERT_EQUAL(0x31465baa, flashJournalCrcCummulative(dummyMsg, 11)); + flashJournalCrcReset(); + TEST_ASSERT_EQUAL(0xaeef4661, flashJournalCrcCummulative(dummyMsg, 12)); /* check for composability */ uint32_t crc; for (unsigned msgLen = 1; msgLen < strlen((const char *)dummyMsg); msgLen++) { for (unsigned partitionIndex = 1; partitionIndex < msgLen; partitionIndex++) { - flashJournalCrcReset(); crc = flashJournalCrcCummulative(dummyMsg, partitionIndex); crc = flashJournalCrcCummulative(dummyMsg + partitionIndex, msgLen - partitionIndex); - flashJournalCrcReset(); TEST_ASSERT_EQUAL(flashJournalCrcCummulative(dummyMsg, msgLen), crc); + flashJournalCrcReset(); + crc = flashJournalCrcCummulative(dummyMsg, partitionIndex); + crc = flashJournalCrcCummulative(dummyMsg + partitionIndex, msgLen - partitionIndex); + flashJournalCrcReset(); + TEST_ASSERT_EQUAL(flashJournalCrcCummulative(dummyMsg, msgLen), crc); } } } @@ -1113,7 +1124,7 @@ Case cases[] = { Case("reset and initialize5", test_resetAndInitialize), Case("log large item and read smaller chunks", test_logLargeAndReadSmallChunks<0xAA>), - Case("read large item in small, odd-sized chunks1", test_readLargeInSmallOddChunks<0xAA, ((BUFFER_SIZE / 2) - 1)>), + Case("read large item in small, odd-sized chunks1", test_readLargeInSmallOddChunks < 0xAA, ((BUFFER_SIZE / 2) - 1) >), Case("read large item in small, odd-sized chunks2", test_readLargeInSmallOddChunks<0xAA, 255>), Case("read large item in small, odd-sized chunks3", test_readLargeInSmallOddChunks<0xAA, 1021>), Case("read large item in small, odd-sized chunks4", test_readLargeInSmallOddChunks<0xAA, 2401>), @@ -1121,7 +1132,7 @@ Case cases[] = { Case("log pattern", test_logPattern<0x55>), Case("readFrom", test_readFromInReverse<0x55, 255>), Case("readFrom", test_readFromInReverse<0x55, 512>), - Case("readFrom", test_readFromInReverse<0x55, ((BUFFER_SIZE / 2) - 1)>), + Case("readFrom", test_readFromInReverse < 0x55, ((BUFFER_SIZE / 2) - 1) >), Case("readFrom", test_readFromInReverse<0x55, BUFFER_SIZE>), Case("readFrom followed by sequential reads", test_readFromFollowedByReads<0x55, 255>), Case("readFrom followed by sequential reads", test_readFromFollowedByReads<0x55, 511>), @@ -1136,7 +1147,7 @@ Case cases[] = { Case("log odd-sized chunk", test_logSeveralOddSizedChunks<1217, 4>), Case("log odd-sized chunk", test_logSeveralOddSizedChunks<2402, 5>), Case("log odd-sized chunk", test_logSeveralOddSizedChunks<4803, 3>), - Case("log odd-sized chunk", test_logSeveralOddSizedChunks<(BUFFER_SIZE-1), 7>), + Case("log odd-sized chunk", test_logSeveralOddSizedChunks < (BUFFER_SIZE - 1), 7 >), Case("initialize4", test_initialize), Case("multiple writes, commit, multiple reads", test_multipleWritesFollowedByCommitFollowedByMultipleReads), @@ -1155,7 +1166,7 @@ Specification specification(greentea_setup, cases); Specification specification(default_setup, cases); #endif -int main(int argc, char** argv) +int main(int argc, char **argv) { // Run the test specification Harness::run(specification); diff --git a/features/storage/FEATURE_STORAGE/TESTS/storage-volume-manager/basicAPI/basicAPI.cpp b/features/storage/FEATURE_STORAGE/TESTS/storage-volume-manager/basicAPI/basicAPI.cpp index 8200f8565d5..2b2091832d3 100644 --- a/features/storage/FEATURE_STORAGE/TESTS/storage-volume-manager/basicAPI/basicAPI.cpp +++ b/features/storage/FEATURE_STORAGE/TESTS/storage-volume-manager/basicAPI/basicAPI.cpp @@ -158,7 +158,7 @@ control_t test_againstSingleVolumeAtOffset(const size_t call_count) /* synchronous completion */ TEST_ASSERT(rc == 1); - /* intentional fall-through */ + /* intentional fall-through */ case BASIC_SYNCHRONOUS_API_TESTING: TEST_ASSERT_EQUAL(true, volumeManager.isInitialized()); @@ -168,7 +168,7 @@ control_t test_againstSingleVolumeAtOffset(const size_t call_count) TEST_ASSERT(info.total_storage > 0); { /* add volume */ - rc = volumeManager.addVolume(firstBlock.addr + OFFSET /*addr*/, info.total_storage - OFFSET /*size*/ , &volumeP); + rc = volumeManager.addVolume(firstBlock.addr + OFFSET /*addr*/, info.total_storage - OFFSET /*size*/, &volumeP); TEST_ASSERT_EQUAL(ARM_DRIVER_OK, rc); TEST_ASSERT_EQUAL(true, volumeManager.volumeAtIndex(0)->isAllocated()); @@ -253,7 +253,7 @@ control_t test_againstSingleVolumeAtOffset(const size_t call_count) } state = READ_DATA; - /* intentional fallthrough */ + /* intentional fallthrough */ case READ_DATA: sizeofDataOperation = ((info.total_storage - OFFSET) > BUFFER_SIZE) ? BUFFER_SIZE : (info.total_storage - OFFSET); @@ -269,7 +269,7 @@ control_t test_againstSingleVolumeAtOffset(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case ERASE: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -284,7 +284,7 @@ control_t test_againstSingleVolumeAtOffset(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case READ_AFTER_ERASE: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -299,7 +299,7 @@ control_t test_againstSingleVolumeAtOffset(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case PROGRAM_DATA: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -321,7 +321,7 @@ control_t test_againstSingleVolumeAtOffset(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case READ_AFTER_PROGRAM_DATA: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -336,7 +336,7 @@ control_t test_againstSingleVolumeAtOffset(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case VERIFY_PROGRAM_DATA: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -346,12 +346,12 @@ control_t test_againstSingleVolumeAtOffset(const size_t call_count) } TEST_ASSERT_EQUAL(PATTERN_FOR_PROGRAM_DATA, buffer[index]); } - /* intentional fallthrough */ + /* intentional fallthrough */ case DISCONNECT_VOLUME_MANAGER_CALLBACK: rc = drv->Initialize(mtdCallbackHandler); TEST_ASSERT_EQUAL(1, rc); /* expect synchronous completion */ - /* intentional fallthrough */ + /* intentional fallthrough */ case READ_FROM_DRV_AFTER_PROGRAM_DATA: /* Read after Program */ @@ -364,7 +364,7 @@ control_t test_againstSingleVolumeAtOffset(const size_t call_count) } callbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case VERIFY_PROGRAM_DATA2: TEST_ASSERT_EQUAL(sizeofDataOperation, callbackStatus); @@ -430,7 +430,7 @@ control_t test_againstSingleCStorageAtOffset(const size_t call_count) /* synchronous completion */ TEST_ASSERT(rc == 1); - /* intentional fall-through */ + /* intentional fall-through */ case BASIC_SYNCHRONOUS_API_TESTING: TEST_ASSERT_EQUAL(true, volumeManager.isInitialized()); @@ -440,7 +440,7 @@ control_t test_againstSingleCStorageAtOffset(const size_t call_count) TEST_ASSERT(info.total_storage > 0); { /* add volume */ - rc = volumeManager.addVolume_C(firstBlock.addr + OFFSET /*addr*/, info.total_storage - OFFSET /*size*/ , &mtd); + rc = volumeManager.addVolume_C(firstBlock.addr + OFFSET /*addr*/, info.total_storage - OFFSET /*size*/, &mtd); TEST_ASSERT_EQUAL(ARM_DRIVER_OK, rc); TEST_ASSERT_EQUAL(true, volumeManager.volumeAtIndex(0)->isAllocated()); @@ -531,7 +531,7 @@ control_t test_againstSingleCStorageAtOffset(const size_t call_count) } state = READ_DATA; - /* intentional fallthrough */ + /* intentional fallthrough */ case READ_DATA: sizeofDataOperation = ((info.total_storage - OFFSET) > BUFFER_SIZE) ? BUFFER_SIZE : (info.total_storage - OFFSET); @@ -547,7 +547,7 @@ control_t test_againstSingleCStorageAtOffset(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case ERASE: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -562,7 +562,7 @@ control_t test_againstSingleCStorageAtOffset(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case READ_AFTER_ERASE: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -577,7 +577,7 @@ control_t test_againstSingleCStorageAtOffset(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case PROGRAM_DATA: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -599,7 +599,7 @@ control_t test_againstSingleCStorageAtOffset(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case READ_AFTER_PROGRAM_DATA: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -614,7 +614,7 @@ control_t test_againstSingleCStorageAtOffset(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case VERIFY_PROGRAM_DATA: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -624,12 +624,12 @@ control_t test_againstSingleCStorageAtOffset(const size_t call_count) } TEST_ASSERT_EQUAL(PATTERN_FOR_PROGRAM_DATA, buffer[index]); } - /* intentional fallthrough */ + /* intentional fallthrough */ case DISCONNECT_VOLUME_MANAGER_CALLBACK: rc = drv->Initialize(mtdCallbackHandler); TEST_ASSERT_EQUAL(1, rc); /* expect synchronous completion */ - /* intentional fallthrough */ + /* intentional fallthrough */ case READ_FROM_DRV_AFTER_PROGRAM_DATA: /* Read after Program */ @@ -642,7 +642,7 @@ control_t test_againstSingleCStorageAtOffset(const size_t call_count) } callbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case VERIFY_PROGRAM_DATA2: TEST_ASSERT_EQUAL(sizeofDataOperation, callbackStatus); @@ -707,7 +707,7 @@ control_t test_concurrentAccessFromTwoVolumes(const size_t call_count) /* synchronous completion */ TEST_ASSERT(rc == 1); - /* intentional fall-through */ + /* intentional fall-through */ case ADD_VOLUMES: TEST_ASSERT_EQUAL(true, volumeManager.isInitialized()); @@ -727,7 +727,7 @@ control_t test_concurrentAccessFromTwoVolumes(const size_t call_count) rc = drv->GetBlock(OFFSET1 + SIZE1 - 1, &block1); TEST_ASSERT_EQUAL(ARM_DRIVER_OK, rc); - rc = volumeManager.addVolume(OFFSET1 /*addr*/, SIZE1 /*size*/ , &volume1P); + rc = volumeManager.addVolume(OFFSET1 /*addr*/, SIZE1 /*size*/, &volume1P); TEST_ASSERT_EQUAL(ARM_DRIVER_OK, rc); TEST_ASSERT_EQUAL(true, volumeManager.volumeAtIndex(0)->isAllocated()); @@ -751,7 +751,7 @@ control_t test_concurrentAccessFromTwoVolumes(const size_t call_count) rc = drv->GetBlock(OFFSET2 + SIZE2 - 2, &block2); TEST_ASSERT_EQUAL(ARM_DRIVER_OK, rc); - rc = volumeManager.addVolume(OFFSET2 /*addr*/, SIZE2 /*size*/ , &volume2P); + rc = volumeManager.addVolume(OFFSET2 /*addr*/, SIZE2 /*size*/, &volume2P); TEST_ASSERT_EQUAL(ARM_DRIVER_OK, rc); TEST_ASSERT_EQUAL(true, volumeManager.volumeAtIndex(1)->isAllocated()); @@ -770,7 +770,7 @@ control_t test_concurrentAccessFromTwoVolumes(const size_t call_count) TEST_ASSERT((sizeofDataOperation > 0) && (sizeofDataOperation <= BUFFER_SIZE)); memset(buffer, PATTERN_FOR_PROGRAM_DATA, sizeofDataOperation); - /* intentional fall-through */ + /* intentional fall-through */ case ERASE1: rc = volume1P->Erase(0, sizeofDataOperation); @@ -782,7 +782,7 @@ control_t test_concurrentAccessFromTwoVolumes(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case PROGRAM_DATA1: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -818,7 +818,7 @@ control_t test_concurrentAccessFromTwoVolumes(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case ERASE2: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -832,7 +832,7 @@ control_t test_concurrentAccessFromTwoVolumes(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case PROGRAM_DATA2: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -868,13 +868,13 @@ control_t test_concurrentAccessFromTwoVolumes(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case DISCONNECT_VOLUME_MANAGER_CALLBACK: tr_info("DISCONNECT_VOLUME_MANAGER_CALLBACK"); rc = drv->Initialize(mtdCallbackHandler); TEST_ASSERT_EQUAL(1, rc); /* expect synchronous completion */ - /* intentional fallthrough */ + /* intentional fallthrough */ case READ_FROM_DRV_AFTER_PROGRAM_DATA1: tr_info("verifying state"); @@ -888,7 +888,7 @@ control_t test_concurrentAccessFromTwoVolumes(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case VERIFY_PROGRAM_DATA1: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -899,7 +899,7 @@ control_t test_concurrentAccessFromTwoVolumes(const size_t call_count) } TEST_ASSERT_EQUAL(PATTERN_FOR_PROGRAM_DATA, buffer[index]); } - /* intentional fallthrough */ + /* intentional fallthrough */ case READ_FROM_DRV_AFTER_PROGRAM_DATA2: /* Read after Program */ @@ -912,7 +912,7 @@ control_t test_concurrentAccessFromTwoVolumes(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case VERIFY_PROGRAM_DATA2: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -978,7 +978,7 @@ control_t test_concurrentAccessFromTwoCStorageDevices(const size_t call_count) /* synchronous completion */ TEST_ASSERT(rc == 1); - /* intentional fall-through */ + /* intentional fall-through */ case ADD_VOLUMES: TEST_ASSERT_EQUAL(true, volumeManager.isInitialized()); @@ -994,7 +994,7 @@ control_t test_concurrentAccessFromTwoCStorageDevices(const size_t call_count) rc = drv->GetBlock(OFFSET1 + SIZE1 - 1, &block1); TEST_ASSERT_EQUAL(ARM_DRIVER_OK, rc); - rc = volumeManager.addVolume_C(OFFSET1 /*addr*/, SIZE1 /*size*/ , &mtd1); + rc = volumeManager.addVolume_C(OFFSET1 /*addr*/, SIZE1 /*size*/, &mtd1); TEST_ASSERT_EQUAL(ARM_DRIVER_OK, rc); TEST_ASSERT_EQUAL(true, volumeManager.volumeAtIndex(0)->isAllocated()); @@ -1014,7 +1014,7 @@ control_t test_concurrentAccessFromTwoCStorageDevices(const size_t call_count) rc = drv->GetBlock(OFFSET2 + SIZE2 - 2, &block2); TEST_ASSERT_EQUAL(ARM_DRIVER_OK, rc); - rc = volumeManager.addVolume_C(OFFSET2 /*addr*/, SIZE2 /*size*/ , &mtd2); + rc = volumeManager.addVolume_C(OFFSET2 /*addr*/, SIZE2 /*size*/, &mtd2); TEST_ASSERT_EQUAL(ARM_DRIVER_OK, rc); TEST_ASSERT_EQUAL(true, volumeManager.volumeAtIndex(1)->isAllocated()); @@ -1033,7 +1033,7 @@ control_t test_concurrentAccessFromTwoCStorageDevices(const size_t call_count) TEST_ASSERT((sizeofDataOperation > 0) && (sizeofDataOperation <= BUFFER_SIZE)); memset(buffer, PATTERN_FOR_PROGRAM_DATA, sizeofDataOperation); - /* intentional fall-through */ + /* intentional fall-through */ case ERASE1: rc = mtd1.Erase(0, sizeofDataOperation); @@ -1045,7 +1045,7 @@ control_t test_concurrentAccessFromTwoCStorageDevices(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case PROGRAM_DATA1: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -1081,7 +1081,7 @@ control_t test_concurrentAccessFromTwoCStorageDevices(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case ERASE2: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -1095,7 +1095,7 @@ control_t test_concurrentAccessFromTwoCStorageDevices(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case PROGRAM_DATA2: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -1131,13 +1131,13 @@ control_t test_concurrentAccessFromTwoCStorageDevices(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case DISCONNECT_VOLUME_MANAGER_CALLBACK: tr_info("DISCONNECT_VOLUME_MANAGER_CALLBACK"); rc = drv->Initialize(mtdCallbackHandler); TEST_ASSERT_EQUAL(1, rc); /* expect synchronous completion */ - /* intentional fallthrough */ + /* intentional fallthrough */ case READ_FROM_DRV_AFTER_PROGRAM_DATA1: tr_info("verifying state"); @@ -1151,7 +1151,7 @@ control_t test_concurrentAccessFromTwoCStorageDevices(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case VERIFY_PROGRAM_DATA1: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -1162,7 +1162,7 @@ control_t test_concurrentAccessFromTwoCStorageDevices(const size_t call_count) } TEST_ASSERT_EQUAL(PATTERN_FOR_PROGRAM_DATA, buffer[index]); } - /* intentional fallthrough */ + /* intentional fallthrough */ case READ_FROM_DRV_AFTER_PROGRAM_DATA2: /* Read after Program */ @@ -1175,7 +1175,7 @@ control_t test_concurrentAccessFromTwoCStorageDevices(const size_t call_count) } virtualVolumeCallbackStatus = rc; - /* intentional fallthrough */ + /* intentional fallthrough */ case VERIFY_PROGRAM_DATA2: TEST_ASSERT_EQUAL(sizeofDataOperation, virtualVolumeCallbackStatus); @@ -1208,23 +1208,26 @@ Case cases[] = { Case("Against a single C_Storage at offset", test_againstSingleCStorageAtOffset<65536>), /* note: the following tests are unportable in the sense that they require the underlying storage device to support certain address ranges. */ - Case("Concurrent accesss from two volumes", test_concurrentAccessFromTwoVolumes<512*1024, 128*1024, (512+128)*1024, 128*1024>), - Case("Concurrent accesss from two volumes", test_concurrentAccessFromTwoVolumes<512*1024, 128*1024, (512+128)*1024, 128*1024>), - Case("Concurrent accesss from two volumes", test_concurrentAccessFromTwoVolumes<512*1024, 128*1024, (512+256)*1024, 128*1024>), - Case("Concurrent accesss from two volumes", test_concurrentAccessFromTwoVolumes<512*1024, 128*1024, (512+384)*1024, 128*1024>), - Case("Concurrent accesss from two C_Storage devices", test_concurrentAccessFromTwoCStorageDevices<512*1024, 128*1024, (512+128)*1024, 128*1024>), - Case("Concurrent accesss from two C_Storage devices", test_concurrentAccessFromTwoCStorageDevices<512*1024, 128*1024, (512+256)*1024, 128*1024>), - Case("Concurrent accesss from two C_Storage devices", test_concurrentAccessFromTwoCStorageDevices<512*1024, 128*1024, (512+384)*1024, 128*1024>), + Case("Concurrent accesss from two volumes", test_concurrentAccessFromTwoVolumes < 512 * 1024, 128 * 1024, (512 + 128) * 1024, 128 * 1024 >), + Case("Concurrent accesss from two volumes", test_concurrentAccessFromTwoVolumes < 512 * 1024, 128 * 1024, (512 + 128) * 1024, 128 * 1024 >), + Case("Concurrent accesss from two volumes", test_concurrentAccessFromTwoVolumes < 512 * 1024, 128 * 1024, (512 + 256) * 1024, 128 * 1024 >), + Case("Concurrent accesss from two volumes", test_concurrentAccessFromTwoVolumes < 512 * 1024, 128 * 1024, (512 + 384) * 1024, 128 * 1024 >), + Case("Concurrent accesss from two C_Storage devices", test_concurrentAccessFromTwoCStorageDevices < 512 * 1024, 128 * 1024, (512 + 128) * 1024, 128 * 1024 >), + Case("Concurrent accesss from two C_Storage devices", test_concurrentAccessFromTwoCStorageDevices < 512 * 1024, 128 * 1024, (512 + 256) * 1024, 128 * 1024 >), + Case("Concurrent accesss from two C_Storage devices", test_concurrentAccessFromTwoCStorageDevices < 512 * 1024, 128 * 1024, (512 + 384) * 1024, 128 * 1024 >), }; // Declare your test specification with a custom setup handler #ifndef AVOID_GREENTEA Specification specification(greentea_setup, cases); #else -Specification specification([](const size_t) {return STATUS_CONTINUE;}, cases); +Specification specification([](const size_t) +{ + return STATUS_CONTINUE; +}, cases); #endif -int main(int argc, char** argv) +int main(int argc, char **argv) { mbed_trace_init(); // initialize the trace library mbed_trace_config_set(TRACE_MODE_COLOR | TRACE_ACTIVE_LEVEL_INFO | TRACE_CARRIAGE_RETURN); diff --git a/features/storage/FEATURE_STORAGE/cfstore/configuration-store/configuration_store.h b/features/storage/FEATURE_STORAGE/cfstore/configuration-store/configuration_store.h index 6e92aea9813..ea56524093e 100644 --- a/features/storage/FEATURE_STORAGE/cfstore/configuration-store/configuration_store.h +++ b/features/storage/FEATURE_STORAGE/cfstore/configuration-store/configuration_store.h @@ -80,11 +80,11 @@ extern "C" { #endif #include -#include /* requierd for memset() in ARM_CFSTORE_HANDLE_INIT() */ +#include /* requierd for memset() in ARM_CFSTORE_HANDLE_INIT() */ #include "mbed_toolchain.h" /* required for MBED_DEPRECATED_SINCE */ -#define DEVICE_STORAGE 1 /* enable storage */ +#define DEVICE_STORAGE 1 /* enable storage */ /// @cond CFSTORE_DOXYGEN_DISABLE #include #include @@ -145,17 +145,17 @@ typedef size_t ARM_CFSTORE_OFFSET; //!< CFSTORE type for offset parameters. */ typedef struct _ARM_CFSTORE_STATUS { uint32_t in_progress : 1; //!< indicates a previous \ref ARM_CFSTORE_DRIVER ::Dispatch_Method_Xxx() - //!< function is still in progress and will complete sometime in the future. + //!< function is still in progress and will complete sometime in the future. uint32_t error : 1; //!< indicates a previous \ref ARM_CFSTORE_DRIVER ::Dispatch_Method_Xxx() - //!< function is errored and will complete sometime in the future. + //!< function is errored and will complete sometime in the future. } ARM_CFSTORE_STATUS; /* Defines */ #define CFSTORE_KEY_NAME_MAX_LENGTH 220 //!< The maximum length of the null terminated character - //!< string used as a key name string. +//!< string used as a key name string. #define CFSTORE_VALUE_SIZE_MAX (1<<26) //!< Max size of the KV value blob (currently 64MB) #define CFSTORE_HANDLE_BUFSIZE 24 //!< size of the buffer owned and supplied by client - //!< to CFSTORE to hold internal data structures, referenced by the key handle. +//!< to CFSTORE to hold internal data structures, referenced by the key handle. /** @brief Helper macro to declare handle and client owned buffer supplied * to CFSTORE for storing opaque handle state @@ -198,8 +198,7 @@ typedef struct _ARM_CFSTORE_STATUS { #endif /** @brief The access control permissions for the key-value. */ -typedef struct ARM_CFSTORE_ACCESS_CONTROL_LIST -{ +typedef struct ARM_CFSTORE_ACCESS_CONTROL_LIST { uint32_t perm_owner_read : 1; //!< When set this KV is owner readable uint32_t perm_owner_write : 1; //!< When set this KV is owner writable. The owner should set this bit to be able delete the KV. uint32_t perm_owner_execute : 1; //!< When set this KV is owner executable @@ -217,35 +216,33 @@ typedef struct ARM_CFSTORE_ACCESS_CONTROL_LIST * - ARM_CFSTORE_DRIVER::(*Create)(), when creating a KV. * - ARM_CFSTORE_DRIVER::(*Open)(), when opening a pre-existing KV. */ -typedef struct ARM_CFSTORE_FMODE -{ +typedef struct ARM_CFSTORE_FMODE { uint32_t continuous : 1; //!< If set, the key value should be stored in a continuous sequence - //!< of hardware addresses (not implemented). + //!< of hardware addresses (not implemented). uint32_t lazy_flush : 1; //!< If set then configuration store will defer flushing the KV - //!< changes until an optimal time. e.g. to save energy rather than - //!< performing the operation immediately (not implemented). + //!< changes until an optimal time. e.g. to save energy rather than + //!< performing the operation immediately (not implemented). uint32_t flush_on_close : 1; //!< If set then the key-value should be flushed to the backing store - //!< when the key is closed (not implemented). + //!< when the key is closed (not implemented). uint32_t read : 1; //!< If set then the KV can be read. uint32_t write : 1; //!< If set then the KV can be written. uint32_t execute : 1; //!< If set then the KV can be executed (not implemented). uint32_t storage_detect : 1; //!< If set then the call to ARM_CFSTORE_DRIVER::(*Create)() returns - //!< whether a key could be created with the required storage - //!< characteristics. The key is not created. + //!< whether a key could be created with the required storage + //!< characteristics. The key is not created. uint32_t reserved : 25; //!< Reserved. } ARM_CFSTORE_FMODE; /** @brief Descriptor used to create keys */ -typedef struct ARM_CFSTORE_KEYDESC -{ +typedef struct ARM_CFSTORE_KEYDESC { /*key descriptor attributes */ ARM_CFSTORE_ACCESS_CONTROL_LIST acl; //!< Access Control List specifying the access permissions of the KV. uint8_t drl; //!< Data retention level for the KV required by the client. - //!< CFSTORE will store the KV in the specified type store/media. + //!< CFSTORE will store the KV in the specified type store/media. ARM_STORAGE_SECURITY_FEATURES security; //!< flash security properties for the KV required by the client. - //!< CFSTORE will store the KV in a storage media supporting - //!< the specified security attributes. + //!< CFSTORE will store the KV in a storage media supporting + //!< the specified security attributes. ARM_CFSTORE_FMODE flags; //!< A bitfield containing the access mode setting for the key. } ARM_CFSTORE_KEYDESC; @@ -304,10 +301,9 @@ typedef void (*ARM_CFSTORE_CALLBACK)(int32_t status, ARM_CFSTORE_OPCODE cmd_code /** @brief Find the capabilities of the configuration store. */ -typedef struct ARM_CFSTORE_CAPABILITIES -{ +typedef struct ARM_CFSTORE_CAPABILITIES { uint32_t asynchronous_ops : 1; //!< When set then the configuration store dispatch interface is operating in non-blocking (asynchronous) mode. - //!< When unset then the configuration store dispatch interface is operating in blocking (synchronous) mode. + //!< When unset then the configuration store dispatch interface is operating in blocking (synchronous) mode. uint32_t uvisor_support_enabled : 1; //!< The configuration store is using uvisor security contexts. } ARM_CFSTORE_CAPABILITIES; @@ -321,8 +317,7 @@ typedef struct ARM_CFSTORE_CAPABILITIES * (*GetCapabilities) method to determine the operational mode and then * behave accordingly. */ -typedef struct _ARM_DRIVER_CFSTORE -{ +typedef struct _ARM_DRIVER_CFSTORE { /** @brief Get driver version. * * The synchronous function GetVersion() returns version information of the @@ -337,7 +332,7 @@ typedef struct _ARM_DRIVER_CFSTORE * @return \ref ARM_DRIVER_VERSION, the configuration store driver * version information */ - ARM_DRIVER_VERSION (*GetVersion)(void); + ARM_DRIVER_VERSION(*GetVersion)(void); /** @brief Close the hkey context previously recovered from CFSTORE. @@ -410,7 +405,7 @@ typedef struct _ARM_DRIVER_CFSTORE * as registered with ARM_CFSTORE_DRIVER::(*Initialize)() * @param hkey now contains returned handle to newly created key. */ - int32_t (*Create)(const char* key_name, ARM_CFSTORE_SIZE value_len, const ARM_CFSTORE_KEYDESC* kdesc, ARM_CFSTORE_HANDLE hkey); + int32_t (*Create)(const char *key_name, ARM_CFSTORE_SIZE value_len, const ARM_CFSTORE_KEYDESC *kdesc, ARM_CFSTORE_HANDLE hkey); /** @brief Delete key-value from configuration store @@ -542,7 +537,7 @@ typedef struct _ARM_DRIVER_CFSTORE * ARM_DRIVER_OK => contains returned handle to newly found key. * else, indeterminate data. */ - int32_t (*Find)(const char* key_name_query, const ARM_CFSTORE_HANDLE previous, ARM_CFSTORE_HANDLE next); + int32_t (*Find)(const char *key_name_query, const ARM_CFSTORE_HANDLE previous, ARM_CFSTORE_HANDLE next); /** @brief @@ -574,7 +569,7 @@ typedef struct _ARM_DRIVER_CFSTORE * * @return \ref ARM_CFSTORE_CAPABILITIES */ - ARM_CFSTORE_CAPABILITIES (*GetCapabilities)(void); + ARM_CFSTORE_CAPABILITIES(*GetCapabilities)(void); /** @brief Get the name of an open key handle. @@ -603,7 +598,7 @@ typedef struct _ARM_DRIVER_CFSTORE * the additional character corresponds to the terminating null. * */ - int32_t (*GetKeyName)(ARM_CFSTORE_HANDLE hkey, char* key_name, uint8_t *key_len); + int32_t (*GetKeyName)(ARM_CFSTORE_HANDLE hkey, char *key_name, uint8_t *key_len); /** @brief Get the status of the configuration store. @@ -627,7 +622,7 @@ typedef struct _ARM_DRIVER_CFSTORE * @param hkey * unused. */ - ARM_CFSTORE_STATUS (*GetStatus)(void); + ARM_CFSTORE_STATUS(*GetStatus)(void); /** @brief Get the value length from an open key handle @@ -696,7 +691,7 @@ typedef struct _ARM_DRIVER_CFSTORE * @param hkey, unused. * */ - int32_t (*Initialize)(ARM_CFSTORE_CALLBACK callback, void* client_context); + int32_t (*Initialize)(ARM_CFSTORE_CALLBACK callback, void *client_context); /** @brief Function to set the target configuration store power state. @@ -759,7 +754,7 @@ typedef struct _ARM_DRIVER_CFSTORE * @param client context, registered ARM_CFSTORE_DRIVER::(*Initialize)() * @param hkey, unused. */ - int32_t (*Read)(ARM_CFSTORE_HANDLE hkey, void* data, ARM_CFSTORE_SIZE* len); + int32_t (*Read)(ARM_CFSTORE_HANDLE hkey, void *data, ARM_CFSTORE_SIZE *len); /** @brief Open a key-value object for future operations. @@ -783,7 +778,7 @@ typedef struct _ARM_DRIVER_CFSTORE * @param client context, registered ARM_CFSTORE_DRIVER::(*Initialize)() * @param hkey now contains returned handle to newly opened key. */ - int32_t (*Open)(const char* key_name, ARM_CFSTORE_FMODE flags, ARM_CFSTORE_HANDLE hkey); + int32_t (*Open)(const char *key_name, ARM_CFSTORE_FMODE flags, ARM_CFSTORE_HANDLE hkey); /** @brief Move the position of the read pointer within a value @@ -867,7 +862,7 @@ typedef struct _ARM_DRIVER_CFSTORE * @param client context, registered ARM_CFSTORE_DRIVER::(*Initialize)() * @param hkey, unused. */ - int32_t (*Write)(ARM_CFSTORE_HANDLE hkey, const char* data, ARM_CFSTORE_SIZE* len); + int32_t (*Write)(ARM_CFSTORE_HANDLE hkey, const char *data, ARM_CFSTORE_SIZE *len); } const ARM_CFSTORE_DRIVER; diff --git a/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_config.h b/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_config.h index 3ab1732814e..4ec320a6798 100644 --- a/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_config.h +++ b/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_config.h @@ -18,7 +18,7 @@ /* default values */ #define CFSTORE_CONFIG_BACKEND_UVISOR_ENABLED 0 -#define CFSTORE_CONFIG_MBED_OS_VERSION 3 +#define CFSTORE_CONFIG_MBED_OS_VERSION 3 /* default build config overridden by package manager configuration * diff --git a/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_fnmatch.c b/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_fnmatch.c index 4df26e3fcb4..11062717cd5 100644 --- a/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_fnmatch.c +++ b/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_fnmatch.c @@ -1,6 +1,6 @@ /* * Copyright (c) 1989, 1993, 1994 - * The Regents of the University of California. All rights reserved. + * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Guido van Rossum. @@ -55,15 +55,15 @@ static char sccsid[] = "@(#)cfstore_fnmatch.c 8.2 (Berkeley) 4/16/94"; /* code copied from the original cfstore_fnmatch.h */ -#define FNM_NOESCAPE 0x01 /* Disable backslash escaping. */ -#define FNM_PATHNAME 0x02 /* Slash must be matched by slash. */ -#define FNM_PERIOD 0x04 /* Period must be matched by period. */ +#define FNM_NOESCAPE 0x01 /* Disable backslash escaping. */ +#define FNM_PATHNAME 0x02 /* Slash must be matched by slash. */ +#define FNM_PERIOD 0x04 /* Period must be matched by period. */ -#define FNM_LEADING_DIR 0x08 /* Ignore / after Imatch. */ -#define FNM_CASEFOLD 0x10 /* Case insensitive search. */ +#define FNM_LEADING_DIR 0x08 /* Ignore / after Imatch. */ +#define FNM_CASEFOLD 0x10 /* Case insensitive search. */ -#define EOS '\0' +#define EOS '\0' #define RANGE_MATCH 1 #define RANGE_NOMATCH 0 @@ -75,8 +75,8 @@ static char sccsid[] = "@(#)cfstore_fnmatch.c 8.2 (Berkeley) 4/16/94"; * here: * * Copyright (c) 1995 Alex Tatmanjants - * at Electronni Visti IA, Kiev, Ukraine. - * All rights reserved. + * at Electronni Visti IA, Kiev, Ukraine. + * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -137,21 +137,23 @@ int __collate_load_error = 1; * "[a-z]"-type ranges with national characters. */ -static int __collate_range_cmp (int c1, int c2) +static int __collate_range_cmp(int c1, int c2) { - static char s1[2], s2[2]; - int ret; - - c1 &= UCHAR_MAX; - c2 &= UCHAR_MAX; - if (c1 == c2) - return (0); - - s1[0] = c1; - s2[0] = c2; - if ((ret = strcoll(s1, s2)) != 0) - return (ret); - return (c1 - c2); + static char s1[2], s2[2]; + int ret; + + c1 &= UCHAR_MAX; + c2 &= UCHAR_MAX; + if (c1 == c2) { + return (0); + } + + s1[0] = c1; + s2[0] = c2; + if ((ret = strcoll(s1, s2)) != 0) { + return (ret); + } + return (c1 - c2); } @@ -159,168 +161,192 @@ static int rangematch(const char *, char, int, char **); int cfstore_fnmatch(const char *pattern, const char *string, int flags) { - const char *stringstart; - char *newp; - char c, test; - - for (stringstart = string;;) - switch (c = *pattern++) { - case EOS: - if ((flags & FNM_LEADING_DIR) && *string == '/') - return (0); - return (*string == EOS ? 0 : CFSTORE_FNM_NOMATCH); - case '?': - if (*string == EOS) - return (CFSTORE_FNM_NOMATCH); - if (*string == '/' && (flags & FNM_PATHNAME)) - return (CFSTORE_FNM_NOMATCH); - if (*string == '.' && (flags & FNM_PERIOD) && - (string == stringstart || - ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) - return (CFSTORE_FNM_NOMATCH); - ++string; - break; - case '*': - c = *pattern; - /* Collapse multiple stars. */ - while (c == '*') - c = *++pattern; - - if (*string == '.' && (flags & FNM_PERIOD) && - (string == stringstart || - ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) - return (CFSTORE_FNM_NOMATCH); - - /* Optimize for pattern with * at end or before /. */ - if (c == EOS) - if (flags & FNM_PATHNAME) - return ((flags & FNM_LEADING_DIR) || - strchr(string, '/') == NULL ? - 0 : CFSTORE_FNM_NOMATCH); - else - return (0); - else if (c == '/' && flags & FNM_PATHNAME) { - if ((string = strchr(string, '/')) == NULL) - return (CFSTORE_FNM_NOMATCH); - break; - } - - /* General case, use recursion. */ - while ((test = *string) != EOS) { - if (!cfstore_fnmatch(pattern, string, flags & ~FNM_PERIOD)) - return (0); - if (test == '/' && flags & FNM_PATHNAME) - break; - ++string; - } - return (CFSTORE_FNM_NOMATCH); - case '[': - if (*string == EOS) - return (CFSTORE_FNM_NOMATCH); - if (*string == '/' && (flags & FNM_PATHNAME)) - return (CFSTORE_FNM_NOMATCH); - if (*string == '.' && (flags & FNM_PERIOD) && - (string == stringstart || - ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) - return (CFSTORE_FNM_NOMATCH); - - switch (rangematch(pattern, *string, flags, &newp)) { - case RANGE_ERROR: - goto norm; - case RANGE_MATCH: - pattern = newp; - break; - case RANGE_NOMATCH: - return (CFSTORE_FNM_NOMATCH); - } - ++string; - break; - case '\\': - if (!(flags & FNM_NOESCAPE)) { - if ((c = *pattern++) == EOS) { - c = '\\'; - --pattern; - } - } - /* FALLTHROUGH */ - default: - norm: - if (c == *string) - ; - else if ((flags & FNM_CASEFOLD) && - (tolower((unsigned char)c) == - tolower((unsigned char)*string))) - ; - else - return (CFSTORE_FNM_NOMATCH); - string++; - break; - } - /* NOTREACHED */ + const char *stringstart; + char *newp; + char c, test; + + for (stringstart = string;;) + switch (c = *pattern++) { + case EOS: + if ((flags & FNM_LEADING_DIR) && *string == '/') { + return (0); + } + return (*string == EOS ? 0 : CFSTORE_FNM_NOMATCH); + case '?': + if (*string == EOS) { + return (CFSTORE_FNM_NOMATCH); + } + if (*string == '/' && (flags & FNM_PATHNAME)) { + return (CFSTORE_FNM_NOMATCH); + } + if (*string == '.' && (flags & FNM_PERIOD) && + (string == stringstart || + ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) { + return (CFSTORE_FNM_NOMATCH); + } + ++string; + break; + case '*': + c = *pattern; + /* Collapse multiple stars. */ + while (c == '*') { + c = *++pattern; + } + + if (*string == '.' && (flags & FNM_PERIOD) && + (string == stringstart || + ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) { + return (CFSTORE_FNM_NOMATCH); + } + + /* Optimize for pattern with * at end or before /. */ + if (c == EOS) + if (flags & FNM_PATHNAME) + return ((flags & FNM_LEADING_DIR) || + strchr(string, '/') == NULL ? + 0 : CFSTORE_FNM_NOMATCH); + else { + return (0); + } else if (c == '/' && flags & FNM_PATHNAME) { + if ((string = strchr(string, '/')) == NULL) { + return (CFSTORE_FNM_NOMATCH); + } + break; + } + + /* General case, use recursion. */ + while ((test = *string) != EOS) { + if (!cfstore_fnmatch(pattern, string, flags & ~FNM_PERIOD)) { + return (0); + } + if (test == '/' && flags & FNM_PATHNAME) { + break; + } + ++string; + } + return (CFSTORE_FNM_NOMATCH); + case '[': + if (*string == EOS) { + return (CFSTORE_FNM_NOMATCH); + } + if (*string == '/' && (flags & FNM_PATHNAME)) { + return (CFSTORE_FNM_NOMATCH); + } + if (*string == '.' && (flags & FNM_PERIOD) && + (string == stringstart || + ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) { + return (CFSTORE_FNM_NOMATCH); + } + + switch (rangematch(pattern, *string, flags, &newp)) { + case RANGE_ERROR: + goto norm; + case RANGE_MATCH: + pattern = newp; + break; + case RANGE_NOMATCH: + return (CFSTORE_FNM_NOMATCH); + } + ++string; + break; + case '\\': + if (!(flags & FNM_NOESCAPE)) { + if ((c = *pattern++) == EOS) { + c = '\\'; + --pattern; + } + } + /* FALLTHROUGH */ + default: +norm: + if (c == *string) + ; + else if ((flags & FNM_CASEFOLD) && + (tolower((unsigned char)c) == + tolower((unsigned char)*string))) + ; + else { + return (CFSTORE_FNM_NOMATCH); + } + string++; + break; + } + /* NOTREACHED */ } static int rangematch(const char *pattern, char test, int flags, char **newp) { - int negate, ok; - char c, c2; - - /* - * A bracket expression starting with an unquoted circumflex - * character produces unspecified results (IEEE 1003.2-1992, - * 3.13.2). This implementation treats it like '!', for - * consistency with the regular expression syntax. - * J.T. Conklin (conklin@ngai.kaleida.com) - */ - negate = (*pattern == '!' || *pattern == '^'); - if ( negate ) - ++pattern; - - if (flags & FNM_CASEFOLD) - test = tolower((unsigned char)test); - - /* - * A right bracket shall lose its special meaning and represent - * itself in a bracket expression if it occurs first in the list. - * -- POSIX.2 2.8.3.2 - */ - ok = 0; - c = *pattern++; - do { - if (c == '\\' && !(flags & FNM_NOESCAPE)) - c = *pattern++; - if (c == EOS) - return (RANGE_ERROR); - - if (c == '/' && (flags & FNM_PATHNAME)) - return (RANGE_NOMATCH); - - if (flags & FNM_CASEFOLD) - c = tolower((unsigned char)c); - - if (*pattern == '-' - && (c2 = *(pattern+1)) != EOS && c2 != ']') { - pattern += 2; - if (c2 == '\\' && !(flags & FNM_NOESCAPE)) - c2 = *pattern++; - if (c2 == EOS) - return (RANGE_ERROR); - - if (flags & FNM_CASEFOLD) - c2 = tolower((unsigned char)c2); - - if (__collate_load_error ? - c <= test && test <= c2 : - __collate_range_cmp(c, test) <= 0 - && __collate_range_cmp(test, c2) <= 0 - ) - ok = 1; - } else if (c == test) - ok = 1; - } while ((c = *pattern++) != ']'); - - *newp = (char *)pattern; - return (ok == negate ? RANGE_NOMATCH : RANGE_MATCH); + int negate, ok; + char c, c2; + + /* + * A bracket expression starting with an unquoted circumflex + * character produces unspecified results (IEEE 1003.2-1992, + * 3.13.2). This implementation treats it like '!', for + * consistency with the regular expression syntax. + * J.T. Conklin (conklin@ngai.kaleida.com) + */ + negate = (*pattern == '!' || *pattern == '^'); + if (negate) { + ++pattern; + } + + if (flags & FNM_CASEFOLD) { + test = tolower((unsigned char)test); + } + + /* + * A right bracket shall lose its special meaning and represent + * itself in a bracket expression if it occurs first in the list. + * -- POSIX.2 2.8.3.2 + */ + ok = 0; + c = *pattern++; + do { + if (c == '\\' && !(flags & FNM_NOESCAPE)) { + c = *pattern++; + } + if (c == EOS) { + return (RANGE_ERROR); + } + + if (c == '/' && (flags & FNM_PATHNAME)) { + return (RANGE_NOMATCH); + } + + if (flags & FNM_CASEFOLD) { + c = tolower((unsigned char)c); + } + + if (*pattern == '-' + && (c2 = *(pattern + 1)) != EOS && c2 != ']') { + pattern += 2; + if (c2 == '\\' && !(flags & FNM_NOESCAPE)) { + c2 = *pattern++; + } + if (c2 == EOS) { + return (RANGE_ERROR); + } + + if (flags & FNM_CASEFOLD) { + c2 = tolower((unsigned char)c2); + } + + if (__collate_load_error ? + c <= test && test <= c2 : + __collate_range_cmp(c, test) <= 0 + && __collate_range_cmp(test, c2) <= 0 + ) { + ok = 1; + } + } else if (c == test) { + ok = 1; + } + } while ((c = *pattern++) != ']'); + + *newp = (char *)pattern; + return (ok == negate ? RANGE_NOMATCH : RANGE_MATCH); } #endif /* CFSTORE_NO_FNMATCH */ diff --git a/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_fnmatch.h b/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_fnmatch.h index 81ba133cb54..3fedbb6580a 100644 --- a/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_fnmatch.h +++ b/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_fnmatch.h @@ -1,6 +1,6 @@ /*- * Copyright (c) 1992, 1993 - * The Regents of the University of California. All rights reserved. + * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -27,14 +27,14 @@ * SUCH DAMAGE. * * $FreeBSD: src/include/fnmatch.h,v 1.10 2002/03/23 17:24:53 imp Exp $ - * @(#)fnmatch.h 8.1 (Berkeley) 6/2/93 + * @(#)fnmatch.h 8.1 (Berkeley) 6/2/93 */ -#ifndef __CFSTORE_FNMATCH_H_ -#define __CFSTORE_FNMATCH_H_ +#ifndef __CFSTORE_FNMATCH_H_ +#define __CFSTORE_FNMATCH_H_ -#define CFSTORE_FNM_NOMATCH 1 /* Match failed. */ +#define CFSTORE_FNM_NOMATCH 1 /* Match failed. */ -int cfstore_fnmatch(const char *, const char *, int); +int cfstore_fnmatch(const char *, const char *, int); #endif /* !__CFSTORE_FNMATCH_H_ */ diff --git a/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_list.h b/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_list.h index 8e52da8d1c7..5233ba83b2f 100644 --- a/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_list.h +++ b/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_list.h @@ -26,8 +26,7 @@ * Introduction to Algorithms, TH Cormen, CE Leiserson, Rl Rivest, * ISBN 0-262-03141-8 (1989), Pages 206-207. */ -typedef struct cfstore_list_node_t -{ +typedef struct cfstore_list_node_t { struct cfstore_list_node_t *next; struct cfstore_list_node_t *prev; } cfstore_list_node_t; @@ -46,7 +45,7 @@ typedef struct cfstore_list_node_t } while (0) /* brief insert the new_node between 2 other nodes, the one before being node_before, the one after being node_after */ -static inline void cfstore_listAdd(cfstore_list_node_t* node_before, cfstore_list_node_t * new_node, cfstore_list_node_t* node_after) +static inline void cfstore_listAdd(cfstore_list_node_t *node_before, cfstore_list_node_t *new_node, cfstore_list_node_t *node_after) { /* init new node before insertion */ new_node->next = node_after; diff --git a/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_svm.cpp b/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_svm.cpp index ce795243902..e3097cbfb08 100644 --- a/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_svm.cpp +++ b/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_svm.cpp @@ -54,12 +54,12 @@ StorageVolumeManager volumeManager; /* used only for the initialization of the volume-manager. */ static void cfstore_svm_volume_manager_initialize_callback(int32_t status) { - CFSTORE_FENTRYLOG("%s: with status %d" , __func__, (int) status); + CFSTORE_FENTRYLOG("%s: with status %d", __func__, (int) status); } static void cfstore_svm_journal_mtc_callback(int32_t status, ARM_STORAGE_OPERATION operation) { - CFSTORE_FENTRYLOG("%s: operation %d with status %d" , __func__, (int) operation, (int) status); + CFSTORE_FENTRYLOG("%s: operation %d with status %d", __func__, (int) operation, (int) status); } int32_t cfstore_svm_init(struct _ARM_DRIVER_STORAGE *storage_mtd) @@ -68,17 +68,17 @@ int32_t cfstore_svm_init(struct _ARM_DRIVER_STORAGE *storage_mtd) CFSTORE_FENTRYLOG("%s:entered\n", __func__); ret = volumeManager.initialize(cfstore_svm_storage_drv, cfstore_svm_volume_manager_initialize_callback); - if(ret < ARM_DRIVER_OK) { + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:debug: volume-manager::initialize() failed for storage_mtd=%p (ret=%d)", __func__, storage_mtd, (int) ret); return ret; } ret = volumeManager.addVolume_C(CFSTORE_SVM_VOL_01_START_OFFSET, CFSTORE_SVM_VOL_01_SIZE, storage_mtd); - if(ret < ARM_DRIVER_OK) { + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:debug: volume-manager::addVolume_C() failed for storage_mtd=%p (ret=%d)", __func__, storage_mtd, (int) ret); return ret; } ret = storage_mtd->Initialize(cfstore_svm_journal_mtc_callback); - if(ret < ARM_DRIVER_OK) { + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:debug: storage_mtd->initialize() failed for storage_mtd=%p (ret=%d)", __func__, storage_mtd, (int) ret); return ret; } diff --git a/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_test.c b/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_test.c index f43dabbfb0f..32830aeac38 100644 --- a/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_test.c +++ b/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_test.c @@ -70,39 +70,37 @@ const uint8_t cfstore_test_byte_data_table[CFSTORE_TEST_BYTE_DATA_TABLE_SIZE] = /* @brief set of test data for sequential write tests */ -cfstore_test_rw_data_entry_t cfstore_test_rw_data_table[] = -{ - { 25, 'z' }, - { 00, 'a' }, - { 24, 'y' }, - { 01, 'b' }, - { 23, 'x' }, - { 02, 'c' }, - { 22, 'w' }, - { 03, 'd' }, - { 21, 'v' }, - { 04, 'e' }, - { 20, 'u' }, - { 05, 'f' }, - { 19, 't' }, - { 06, 'g' }, - { 18, 's' }, - { 07, 'h' }, - { 17, 'r' }, - { 8, 'i' }, - { 16, 'q' }, - { 9, 'j' }, - { 15, 'p' }, - { 10, 'k' }, - { 14, 'o' }, - { 11, 'l' }, - { 13, 'n' }, - { 12, 'm' }, - { CFSTORE_TEST_RW_TABLE_SENTINEL, '@' }, +cfstore_test_rw_data_entry_t cfstore_test_rw_data_table[] = { + { 25, 'z' }, + { 00, 'a' }, + { 24, 'y' }, + { 01, 'b' }, + { 23, 'x' }, + { 02, 'c' }, + { 22, 'w' }, + { 03, 'd' }, + { 21, 'v' }, + { 04, 'e' }, + { 20, 'u' }, + { 05, 'f' }, + { 19, 't' }, + { 06, 'g' }, + { 18, 's' }, + { 07, 'h' }, + { 17, 'r' }, + { 8, 'i' }, + { 16, 'q' }, + { 9, 'j' }, + { 15, 'p' }, + { 10, 'k' }, + { 14, 'o' }, + { 11, 'l' }, + { 13, 'n' }, + { 12, 'm' }, + { CFSTORE_TEST_RW_TABLE_SENTINEL, '@' }, }; -const char* cfstore_test_opcode_str[] = -{ +const char *cfstore_test_opcode_str[] = { "UNDEFINED", "CFSTORE_OPCODE_CLOSE", "CFSTORE_OPCODE_CREATE", @@ -123,28 +121,28 @@ const char* cfstore_test_opcode_str[] = }; -static int32_t cfstore_test_dump_print_array(const char* data, ARM_CFSTORE_SIZE len) +static int32_t cfstore_test_dump_print_array(const char *data, ARM_CFSTORE_SIZE len) { int i; char buf[80]; char sbuf[80]; - char* outbuf = buf; - char* soutbuf = sbuf; + char *outbuf = buf; + char *soutbuf = sbuf; memset(outbuf, 0, 80); memset(soutbuf, 0, 80); outbuf += sprintf(outbuf, " "); soutbuf += sprintf(soutbuf, " "); - for (i = 0; i < (int) len; i++){ + for (i = 0; i < (int) len; i++) { outbuf += sprintf(outbuf, "%02X ", data[i]); - if( !(isalnum( (int) data[i]) || ispunct( (int) data[i])) ){ + if (!(isalnum((int) data[i]) || ispunct((int) data[i]))) { *soutbuf++ = '*'; } else { *soutbuf++ = data[i]; } - if( (i % 16 == 0) && i > 0){ + if ((i % 16 == 0) && i > 0) { CFSTORE_LOG("%s", buf); CFSTORE_LOG("%s\n", sbuf); outbuf = buf; @@ -155,9 +153,9 @@ static int32_t cfstore_test_dump_print_array(const char* data, ARM_CFSTORE_SIZE soutbuf += sprintf(soutbuf, " "); } } - if(i % 16){ + if (i % 16) { /* Pad the end of the string to align string data. */ - while(i % 16){ + while (i % 16) { outbuf += sprintf(outbuf, " "); i++; } @@ -173,13 +171,13 @@ static int32_t cfstore_test_dump_print_array(const char* data, ARM_CFSTORE_SIZE */ int32_t cfstore_test_dump(void) { - const char* key_name_query = "*"; - char* read_buf = NULL; - char key_name[CFSTORE_KEY_NAME_MAX_LENGTH+1]; - uint8_t len = CFSTORE_KEY_NAME_MAX_LENGTH+1; + const char *key_name_query = "*"; + char *read_buf = NULL; + char key_name[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; + uint8_t len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; ARM_CFSTORE_SIZE vlen = 0; int32_t ret = ARM_DRIVER_ERROR; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_HANDLE_INIT(next); ARM_CFSTORE_HANDLE_INIT(prev); ARM_CFSTORE_CAPABILITIES caps = cfstore_driver.GetCapabilities(); @@ -188,26 +186,25 @@ int32_t cfstore_test_dump(void) CFSTORE_LOG("CFSTORE Flash Entries%s", "\n"); CFSTORE_LOG("=====================%s", "\n\n"); - while((ret = drv->Find(key_name_query, prev, next)) == ARM_DRIVER_OK) - { - len = CFSTORE_KEY_NAME_MAX_LENGTH+1; + while ((ret = drv->Find(key_name_query, prev, next)) == ARM_DRIVER_OK) { + len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; ret = drv->GetKeyName(next, key_name, &len); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("Error: failed to get key name%s", "\n"); break; } ret = drv->GetValueLen(next, &vlen); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("Error: failed to get value length%s", "\n"); break; } - read_buf = (char*) malloc(vlen+1); - if(read_buf == NULL){ + read_buf = (char *) malloc(vlen + 1); + if (read_buf == NULL) { CFSTORE_ERRLOG("Error: failed to malloc() read buffer%s", "\n"); break; } ret = drv->Read(next, read_buf, &vlen); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("Error: failed to read key value%s", "\n"); free(read_buf); break; @@ -216,7 +213,7 @@ int32_t cfstore_test_dump(void) CFSTORE_LOG(" name len : %d\n", (int) len); CFSTORE_LOG(" value len : %d\n", (int) vlen); CFSTORE_LOG(" data :%s", "\n"); - cfstore_test_dump_print_array((const char*) read_buf, vlen); + cfstore_test_dump_print_array((const char *) read_buf, vlen); CFSTORE_LOG("%s", ".\n"); free(read_buf); CFSTORE_HANDLE_SWAP(prev, next); @@ -226,7 +223,7 @@ int32_t cfstore_test_dump(void) CFSTORE_LOG("%s", ".\n"); CFSTORE_LOG("== End ==============%s", "\n\n"); - if(ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { + if (ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { /* As expected, no more keys have been found by the Find(). */ ret = ARM_DRIVER_OK; } @@ -239,24 +236,24 @@ int32_t cfstore_test_dump(void) int32_t cfstore_test_startup(void) { int32_t ret = ARM_DRIVER_ERROR; - ARM_CFSTORE_DRIVER* cfstore_drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *cfstore_drv = &cfstore_driver; ARM_CFSTORE_CAPABILITIES caps = cfstore_driver.GetCapabilities(); CFSTORE_LOG("INITIALIZING: caps.asynchronous_ops=%d\n", (int) caps.asynchronous_ops); /* Dump contents of CFSTORE */ ret = cfstore_drv->Initialize(NULL, NULL); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to initialize CFSTORE (ret=%d)\n", __func__, (int) ret); return ARM_DRIVER_ERROR; } ret = cfstore_test_dump(); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to dump CFSTORE (ret=%d)\n", __func__, (int) ret); return ARM_DRIVER_ERROR; } ret = cfstore_drv->Uninitialize(); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to uninitialize CFSTORE (ret=%d)\n", __func__, (int) ret); return ARM_DRIVER_ERROR; } @@ -268,12 +265,12 @@ int32_t cfstore_test_startup(void) const ARM_DRIVER_STORAGE *drv = &ARM_Driver_Storage_MTD_K64F; ret = FlashJournal_initialize(&jrnl, drv, &FLASH_JOURNAL_STRATEGY_SEQUENTIAL, NULL); - if(ret < JOURNAL_STATUS_OK){ + if (ret < JOURNAL_STATUS_OK) { CFSTORE_ERRLOG("%s:Error: failed to initialize flash journaling layer (ret=%d)\n", __func__, (int) ret); return ARM_DRIVER_ERROR; } ret = FlashJournal_reset(&jrnl); - if(ret < JOURNAL_STATUS_OK){ + if (ret < JOURNAL_STATUS_OK) { CFSTORE_ERRLOG("%s:Error: failed to reset flash journal (ret=%d)\n", __func__, (int) ret); return ARM_DRIVER_ERROR; } @@ -288,12 +285,12 @@ int32_t cfstore_test_startup(void) * @note this function expects cfstore to have been initialised with * a call to ARM_CFSTORE_DRIVER::Initialize() */ -int32_t cfstore_test_check_node_correct(const cfstore_kv_data_t* node) +int32_t cfstore_test_check_node_correct(const cfstore_kv_data_t *node) { - char* read_buf; + char *read_buf; int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE len = 0; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_HANDLE_INIT(hkey); ARM_CFSTORE_FMODE flags; @@ -301,29 +298,31 @@ int32_t cfstore_test_check_node_correct(const cfstore_kv_data_t* node) memset(&flags, 0, sizeof(flags)); ret = drv->Open(node->key_name, flags, hkey); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to open node (key_name=\"%s\", value=\"%s\")(ret=%d)\r\n", __func__, node->key_name, node->value, (int) ret); goto out0; } len = strlen(node->value) + 1; - read_buf = (char*) malloc(len); - if(read_buf == NULL) { + read_buf = (char *) malloc(len); + if (read_buf == NULL) { CFSTORE_ERRLOG("%s:Error: failed to allocated read buffer \r\n", __func__); goto out1; } memset(read_buf, 0, len); ret = drv->Read(hkey, read_buf, &len); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to write key (key_name=\"%s\", value=\"%s\")\r\n", __func__, node->key_name, node->value); goto out2; } /* check read data is as expected */ - if(strncmp(read_buf, node->value, strlen(node->value)) != 0){ + if (strncmp(read_buf, node->value, strlen(node->value)) != 0) { CFSTORE_ERRLOG("%s:Error: read value data (%s) != KV value data (key_name=\"%s\", value=\"%s\")\r\n", __func__, read_buf, node->key_name, node->value); ret = ARM_DRIVER_ERROR; } out2: - if(read_buf) free(read_buf); + if (read_buf) { + free(read_buf); + } out1: drv->Close(hkey); hkey = NULL; @@ -336,20 +335,20 @@ int32_t cfstore_test_check_node_correct(const cfstore_kv_data_t* node) * @note this function expects cfstore to have been initialised with * a call to ARM_CFSTORE_DRIVER::Initialize() */ -int32_t cfstore_test_delete(const char* key_name) +int32_t cfstore_test_delete(const char *key_name) { int32_t ret = ARM_DRIVER_ERROR; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_HANDLE_INIT(hkey); ARM_CFSTORE_FMODE flags; CFSTORE_FENTRYLOG("%s:entered.\r\n", __func__); memset(&flags, 0, sizeof(flags)); ret = drv->Open(key_name, flags, hkey); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { return ret; } - if(hkey != NULL){ + if (hkey != NULL) { ret = drv->Delete(hkey); drv->Close(hkey); } @@ -362,28 +361,27 @@ int32_t cfstore_test_delete(const char* key_name) */ int32_t cfstore_test_delete_all(void) { - const char* key_name_query = "*"; - char key_name[CFSTORE_KEY_NAME_MAX_LENGTH+1]; - uint8_t len = CFSTORE_KEY_NAME_MAX_LENGTH+1; + const char *key_name_query = "*"; + char key_name[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; + uint8_t len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; int32_t ret = ARM_DRIVER_ERROR; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_HANDLE_INIT(next); ARM_CFSTORE_HANDLE_INIT(prev); CFSTORE_FENTRYLOG("%s:entered.\r\n", __func__); - while((ret = drv->Find(key_name_query, prev, next)) == ARM_DRIVER_OK) - { - len = CFSTORE_KEY_NAME_MAX_LENGTH+1; + while ((ret = drv->Find(key_name_query, prev, next)) == ARM_DRIVER_OK) { + len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; drv->GetKeyName(next, key_name, &len); CFSTORE_TP(CFSTORE_TP_DELETE, "%s:deleting key_name=%s, len=%d\r\n", __func__, key_name, (int) len); ret = drv->Delete(next); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to delete key_name=%s, len=%d\r\n", __func__, key_name, (int) len); return ret; } CFSTORE_HANDLE_SWAP(prev, next); } - if(ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { + if (ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { /* as expected, no more keys have been found by the Find()*/ ret = ARM_DRIVER_OK; } @@ -396,27 +394,27 @@ int32_t cfstore_test_delete_all(void) * @note this function expects cfstore to have been initialised with * a call to ARM_CFSTORE_DRIVER::Initialize() */ -int32_t cfstore_test_create(const char* key_name, const char* data, ARM_CFSTORE_SIZE* len, ARM_CFSTORE_KEYDESC* kdesc) +int32_t cfstore_test_create(const char *key_name, const char *data, ARM_CFSTORE_SIZE *len, ARM_CFSTORE_KEYDESC *kdesc) { int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE value_len = 0; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_HANDLE_INIT(hkey); CFSTORE_FENTRYLOG("%s:entered.\r\n", __func__); value_len = *len; kdesc->drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE; ret = drv->Create(key_name, value_len, kdesc, hkey); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { return ret; } value_len = *len; ret = drv->Write(hkey, data, &value_len); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { drv->Close(hkey); return ret; } - if(value_len != *len){ + if (value_len != *len) { drv->Close(hkey); return ARM_DRIVER_ERROR; } @@ -428,22 +426,21 @@ int32_t cfstore_test_create(const char* key_name, const char* data, ARM_CFSTORE_ * @note this function expects cfstore to have been initialised with * a call to ARM_CFSTORE_DRIVER::Initialize() */ -int32_t cfstore_test_create_table(const cfstore_kv_data_t* table) +int32_t cfstore_test_create_table(const cfstore_kv_data_t *table) { int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE len = 0; - cfstore_kv_data_t* node = NULL; + cfstore_kv_data_t *node = NULL; ARM_CFSTORE_KEYDESC kdesc; (void) node; /* suppresses warning when building release */ CFSTORE_FENTRYLOG("%s:entered.\r\n", __func__); memset(&kdesc, 0, sizeof(kdesc)); kdesc.drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE; - while(table->key_name != NULL) - { + while (table->key_name != NULL) { len = strlen(table->value); ret = cfstore_test_create(table->key_name, table->value, &len, &kdesc); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to create node (key_name=\"%s\", value=\"%s\")\r\n", __func__, node->key_name, node->value); return ret; } @@ -453,65 +450,65 @@ int32_t cfstore_test_create_table(const cfstore_kv_data_t* table) } cfstore_kv_data_t cfstore_test_init_1_data[] = { - CFSTORE_INIT_1_TABLE_HEAD, - { "b", "1"}, - { "c", "12"}, - { "d", "123"}, - { "e", "1234"}, - { "g", "12345"}, - { "h", "123456"}, - { "i", "1234567"}, - { "j", "12345678"}, - { "k", "123456789"}, - { "l", "1234567890"}, - { "m", "12345678901"}, - { "n", "123456789012"}, - { "o", "1234567890123"}, - { "p", "12345678901234"}, - { "q", "123456789012345"}, - { "r", "1234567890123456"}, - { "0", "a"}, - { "01", "ab"}, - { "012", "abc"}, - { "0123", "abcd"}, - { "01234", "abcde"}, - { "012345", "abcdef"}, - { "0123456", "abcdefg"}, - { "01234567", "abcdefgh"}, - { "012345678", "abcdefghi"}, - { "0123456789", "abcdefghj"}, - { "0123456789a", "abcdefghjk"}, - { "0123456789ab", "abcdefghjkl"}, - { "0123456789abc", "abcdefghjklm"}, - { "0123456789abcd", "abcdefghjklmn"}, - { "0123456789abcde", "abcdefghjklmno"}, - { "0123456789abcdef", "abcdefghjklmnop"}, - { "0123456789abcdef0", "abcdefghjklmnopq"}, - { "0123456789abcdef01", "abcdefghjklmnopqr"}, - { "0123456789abcdef012", "abcdefghjklmnopqrs"}, - { "0123456789abcdef0123", "abcdefghjklmnopqrst"}, - { "0123456789abcdef01234", "abcdefghjklmnopqrstu"}, - { "0123456789abcdef012345", "abcdefghjklmnopqrstuv"}, - CFSTORE_INIT_1_TABLE_MID_NODE, - { "0123456789abcdef01234567", "abcdefghjklmnopqrstuvwx"}, - { "0123456789abcdef012345678", "abcdefghjklmnopqrstuvwxy"}, - { "0123456789abcdef0123456789", "abcdefghjklmnopqrstuvwxyz"}, - { "0123456789abcdef0123456789a", "b"}, - { "0123456789abcdef0123456789ab", "c"}, - { "0123456789abcdef0123456789abc", "d"}, - { "0123456789abcdef0123456789abcd", "e"}, - { "0123456789abcdef0123456789abcde", "f"}, - { "0123456789abcdef0123456789abcdef", "g"}, - { "com.arm.mbed.wifi.accesspoint.essid", ""}, - { "com.arm.mbed.wifi.accesspoint.essid2", ""}, - { "yotta.your-yotta-registry-module-name.module1", ""}, - { "yotta.hello-world.animal{wobbly-dog}{foot}frontLeft", "missing"}, - { "yotta.hello-world.animal{wobbly-dog}{foot}frontRight", "present"}, - { "yotta.hello-world.animal{wobbly-dog}{foot}backLeft", "half present"}, - { "piety.demands.us.to.honour.truth.above.our.friends", "Aristotle"}, - { "basement.medicine.pavement.government.trenchcoat.off.cough.off.kid.did.when.again.alleyway.friend.cap.pen.dollarbills.ten.foot.soot.put.but.anyway.say.May.DA.kid.did.toes.bows.those.hose.nose.clothes.man.blows.well.well", "TheRollingStone" }, - CFSTORE_INIT_1_TABLE_TAIL, - { NULL, NULL}, + CFSTORE_INIT_1_TABLE_HEAD, + { "b", "1"}, + { "c", "12"}, + { "d", "123"}, + { "e", "1234"}, + { "g", "12345"}, + { "h", "123456"}, + { "i", "1234567"}, + { "j", "12345678"}, + { "k", "123456789"}, + { "l", "1234567890"}, + { "m", "12345678901"}, + { "n", "123456789012"}, + { "o", "1234567890123"}, + { "p", "12345678901234"}, + { "q", "123456789012345"}, + { "r", "1234567890123456"}, + { "0", "a"}, + { "01", "ab"}, + { "012", "abc"}, + { "0123", "abcd"}, + { "01234", "abcde"}, + { "012345", "abcdef"}, + { "0123456", "abcdefg"}, + { "01234567", "abcdefgh"}, + { "012345678", "abcdefghi"}, + { "0123456789", "abcdefghj"}, + { "0123456789a", "abcdefghjk"}, + { "0123456789ab", "abcdefghjkl"}, + { "0123456789abc", "abcdefghjklm"}, + { "0123456789abcd", "abcdefghjklmn"}, + { "0123456789abcde", "abcdefghjklmno"}, + { "0123456789abcdef", "abcdefghjklmnop"}, + { "0123456789abcdef0", "abcdefghjklmnopq"}, + { "0123456789abcdef01", "abcdefghjklmnopqr"}, + { "0123456789abcdef012", "abcdefghjklmnopqrs"}, + { "0123456789abcdef0123", "abcdefghjklmnopqrst"}, + { "0123456789abcdef01234", "abcdefghjklmnopqrstu"}, + { "0123456789abcdef012345", "abcdefghjklmnopqrstuv"}, + CFSTORE_INIT_1_TABLE_MID_NODE, + { "0123456789abcdef01234567", "abcdefghjklmnopqrstuvwx"}, + { "0123456789abcdef012345678", "abcdefghjklmnopqrstuvwxy"}, + { "0123456789abcdef0123456789", "abcdefghjklmnopqrstuvwxyz"}, + { "0123456789abcdef0123456789a", "b"}, + { "0123456789abcdef0123456789ab", "c"}, + { "0123456789abcdef0123456789abc", "d"}, + { "0123456789abcdef0123456789abcd", "e"}, + { "0123456789abcdef0123456789abcde", "f"}, + { "0123456789abcdef0123456789abcdef", "g"}, + { "com.arm.mbed.wifi.accesspoint.essid", ""}, + { "com.arm.mbed.wifi.accesspoint.essid2", ""}, + { "yotta.your-yotta-registry-module-name.module1", ""}, + { "yotta.hello-world.animal{wobbly-dog}{foot}frontLeft", "missing"}, + { "yotta.hello-world.animal{wobbly-dog}{foot}frontRight", "present"}, + { "yotta.hello-world.animal{wobbly-dog}{foot}backLeft", "half present"}, + { "piety.demands.us.to.honour.truth.above.our.friends", "Aristotle"}, + { "basement.medicine.pavement.government.trenchcoat.off.cough.off.kid.did.when.again.alleyway.friend.cap.pen.dollarbills.ten.foot.soot.put.but.anyway.say.May.DA.kid.did.toes.bows.those.hose.nose.clothes.man.blows.well.well", "TheRollingStone" }, + CFSTORE_INIT_1_TABLE_TAIL, + { NULL, NULL}, }; @@ -522,58 +519,56 @@ cfstore_kv_data_t cfstore_test_init_1_data[] = { */ int32_t cfstore_test_init_1(void) { - char* read_buf = NULL; - const uint8_t key_name_max_len = CFSTORE_KEY_NAME_MAX_LENGTH+1; + char *read_buf = NULL; + const uint8_t key_name_max_len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; uint8_t key_name_len = 0; - char key_name_buf[CFSTORE_KEY_NAME_MAX_LENGTH+1]; + char key_name_buf[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE len = 0; ARM_CFSTORE_SIZE max_len = 0; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; - cfstore_kv_data_t* node = NULL; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; + cfstore_kv_data_t *node = NULL; ARM_CFSTORE_KEYDESC kdesc; ARM_CFSTORE_HANDLE_INIT(hkey); CFSTORE_FENTRYLOG("%s:entered\r\n", __func__); memset(&kdesc, 0, sizeof(kdesc)); - memset(key_name_buf, 0, CFSTORE_KEY_NAME_MAX_LENGTH+1); + memset(key_name_buf, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); /*scan for max length of value blob*/ node = cfstore_test_init_1_data; - while(node->key_name != NULL) - { + while (node->key_name != NULL) { len = strlen(node->value); - if(len > max_len){ + if (len > max_len) { max_len = len; max_len++; } node++; } - read_buf = (char*) malloc(max_len); - if(read_buf == NULL) { + read_buf = (char *) malloc(max_len); + if (read_buf == NULL) { CFSTORE_ERRLOG("%s:Error: failed to allocated read buffer \r\n", __func__); return ret; } kdesc.drl = ARM_RETENTION_WHILE_DEVICE_ACTIVE; node = cfstore_test_init_1_data; - while(node->key_name != NULL) - { + while (node->key_name != NULL) { CFSTORE_DBGLOG("%s:About to create new node (key_name=\"%s\", value=\"%s\")\r\n", __func__, node->key_name, node->value); ret = drv->Create(node->key_name, strlen(node->value), &kdesc, hkey); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to create node (key_name=\"%s\", value=\"%s\")\r\n", __func__, node->key_name, node->value); return ret; } CFSTORE_DBGLOG("%s:length of KV=%d (key_name=\"%s\", value=\"%s\")\r\n", __func__, (int) len, node->key_name, node->value); len = strlen(node->value); - ret = drv->Write(hkey, (char*) node->value, &len); - if(ret < ARM_DRIVER_OK){ + ret = drv->Write(hkey, (char *) node->value, &len); + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to write key (key_name=\"%s\", value=\"%s\")\r\n", __func__, node->key_name, node->value); drv->Close(hkey); return ret; } - if(len != strlen(node->value)){ + if (len != strlen(node->value)) { CFSTORE_ERRLOG("%s:Error: failed to write full value data (key_name=\"%s\", value=\"%s\"), len=%d\r\n", __func__, node->key_name, node->value, (int) len); drv->Close(hkey); return ARM_DRIVER_ERROR; @@ -582,12 +577,12 @@ int32_t cfstore_test_init_1(void) len = strlen(node->value); memset(read_buf, 0, max_len); ret = drv->Read(hkey, read_buf, &len); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to read key (key_name=\"%s\", value=\"%s\")\r\n", __func__, node->key_name, node->value); drv->Close(hkey); return ret; } - if(len != strlen(node->value)){ + if (len != strlen(node->value)) { CFSTORE_ERRLOG("%s:Error: failed to read full value data (key_name=\"%s\", value=\"%s\"), len=%d, ret=%d\r\n", __func__, node->key_name, node->value, (int) len, (int) ret); drv->Close(hkey); return ARM_DRIVER_ERROR; @@ -595,7 +590,7 @@ int32_t cfstore_test_init_1(void) key_name_len = key_name_max_len; memset(key_name_buf, 0, key_name_len); drv->GetKeyName(hkey, key_name_buf, &key_name_len); - if(len != strlen(node->value)){ + if (len != strlen(node->value)) { CFSTORE_ERRLOG("%s:Error: failed to GetKeyName() (key_name=\"%s\", value=\"%s\"), len=%d\r\n", __func__, node->key_name, node->value, (int) len); drv->Close(hkey); return ARM_DRIVER_ERROR; @@ -614,20 +609,20 @@ int32_t cfstore_test_init_1(void) * @note this function expects cfstore to have been initialised with * a call to ARM_CFSTORE_DRIVER::Initialize() */ -int32_t cfstore_test_kv_is_found(const char* key_name, bool* bfound) +int32_t cfstore_test_kv_is_found(const char *key_name, bool *bfound) { CFSTORE_FENTRYLOG("%s:entered.\r\n", __func__); int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_HANDLE_INIT(prev); ARM_CFSTORE_HANDLE_INIT(next); - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; CFSTORE_ASSERT(bfound != NULL); CFSTORE_ASSERT(key_name != NULL); *bfound = 0; ret = drv->Find(key_name, prev, next); - if(ret == ARM_DRIVER_OK){ + if (ret == ARM_DRIVER_OK) { *bfound = 1; CFSTORE_DBGLOG("%s:Found key_name=\"%s\", about to call close.\r\n", __func__, key_name); drv->Close(next); @@ -639,18 +634,17 @@ int32_t cfstore_test_kv_is_found(const char* key_name, bool* bfound) /* @brief support function for generating a kv_name * @param name buffer to hold kv name * @param len length of kv name to generate - * @note braces are not included in the generated names as the names are + * @note braces are not included in the generated names as the names are * of varible length and theyre may be unmatched * */ #define CFSTORE_TEST_KV_NAME_BUF_MAX_DATA (10+26+26+4) -int32_t cfstore_test_kv_name_gen(char* name, const size_t len) +int32_t cfstore_test_kv_name_gen(char *name, const size_t len) { size_t i; - const char buf[CFSTORE_TEST_KV_NAME_BUF_MAX_DATA+1] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_@"; + const char buf[CFSTORE_TEST_KV_NAME_BUF_MAX_DATA + 1] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_@"; CFSTORE_FENTRYLOG("%s:entered\n", __func__); - for(i = 0; i < len; i++) - { + for (i = 0; i < len; i++) { name[i] = buf[i % CFSTORE_TEST_KV_NAME_BUF_MAX_DATA]; } return ARM_DRIVER_OK; @@ -660,34 +654,34 @@ int32_t cfstore_test_kv_name_gen(char* name, const size_t len) * @note this function expects cfstore to have been initialised with * a call to ARM_CFSTORE_DRIVER::Initialize() */ -int32_t cfstore_test_read(const char* key_name, char* data, ARM_CFSTORE_SIZE* len) +int32_t cfstore_test_read(const char *key_name, char *data, ARM_CFSTORE_SIZE *len) { int32_t ret = ARM_DRIVER_ERROR; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_HANDLE_INIT(hkey); ARM_CFSTORE_FMODE flags; CFSTORE_FENTRYLOG("%s:entered\r\n", __func__); memset(&flags, 0, sizeof(flags)); - if(key_name == NULL) { + if (key_name == NULL) { CFSTORE_ERRLOG("%s:invalid key_name argument \r\n", __func__); goto out0; } - if(data == NULL) { + if (data == NULL) { CFSTORE_ERRLOG("%s:invalid data argument \r\n", __func__); goto out0; } - if(len == NULL) { + if (len == NULL) { CFSTORE_ERRLOG("%s:invalid len argument \r\n", __func__); goto out0; } ret = drv->Open(key_name, flags, hkey); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to open node (key_name=\"%s\")(ret=%d)\r\n", __func__, key_name, (int) ret); goto out1; } ret = drv->Read(hkey, data, len); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to read key (key_name=\"%s\"\r\n", __func__, key_name); goto out2; } @@ -702,35 +696,35 @@ int32_t cfstore_test_read(const char* key_name, char* data, ARM_CFSTORE_SIZE* le * @note this function expects cfstore to have been initialised with * a call to ARM_CFSTORE_DRIVER::Initialize() */ -int32_t cfstore_test_write(const char* key_name, const char* data, ARM_CFSTORE_SIZE* len) +int32_t cfstore_test_write(const char *key_name, const char *data, ARM_CFSTORE_SIZE *len) { int32_t ret = ARM_DRIVER_ERROR; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; ARM_CFSTORE_HANDLE_INIT(hkey); ARM_CFSTORE_FMODE flags; CFSTORE_FENTRYLOG("%s:entered\r\n", __func__); memset(&flags, 0, sizeof(flags)); - if(key_name == NULL) { + if (key_name == NULL) { CFSTORE_ERRLOG("%s:Error: invalid key_name argument \r\n", __func__); goto out0; } - if(data == NULL) { + if (data == NULL) { CFSTORE_ERRLOG("%s:Error: invalid data argument \r\n", __func__); goto out0; } - if(len == NULL) { + if (len == NULL) { CFSTORE_ERRLOG("%s:Error: invalid len argument \r\n", __func__); goto out0; } flags.write = 1; ret = drv->Open(key_name, flags, hkey); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to open node (key_name=\"%s\")(ret=%d)\r\n", __func__, key_name, (int) ret); goto out1; } ret = drv->Write(hkey, data, len); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to write key (key_name=\"%s\")\r\n", __func__, key_name); goto out2; } diff --git a/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_test.h b/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_test.h index 19761ee78d6..beed0826741 100644 --- a/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_test.h +++ b/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_test.h @@ -34,7 +34,7 @@ extern "C" { #define CFSTORE_TEST_BYTE_DATA_TABLE_SIZE 256 #define CFSTORE_UTEST_MSG_BUF_SIZE 256 #define CFSTORE_UTEST_DEFAULT_TIMEOUT_MS 10000 -#define CFSTORE_MBED_HOSTTEST_TIMEOUT 60 +#define CFSTORE_MBED_HOSTTEST_TIMEOUT 60 /* support macro for make string for utest _MESSAGE macros, which dont support formatted output */ #define CFSTORE_TEST_UTEST_MESSAGE(_buf, _max_len, _fmt, ...) \ @@ -50,12 +50,11 @@ extern "C" { /* kv data for test */ typedef struct cfstore_kv_data_t { - const char* key_name; - const char* value; + const char *key_name; + const char *value; } cfstore_kv_data_t; -typedef struct cfstore_test_rw_data_entry_t -{ +typedef struct cfstore_test_rw_data_entry_t { uint32_t offset; char rw_char; } cfstore_test_rw_data_entry_t; @@ -63,21 +62,21 @@ typedef struct cfstore_test_rw_data_entry_t extern cfstore_kv_data_t cfstore_test_init_1_data[]; extern cfstore_test_rw_data_entry_t cfstore_test_rw_data_table[]; -extern const char* cfstore_test_opcode_str[]; +extern const char *cfstore_test_opcode_str[]; extern const uint8_t cfstore_test_byte_data_table[CFSTORE_TEST_BYTE_DATA_TABLE_SIZE]; -int32_t cfstore_test_check_node_correct(const cfstore_kv_data_t* node); -int32_t cfstore_test_create(const char* key_name, const char* data, size_t* len, ARM_CFSTORE_KEYDESC* kdesc); -int32_t cfstore_test_create_table(const cfstore_kv_data_t* table); -int32_t cfstore_test_delete(const char* key_name); +int32_t cfstore_test_check_node_correct(const cfstore_kv_data_t *node); +int32_t cfstore_test_create(const char *key_name, const char *data, size_t *len, ARM_CFSTORE_KEYDESC *kdesc); +int32_t cfstore_test_create_table(const cfstore_kv_data_t *table); +int32_t cfstore_test_delete(const char *key_name); int32_t cfstore_test_delete_all(void); int32_t cfstore_test_dump(void); int32_t cfstore_test_init_1(void); -int32_t cfstore_test_kv_is_found(const char* key_name, bool* bfound); -int32_t cfstore_test_kv_name_gen(char* name, const size_t len); -int32_t cfstore_test_read(const char* key_name, char* data, size_t* len); +int32_t cfstore_test_kv_is_found(const char *key_name, bool *bfound); +int32_t cfstore_test_kv_name_gen(char *name, const size_t len); +int32_t cfstore_test_read(const char *key_name, char *data, size_t *len); int32_t cfstore_test_startup(void); -int32_t cfstore_test_write(const char* key_name, const char* data, size_t* len); +int32_t cfstore_test_write(const char *key_name, const char *data, size_t *len); #ifdef __cplusplus } diff --git a/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_utest.h b/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_utest.h index c0c2fd22207..33156cf135b 100644 --- a/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_utest.h +++ b/features/storage/FEATURE_STORAGE/cfstore/source/cfstore_utest.h @@ -33,25 +33,24 @@ void cfstore_utest_default_callback(int32_t status, ARM_CFSTORE_OPCODE cmd_code, (void) handle; CFSTORE_FENTRYLOG("%s:entered: status=%d, cmd_code=%d (%s) handle=%p\n", __func__, (int) status, (int) cmd_code, cfstore_test_opcode_str[cmd_code], handle); - switch(cmd_code) - { - case CFSTORE_OPCODE_INITIALIZE: - case CFSTORE_OPCODE_FLUSH: - case CFSTORE_OPCODE_UNINITIALIZE: - case CFSTORE_OPCODE_CLOSE: - case CFSTORE_OPCODE_CREATE: - case CFSTORE_OPCODE_DELETE: - case CFSTORE_OPCODE_FIND: - case CFSTORE_OPCODE_GET_KEY_NAME: - case CFSTORE_OPCODE_GET_STATUS: - case CFSTORE_OPCODE_GET_VALUE_LEN: - case CFSTORE_OPCODE_OPEN: - case CFSTORE_OPCODE_POWER_CONTROL: - case CFSTORE_OPCODE_READ: - case CFSTORE_OPCODE_RSEEK: - case CFSTORE_OPCODE_WRITE: - default: - CFSTORE_DBGLOG("%s:debug: received asynchronous notification for opcode=%d (%s)", __func__, cmd_code, cmd_code < CFSTORE_OPCODE_MAX ? cfstore_test_opcode_str[cmd_code] : "unknown"); + switch (cmd_code) { + case CFSTORE_OPCODE_INITIALIZE: + case CFSTORE_OPCODE_FLUSH: + case CFSTORE_OPCODE_UNINITIALIZE: + case CFSTORE_OPCODE_CLOSE: + case CFSTORE_OPCODE_CREATE: + case CFSTORE_OPCODE_DELETE: + case CFSTORE_OPCODE_FIND: + case CFSTORE_OPCODE_GET_KEY_NAME: + case CFSTORE_OPCODE_GET_STATUS: + case CFSTORE_OPCODE_GET_VALUE_LEN: + case CFSTORE_OPCODE_OPEN: + case CFSTORE_OPCODE_POWER_CONTROL: + case CFSTORE_OPCODE_READ: + case CFSTORE_OPCODE_RSEEK: + case CFSTORE_OPCODE_WRITE: + default: + CFSTORE_DBGLOG("%s:debug: received asynchronous notification for opcode=%d (%s)", __func__, cmd_code, cmd_code < CFSTORE_OPCODE_MAX ? cfstore_test_opcode_str[cmd_code] : "unknown"); } CFSTORE_DBGLOG("%s:about to validate callback\n", __func__); Harness::validate_callback(); @@ -62,7 +61,7 @@ void cfstore_utest_default_callback(int32_t status, ARM_CFSTORE_OPCODE cmd_code, static control_t cfstore_utest_default_start(const size_t call_count) { int32_t ret = ARM_DRIVER_ERROR; - ARM_CFSTORE_DRIVER* drv = &cfstore_driver; + ARM_CFSTORE_DRIVER *drv = &cfstore_driver; char cfstore_utest_msg[CFSTORE_UTEST_MSG_BUF_SIZE]; CFSTORE_FENTRYLOG("%s:entered\n", __func__); diff --git a/features/storage/FEATURE_STORAGE/cfstore/source/configuration_store.c b/features/storage/FEATURE_STORAGE/cfstore/source/configuration_store.c index a988de6ebc7..7aac9525fbe 100644 --- a/features/storage/FEATURE_STORAGE/cfstore/source/configuration_store.c +++ b/features/storage/FEATURE_STORAGE/cfstore/source/configuration_store.c @@ -90,7 +90,7 @@ struct _ARM_DRIVER_STORAGE cfstore_journal_mtd; #define CFSTORE_HKVT_REFCOUNT_MAX 0xff #define CFSTORE_LOCK_REFCOUNT_MAX 0xffff #define CFSTORE_FILE_CREATE_MODE_DEFAULT (ARM_CFSTORE_FMODE)0 -#define CFSTORE_FLASH_STACK_BUF_SIZE 64 +#define CFSTORE_FLASH_STACK_BUF_SIZE 64 #define CFSTORE_FLASH_AREA_SIZE_MIN (sizeof(cfstore_area_header_t) - 1) #define CFSTORE_FLASH_NUMSLOTS 4 #define cfstore_fsm_null NULL @@ -137,8 +137,7 @@ struct _ARM_DRIVER_STORAGE cfstore_journal_mtd; * @param delete * indicates this KV is being deleted */ -typedef struct cfstore_area_header_t -{ +typedef struct cfstore_area_header_t { uint32_t vlength; uint8_t klength; uint8_t perm_owner_read : 1; @@ -157,8 +156,7 @@ typedef struct cfstore_area_header_t /* helper struct */ -typedef struct cfstore_area_hkvt_t -{ +typedef struct cfstore_area_hkvt_t { uint8_t *head; uint8_t *key; uint8_t *value; @@ -167,8 +165,7 @@ typedef struct cfstore_area_hkvt_t /* helper struct */ -typedef struct cfstore_client_notify_data_t -{ +typedef struct cfstore_client_notify_data_t { uint32_t opcode; int32_t status; ARM_CFSTORE_HANDLE handle; @@ -199,11 +196,10 @@ typedef enum cfstore_fsm_event_t { cfstore_fsm_event_max, } cfstore_fsm_event_t; -typedef int32_t (*cfstore_fsm_handler)(void* ctx); +typedef int32_t (*cfstore_fsm_handler)(void *ctx); /* @brief flash finite state machine helper function */ -typedef struct cfstore_fsm_t -{ +typedef struct cfstore_fsm_t { cfstore_fsm_state_t state; cfstore_fsm_event_t event; } cfstore_fsm_t; @@ -212,8 +208,7 @@ typedef struct cfstore_fsm_t #ifdef CFSTORE_DEBUG #ifdef CFSTORE_CONFIG_BACKEND_FLASH_ENABLED /* strings used for debug trace */ -static const char* cfstore_flash_opcode_str[] = -{ +static const char *cfstore_flash_opcode_str[] = { "FLASH_JOURNAL_OPCODE_FORMAT", "FLASH_JOURNAL_OPCODE_INITIALIZE", "FLASH_JOURNAL_OPCODE_GET_INFO", @@ -223,8 +218,7 @@ static const char* cfstore_flash_opcode_str[] = "FLASH_JOURNAL_OPCODE_RESET", }; -static const char* cfstore_flash_state_str[] = -{ +static const char *cfstore_flash_state_str[] = { "stopped", "initializing", "reading", @@ -236,8 +230,7 @@ static const char* cfstore_flash_state_str[] = "unknown" }; -static const char* cfstore_flash_event_str[] = -{ +static const char *cfstore_flash_event_str[] = { "init_done", "read_done", "log_done", @@ -255,10 +248,10 @@ static const char* cfstore_flash_event_str[] = * Forward decl */ #ifdef CFSTORE_CONFIG_BACKEND_FLASH_ENABLED -static int32_t cfstore_fsm_state_handle_event(cfstore_fsm_t* fsm, cfstore_fsm_event_t event, void* context); -static int32_t cfstore_fsm_state_set(cfstore_fsm_t* fsm, cfstore_fsm_state_t new_state, void* ctx); +static int32_t cfstore_fsm_state_handle_event(cfstore_fsm_t *fsm, cfstore_fsm_event_t event, void *context); +static int32_t cfstore_fsm_state_set(cfstore_fsm_t *fsm, cfstore_fsm_state_t new_state, void *ctx); #endif /* CFSTORE_CONFIG_BACKEND_FLASH_ENABLED */ -static int32_t cfstore_get_key_name_ex(cfstore_area_hkvt_t *hkvt, char* key_name, uint8_t *key_name_len); +static int32_t cfstore_get_key_name_ex(cfstore_area_hkvt_t *hkvt, char *key_name, uint8_t *key_name_len); /* Walking Area HKVT's While Inserting a New HKVT: @@ -379,8 +372,7 @@ static int32_t cfstore_get_key_name_ex(cfstore_area_hkvt_t *hkvt, char* key_name * program_unit. * - accessed in app & intr context; hence needs CS protection. */ -typedef struct cfstore_ctx_t -{ +typedef struct cfstore_ctx_t { cfstore_list_node_t file_list; int32_t init_ref_count; CFSTORE_LOCK rw_area0_lock; @@ -392,7 +384,7 @@ typedef struct cfstore_ctx_t int32_t status; /* client notification data */ - void* client_context; + void *client_context; ARM_CFSTORE_CALLBACK client_callback; cfstore_client_notify_data_t client_notify_data; @@ -426,13 +418,12 @@ typedef struct cfstore_ctx_t * indicates file is readable, * @param executable * indicates file is readable, - * @param uvisor_client_box_id - * box id of caller using this file. set on create/open and thereafter used by other methods to check accesses. - * Q: is it safe to store this here? Is it of any value? i.e. a client can change the value - * after cfstore has set it so cfstore cant rely on it being secure. + * @param uvisor_client_box_id + * box id of caller using this file. set on create/open and thereafter used by other methods to check accesses. + * Q: is it safe to store this here? Is it of any value? i.e. a client can change the value + * after cfstore has set it so cfstore cant rely on it being secure. */ -typedef struct cfstore_file_t -{ +typedef struct cfstore_file_t { cfstore_list_node_t node; uint32_t rlocation; uint32_t wlocation; @@ -446,8 +437,7 @@ typedef struct cfstore_file_t } cfstore_file_t; /* @brief structure used to compose table for mapping flash journal error codes to cfstore error codes */ -typedef struct cfstore_flash_journal_error_code_node -{ +typedef struct cfstore_flash_journal_error_code_node { int32_t flash_journal_error_code; int32_t cfstore_error_code; } cfstore_flash_journal_error_code_node; @@ -467,16 +457,16 @@ static const ARM_DRIVER_VERSION cfstore_driver_version_g = { .api = ARM_CFSTORE_ #ifndef YOTTA_CFG_CFSTORE_UVISOR /* uvisor is not being used so instantiate a context */ static cfstore_ctx_t cfstore_ctx_g = { - .file_list.next = NULL, - .file_list.prev = NULL, - .init_ref_count = 0, - .rw_area0_lock = 0, - .power_state = ARM_POWER_FULL, - .area_0_head = NULL, - .area_0_tail = NULL, - .client_callback = NULL, - .client_context = NULL, - .f_reserved0 = 0, + .file_list.next = NULL, + .file_list.prev = NULL, + .init_ref_count = 0, + .rw_area0_lock = 0, + .power_state = ARM_POWER_FULL, + .area_0_head = NULL, + .area_0_tail = NULL, + .client_callback = NULL, + .client_context = NULL, + .f_reserved0 = 0, }; #endif /* YOTTA_CFG_CFSTORE_UVISOR */ @@ -498,14 +488,14 @@ static const UvisorBoxAclItem cfstore_acl_list_g[] = { 0xbeefbeef = size in bytes of secure flash partition {(void *) 0xabaadfood, 0xbeefbeef, UVISOR_TACLDEF_PERIPH}, */ - /* put reference to k64 subfamily reference manual and cmsis k64f target header as to where this comes from */ - {FTFE, sizeof(*FTFE), UVISOR_TACLDEF_PERIPH}, + /* put reference to k64 subfamily reference manual and cmsis k64f target header as to where this comes from */ + {FTFE, sizeof(*FTFE), UVISOR_TACLDEF_PERIPH}, }; /* UVISOR_BOX_CONFIG_CTX(configuration_store, UVISOR_BOX_STACK_SIZE, cfstore_ctx_t); * * It would be better to use the following macro: - * UVISOR_BOX_CONFIG(configuration_store, cfstore_acl_list_g, UVISOR_BOX_STACK_SIZE, cfstore_ctx_t); + * UVISOR_BOX_CONFIG(configuration_store, cfstore_acl_list_g, UVISOR_BOX_STACK_SIZE, cfstore_ctx_t); * rather than the unpacked macro code that follows. * * #define __UVISOR_BOX_CONFIG(box_name, acl_list, acl_list_count, stack_size, context_size) \ @@ -532,7 +522,7 @@ static const UvisorBoxAclItem cfstore_acl_list_g[] = { * ^ * d:/datastore/public/jobs/yr2016/2247/sdh_dev_10/configuration-store/source/configuration_store.c:490:1: error: (near initialization for 'configuration_store_cfg.box_namespace') * In file included from d:/datastore/public/jobs/yr2016/2247/sdh_dev_10/configuration-store/yotta_modules/uvisor-lib/uvisor-lib/uvisor-lib.h:38:0, - * from d:/datastore/public/jobs/yr2016/2247/sdh_dev_10/configuration-store/source/configuration_store.c:27: + * from d:/datastore/public/jobs/yr2016/2247/sdh_dev_10/configuration-store/source/configuration_store.c:27: * d:/datastore/public/jobs/yr2016/2247/sdh_dev_10/configuration-store/source/configuration_store.c:490:19: warning: 'configuration_store_cfg_ptr' initialized and declared 'extern' * UVISOR_BOX_CONFIG(configuration_store, cfstore_acl_list_g, UVISOR_BOX_STACK_SIZE, cfstore_ctx_t); * ^ @@ -552,32 +542,32 @@ static const UvisorBoxAclItem cfstore_acl_list_g[] = { * error: command ['ninja'] failed * ===================================================================================================================================================================================== * The UVISOR_BOX_CONFIG() macro expands to include the following: - * extern const __attribute__((section(".keep.uvisor.cfgtbl_ptr"), aligned(4))) void * const configuration_store_cfg_ptr = &configuration_store_cfg; + * extern const __attribute__((section(".keep.uvisor.cfgtbl_ptr"), aligned(4))) void * const configuration_store_cfg_ptr = &configuration_store_cfg; * The extern at the beginning of the line creates a warning when in a c file, and so needs to be removed/fixed. * There are also many other warnings from the macro expansion which need to be investigated further. * * todo: possible investigation: move configuration_store.c -> configuration_store.cpp */ -uint8_t __attribute__((section(".keep.uvisor.bss.boxes"), aligned(32))) configuration_store_reserved[UVISOR_STACK_SIZE_ROUND(((UVISOR_MIN_STACK(UVISOR_BOX_STACK_SIZE) + (sizeof(cfstore_ctx_t)))*8)/6)]; +uint8_t __attribute__((section(".keep.uvisor.bss.boxes"), aligned(32))) configuration_store_reserved[UVISOR_STACK_SIZE_ROUND(((UVISOR_MIN_STACK(UVISOR_BOX_STACK_SIZE) + (sizeof(cfstore_ctx_t))) * 8) / 6)]; static const __attribute__((section(".keep.uvisor.cfgtbl"), aligned(4))) UvisorBoxConfig configuration_store_cfg = { - UVISOR_BOX_MAGIC, - UVISOR_BOX_VERSION, - UVISOR_MIN_STACK(UVISOR_BOX_STACK_SIZE), - sizeof(cfstore_ctx_t), - "com.arm.mbed.configuration-store", //problem using__uvisor_box_namespace defined above so inserting string directly here - cfstore_acl_list_g, - UVISOR_ARRAY_COUNT(cfstore_acl_list_g) + UVISOR_BOX_MAGIC, + UVISOR_BOX_VERSION, + UVISOR_MIN_STACK(UVISOR_BOX_STACK_SIZE), + sizeof(cfstore_ctx_t), + "com.arm.mbed.configuration-store", //problem using__uvisor_box_namespace defined above so inserting string directly here + cfstore_acl_list_g, + UVISOR_ARRAY_COUNT(cfstore_acl_list_g) }; -const __attribute__((section(".keep.uvisor.cfgtbl_ptr"), aligned(4))) void * const configuration_store_cfg_ptr = &configuration_store_cfg; -UVISOR_EXTERN cfstore_ctx_t * const uvisor_ctx; +const __attribute__((section(".keep.uvisor.cfgtbl_ptr"), aligned(4))) void *const configuration_store_cfg_ptr = &configuration_store_cfg; +UVISOR_EXTERN cfstore_ctx_t *const uvisor_ctx; #endif /* YOTTA_CFG_CFSTORE_UVISOR */ /* * client notifier helper function */ -static void cfstore_client_notify_data_init(cfstore_client_notify_data_t* data, uint32_t opcode, int32_t status, ARM_CFSTORE_HANDLE handle) +static void cfstore_client_notify_data_init(cfstore_client_notify_data_t *data, uint32_t opcode, int32_t status, ARM_CFSTORE_HANDLE handle) { memset(data, 0, sizeof(cfstore_client_notify_data_t)); data->opcode = opcode; @@ -590,21 +580,21 @@ static void cfstore_client_notify_data_init(cfstore_client_notify_data_t* data, */ /* @brief helper function to report whether the initialisation flag has been set in the cfstore_ctx_g */ -static bool cfstore_ctx_is_initialised(cfstore_ctx_t* ctx) +static bool cfstore_ctx_is_initialised(cfstore_ctx_t *ctx) { - CFSTORE_ASSERT(ctx!= NULL); + CFSTORE_ASSERT(ctx != NULL); return ctx->init_ref_count > 0 ? true : false; } /* @brief helper function to return a pointer to the global cfstore context. */ -static inline cfstore_ctx_t* cfstore_ctx_get(void) +static inline cfstore_ctx_t *cfstore_ctx_get(void) { #ifdef YOTTA_CFG_CFSTORE_UVISOR - /* use the secure cfstore_ctx_t struct allocated by uvisor for use */ - return (cfstore_ctx_t*) uvisor_ctx; + /* use the secure cfstore_ctx_t struct allocated by uvisor for use */ + return (cfstore_ctx_t *) uvisor_ctx; #else - /* use the insecure statically allocated data struct */ - return &cfstore_ctx_g; + /* use the insecure statically allocated data struct */ + return &cfstore_ctx_g; #endif } @@ -619,16 +609,16 @@ static inline cfstore_ctx_t* cfstore_ctx_get(void) static ARM_CFSTORE_SIZE cfstore_ctx_get_kv_total_len(void) { ARM_CFSTORE_SIZE size = 0; - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); - size = (ARM_CFSTORE_SIZE) (ctx->area_0_tail - ctx->area_0_head); + size = (ARM_CFSTORE_SIZE)(ctx->area_0_tail - ctx->area_0_head); return size; } /* @brief helper function to get the program_unit */ -static inline uint32_t cfstore_ctx_get_program_unit(cfstore_ctx_t* ctx) +static inline uint32_t cfstore_ctx_get_program_unit(cfstore_ctx_t *ctx) { - CFSTORE_ASSERT(ctx!= NULL); + CFSTORE_ASSERT(ctx != NULL); #ifdef CFSTORE_CONFIG_BACKEND_FLASH_ENABLED return ctx->info.program_unit; #else @@ -639,11 +629,11 @@ static inline uint32_t cfstore_ctx_get_program_unit(cfstore_ctx_t* ctx) } -static inline void cfstore_ctx_client_notify(cfstore_ctx_t* ctx, cfstore_client_notify_data_t* data) +static inline void cfstore_ctx_client_notify(cfstore_ctx_t *ctx, cfstore_client_notify_data_t *data) { CFSTORE_FENTRYLOG("%s:entered: ctx=%p, ctx->client_callback=%p, ctx->client_context=%p\n", __func__, ctx, ctx->client_callback, ctx->client_context); CFSTORE_TP(CFSTORE_TP_CALLBACK, "%s:data=%p, data->opcode=%d, data->status=%d, data->handle=%p\n", __func__, data, (int) data->opcode, (int) data->status, data->handle); - if(ctx->client_callback){ + if (ctx->client_callback) { ctx->client_callback(data->status, (ARM_CFSTORE_OPCODE) data->opcode, ctx->client_context, data->handle); } return; @@ -669,9 +659,9 @@ static inline void cfstore_ctx_client_notify(cfstore_ctx_t* ctx, cfstore_client_ static uint32_t cfstore_malloc_size_g = 0; #define CFSTORE_MALLOC malloc -static void* CFSTORE_REALLOC(void *ptr, size_t size) +static void *CFSTORE_REALLOC(void *ptr, size_t size) { - void* mem; + void *mem; mem = realloc(ptr, size); CFSTORE_TP(CFSTORE_TP_MEM, "%s:ptr=%p, mem=%p, old_size=%u, new_size=%u.\n", __func__, ptr, mem, (int) cfstore_malloc_size_g, (int) size); @@ -724,14 +714,14 @@ void *cfstore_realloc(void *ptr, ARM_CFSTORE_SIZE size) static uint8_t *cfstore_sram_head = NULL; static uint8_t *cfstore_sram_tail = NULL; - if(size > 0) { - if(size <= CFSTORE_YOTTA_CFG_CFSTORE_SRAM_SIZE) { - if(ptr == NULL) { + if (size > 0) { + if (size <= CFSTORE_YOTTA_CFG_CFSTORE_SRAM_SIZE) { + if (ptr == NULL) { memset(CFSTORE_YOTTA_CFG_CFSTORE_SRAM_ADDR, 0, CFSTORE_YOTTA_CFG_CFSTORE_SRAM_SIZE); cfstore_sram_head = CFSTORE_YOTTA_CFG_CFSTORE_SRAM_ADDR; } cfstore_sram_tail = cfstore_sram_head + size; - return (void*) cfstore_sram_head; + return (void *) cfstore_sram_head; } /* requested size is too big so fail the operation by setting * head/tail to NULL */ @@ -739,34 +729,46 @@ void *cfstore_realloc(void *ptr, ARM_CFSTORE_SIZE size) /* size == 0 => reset */ cfstore_sram_head = NULL; cfstore_sram_tail = NULL; - return (void*) cfstore_sram_head; + return (void *) cfstore_sram_head; } #endif /* CFSTORE_YOTTA_CFG_CFSTORE_SRAM_ADDR */ #ifdef CFSTORE_TARGET_LIKE_X86_LINUX_NATIVE -static inline void cfstore_critical_section_lock(CFSTORE_LOCK* lock, const char* tag){ (void) tag; __sync_fetch_and_add(lock, 1); } -static inline void cfstore_critical_section_unlock(CFSTORE_LOCK* lock, const char* tag){(void) tag; __sync_fetch_and_sub(lock, 1); } +static inline void cfstore_critical_section_lock(CFSTORE_LOCK *lock, const char *tag) +{ + (void) tag; + __sync_fetch_and_add(lock, 1); +} +static inline void cfstore_critical_section_unlock(CFSTORE_LOCK *lock, const char *tag) +{ + (void) tag; + __sync_fetch_and_sub(lock, 1); +} -static CFSTORE_INLINE int32_t cfstore_hkvt_refcount_dec(cfstore_area_hkvt_t* hkvt, uint8_t *refcount) +static CFSTORE_INLINE int32_t cfstore_hkvt_refcount_dec(cfstore_area_hkvt_t *hkvt, uint8_t *refcount) { - cfstore_area_header_t *hdr = (cfstore_area_header_t*) hkvt->head; + cfstore_area_header_t *hdr = (cfstore_area_header_t *) hkvt->head; uint32_t __refcount; - __refcount =__sync_fetch_and_sub(&hdr->refcount, 1); - if(refcount) *refcount = __refcount; + __refcount = __sync_fetch_and_sub(&hdr->refcount, 1); + if (refcount) { + *refcount = __refcount; + } return ARM_DRIVER_OK; } -static CFSTORE_INLINE int32_t cfstore_hkvt_refcount_inc(cfstore_area_hkvt_t* hkvt, uint8_t *refcount) +static CFSTORE_INLINE int32_t cfstore_hkvt_refcount_inc(cfstore_area_hkvt_t *hkvt, uint8_t *refcount) { int32_t ret = ARM_CFSTORE_DRIVER_ERROR_HANDLE_COUNT_MAX; uint32_t __refcount; - cfstore_area_header_t *hdr = (cfstore_area_header_t*) hkvt->head; + cfstore_area_header_t *hdr = (cfstore_area_header_t *) hkvt->head; - if( (__refcount = __sync_fetch_and_add(&hdr->refcount, 1)) < CFSTORE_LOCK_REFCOUNT_MAX) { - if(refcount) *refcount = __refcount; + if ((__refcount = __sync_fetch_and_add(&hdr->refcount, 1)) < CFSTORE_LOCK_REFCOUNT_MAX) { + if (refcount) { + *refcount = __refcount; + } ret = ARM_DRIVER_OK; } else { /* maximum count reach, back down and return error*/ @@ -782,7 +784,7 @@ static CFSTORE_INLINE int32_t cfstore_hkvt_refcount_inc(cfstore_area_hkvt_t* hkv * Platform Specific Function Implementations */ -static inline void cfstore_critical_section_unlock(CFSTORE_LOCK* lock, const char* tag) +static inline void cfstore_critical_section_unlock(CFSTORE_LOCK *lock, const char *tag) { (void) lock; (void) tag; @@ -792,7 +794,7 @@ static inline void cfstore_critical_section_unlock(CFSTORE_LOCK* lock, const cha CFSTORE_DBGLOG("%s:after critical_section_exit()(lock=%lu)\n", tag, *lock); } -static inline void cfstore_critical_section_lock(CFSTORE_LOCK* lock, const char* tag) +static inline void cfstore_critical_section_lock(CFSTORE_LOCK *lock, const char *tag) { (void) lock; (void) tag; @@ -802,27 +804,30 @@ static inline void cfstore_critical_section_lock(CFSTORE_LOCK* lock, const char* CFSTORE_DBGLOG("%s:after critical_section_enter()(lock=%lu)\n", tag, *lock); } -static CFSTORE_INLINE int32_t cfstore_hkvt_refcount_dec(cfstore_area_hkvt_t* hkvt, uint8_t *refcount) +static CFSTORE_INLINE int32_t cfstore_hkvt_refcount_dec(cfstore_area_hkvt_t *hkvt, uint8_t *refcount) { - cfstore_area_header_t *hdr = (cfstore_area_header_t*) hkvt->head; + cfstore_area_header_t *hdr = (cfstore_area_header_t *) hkvt->head; /* todo: put mbedosv3++ critical section enter here */ hdr->refcount--; - if(refcount) *refcount = hdr->refcount; + if (refcount) { + *refcount = hdr->refcount; + } /* todo: put mbedosv3++ critical section exit here */ return ARM_DRIVER_OK; } -static CFSTORE_INLINE int32_t cfstore_hkvt_refcount_inc(cfstore_area_hkvt_t* hkvt, uint8_t *refcount) +static CFSTORE_INLINE int32_t cfstore_hkvt_refcount_inc(cfstore_area_hkvt_t *hkvt, uint8_t *refcount) { int32_t ret = ARM_CFSTORE_DRIVER_ERROR_HANDLE_COUNT_MAX; - cfstore_area_header_t *hdr = (cfstore_area_header_t*) hkvt->head; + cfstore_area_header_t *hdr = (cfstore_area_header_t *) hkvt->head; /* todo: put mbedosv3++ critical section enter here */ - if(hdr->refcount < CFSTORE_HKVT_REFCOUNT_MAX) - { + if (hdr->refcount < CFSTORE_HKVT_REFCOUNT_MAX) { hdr->refcount++; - if(refcount) *refcount = hdr->refcount; + if (refcount) { + *refcount = hdr->refcount; + } ret = ARM_DRIVER_OK; } /* todo: put mbedosv3++ critical section exit here */ @@ -843,19 +848,19 @@ static CFSTORE_INLINE int32_t cfstore_hkvt_refcount_inc(cfstore_area_hkvt_t* hkv * determined by the clients namespace and whether the KV path name falls * within that name space * @param key_name - * the name of the KV being created. - * the validation that the key_name is composed of permissible chars is - * carried out before this function is called. + * the name of the KV being created. + * the validation that the key_name is composed of permissible chars is + * carried out before this function is called. * @note * Conceptually, cfstore supports the following KV path namespaces: - * - com.arm.mbed. - * - guids of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where x is a hex digit. + * - com.arm.mbed. + * - guids of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where x is a hex digit. * * In the cfstore implementation, explicit checking of the structure of the * namespace string is not required. Cfstore only need enforce that: - * the root of the KV pathname == cfstore client uvisor namespace. + * the root of the KV pathname == cfstore client uvisor namespace. */ -static int32_t cfstore_uvisor_is_client_kv_owner(char* key_name, int32_t* cfstore_uvisor_box_id) +static int32_t cfstore_uvisor_is_client_kv_owner(char *key_name, int32_t *cfstore_uvisor_box_id) { int32_t calling_box_id; int32_t ret; @@ -866,14 +871,14 @@ static int32_t cfstore_uvisor_is_client_kv_owner(char* key_name, int32_t* cfstor memset(calling_box_namespace, 0, sizeof(calling_box_namespace)); /* Get the ID of the box that called this box through the most recent secure gateway. */ calling_box_id = uvisor_box_id_caller(); - if(calling_box_id < 0){ + if (calling_box_id < 0) { CFSTORE_ERRLOG("%s: Error: uvisor uvisor_box_id_caller() returned invalid id (calling_box_id=%d\n", __func__, (int) calling_box_id); return ARM_CFSTORE_DRIVER_ERROR_UVISOR_BOX_ID; } - if(cfstore_uvisor_box_id){ + if (cfstore_uvisor_box_id) { *cfstore_uvisor_box_id = calling_box_id; } - if(calling_box_id == 0){ + if (calling_box_id == 0) { /* the cfstore uvisor client is the main box. * main box is not allowed to create a key as a client is only permitted to create KVs in their namespace. */ CFSTORE_ERRLOG("%s: Error: uvisor box id identifies cfstore client cannot create KVs (calling_box_id=%d\n", __func__, (int) calling_box_id); @@ -881,18 +886,18 @@ static int32_t cfstore_uvisor_is_client_kv_owner(char* key_name, int32_t* cfstor } /* Copy the name of the calling box to our stack. */ ret = uvisor_box_namespace(calling_box_id, calling_box_namespace, sizeof(calling_box_namespace)); - if(ret < 0){ + if (ret < 0) { /* error */ CFSTORE_ERRLOG("%s: Error: unable to recover uvisor box namespace\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_UVISOR_NAMESPACE; } /* check the cfstore client uvisor box namespace is non-trivial */ - if(strlen(calling_box_namespace) == 0){ + if (strlen(calling_box_namespace) == 0) { CFSTORE_ERRLOG("%s: Error: uvisor box namespace is zero length\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_UVISOR_NAMESPACE; } /* check that the key name is within the root domain namespace */ - if(strncmp(calling_box_namespace, key_name, sizeof(calling_box_namespace)) != 0) { + if (strncmp(calling_box_namespace, key_name, sizeof(calling_box_namespace)) != 0) { /* The key_name does not fall within the cfstore-uvisor client namespace and therefore the create is not allowed */ CFSTORE_ERRLOG("%s: Error: key name (%s) is not permitted to be created within client uvisor box namespace (%s) of cfstore client\n", __func__, key_name, calling_box_namespace); return ARM_CFSTORE_DRIVER_ERROR_NO_PERMISSIONS; @@ -908,18 +913,18 @@ static int32_t cfstore_uvisor_is_client_kv_owner(char* key_name, int32_t* cfstor * * @note This function is the cfstore equivalent of "is_calling_box_allowed" */ -static int32_t cfstore_uvisor_security_context_prefix_check(const char* key_name) +static int32_t cfstore_uvisor_security_context_prefix_check(const char *key_name) { /*todo: implement : A client uvisor security context should exist with * a security_prefix_name that matches the first part of the * key_name. Make sure this is the case. */ - // if the caller is the main box then deny access, as only secure uvisor boxes - // are permitted to access cfstore. + // if the caller is the main box then deny access, as only secure uvisor boxes + // are permitted to access cfstore. - // get box_id of caller - // get namespace of caller - // if the keyname is in the namespace then permit, otherwise deny + // get box_id of caller + // get namespace of caller + // if the keyname is in the namespace then permit, otherwise deny (void) key_name; return ARM_DRIVER_OK; @@ -928,23 +933,23 @@ static int32_t cfstore_uvisor_security_context_prefix_check(const char* key_name /* @brief check that a client (cfstore-uvisor client box) is the "owner" of the * KV (wrapper). see cfstore_uvisor_is_client_kv_owner() for more details. */ -static int32_t cfstore_is_client_kv_owner(const char* key_name, int32_t* cfstore_uvisor_box_id) +static int32_t cfstore_is_client_kv_owner(const char *key_name, int32_t *cfstore_uvisor_box_id) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); -/* -#ifdef YOTTA_CFG_CFSTORE_UVISOR - return cfstore_uvisor_is_client_kv_owner(key_name, cfstore_uvisor_box_id); -#else - return ARM_DRIVER_OK; -#endif -*/ + /* + #ifdef YOTTA_CFG_CFSTORE_UVISOR + return cfstore_uvisor_is_client_kv_owner(key_name, cfstore_uvisor_box_id); + #else + return ARM_DRIVER_OK; + #endif + */ (void) key_name; (void) cfstore_uvisor_box_id; return ARM_DRIVER_OK; } /* @brief helper function to determine whether this client can close a given KV */ -static bool cfstore_is_kv_client_closable(cfstore_file_t* file) +static bool cfstore_is_kv_client_closable(cfstore_file_t *file) { /* todo: integrate with uvisor to get boxId (security prefix name) * - check the kv key_name prefix matches the security context to determine whether client is @@ -956,7 +961,7 @@ static bool cfstore_is_kv_client_closable(cfstore_file_t* file) } /* @brief helper function to determine whether this client can delete a given KV */ -static bool cfstore_is_kv_client_deletable(cfstore_file_t* file) +static bool cfstore_is_kv_client_deletable(cfstore_file_t *file) { /* todo: integrate with uvisor to get boxId (security prefix name) * - check the kv key_name prefix matches the security context to determine whether client is @@ -969,24 +974,24 @@ static bool cfstore_is_kv_client_deletable(cfstore_file_t* file) #ifdef YOTTA_CFG_CFSTORE_UVISOR /* @brief helper function to determine whether this cfstore-uvisor client box can read a given KV */ -static bool cfstore_is_kv_client_readable(cfstore_area_hkvt_t* hkvt) +static bool cfstore_is_kv_client_readable(cfstore_area_hkvt_t *hkvt) { bool bret = false; int32_t ret = ARM_DRIVER_ERROR; - char key_name[CFSTORE_KEY_NAME_MAX_LENGTH+1]; - uint8_t key_name_len = CFSTORE_KEY_NAME_MAX_LENGTH+1; - cfstore_area_header_t *hdr = (cfstore_area_header_t*) hkvt->head; + char key_name[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; + uint8_t key_name_len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; + cfstore_area_header_t *hdr = (cfstore_area_header_t *) hkvt->head; CFSTORE_FENTRYLOG("%s:entered\n", __func__); memset(key_name, 0, key_name_len); ret = cfstore_get_key_name_ex(hkvt, key_name, &key_name_len); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: cfstore_get_key_name_ex() returned error.\n", __func__); return bret; } ret = cfstore_is_client_kv_owner(key_name, NULL); - if(ret == ARM_DRIVER_OK){ + if (ret == ARM_DRIVER_OK) { /* cfstore-usvisor client box is the "owner" of the key */ bret = hdr->perm_owner_read; } else { @@ -997,23 +1002,23 @@ static bool cfstore_is_kv_client_readable(cfstore_area_hkvt_t* hkvt) } /* @brief helper function to determine whether this client can write a given KV */ -static bool cfstore_is_kv_client_writable(cfstore_area_hkvt_t* hkvt) +static bool cfstore_is_kv_client_writable(cfstore_area_hkvt_t *hkvt) { bool bret = false; int32_t ret = ARM_DRIVER_ERROR; - char key_name[CFSTORE_KEY_NAME_MAX_LENGTH+1]; - uint8_t key_name_len = CFSTORE_KEY_NAME_MAX_LENGTH+1; - cfstore_area_header_t *hdr = (cfstore_area_header_t*) hkvt->head; + char key_name[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; + uint8_t key_name_len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; + cfstore_area_header_t *hdr = (cfstore_area_header_t *) hkvt->head; CFSTORE_FENTRYLOG("%s:entered\n", __func__); memset(key_name, 0, key_name_len); ret = cfstore_get_key_name_ex(hkvt, key_name, &key_name_len); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: cfstore_get_key_name_ex() returned error.\n", __func__); return bret; } ret = cfstore_is_client_kv_owner(key_name, NULL); - if(ret == ARM_DRIVER_OK){ + if (ret == ARM_DRIVER_OK) { /* cfstore-usvisor client box is the "owner" of the key */ bret = hdr->perm_owner_write; } else { @@ -1024,23 +1029,23 @@ static bool cfstore_is_kv_client_writable(cfstore_area_hkvt_t* hkvt) } /* @brief helper function to determine whether this client can execute a given KV */ -static bool cfstore_is_kv_client_executable(cfstore_area_hkvt_t* hkvt) +static bool cfstore_is_kv_client_executable(cfstore_area_hkvt_t *hkvt) { bool bret = false; int32_t ret = ARM_DRIVER_ERROR; - char key_name[CFSTORE_KEY_NAME_MAX_LENGTH+1]; - uint8_t key_name_len = CFSTORE_KEY_NAME_MAX_LENGTH+1; - cfstore_area_header_t *hdr = (cfstore_area_header_t*) hkvt->head; + char key_name[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; + uint8_t key_name_len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; + cfstore_area_header_t *hdr = (cfstore_area_header_t *) hkvt->head; CFSTORE_FENTRYLOG("%s:entered\n", __func__); memset(key_name, 0, key_name_len); ret = cfstore_get_key_name_ex(hkvt, key_name, &key_name_len); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: cfstore_get_key_name_ex() returned error.\n", __func__); return bret; } ret = cfstore_is_client_kv_owner(key_name, NULL); - if(ret == ARM_DRIVER_OK){ + if (ret == ARM_DRIVER_OK) { /* cfstore-usvisor client box is the "owner" of the key */ bret = hdr->perm_owner_execute; } else { @@ -1052,7 +1057,7 @@ static bool cfstore_is_kv_client_executable(cfstore_area_hkvt_t* hkvt) #endif /* YOTTA_CFG_CFSTORE_UVISOR */ /* @brief helper function to determine whether this client can read a given KV */ -static bool cfstore_is_kv_client_readable(cfstore_area_hkvt_t* hkvt) +static bool cfstore_is_kv_client_readable(cfstore_area_hkvt_t *hkvt) { /* todo: integrate with uvisor to get boxId (security prefix name) * - check the kv key_name prefix matches the security context to determine whether client is @@ -1076,9 +1081,9 @@ static bool cfstore_is_kv_client_readable(cfstore_area_hkvt_t* hkvt) } /* @brief helper function to determine whether this client can write a given KV */ -static bool cfstore_is_kv_client_writable(cfstore_area_hkvt_t* hkvt) +static bool cfstore_is_kv_client_writable(cfstore_area_hkvt_t *hkvt) { - cfstore_area_header_t *hdr = (cfstore_area_header_t*) hkvt->head; + cfstore_area_header_t *hdr = (cfstore_area_header_t *) hkvt->head; /* todo: integrate with uvisor to get boxId (security prefix name) * - check the kv key_name prefix matches the security context to determine whether client is @@ -1103,7 +1108,7 @@ static bool cfstore_is_kv_client_writable(cfstore_area_hkvt_t* hkvt) } /* @brief helper function to determine whether this client can execute a given KV */ -static bool cfstore_is_kv_client_executable(cfstore_area_hkvt_t* hkvt) +static bool cfstore_is_kv_client_executable(cfstore_area_hkvt_t *hkvt) { /* todo: integrate with uvisor to get boxId (security prefix name) * - check the kv key_name prefix matches the security context to determine whether client is @@ -1132,13 +1137,12 @@ static bool cfstore_is_kv_client_executable(cfstore_area_hkvt_t* hkvt) */ static bool cfstore_acl_is_default(ARM_CFSTORE_ACCESS_CONTROL_LIST acl) { - if( acl.perm_owner_read == false && + if (acl.perm_owner_read == false && acl.perm_owner_write == false && acl.perm_owner_execute == false && acl.perm_other_read == false && acl.perm_other_write == false && - acl.perm_other_execute == false ) - { + acl.perm_other_execute == false) { /* flags are set to indicate "adopt some meaningful default behaviour" */ return true; } @@ -1150,13 +1154,12 @@ static bool cfstore_acl_is_default(ARM_CFSTORE_ACCESS_CONTROL_LIST acl) */ static bool cfstore_flags_is_default(ARM_CFSTORE_FMODE flags) { - if( flags.read == 0 && - flags.write == 0 && - flags.continuous == 0 && - flags.flush_on_close == 0 && - flags.lazy_flush == 0 && - flags.storage_detect == 0 ) - { + if (flags.read == 0 && + flags.write == 0 && + flags.continuous == 0 && + flags.flush_on_close == 0 && + flags.lazy_flush == 0 && + flags.storage_detect == 0) { /* flags are set to indicate "adopt some meaningful default behaviour" */ return true; } @@ -1165,36 +1168,36 @@ static bool cfstore_flags_is_default(ARM_CFSTORE_FMODE flags) static CFSTORE_INLINE bool cfstore_hkvt_get_flags_delete(cfstore_area_hkvt_t *hkvt) { - return ((cfstore_area_header_t*) hkvt->head)->flags.delete; + return ((cfstore_area_header_t *) hkvt->head)->flags.delete; } static CFSTORE_INLINE void cfstore_hkvt_set_flags_delete(cfstore_area_hkvt_t *hkvt, bool flag) { CFSTORE_ASSERT(hkvt != NULL); - ((cfstore_area_header_t*) hkvt->head)->flags.delete = flag; + ((cfstore_area_header_t *) hkvt->head)->flags.delete = flag; } /* * struct cfstore_area_hkvt_t helper operations */ -static CFSTORE_INLINE uint8_t cfstore_hkvt_get_key_len(cfstore_area_hkvt_t* hkvt) +static CFSTORE_INLINE uint8_t cfstore_hkvt_get_key_len(cfstore_area_hkvt_t *hkvt) { cfstore_area_header_t *header; CFSTORE_ASSERT(hkvt != NULL); - header = (cfstore_area_header_t*) hkvt->head; + header = (cfstore_area_header_t *) hkvt->head; return header->klength; } -static CFSTORE_INLINE uint32_t cfstore_hkvt_get_value_len(cfstore_area_hkvt_t* hkvt) +static CFSTORE_INLINE uint32_t cfstore_hkvt_get_value_len(cfstore_area_hkvt_t *hkvt) { cfstore_area_header_t *header; CFSTORE_ASSERT(hkvt != NULL); - header = (cfstore_area_header_t*) hkvt->head; + header = (cfstore_area_header_t *) hkvt->head; return header->vlength; } -static CFSTORE_INLINE ARM_CFSTORE_SIZE cfstore_hkvt_get_size(cfstore_area_hkvt_t* hkvt) +static CFSTORE_INLINE ARM_CFSTORE_SIZE cfstore_hkvt_get_size(cfstore_area_hkvt_t *hkvt) { ARM_CFSTORE_SIZE kv_size = 0; @@ -1204,7 +1207,7 @@ static CFSTORE_INLINE ARM_CFSTORE_SIZE cfstore_hkvt_get_size(cfstore_area_hkvt_t return kv_size; } -static CFSTORE_INLINE void cfstore_hkvt_init(cfstore_area_hkvt_t* hkvt) +static CFSTORE_INLINE void cfstore_hkvt_init(cfstore_area_hkvt_t *hkvt) { memset(hkvt, 0, sizeof(cfstore_area_hkvt_t)); } @@ -1212,18 +1215,18 @@ static CFSTORE_INLINE void cfstore_hkvt_init(cfstore_area_hkvt_t* hkvt) static CFSTORE_INLINE bool cfstore_hkvt_is_valid(cfstore_area_hkvt_t *hkvt, uint8_t *area_0_tail) { - if(hkvt->head && hkvt->head != area_0_tail && hkvt->key && hkvt->value && hkvt->tail) { + if (hkvt->head && hkvt->head != area_0_tail && hkvt->key && hkvt->value && hkvt->tail) { return true; } return false; } -static CFSTORE_INLINE uint32_t cfstore_hkvt_set_value_len(cfstore_area_hkvt_t* hkvt, uint32_t value_len) +static CFSTORE_INLINE uint32_t cfstore_hkvt_set_value_len(cfstore_area_hkvt_t *hkvt, uint32_t value_len) { uint32_t vlength; cfstore_area_header_t *hdr; CFSTORE_ASSERT(hkvt != NULL); - hdr = (cfstore_area_header_t*) hkvt->head; + hdr = (cfstore_area_header_t *) hkvt->head; vlength = hdr->vlength; hdr->vlength = value_len; return vlength; @@ -1232,10 +1235,10 @@ static CFSTORE_INLINE uint32_t cfstore_hkvt_set_value_len(cfstore_area_hkvt_t* h /* @brief helper function to detect if there are any KV's stored in the sram area */ static bool cfstore_area_has_hkvt(void) { - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); /* head and tail pointer equal means there are no KVs stored */ - if(ctx->area_0_head == ctx->area_0_tail){ + if (ctx->area_0_head == ctx->area_0_tail) { /* there are no KV's stored*/ return false; } @@ -1244,16 +1247,16 @@ static bool cfstore_area_has_hkvt(void) /* @brief helper function to get the first KV in the sram area */ -static cfstore_area_hkvt_t cfstore_get_hkvt_from_head_ptr(uint8_t* head) +static cfstore_area_hkvt_t cfstore_get_hkvt_from_head_ptr(uint8_t *head) { cfstore_area_hkvt_t hkvt; CFSTORE_ASSERT(head != NULL); - memset((void*) &hkvt, 0, sizeof(hkvt)); + memset((void *) &hkvt, 0, sizeof(hkvt)); hkvt.head = head; hkvt.key = hkvt.head + sizeof(cfstore_area_header_t); - hkvt.value = hkvt.key + ((cfstore_area_header_t*) hkvt.head)->klength; - hkvt.tail = hkvt.value + ((cfstore_area_header_t*) hkvt.head)->vlength; + hkvt.value = hkvt.key + ((cfstore_area_header_t *) hkvt.head)->klength; + hkvt.tail = hkvt.value + ((cfstore_area_header_t *) hkvt.head)->vlength; return hkvt; } @@ -1261,21 +1264,21 @@ static cfstore_area_hkvt_t cfstore_get_hkvt_from_head_ptr(uint8_t* head) /* @brief helper function to convert a opaque handle to a struct cfstore_area_hkvt_t */ static cfstore_area_hkvt_t cfstore_get_hkvt(ARM_CFSTORE_HANDLE hkey) { - cfstore_file_t* file = (cfstore_file_t*) hkey; - return cfstore_get_hkvt_from_head_ptr((uint8_t*) file->head); + cfstore_file_t *file = (cfstore_file_t *) hkey; + return cfstore_get_hkvt_from_head_ptr((uint8_t *) file->head); } /* @brief helper function to convert a opaque handle to a struct cfstore_area_hkvt_t */ -static int32_t cfstore_get_head_hkvt(cfstore_area_hkvt_t* hkvt) +static int32_t cfstore_get_head_hkvt(cfstore_area_hkvt_t *hkvt) { - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); CFSTORE_FENTRYLOG("%s:entered\n", __func__); CFSTORE_ASSERT(hkvt != NULL); - if(!cfstore_area_has_hkvt()){ + if (!cfstore_area_has_hkvt()) { CFSTORE_TP(CFSTORE_TP_VERBOSE1, "%s:CFSTORE has no KVs\n", __func__); - memset((void*) hkvt, 0, sizeof(cfstore_area_hkvt_t)); + memset((void *) hkvt, 0, sizeof(cfstore_area_hkvt_t)); return ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND; } @@ -1293,21 +1296,21 @@ static int32_t cfstore_get_head_hkvt(cfstore_area_hkvt_t* hkvt) * @param next * pointer to next hkvt for which the pointers need calculating. */ -static int32_t cfstore_get_next_hkvt(cfstore_area_hkvt_t* prev, cfstore_area_hkvt_t* next) +static int32_t cfstore_get_next_hkvt(cfstore_area_hkvt_t *prev, cfstore_area_hkvt_t *next) { - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); - CFSTORE_ASSERT(prev != NULL); + CFSTORE_ASSERT(prev != NULL); CFSTORE_ASSERT(next != NULL); CFSTORE_ASSERT(prev->tail <= ctx->area_0_tail); - if(prev->tail == ctx->area_0_tail){ + if (prev->tail == ctx->area_0_tail) { CFSTORE_TP(CFSTORE_TP_VERBOSE1, "%s:reached the end of the list. return NULL entry\n", __func__); - memset((void*) next, 0, sizeof(cfstore_area_hkvt_t)); + memset((void *) next, 0, sizeof(cfstore_area_hkvt_t)); return ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND; } /* use the prev tail pointer to find the next head pointer */ - *next = cfstore_get_hkvt_from_head_ptr((uint8_t*) prev->tail); + *next = cfstore_get_hkvt_from_head_ptr((uint8_t *) prev->tail); return ARM_DRIVER_OK; } @@ -1316,7 +1319,7 @@ static int32_t cfstore_get_next_hkvt(cfstore_area_hkvt_t* prev, cfstore_area_hkv * Flash support functions */ -static CFSTORE_INLINE void cfstore_hkvt_dump(cfstore_area_hkvt_t* hkvt, const char* tag); +static CFSTORE_INLINE void cfstore_hkvt_dump(cfstore_area_hkvt_t *hkvt, const char *tag); /** @brief Set the context tail pointer area_0_tail to point to the end of the * last KV in the memory area. @@ -1344,9 +1347,9 @@ static CFSTORE_INLINE void cfstore_hkvt_dump(cfstore_area_hkvt_t* hkvt, const ch static int32_t cfstore_flash_set_tail(void) { int32_t ret = ARM_DRIVER_ERROR; - uint8_t* ptr = NULL; - cfstore_ctx_t* ctx = cfstore_ctx_get(); - uint8_t* tail = NULL; + uint8_t *ptr = NULL; + cfstore_ctx_t *ctx = cfstore_ctx_get(); + uint8_t *tail = NULL; cfstore_area_hkvt_t hkvt; CFSTORE_FENTRYLOG("%s:entered: \n", __func__); @@ -1355,16 +1358,16 @@ static int32_t cfstore_flash_set_tail(void) /* Check for cases where the tail pointer is already set correctly * e.g. where the area is of zero length */ - if(cfstore_ctx_get_kv_total_len() == 0) { + if (cfstore_ctx_get_kv_total_len() == 0) { /* tail pointer already set correctly */ return ARM_DRIVER_OK; } ptr = ctx->area_0_head; tail = ctx->area_0_tail; - while(ptr <= tail) { + while (ptr <= tail) { CFSTORE_FENTRYLOG("%s:ptr=%p, tail=%p: \n", __func__, ptr, tail); hkvt = cfstore_get_hkvt_from_head_ptr(ptr); - if(cfstore_hkvt_is_valid(&hkvt, tail) == false) { + if (cfstore_hkvt_is_valid(&hkvt, tail) == false) { CFSTORE_ERRLOG("%s:Error:found invalid hkvt entry in area\n", __func__); break; } @@ -1374,7 +1377,7 @@ static int32_t cfstore_flash_set_tail(void) * area_0_tail correctly to the end of the last KV. This works OK for the present support * (where flash_program_unit ~ sizeof(cfstore_area_header_t)) but may need * revisiting where flash_program_unit > sizeof(cfstore_area_header_t) */ - if((uint32_t)(tail - hkvt.tail) < sizeof(cfstore_area_header_t)){ + if ((uint32_t)(tail - hkvt.tail) < sizeof(cfstore_area_header_t)) { /* ptr is last KV in area as there isn't space for another header */ ctx->area_0_tail = hkvt.tail; ret = ARM_DRIVER_OK; @@ -1409,13 +1412,13 @@ static int32_t cfstore_flash_set_tail(void) */ static int32_t cfstore_realloc_ex(ARM_CFSTORE_SIZE size, uint64_t *allocated_size) { - uint8_t* ptr = NULL; + uint8_t *ptr = NULL; int32_t ret = ARM_DRIVER_ERROR; int32_t len_diff = 0; - cfstore_ctx_t* ctx = cfstore_ctx_get(); - cfstore_file_t* file; - cfstore_list_node_t* node; - cfstore_list_node_t* file_list = &ctx->file_list; + cfstore_ctx_t *ctx = cfstore_ctx_get(); + cfstore_file_t *file; + cfstore_list_node_t *node; + cfstore_list_node_t *file_list = &ctx->file_list; ARM_CFSTORE_SIZE total_kv_size = size; /* Switch on the size of the sram area to create: @@ -1429,16 +1432,15 @@ static int32_t cfstore_realloc_ex(ARM_CFSTORE_SIZE size, uint64_t *allocated_siz CFSTORE_FENTRYLOG("%s:entered:\n", __func__); CFSTORE_TP(CFSTORE_TP_MEM, "%s:cfstore_ctx_g.area_0_head=%p, cfstore_ctx_g.area_0_tail=%p, cfstore_ctx_g.area_0_len=%d, size=%d, \n", __func__, ctx->area_0_head, ctx->area_0_tail, (int) ctx->area_0_len, (int) size); - if(size > 0) - { + if (size > 0) { /* In the general case (size % program_unit > 0). The new area_0 size is * aligned to a flash program_unit boundary to facilitate r/w to flash * and so the memory realloc size is calculated to align, as follows */ - if(size % cfstore_ctx_get_program_unit(ctx) > 0){ + if (size % cfstore_ctx_get_program_unit(ctx) > 0) { size += (cfstore_ctx_get_program_unit(ctx) - (size % cfstore_ctx_get_program_unit(ctx))); } - ptr = (uint8_t*) CFSTORE_REALLOC((void*) ctx->area_0_head, size); + ptr = (uint8_t *) CFSTORE_REALLOC((void *) ctx->area_0_head, size); if (ptr == NULL) { if (total_kv_size <= ctx->area_0_len) { /* Size is shrinking so a realloc failure is recoverable. @@ -1447,7 +1449,7 @@ static int32_t cfstore_realloc_ex(ARM_CFSTORE_SIZE size, uint64_t *allocated_siz ptr = ctx->area_0_head; } } - if(ptr == NULL){ + if (ptr == NULL) { CFSTORE_ERRLOG("%s:Error: unable to allocate memory (size=%d)\n", __func__, (int) size); /* realloc() has failed to allocate the required memory object. If previously * allocation has been made, the old memory object remains allocated. On error, the client @@ -1457,17 +1459,17 @@ static int32_t cfstore_realloc_ex(ARM_CFSTORE_SIZE size, uint64_t *allocated_siz return ARM_CFSTORE_DRIVER_ERROR_OUT_OF_MEMORY; } /* check realloc() hasn't move area in memory from cfstore_ctx_g.area_0_head */ - if(ptr != ctx->area_0_head){ + if (ptr != ctx->area_0_head) { /* realloc() has moved the area in memory */ CFSTORE_TP(CFSTORE_TP_MEM, "%s: realloc() has moved memory area and area_0_head ptr must change. old cfstore_ctx_g.area_0_head=%p, new head ptr=%p)\n", __func__, ctx->area_0_head, ptr); /* now have to walk the file list updating head pointers to point into the realloc-ed * To begin with, leave the relative position of the file pointers unaltered */ node = file_list->next; - while(node != file_list){ - file = (cfstore_file_t*) node; - file->head = (uint8_t *) (file->head - ctx->area_0_head); - file->head = (uint8_t *) ((int32_t) file->head + (int32_t) ptr); + while (node != file_list) { + file = (cfstore_file_t *) node; + file->head = (uint8_t *)(file->head - ctx->area_0_head); + file->head = (uint8_t *)((int32_t) file->head + (int32_t) ptr); node = node->next; } ctx->area_0_head = ptr; @@ -1475,7 +1477,7 @@ static int32_t cfstore_realloc_ex(ARM_CFSTORE_SIZE size, uint64_t *allocated_siz /* If the area is growing then zero the new space at the end of the area */ len_diff = size - (int32_t) ctx->area_0_len; - if(len_diff > 0) { + if (len_diff > 0) { memset(ptr + ctx->area_0_len, 0, len_diff); } /* Set area_0_tail to be the memory address after the end of the last KV in the memory area. @@ -1484,14 +1486,12 @@ static int32_t cfstore_realloc_ex(ARM_CFSTORE_SIZE size, uint64_t *allocated_siz */ ctx->area_0_len = size; ctx->area_0_tail = ptr + total_kv_size; - if(allocated_size != NULL) { + if (allocated_size != NULL) { *allocated_size = size; } - } - else - { + } else { /* size = 0 so delete the memory */ - CFSTORE_FREE((void*) ctx->area_0_head); + CFSTORE_FREE((void *) ctx->area_0_head); ctx->area_0_head = NULL; ctx->area_0_tail = NULL; ctx->area_0_len = 0; @@ -1510,8 +1510,7 @@ static int32_t cfstore_realloc_ex(ARM_CFSTORE_SIZE size, uint64_t *allocated_siz */ /* @brief table for mapping flash journal error codes to equivalent cfstore error codes */ -static cfstore_flash_journal_error_code_node cfstore_flash_journal_error_code_map[]= -{ +static cfstore_flash_journal_error_code_node cfstore_flash_journal_error_code_map[] = { { JOURNAL_STATUS_OK, ARM_DRIVER_OK}, { JOURNAL_STATUS_ERROR, ARM_CFSTORE_DRIVER_ERROR_JOURNAL_STATUS_ERROR}, { JOURNAL_STATUS_BUSY, ARM_CFSTORE_DRIVER_ERROR_JOURNAL_STATUS_BUSY}, @@ -1529,12 +1528,10 @@ static cfstore_flash_journal_error_code_node cfstore_flash_journal_error_code_ma static int32_t cfstore_flash_map_error(int32_t flash_journal_status_code) { - cfstore_flash_journal_error_code_node* node = cfstore_flash_journal_error_code_map; + cfstore_flash_journal_error_code_node *node = cfstore_flash_journal_error_code_map; - while(node->flash_journal_error_code != (int32_t) CFSTORE_SENTINEL) - { - if(flash_journal_status_code == node->flash_journal_error_code) - { + while (node->flash_journal_error_code != (int32_t) CFSTORE_SENTINEL) { + if (flash_journal_status_code == node->flash_journal_error_code) { return node->cfstore_error_code; } } @@ -1561,52 +1558,51 @@ static int32_t cfstore_flash_map_error(int32_t flash_journal_status_code) */ static void cfstore_flash_journal_callback(int32_t status, FlashJournal_OpCode_t cmd_code) { - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); CFSTORE_FENTRYLOG("%s:entered: status=%d, cmd_code=%d (%s)\n", __func__, (int) status, (int) cmd_code, cfstore_flash_opcode_str[cmd_code]); - switch(cmd_code) - { - case FLASH_JOURNAL_OPCODE_FORMAT: - ctx->fsm.event = cfstore_fsm_event_format_done; - break; - case FLASH_JOURNAL_OPCODE_INITIALIZE: - ctx->fsm.event = cfstore_fsm_event_init_done; - break; - case FLASH_JOURNAL_OPCODE_READ_BLOB: - ctx->fsm.event = cfstore_fsm_event_read_done; - break; - case FLASH_JOURNAL_OPCODE_LOG_BLOB: - ctx->fsm.event = cfstore_fsm_event_log_done; - break; - case FLASH_JOURNAL_OPCODE_COMMIT: - ctx->fsm.event = cfstore_fsm_event_commit_done; - break; - case FLASH_JOURNAL_OPCODE_RESET: - ctx->fsm.event = cfstore_fsm_event_reset_done; - break; - case FLASH_JOURNAL_OPCODE_GET_INFO: - default: - CFSTORE_ERRLOG("%s:Error: notification of unsupported cmd_code event (status=%d, cmd_code=%d)\n", __func__, (int) status, (int) cmd_code); - return; + switch (cmd_code) { + case FLASH_JOURNAL_OPCODE_FORMAT: + ctx->fsm.event = cfstore_fsm_event_format_done; + break; + case FLASH_JOURNAL_OPCODE_INITIALIZE: + ctx->fsm.event = cfstore_fsm_event_init_done; + break; + case FLASH_JOURNAL_OPCODE_READ_BLOB: + ctx->fsm.event = cfstore_fsm_event_read_done; + break; + case FLASH_JOURNAL_OPCODE_LOG_BLOB: + ctx->fsm.event = cfstore_fsm_event_log_done; + break; + case FLASH_JOURNAL_OPCODE_COMMIT: + ctx->fsm.event = cfstore_fsm_event_commit_done; + break; + case FLASH_JOURNAL_OPCODE_RESET: + ctx->fsm.event = cfstore_fsm_event_reset_done; + break; + case FLASH_JOURNAL_OPCODE_GET_INFO: + default: + CFSTORE_ERRLOG("%s:Error: notification of unsupported cmd_code event (status=%d, cmd_code=%d)\n", __func__, (int) status, (int) cmd_code); + return; } ctx->status = status; ctx->cmd_code = cmd_code; - cfstore_fsm_state_handle_event(&ctx->fsm, ctx->fsm.event, (void*) ctx); + cfstore_fsm_state_handle_event(&ctx->fsm, ctx->fsm.event, (void *) ctx); return; } /* @brief */ -static int32_t cfstore_fsm_stop_on_entry(void* context) +static int32_t cfstore_fsm_stop_on_entry(void *context) { - cfstore_ctx_t* ctx = (cfstore_ctx_t*) context; + cfstore_ctx_t *ctx = (cfstore_ctx_t *) context; /* reset fsm state */ CFSTORE_FENTRYLOG("%s:entered\n", __func__); CFSTORE_ASSERT(ctx->fsm.state == cfstore_fsm_state_stopped); ctx->fsm.event = cfstore_fsm_event_max; - ctx->cmd_code = (FlashJournal_OpCode_t)((int) FLASH_JOURNAL_OPCODE_RESET+1); + ctx->cmd_code = (FlashJournal_OpCode_t)((int) FLASH_JOURNAL_OPCODE_RESET + 1); return ARM_DRIVER_OK; } @@ -1621,15 +1617,15 @@ static int32_t cfstore_fsm_stop_on_entry(void* context) * journal sync and asyc modes. There are no outstanding async requests * so it cannot be interrupted, and therefore doesnt need CS protection. */ -static int32_t cfstore_fsm_init_on_entry(void* context) +static int32_t cfstore_fsm_init_on_entry(void *context) { int32_t ret = ARM_DRIVER_ERROR; - cfstore_ctx_t* ctx = (cfstore_ctx_t*) context; + cfstore_ctx_t *ctx = (cfstore_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered\n", __func__); ret = cfstore_svm_init(&cfstore_journal_mtd); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_DBGLOG("%s:Error: Unable to initialize storage volume manager\n", __func__); cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_formatting, ctx); return ARM_DRIVER_OK; @@ -1637,21 +1633,20 @@ static int32_t cfstore_fsm_init_on_entry(void* context) ret = FlashJournal_initialize(&ctx->jrnl, (ARM_DRIVER_STORAGE *) &cfstore_journal_mtd, &FLASH_JOURNAL_STRATEGY_SEQUENTIAL, cfstore_flash_journal_callback); CFSTORE_TP(CFSTORE_TP_FSM, "%s:FlashJournal_initialize ret=%d\n", __func__, (int) ret); - if(ret < ARM_DRIVER_OK){ - if(ret == JOURNAL_STATUS_NOT_FORMATTED) { + if (ret < ARM_DRIVER_OK) { + if (ret == JOURNAL_STATUS_NOT_FORMATTED) { CFSTORE_DBGLOG("%s:Error: flash not formatted\n", __func__); cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_formatting, ctx); return ARM_DRIVER_OK; } - if(ret == JOURNAL_STATUS_METADATA_ERROR) { + if (ret == JOURNAL_STATUS_METADATA_ERROR) { CFSTORE_ERRLOG("%s:Error: flash meta-data (CRC) error detected when initializing flash. Reformatting flash.\n", __func__); cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_formatting, ctx); return ARM_DRIVER_OK; } CFSTORE_ERRLOG("%s:Error: failed to initialize flash journaling layer (ret=%d)\n", __func__, (int) ret); cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_stopped, ctx); - } - else if(ret > 0){ + } else if (ret > 0) { /* operation completed synchronously*/ cfstore_flash_journal_callback(ret, FLASH_JOURNAL_OPCODE_INITIALIZE); } @@ -1668,19 +1663,19 @@ static int32_t cfstore_fsm_init_on_entry(void* context) * journal invokes the callback handler for FLASH_JOURNAL_OPCODE_INITIALIZE * Hence as running at intr level, no CS protection is required. */ -static int32_t cfstore_fsm_initing(void* context) +static int32_t cfstore_fsm_initing(void *context) { int32_t ret = ARM_DRIVER_OK; - cfstore_ctx_t* ctx = (cfstore_ctx_t*) context; + cfstore_ctx_t *ctx = (cfstore_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered\n", __func__); CFSTORE_ASSERT(ctx->fsm.state == cfstore_fsm_state_initing); CFSTORE_ASSERT(ctx->cmd_code == FLASH_JOURNAL_OPCODE_INITIALIZE); /* only change state if status > 0*/ - if(ctx->status > 0){ + if (ctx->status > 0) { ret = cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_reading, ctx); - } else if(ctx->status < 0) { + } else if (ctx->status < 0) { CFSTORE_ERRLOG("%s:Error: failed to initialize flash journaling layer (ret=%d)\n", __func__, (int) ctx->status); cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_stopped, ctx); } @@ -1699,41 +1694,40 @@ static int32_t cfstore_fsm_initing(void* context) * journal invokes the callback handler for FLASH_JOURNAL_OPCODE_INITIALIZE * Hence as running at intr level, no CS protection is required. */ -static int32_t cfstore_fsm_read_on_entry(void* context) +static int32_t cfstore_fsm_read_on_entry(void *context) { int32_t ret = 0; FlashJournal_Status_t status = JOURNAL_STATUS_ERROR; - cfstore_ctx_t* ctx = (cfstore_ctx_t*) context; + cfstore_ctx_t *ctx = (cfstore_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered\n", __func__); CFSTORE_ASSERT(ctx != NULL); /* FlashJournal_getInfo() is synchronous */ status = FlashJournal_getInfo(&ctx->jrnl, &ctx->info); - if(status < JOURNAL_STATUS_OK){ + if (status < JOURNAL_STATUS_OK) { CFSTORE_TP(CFSTORE_TP_FSM, "%s:Error: failed get journal info (status=%d)\n", __func__, (int) status); /* move to ready state. cfstore client is expected to Uninitialize() before further calls */ cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_ready, ctx); ret = ARM_CFSTORE_DRIVER_ERROR_INTERNAL; goto out; } - if(ctx->info.sizeofJournaledBlob > 0) - { + if (ctx->info.sizeofJournaledBlob > 0) { /* setup the expected blob size for writing */ ctx->expected_blob_size = ctx->info.sizeofJournaledBlob; ret = cfstore_realloc_ex(ctx->expected_blob_size, &ctx->expected_blob_size); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: cfstore_realloc_ex() failed (ret=%d)\n", __func__, (int) ret); /* move to ready state. cfstore client is expected to Uninitialize() before further calls */ cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_ready, ctx); goto out; } - ret = FlashJournal_read(&ctx->jrnl, (void*) ctx->area_0_head, ctx->info.sizeofJournaledBlob); - if(ret < ARM_DRIVER_OK){ + ret = FlashJournal_read(&ctx->jrnl, (void *) ctx->area_0_head, ctx->info.sizeofJournaledBlob); + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to initialize flash journaling layer (ret=%d)\n", __func__, (int) ret); /* move to ready state. cfstore client is expected to Uninitialize() before further calls */ cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_ready, ctx); goto out; - } else if(ret > 0){ + } else if (ret > 0) { /* read has completed synchronously*/ CFSTORE_TP(CFSTORE_TP_FSM, "%s:debug:ret > 0: (ret=%d)\n", __func__, (int) ret); cfstore_flash_journal_callback(ret, FLASH_JOURNAL_OPCODE_READ_BLOB); @@ -1756,29 +1750,26 @@ static int32_t cfstore_fsm_read_on_entry(void* context) /* @brief fsm handler when in reading state */ -static int32_t cfstore_fsm_reading(void* context) +static int32_t cfstore_fsm_reading(void *context) { int32_t ret = ARM_DRIVER_ERROR; - cfstore_ctx_t* ctx = (cfstore_ctx_t*) context; + cfstore_ctx_t *ctx = (cfstore_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered\n", __func__); CFSTORE_ASSERT(ctx->fsm.state == cfstore_fsm_state_reading); CFSTORE_ASSERT(ctx->cmd_code == FLASH_JOURNAL_OPCODE_READ_BLOB); - if(ctx->status > 0) - { - if(ctx->status > (int32_t) CFSTORE_FLASH_AREA_SIZE_MIN) - { + if (ctx->status > 0) { + if (ctx->status > (int32_t) CFSTORE_FLASH_AREA_SIZE_MIN) { CFSTORE_TP(CFSTORE_TP_FSM, "%s:debug:ctx->status > (int32_t) CFSTORE_FLASH_AREA_SIZE_MIN:\n", __func__); /* check the correct amount of data was read, which is the status code */ - if(ctx->status == (int32_t) ctx->expected_blob_size) - { + if (ctx->status == (int32_t) ctx->expected_blob_size) { /* now have to allow for the fact that there may have been some padding * at the end of the last _log() to flash, so the read back area may have * padding at the end, and the tail_pointer needs to not point to the * end where the padding is located, but to the end of the last KV. */ ret = cfstore_flash_set_tail(); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: cfstore_flash_set_tail() failed (ret=%d)\n", __func__, (int) ret); /* move to ready state. cfstore client is expected to Uninitialize() before further calls */ cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_ready, ctx); @@ -1786,38 +1777,32 @@ static int32_t cfstore_fsm_reading(void* context) goto out; } ret = cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_ready, ctx); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: cfstore_fsm_state_set() failed (ret=%d)\n", __func__, (int) ret); goto out; } ret = ctx->status; - } - else - { + } else { CFSTORE_ERRLOG("%s:Error: read bytes (%d) does not equal requested read size (%d)\n", __func__, (int) ctx->status, (int) ctx->expected_blob_size); ret = cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_ready, ctx); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { /* move to ready state. cfstore client is expected to Uninitialize() before further calls */ CFSTORE_ERRLOG("%s:Error: cfstore_fsm_state_set() failed (ret=%d)\n", __func__, (int) ret); goto out; } ret = ctx->status; } - } - else - { + } else { CFSTORE_TP(CFSTORE_TP_FSM, "%s:debug:ctx->status <= (int32_t) CFSTORE_FLASH_AREA_SIZE_MIN:\n", __func__); ret = cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_ready, ctx); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { /* move to ready state. cfstore client is expected to Uninitialize() before further calls */ CFSTORE_ERRLOG("%s:Error: cfstore_fsm_state_set() failed (ret=%d)\n", __func__, (int) ret); goto out; } ret = ctx->status; } - } - else if(ctx->status < 0) - { + } else if (ctx->status < 0) { CFSTORE_TP(CFSTORE_TP_FSM, "%s:debug:ctx->status < 0:\n", __func__); ret = ctx->status; } @@ -1826,9 +1811,9 @@ static int32_t cfstore_fsm_reading(void* context) } -static int32_t cfstore_fsm_read_on_exit(void* context) +static int32_t cfstore_fsm_read_on_exit(void *context) { - cfstore_ctx_t* ctx = (cfstore_ctx_t*) context; + cfstore_ctx_t *ctx = (cfstore_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered:\n", __func__); /* notify client of initialisation status */ @@ -1840,10 +1825,10 @@ static int32_t cfstore_fsm_read_on_exit(void* context) /* int32_t cfstore_fsm_log_on_entry(void* context){ (void) context;} */ /* @brief on entry to writing state, update value */ -int32_t cfstore_fsm_log_on_entry(void* context) +int32_t cfstore_fsm_log_on_entry(void *context) { int32_t ret = 0; - cfstore_ctx_t* ctx = (cfstore_ctx_t*) context; + cfstore_ctx_t *ctx = (cfstore_ctx_t *) context; FlashJournal_Info_t info; FlashJournal_Status_t status = JOURNAL_STATUS_ERROR; @@ -1851,7 +1836,7 @@ int32_t cfstore_fsm_log_on_entry(void* context) memset(&info, 0, sizeof(info)); status = FlashJournal_getInfo(&ctx->jrnl, &info); - if(status < JOURNAL_STATUS_OK){ + if (status < JOURNAL_STATUS_OK) { CFSTORE_ERRLOG("%s:Error: failed get journal info (status=%d)\n", __func__, (int) status); /* move to ready state. cfstore client is expected to Uninitialize() before further calls */ cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_ready, ctx); @@ -1859,22 +1844,21 @@ int32_t cfstore_fsm_log_on_entry(void* context) } /* compute the expected_blob_size = area_size plus the padding at the end of the area to align with program_unit*/ ctx->expected_blob_size = cfstore_ctx_get_kv_total_len(); - if(ctx->expected_blob_size % info.program_unit > 0){ + if (ctx->expected_blob_size % info.program_unit > 0) { ctx->expected_blob_size += (info.program_unit - (ctx->expected_blob_size % info.program_unit)); } /* log the changes to flash even when the area has shrunk to 0, as its necessary to erase the flash */ - if(ctx->area_dirty_flag == true) - { - if(ctx->expected_blob_size > 0){ + if (ctx->area_dirty_flag == true) { + if (ctx->expected_blob_size > 0) { CFSTORE_TP(CFSTORE_TP_FLUSH, "%s:logging: ctx->area_0_head=%p, ctx->expected_blob_size-%d\n", __func__, ctx->area_0_head, (int) ctx->expected_blob_size); - ret = FlashJournal_log(&ctx->jrnl, (const void*) ctx->area_0_head, ctx->expected_blob_size); - if(ret < JOURNAL_STATUS_OK){ + ret = FlashJournal_log(&ctx->jrnl, (const void *) ctx->area_0_head, ctx->expected_blob_size); + if (ret < JOURNAL_STATUS_OK) { CFSTORE_ERRLOG("%s:Error: FlashJournal_commit() failed (ret=%d)\n", __func__, (int) ret); ret = cfstore_flash_map_error(status); /* move to ready state. cfstore client is expected to Uninitialize() before further calls */ cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_ready, ctx); goto out0; - } else if(ret > 0){ + } else if (ret > 0) { /* read has completed synchronously*/ cfstore_flash_journal_callback(ret, FLASH_JOURNAL_OPCODE_LOG_BLOB); ret = ctx->status; @@ -1890,9 +1874,7 @@ int32_t cfstore_fsm_log_on_entry(void* context) ret = JOURNAL_STATUS_OK; cfstore_flash_journal_callback(ret, FLASH_JOURNAL_OPCODE_LOG_BLOB); } - } - else - { + } else { /* nothing to be logged so move back to ready state indicating success*/ CFSTORE_TP(CFSTORE_TP_FLUSH, "%s:not logging: ctx->area_0_head=%p, ctx->expected_blob_size-=%d\n", __func__, ctx->area_0_head, (int) ctx->expected_blob_size); cfstore_flash_journal_callback(ctx->expected_blob_size, FLASH_JOURNAL_OPCODE_LOG_BLOB); @@ -1902,21 +1884,20 @@ int32_t cfstore_fsm_log_on_entry(void* context) } /* @brief fsm handler when in reading state */ -static int32_t cfstore_fsm_logging(void* context) +static int32_t cfstore_fsm_logging(void *context) { - cfstore_ctx_t* ctx = (cfstore_ctx_t*) context; + cfstore_ctx_t *ctx = (cfstore_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered:ctx->status=%ld\n", __func__, ctx->status); /* check the correct amount of data was written */ - if(ctx->status < JOURNAL_STATUS_OK){ + if (ctx->status < JOURNAL_STATUS_OK) { CFSTORE_ERRLOG("%s:Error: FlashJournal_log() failed (ret=%d)\n", __func__, (int) ctx->status); /* move to ready state. cfstore client is expected to Uninitialize() before further calls */ cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_ready, ctx); ctx->status = cfstore_flash_map_error(ctx->status); - } - else - { /* ctx->status >= 0 (status == 0 when everything is deleted) */ - if(ctx->status == (int32_t)ctx->expected_blob_size){ + } else { + /* ctx->status >= 0 (status == 0 when everything is deleted) */ + if (ctx->status == (int32_t)ctx->expected_blob_size) { /* move to the committing state to commit to flash*/ ctx->status = cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_committing, ctx); } else { @@ -1928,9 +1909,9 @@ static int32_t cfstore_fsm_logging(void* context) } -static int32_t cfstore_fsm_log_on_exit(void* context) +static int32_t cfstore_fsm_log_on_exit(void *context) { - (void) context; + (void) context; CFSTORE_FENTRYLOG("%s:entered:\n", __func__); return ARM_DRIVER_OK; } @@ -1942,37 +1923,34 @@ static int32_t cfstore_fsm_log_on_exit(void* context) * _log() operations affecting the commit have been performed, and no more _log() operations * can happen until we're back in the ready state */ -static int32_t cfstore_fsm_commit_on_entry(void* context) +static int32_t cfstore_fsm_commit_on_entry(void *context) { int32_t ret = JOURNAL_STATUS_OK; - cfstore_ctx_t* ctx = (cfstore_ctx_t*) context; + cfstore_ctx_t *ctx = (cfstore_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered:\n", __func__); - if(ctx->area_dirty_flag == true) - { - ret = FlashJournal_commit(&ctx->jrnl); - CFSTORE_TP(CFSTORE_TP_FSM, "%s:debug: FlashJournal_commit() (ret=%d)\n", __func__, (int) ret); - if(ret < JOURNAL_STATUS_OK){ - CFSTORE_ERRLOG("%s:Error: FlashJournal_commit() failed (ret=%d)\n", __func__, (int) ret); - /* move to ready state. cfstore client is expected to Uninitialize() before further calls */ - cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_ready, ctx); - } else if(ret > 0){ - /* read has completed synchronously*/ - cfstore_flash_journal_callback(ret, FLASH_JOURNAL_OPCODE_COMMIT); - ret = ctx->status; - } - } - else - { - /* a commit should not be made because there have been no flashJournal_log() calls since the last commit. - * If a _commit() call was made without any _log() calls then it would result in the flash being erased - * because flash journal essentially contains a mirror image of the configuration store sram area, which - * has to be *** FULLY*** repopulated before each _commit(). */ - cfstore_flash_journal_callback(ARM_DRIVER_OK_DONE, FLASH_JOURNAL_OPCODE_COMMIT); - ret = ctx->status; - } - /* wait for async callback */ - CFSTORE_FENTRYLOG("%s:exiting: FlashJournal_commit() (ret=%d)\n", __func__, (int) ret); + if (ctx->area_dirty_flag == true) { + ret = FlashJournal_commit(&ctx->jrnl); + CFSTORE_TP(CFSTORE_TP_FSM, "%s:debug: FlashJournal_commit() (ret=%d)\n", __func__, (int) ret); + if (ret < JOURNAL_STATUS_OK) { + CFSTORE_ERRLOG("%s:Error: FlashJournal_commit() failed (ret=%d)\n", __func__, (int) ret); + /* move to ready state. cfstore client is expected to Uninitialize() before further calls */ + cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_ready, ctx); + } else if (ret > 0) { + /* read has completed synchronously*/ + cfstore_flash_journal_callback(ret, FLASH_JOURNAL_OPCODE_COMMIT); + ret = ctx->status; + } + } else { + /* a commit should not be made because there have been no flashJournal_log() calls since the last commit. + * If a _commit() call was made without any _log() calls then it would result in the flash being erased + * because flash journal essentially contains a mirror image of the configuration store sram area, which + * has to be *** FULLY*** repopulated before each _commit(). */ + cfstore_flash_journal_callback(ARM_DRIVER_OK_DONE, FLASH_JOURNAL_OPCODE_COMMIT); + ret = ctx->status; + } + /* wait for async callback */ + CFSTORE_FENTRYLOG("%s:exiting: FlashJournal_commit() (ret=%d)\n", __func__, (int) ret); return ret; } @@ -1983,35 +1961,32 @@ static int32_t cfstore_fsm_commit_on_entry(void* context) * _log() operations affecting the commit have been performed, and no more _log() operations * can happen until we're back in the ready state */ -static int32_t cfstore_fsm_committing(void* context) +static int32_t cfstore_fsm_committing(void *context) { - cfstore_ctx_t* ctx = (cfstore_ctx_t*) context; + cfstore_ctx_t *ctx = (cfstore_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered\n", __func__); CFSTORE_ASSERT(ctx->fsm.state == cfstore_fsm_state_committing); CFSTORE_ASSERT(ctx->cmd_code == FLASH_JOURNAL_OPCODE_COMMIT); /* check the correct amount of data was written */ - if(ctx->status < JOURNAL_STATUS_OK){ + if (ctx->status < JOURNAL_STATUS_OK) { CFSTORE_ERRLOG("%s:Error: FlashJournal_commit() failed (ret=%d)\n", __func__, (int) ctx->status); /* move to ready state. cfstore client is expected to Uninitialize() before further calls */ cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_ready, ctx); ctx->status = cfstore_flash_map_error(ctx->status); - } - else if(ctx->status == JOURNAL_STATUS_OK) - { + } else if (ctx->status == JOURNAL_STATUS_OK) { ctx->status = cfstore_flash_map_error(ctx->status); - } - else - { /* ctx->status > 0. for flash-journal-strategy-sequential version >0.4.0, commit() return no longer reports size of commit block */ + } else { + /* ctx->status > 0. for flash-journal-strategy-sequential version >0.4.0, commit() return no longer reports size of commit block */ ctx->status = cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_ready, ctx); } return ctx->status; } -static int32_t cfstore_fsm_commit_on_exit(void* context) +static int32_t cfstore_fsm_commit_on_exit(void *context) { - cfstore_ctx_t* ctx = (cfstore_ctx_t*) context; + cfstore_ctx_t *ctx = (cfstore_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered:\n", __func__); ctx->area_dirty_flag = false; @@ -2026,9 +2001,9 @@ static int32_t cfstore_fsm_commit_on_exit(void* context) /* int32_t cfstore_fsm_reset_on_exit(void* context){ (void) context;} */ -static int32_t cfstore_fsm_ready_on_commit_req(void* context) +static int32_t cfstore_fsm_ready_on_commit_req(void *context) { - cfstore_ctx_t* ctx = (cfstore_ctx_t*) context; + cfstore_ctx_t *ctx = (cfstore_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered\n", __func__); return cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_logging, ctx); } @@ -2040,20 +2015,19 @@ static int32_t cfstore_fsm_ready_on_commit_req(void* context) /** @brief fsm handler when entering the formatting state */ -static int32_t cfstore_fsm_format_on_entry(void* context) +static int32_t cfstore_fsm_format_on_entry(void *context) { int32_t ret = ARM_DRIVER_ERROR; - cfstore_ctx_t* ctx = (cfstore_ctx_t*) context; + cfstore_ctx_t *ctx = (cfstore_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered\n", __func__); ret = flashJournalStrategySequential_format((ARM_DRIVER_STORAGE *) &cfstore_journal_mtd, CFSTORE_FLASH_NUMSLOTS, cfstore_flash_journal_callback); CFSTORE_TP(CFSTORE_TP_FSM, "%s:flashJournalStrategySequential_format ret=%d\n", __func__, (int) ret); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to format flash (ret=%d)\n", __func__, (int) ret); cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_stopped, ctx); - } - else if(ret > 0){ + } else if (ret > 0) { /* operation completed synchronously*/ cfstore_flash_journal_callback(ret, FLASH_JOURNAL_OPCODE_FORMAT); } @@ -2062,19 +2036,19 @@ static int32_t cfstore_fsm_format_on_entry(void* context) /** @brief fsm handler when in formatting state */ -int32_t cfstore_fsm_formatting(void* context) +int32_t cfstore_fsm_formatting(void *context) { int32_t ret = ARM_DRIVER_OK; - cfstore_ctx_t* ctx = (cfstore_ctx_t*) context; + cfstore_ctx_t *ctx = (cfstore_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered\n", __func__); CFSTORE_ASSERT(ctx->fsm.state == cfstore_fsm_state_formatting); CFSTORE_ASSERT(ctx->cmd_code == FLASH_JOURNAL_OPCODE_FORMAT); /* only change state if status > 0*/ - if(ctx->status > 0){ + if (ctx->status > 0) { ret = cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_initing, ctx); - } else if(ctx->status < 0) { + } else if (ctx->status < 0) { CFSTORE_ERRLOG("%s:Error: failed to format flash (ret=%d)\n", __func__, (int) ctx->status); cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_stopped, ctx); } @@ -2085,22 +2059,20 @@ int32_t cfstore_fsm_formatting(void* context) /* handler functions while in state */ -static cfstore_fsm_handler cfstore_flash_fsm[cfstore_fsm_state_max][cfstore_fsm_event_max] = -{ -/* state\event: init_done read_done log_done commit_req commit_done reset_done format_done, */ -/* stopped */ {cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null }, -/* init */ {cfstore_fsm_initing, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null }, -/* reading */ {cfstore_fsm_null, cfstore_fsm_reading, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null }, -/* logging */ {cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_logging, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null }, -/* committing */ {cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_committing, cfstore_fsm_null, cfstore_fsm_null }, -/* resetting */ {cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null }, -/* ready */ {cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_ready_on_commit_req, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null }, -/* formatting */ {cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_formatting }, +static cfstore_fsm_handler cfstore_flash_fsm[cfstore_fsm_state_max][cfstore_fsm_event_max] = { + /* state\event: init_done read_done log_done commit_req commit_done reset_done format_done, */ + /* stopped */ {cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null }, + /* init */ {cfstore_fsm_initing, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null }, + /* reading */ {cfstore_fsm_null, cfstore_fsm_reading, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null }, + /* logging */ {cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_logging, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null }, + /* committing */ {cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_committing, cfstore_fsm_null, cfstore_fsm_null }, + /* resetting */ {cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null }, + /* ready */ {cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_ready_on_commit_req, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null }, + /* formatting */ {cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_null, cfstore_fsm_formatting }, }; /* handler functions for entering the state*/ -cfstore_fsm_handler cfstore_fsm_on_entry[cfstore_fsm_state_max] = -{ +cfstore_fsm_handler cfstore_fsm_on_entry[cfstore_fsm_state_max] = { cfstore_fsm_stop_on_entry, cfstore_fsm_init_on_entry, cfstore_fsm_read_on_entry, @@ -2112,8 +2084,7 @@ cfstore_fsm_handler cfstore_fsm_on_entry[cfstore_fsm_state_max] = }; /* handler functions for exiting state, currently none used */ -cfstore_fsm_handler cfstore_fsm_on_exit[cfstore_fsm_state_max] = -{ +cfstore_fsm_handler cfstore_fsm_on_exit[cfstore_fsm_state_max] = { cfstore_fsm_null, /* cfstore_fsm_stop_on_exit */ cfstore_fsm_null, /* cfstore_fsm_init_on_exit */ cfstore_fsm_read_on_exit, @@ -2126,20 +2097,20 @@ cfstore_fsm_handler cfstore_fsm_on_exit[cfstore_fsm_state_max] = /* @brief inject event into fsm */ -static int32_t cfstore_fsm_state_handle_event(cfstore_fsm_t* fsm, cfstore_fsm_event_t event, void* context) +static int32_t cfstore_fsm_state_handle_event(cfstore_fsm_t *fsm, cfstore_fsm_event_t event, void *context) { int32_t ret = ARM_DRIVER_ERROR; - cfstore_ctx_t* ctx = (cfstore_ctx_t*) context; + cfstore_ctx_t *ctx = (cfstore_ctx_t *) context; CFSTORE_FENTRYLOG("%s:entered: fsm=%p, fsm->state=%d, event=%d (%s), ctx=%p\n", __func__, fsm, fsm->state, event, cfstore_flash_event_str[event], ctx); CFSTORE_ASSERT(event < cfstore_fsm_event_max); fsm->event = event; - if(cfstore_flash_fsm[fsm->state][fsm->event] != NULL){ + if (cfstore_flash_fsm[fsm->state][fsm->event] != NULL) { ret = cfstore_flash_fsm[fsm->state][fsm->event](ctx); - if(ret < ARM_DRIVER_OK){ - #ifdef CFSTORE_DEBUG - CFSTORE_ERRLOG("%s:FSM:EVT:Error: cfstore_flash_fsm[%s][%s] failed\n", __func__, (char*) cfstore_flash_state_str[fsm->state], (char*) cfstore_flash_event_str[fsm->event]); - #endif + if (ret < ARM_DRIVER_OK) { +#ifdef CFSTORE_DEBUG + CFSTORE_ERRLOG("%s:FSM:EVT:Error: cfstore_flash_fsm[%s][%s] failed\n", __func__, (char *) cfstore_flash_state_str[fsm->state], (char *) cfstore_flash_event_str[fsm->event]); +#endif return ret; } } @@ -2154,52 +2125,51 @@ static int32_t cfstore_fsm_state_handle_event(cfstore_fsm_t* fsm, cfstore_fsm_ev /* @brief get the current state of the fsm */ -static cfstore_fsm_state_t cfstore_fsm_state_get(cfstore_fsm_t* fsm) +static cfstore_fsm_state_t cfstore_fsm_state_get(cfstore_fsm_t *fsm) { return fsm->state; } /* @brief function to move to new fsm state, calling state exit function for old state and entry function for new state */ -static int32_t cfstore_fsm_state_set(cfstore_fsm_t* fsm, cfstore_fsm_state_t new_state, void* ctx) +static int32_t cfstore_fsm_state_set(cfstore_fsm_t *fsm, cfstore_fsm_state_t new_state, void *ctx) { int32_t ret = ARM_DRIVER_ERROR; - cfstore_ctx_t* context = (cfstore_ctx_t*) ctx; - #ifdef CFSTORE_DEBUG + cfstore_ctx_t *context = (cfstore_ctx_t *) ctx; +#ifdef CFSTORE_DEBUG cfstore_fsm_state_t old_state = fsm->state; - #endif +#endif CFSTORE_FENTRYLOG("%s:entered: fsm=%p, ctx=%p\n", __func__, fsm, ctx); - #ifdef CFSTORE_DEBUG +#ifdef CFSTORE_DEBUG CFSTORE_TP(CFSTORE_TP_FSM, "%s:FSM:REQ RX: fsm->state=%d (%s): new_state=%d (%s)\n", __func__, (int) fsm->state, cfstore_flash_state_str[fsm->state], (int) new_state, cfstore_flash_state_str[new_state]); - #endif +#endif CFSTORE_ASSERT(fsm != NULL); CFSTORE_ASSERT(new_state < cfstore_fsm_state_max); CFSTORE_ASSERT(ctx != NULL); CFSTORE_ASSERT(fsm->state < cfstore_fsm_state_max); - if(cfstore_fsm_on_exit[fsm->state] != NULL){ + if (cfstore_fsm_on_exit[fsm->state] != NULL) { ret = cfstore_fsm_on_exit[fsm->state](ctx); - if(ret < ARM_DRIVER_OK){ - #ifdef CFSTORE_DEBUG + if (ret < ARM_DRIVER_OK) { +#ifdef CFSTORE_DEBUG CFSTORE_ERRLOG("%s:FSM:REQ RX:%s:%s:Error: cfstore_fsm_on_exit() failed\n", __func__, cfstore_flash_state_str[fsm->state], cfstore_flash_state_str[new_state]); - #endif +#endif /* handling of the error is done in the on_exit() method, which best knows how the state to move to */ return ret; } } fsm->state = new_state; - if(cfstore_fsm_on_entry[new_state] != NULL){ + if (cfstore_fsm_on_entry[new_state] != NULL) { ret = cfstore_fsm_on_entry[new_state](ctx); - if(ret < ARM_DRIVER_OK){ - #ifdef CFSTORE_DEBUG + if (ret < ARM_DRIVER_OK) { +#ifdef CFSTORE_DEBUG CFSTORE_TP(CFSTORE_TP_FSM, "%s:FSM:REQ RX: fsm->state=%d (%s): new_state=%d (%s): Error: cfstore_fsm_on_entry() failed (ret=%d)\n", __func__, (int) fsm->state, cfstore_flash_state_str[fsm->state], (int) new_state, cfstore_flash_state_str[new_state], (int) ret); - #endif +#endif /* handling of the error is done in the on_entry() method, which best knows how the state to move to */ return ret; } } - if(context->client_callback_notify_flag == true) - { + if (context->client_callback_notify_flag == true) { cfstore_client_notify_data_t notify_data; CFSTORE_TP(CFSTORE_TP_FSM, "%s:doing client callback\n", __func__); @@ -2216,11 +2186,10 @@ static int32_t cfstore_fsm_state_set(cfstore_fsm_t* fsm, cfstore_fsm_state_t new return ret; } -static bool cfstore_flash_journal_is_async_op_pending(cfstore_ctx_t* ctx) +static bool cfstore_flash_journal_is_async_op_pending(cfstore_ctx_t *ctx) { - CFSTORE_FENTRYLOG("%s:entered: fsm->state=%s\n", __func__, (char*) cfstore_flash_state_str[cfstore_fsm_state_get(&ctx->fsm)]); - if(cfstore_fsm_state_get(&ctx->fsm) != cfstore_fsm_state_ready) - { + CFSTORE_FENTRYLOG("%s:entered: fsm->state=%s\n", __func__, (char *) cfstore_flash_state_str[cfstore_fsm_state_get(&ctx->fsm)]); + if (cfstore_fsm_state_get(&ctx->fsm) != cfstore_fsm_state_ready) { /* flash journal async operation is in progress */ return true; } @@ -2230,16 +2199,16 @@ static bool cfstore_flash_journal_is_async_op_pending(cfstore_ctx_t* ctx) static int32_t cfstore_flash_init(void) { int32_t ret = ARM_DRIVER_ERROR; - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); CFSTORE_FENTRYLOG("%s:entered: \n", __func__); - ctx->cmd_code = (FlashJournal_OpCode_t)((int) FLASH_JOURNAL_OPCODE_RESET+1); + ctx->cmd_code = (FlashJournal_OpCode_t)((int) FLASH_JOURNAL_OPCODE_RESET + 1); ctx->expected_blob_size = 0; ctx->fsm.event = cfstore_fsm_event_max; ctx->fsm.state = cfstore_fsm_state_stopped; memset(&ctx->info, 0, sizeof(ctx->info)); ret = cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_initing, ctx); - if(ret < 0){ + if (ret < 0) { CFSTORE_DBGLOG("%s:Error: cfstore_fsm_state_set() failed\n", __func__); return ret; } @@ -2251,11 +2220,11 @@ static int32_t cfstore_flash_init(void) static int32_t cfstore_flash_deinit(void) { int32_t ret = ARM_DRIVER_ERROR; - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); - CFSTORE_FENTRYLOG("%s:entered: fsm->state=%s\n", __func__, (char*) cfstore_flash_state_str[cfstore_fsm_state_get(&ctx->fsm)]); + CFSTORE_FENTRYLOG("%s:entered: fsm->state=%s\n", __func__, (char *) cfstore_flash_state_str[cfstore_fsm_state_get(&ctx->fsm)]); ret = cfstore_fsm_state_set(&ctx->fsm, cfstore_fsm_state_stopped, ctx); - if(ret < 0){ + if (ret < 0) { CFSTORE_TP(CFSTORE_TP_INIT, "%s:Error: cfstore_fsm_state_set() failed\n", __func__); } return ret; @@ -2277,33 +2246,38 @@ static int32_t cfstore_flash_reset(void) } */ -static int32_t cfstore_flash_flush(cfstore_ctx_t* ctx) +static int32_t cfstore_flash_flush(cfstore_ctx_t *ctx) { int32_t ret = ARM_DRIVER_OK; CFSTORE_FENTRYLOG("%s:entered\n", __func__); /* put the async completion code state variables into a known state */ ctx->status = ARM_DRIVER_OK; - ctx->cmd_code = (FlashJournal_OpCode_t)((int) FLASH_JOURNAL_OPCODE_RESET+1); + ctx->cmd_code = (FlashJournal_OpCode_t)((int) FLASH_JOURNAL_OPCODE_RESET + 1); /* cfstore_fsm_state_handle_event() is called at intr context via * cfstore_flash_journal_callback(), and hence calls from app context are * protected with CSs */ cfstore_critical_section_lock(&ctx->rw_area0_lock, __func__); - ret = cfstore_fsm_state_handle_event(&ctx->fsm, cfstore_fsm_event_commit_req, (void*) ctx); + ret = cfstore_fsm_state_handle_event(&ctx->fsm, cfstore_fsm_event_commit_req, (void *) ctx); cfstore_critical_section_unlock(&ctx->rw_area0_lock, __func__); return ret; } #else /* CFSTORE_CONFIG_BACKEND_FLASH_ENABLED */ -static bool cfstore_flash_journal_is_async_op_pending(cfstore_ctx_t* ctx) { CFSTORE_FENTRYLOG("%s:SRAM:entered:\n", __func__); (void) ctx; return false; } +static bool cfstore_flash_journal_is_async_op_pending(cfstore_ctx_t *ctx) +{ + CFSTORE_FENTRYLOG("%s:SRAM:entered:\n", __func__); + (void) ctx; + return false; +} /* @brief generate the CFSTORE_OPCODE_INITIALIZE callback notification */ static int32_t cfstore_flash_init(void) { cfstore_client_notify_data_t notify_data; - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); CFSTORE_FENTRYLOG("%s:SRAM:entered:\n", __func__); cfstore_client_notify_data_init(¬ify_data, CFSTORE_OPCODE_INITIALIZE, ARM_DRIVER_OK, NULL); @@ -2311,9 +2285,13 @@ static int32_t cfstore_flash_init(void) return ARM_DRIVER_OK; } -static int32_t cfstore_flash_deinit(void){ CFSTORE_FENTRYLOG("%s:SRAM:entered:\n", __func__); return ARM_DRIVER_OK; } +static int32_t cfstore_flash_deinit(void) +{ + CFSTORE_FENTRYLOG("%s:SRAM:entered:\n", __func__); + return ARM_DRIVER_OK; +} /* static int32_t cfstore_flash_reset(void) { CFSTORE_FENTRYLOG("%s:SRAM:entered:\n", __func__); return ARM_DRIVER_OK; }*/ -static int32_t cfstore_flash_flush(cfstore_ctx_t* ctx) +static int32_t cfstore_flash_flush(cfstore_ctx_t *ctx) { cfstore_client_notify_data_t notify_data; @@ -2339,24 +2317,24 @@ static int32_t cfstore_flash_flush(cfstore_ctx_t* ctx) * - size_diff < 0 => decrease in area, |size_diff| bytes have been removed at head, * and the previously following KVs shifted down to lower memory addresses * */ -static int32_t cfstore_file_update(uint8_t* head, int32_t size_diff) +static int32_t cfstore_file_update(uint8_t *head, int32_t size_diff) { - cfstore_ctx_t* ctx = cfstore_ctx_get(); - cfstore_file_t* file; - cfstore_list_node_t* node; - cfstore_list_node_t* file_list = &ctx->file_list; + cfstore_ctx_t *ctx = cfstore_ctx_get(); + cfstore_file_t *file; + cfstore_list_node_t *node; + cfstore_list_node_t *file_list = &ctx->file_list; CFSTORE_FENTRYLOG("%s:entered:(ctx->area_0_head=%p, ctx->area_0_tail=%p)\n", __func__, ctx->area_0_head, ctx->area_0_tail); /* walk the file list updating head pointers for the KVs that remain*/ node = file_list->next; - while(node != file_list){ + while (node != file_list) { /* Any KV positioned later in the area than the deleted KV will require file head pointers updating. * If file's head pointer is beyond the deleted KV tail then the file->head needs to be updated * to reflect the memove */ - file = (cfstore_file_t*) node; - if(file->head >= head){ + file = (cfstore_file_t *) node; + if (file->head >= head) { /* sign of sign_diff used to move file->head up/down in memory*/ file->head += size_diff; } @@ -2366,13 +2344,13 @@ static int32_t cfstore_file_update(uint8_t* head, int32_t size_diff) } -static int32_t cfstore_delete_ex(cfstore_area_hkvt_t* hkvt) +static int32_t cfstore_delete_ex(cfstore_area_hkvt_t *hkvt) { int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE kv_size = 0; ARM_CFSTORE_SIZE kv_total_size = 0; ARM_CFSTORE_SIZE realloc_size = 0; /* size aligned to flash program_unit size */ - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); CFSTORE_FENTRYLOG("%s:entered:(ctx->area_0_head=%p, ctx->area_0_tail=%p)\n", __func__, ctx->area_0_head, ctx->area_0_tail); kv_size = cfstore_hkvt_get_size(hkvt); @@ -2389,11 +2367,11 @@ static int32_t cfstore_delete_ex(cfstore_area_hkvt_t* hkvt) */ memmove(hkvt->head, hkvt->tail, ctx->area_0_tail - hkvt->tail); /* zero the deleted KV memory */ - memset(ctx->area_0_tail-kv_size, 0, kv_size); + memset(ctx->area_0_tail - kv_size, 0, kv_size); /* The KV area has shrunk so a negative size_diff should be indicated to cfstore_file_update(). */ - ret = cfstore_file_update(hkvt->head, -1 *(int32_t)kv_size); - if(ret < ARM_DRIVER_OK){ + ret = cfstore_file_update(hkvt->head, -1 * (int32_t)kv_size); + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error:file update failed\n", __func__); goto out0; } @@ -2401,7 +2379,7 @@ static int32_t cfstore_delete_ex(cfstore_area_hkvt_t* hkvt) /* setup the reallocation memory size. */ realloc_size = kv_total_size - kv_size; ret = cfstore_realloc_ex(realloc_size, NULL); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error:realloc failed\n", __func__); goto out0; } @@ -2414,29 +2392,29 @@ static int32_t cfstore_delete_ex(cfstore_area_hkvt_t* hkvt) * File operations */ -static cfstore_file_t* cfstore_file_get(ARM_CFSTORE_HANDLE hkey) +static cfstore_file_t *cfstore_file_get(ARM_CFSTORE_HANDLE hkey) { - return (cfstore_file_t*) hkey; + return (cfstore_file_t *) hkey; } -static cfstore_file_t* cfstore_file_create(cfstore_area_hkvt_t* hkvt, ARM_CFSTORE_FMODE flags, ARM_CFSTORE_HANDLE hkey, cfstore_list_node_t *list_head) +static cfstore_file_t *cfstore_file_create(cfstore_area_hkvt_t *hkvt, ARM_CFSTORE_FMODE flags, ARM_CFSTORE_HANDLE hkey, cfstore_list_node_t *list_head) { int32_t ret = ARM_DRIVER_ERROR; - cfstore_file_t* file = (cfstore_file_t*) hkey; + cfstore_file_t *file = (cfstore_file_t *) hkey; CFSTORE_FENTRYLOG("%s:entered\n", __func__); - if(file != NULL){ + if (file != NULL) { memset(file, 0, sizeof(cfstore_file_t)); CFSTORE_INIT_LIST_HEAD(&file->node); ret = cfstore_hkvt_refcount_inc(hkvt, NULL); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: cfstore_hkvt_refcount_inc() failed (ret=%d)\n", __func__, (int) ret); return NULL; } file->head = hkvt->head; file->flags.read = flags.read; file->flags.write = flags.write; - if(list_head != NULL){ + if (list_head != NULL) { cfstore_listAdd(list_head, &file->node, list_head); } } @@ -2444,23 +2422,23 @@ static cfstore_file_t* cfstore_file_create(cfstore_area_hkvt_t* hkvt, ARM_CFSTOR } /* @brief required to be in critical section when called. */ -static int32_t cfstore_file_destroy(cfstore_file_t* file) +static int32_t cfstore_file_destroy(cfstore_file_t *file) { int32_t ret = ARM_DRIVER_ERROR; cfstore_area_hkvt_t hkvt; uint8_t refcount = 0; CFSTORE_FENTRYLOG("%s:entered\n", __func__); - if(file) { + if (file) { hkvt = cfstore_get_hkvt_from_head_ptr(file->head); CFSTORE_ASSERT(cfstore_hkvt_is_valid(&hkvt, cfstore_ctx_get()->area_0_tail) == true); ret = ARM_DRIVER_OK; cfstore_hkvt_refcount_dec(&hkvt, &refcount); CFSTORE_TP(CFSTORE_TP_FILE, "%s:refcount =%d file->head=%p\n", __func__, (int)refcount, file->head); - if(refcount == 0){ + if (refcount == 0) { /* check for delete */ CFSTORE_TP(CFSTORE_TP_FILE, "%s:checking delete flag\n", __func__); - if(cfstore_hkvt_get_flags_delete(&hkvt)){ + if (cfstore_hkvt_get_flags_delete(&hkvt)) { ret = cfstore_delete_ex(&hkvt); } } @@ -2482,12 +2460,12 @@ static int32_t cfstore_file_destroy(cfstore_file_t* file) * ctx * IN: cfstore context block */ -static bool cfstore_file_is_valid(ARM_CFSTORE_HANDLE hkey, cfstore_ctx_t* ctx) +static bool cfstore_file_is_valid(ARM_CFSTORE_HANDLE hkey, cfstore_ctx_t *ctx) { - cfstore_file_t* file = cfstore_file_get(hkey); + cfstore_file_t *file = cfstore_file_get(hkey); - if(ctx->area_0_head != NULL && ctx->area_0_tail != NULL){ - if(file->head < ctx->area_0_head || file->head > ctx->area_0_tail){ + if (ctx->area_0_head != NULL && ctx->area_0_tail != NULL) { + if (file->head < ctx->area_0_head || file->head > ctx->area_0_tail) { return 0; } return true; @@ -2508,7 +2486,7 @@ static bool cfstore_file_is_valid(ARM_CFSTORE_HANDLE hkey, cfstore_ctx_t* ctx) static bool cfstore_file_is_empty(ARM_CFSTORE_HANDLE hkey) { ARM_CFSTORE_HANDLE_INIT(zero); - if(hkey != NULL){ + if (hkey != NULL) { return !memcmp(hkey, zero, CFSTORE_HANDLE_BUFSIZE); } return 0; @@ -2527,19 +2505,19 @@ ARM_CFSTORE_CAPABILITIES cfstore_get_capabilities(void) /* @brief check the flags argument are supported */ static int32_t cfstore_validate_fmode_flags(ARM_CFSTORE_FMODE flags) { - if(flags.continuous){ + if (flags.continuous) { CFSTORE_ERRLOG("%s:Error:Continuous flag not supported.\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_NOT_SUPPORTED; } - if(flags.lazy_flush){ + if (flags.lazy_flush) { CFSTORE_ERRLOG("%s:Error:Lazy flush flag not supported.\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_NOT_SUPPORTED; } - if(flags.flush_on_close){ + if (flags.flush_on_close) { CFSTORE_ERRLOG("%s:Error:Flush on close flag not supported.\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_NOT_SUPPORTED; } - if(flags.storage_detect){ + if (flags.storage_detect) { CFSTORE_ERRLOG("%s:Error:Storage detect flag not supported.\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_NOT_SUPPORTED; } @@ -2550,7 +2528,7 @@ static int32_t cfstore_validate_fmode_flags(ARM_CFSTORE_FMODE flags) /* @brief validate the client supplied opaque handle */ static CFSTORE_INLINE int32_t cfstore_validate_handle(ARM_CFSTORE_HANDLE hkey) { - if(hkey == NULL){ + if (hkey == NULL) { return ARM_CFSTORE_DRIVER_ERROR_INVALID_HANDLE; } return ARM_DRIVER_OK; @@ -2561,35 +2539,35 @@ static int32_t cfstore_validate_flash_security_features(const ARM_STORAGE_SECURI { CFSTORE_ASSERT(security != NULL); - if(security->acls){ + if (security->acls) { CFSTORE_ERRLOG("%s:Error: flash security features acls flag not supported.\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_NOT_SUPPORTED; } - if(security->internal_flash){ + if (security->internal_flash) { CFSTORE_ERRLOG("%s:Error: flash security features internal_flash flag not supported.\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_NOT_SUPPORTED; } - if(security->rollback_protection){ + if (security->rollback_protection) { CFSTORE_ERRLOG("%s:Error: flash security features rollback_protection flag not supported.\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_NOT_SUPPORTED; } - if(security->tamper_proof){ + if (security->tamper_proof) { CFSTORE_ERRLOG("%s:Error: flash security features tamper_proof flag not supported.\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_NOT_SUPPORTED; } - if(security->board_level_attacks){ + if (security->board_level_attacks) { CFSTORE_ERRLOG("%s:Error: flash security features board level attacks flag not supported.\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_NOT_SUPPORTED; } - if(security->software_attacks){ + if (security->software_attacks) { CFSTORE_ERRLOG("%s:Error: flash security features device_software flag not supported.\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_NOT_SUPPORTED; } - if(security->chip_level_attacks){ + if (security->chip_level_attacks) { CFSTORE_ERRLOG("%s:Error: flash security features chip level attacks flag not supported.\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_NOT_SUPPORTED; } - if(security->side_channel_attacks){ + if (security->side_channel_attacks) { CFSTORE_ERRLOG("%s:Error: flash security features side channel attacks flag not supported.\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_NOT_SUPPORTED; } @@ -2601,19 +2579,18 @@ static int32_t cfstore_validate_flash_data_retention_level(const uint8_t drl) { int32_t ret = ARM_DRIVER_ERROR; - switch(drl) - { - case ARM_RETENTION_WHILE_DEVICE_ACTIVE : - case ARM_RETENTION_ACROSS_SLEEP : - case ARM_RETENTION_ACROSS_DEEP_SLEEP : - case ARM_RETENTION_BATTERY_BACKED : - case ARM_RETENTION_NVM : - ret = ARM_DRIVER_OK; - break; - default: - CFSTORE_ERRLOG("%s:Error: data retention level (%d) not supported.\n", __func__, drl); - ret = ARM_CFSTORE_DRIVER_ERROR_NOT_SUPPORTED; - break; + switch (drl) { + case ARM_RETENTION_WHILE_DEVICE_ACTIVE : + case ARM_RETENTION_ACROSS_SLEEP : + case ARM_RETENTION_ACROSS_DEEP_SLEEP : + case ARM_RETENTION_BATTERY_BACKED : + case ARM_RETENTION_NVM : + ret = ARM_DRIVER_OK; + break; + default: + CFSTORE_ERRLOG("%s:Error: data retention level (%d) not supported.\n", __func__, drl); + ret = ARM_CFSTORE_DRIVER_ERROR_NOT_SUPPORTED; + break; } return ret; @@ -2622,13 +2599,11 @@ static int32_t cfstore_validate_flash_data_retention_level(const uint8_t drl) /* @brief check the access control list is valid (internal use only) */ static int32_t cfstore_validate_access_control_list(const ARM_CFSTORE_ACCESS_CONTROL_LIST acl) { - if(acl.perm_owner_execute) - { + if (acl.perm_owner_execute) { CFSTORE_ERRLOG("%s:Error: Access control list with permission owner execute set is not supported.\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_NOT_SUPPORTED; } - if(acl.perm_other_execute) - { + if (acl.perm_other_execute) { CFSTORE_ERRLOG("%s:Error: Access control list with permission other execute set is not supported.\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_NOT_SUPPORTED; } @@ -2640,23 +2615,23 @@ static int32_t cfstore_validate_key_desc(const ARM_CFSTORE_KEYDESC *kdesc) { int32_t ret = ARM_DRIVER_ERROR; - if(kdesc == NULL){ + if (kdesc == NULL) { return ARM_CFSTORE_DRIVER_ERROR_INVALID_KEY_DESCRIPTOR; } ret = cfstore_validate_access_control_list(kdesc->acl); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { return ret; } ret = cfstore_validate_flash_data_retention_level(kdesc->drl); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { return ret; } ret = cfstore_validate_flash_security_features(&kdesc->security); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { return ret; } ret = cfstore_validate_fmode_flags(kdesc->flags); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { return ret; } return ARM_DRIVER_OK; @@ -2670,62 +2645,62 @@ static int32_t cfstore_validate_key_desc(const ARM_CFSTORE_KEYDESC *kdesc) */ static CFSTORE_INLINE int32_t cfstore_validate_len_ptr(ARM_CFSTORE_SIZE *len) { - if(len == NULL){ + if (len == NULL) { return ARM_CFSTORE_DRIVER_ERROR_INVALID_KEY_LEN; } return ARM_DRIVER_OK; } -/* @brief return a pointer to the next { or }, or NULL if not present */ -static inline char* cfstore_validate_pos_next_brace(const char* pos) +/* @brief return a pointer to the next { or }, or NULL if not present */ +static inline char *cfstore_validate_pos_next_brace(const char *pos) { - char* pos_open = strchr(pos, '{'); - char* pos_close = strchr(pos, '}'); - if(pos_open != NULL) { - if(pos_close != NULL){ - return pos_open < pos_close ? pos_open : pos_close; - } - return pos_open; - } - return pos_close; + char *pos_open = strchr(pos, '{'); + char *pos_close = strchr(pos, '}'); + if (pos_open != NULL) { + if (pos_close != NULL) { + return pos_open < pos_close ? pos_open : pos_close; + } + return pos_open; + } + return pos_close; } -static int32_t cfstore_validate_key_name_ex(const char* key_name, const char* permissible) +static int32_t cfstore_validate_key_name_ex(const char *key_name, const char *permissible) { - char* pos = NULL; + char *pos = NULL; int brace_count = 0; ARM_CFSTORE_SIZE len = 0; ARM_CFSTORE_SIZE valid_len = 0; CFSTORE_FENTRYLOG("%s:entered\n", __func__); - if(key_name != NULL){ + if (key_name != NULL) { /* check the key_name is terminated by a 0 */ - pos = (char*) memchr(key_name, '\0', CFSTORE_KEY_NAME_MAX_LENGTH+1); - if(pos == NULL){ + pos = (char *) memchr(key_name, '\0', CFSTORE_KEY_NAME_MAX_LENGTH + 1); + if (pos == NULL) { CFSTORE_ERRLOG("%s:key_name does not have terminating null.\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_INVALID_KEY_NAME; } /* check for zero length key_name*/ - if(strlen(key_name) == 0){ + if (strlen(key_name) == 0) { CFSTORE_ERRLOG("%s:Error: invalid key_name.\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_INVALID_KEY_NAME; } /* check the key_name len is less than the max length (220) */ len = strlen(key_name); - if(len > CFSTORE_KEY_NAME_MAX_LENGTH){ + if (len > CFSTORE_KEY_NAME_MAX_LENGTH) { CFSTORE_ERRLOG("%s:key_name string is longer (%d) than the supported maximum (%d).\n", __func__, (int) len, (int) CFSTORE_KEY_NAME_MAX_LENGTH); return ARM_CFSTORE_DRIVER_ERROR_INVALID_KEY_NAME; } /* check the key_name only contains permissible characters */ valid_len = strspn(key_name, permissible); - if(valid_len != len){ + if (valid_len != len) { CFSTORE_ERRLOG("%s:Invalid character (%c) found in key_name (key_name=%s).\n", __func__, key_name[valid_len], key_name); return ARM_CFSTORE_DRIVER_ERROR_INVALID_KEY_NAME; } /*check there isnt a leading '.' on the kv name */ - if(key_name[0] == '.'){ + if (key_name[0] == '.') { CFSTORE_ERRLOG("%s:Leading (.) character found in key_name (key_name=%s) is not allowed.\n", __func__, key_name); return ARM_CFSTORE_DRIVER_ERROR_INVALID_KEY_NAME; } @@ -2740,23 +2715,21 @@ static int32_t cfstore_validate_key_name_ex(const char* key_name, const char* pe * - brace_count must == 0 at end of string */ pos = cfstore_validate_pos_next_brace(key_name); - while(pos != NULL && brace_count >= 0 && brace_count <= 1) - { - switch(*pos) - { - case '{': - brace_count++; - break; - case '}': - brace_count--; - break; - default: - break; - } - pos++; - pos = cfstore_validate_pos_next_brace(pos); + while (pos != NULL && brace_count >= 0 && brace_count <= 1) { + switch (*pos) { + case '{': + brace_count++; + break; + case '}': + brace_count--; + break; + default: + break; + } + pos++; + pos = cfstore_validate_pos_next_brace(pos); } - if(brace_count != 0){ + if (brace_count != 0) { CFSTORE_ERRLOG("%s: Unmatched brace found in key_name (count=%d.\n", __func__, brace_count); return ARM_CFSTORE_DRIVER_ERROR_INVALID_KEY_NAME; } @@ -2766,12 +2739,12 @@ static int32_t cfstore_validate_key_name_ex(const char* key_name, const char* pe /* @brief check the key name is valid */ -static int32_t cfstore_validate_key_name(const char* key_name) +static int32_t cfstore_validate_key_name(const char *key_name) { int32_t ret = ARM_DRIVER_ERROR; ret = cfstore_uvisor_security_context_prefix_check(key_name); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed uvisor security context check.\n", __func__); return ret; } @@ -2779,7 +2752,7 @@ static int32_t cfstore_validate_key_name(const char* key_name) } /* @brief check the key name query is valid */ -static int32_t cfstore_validate_key_name_query(const char* key_name_query) +static int32_t cfstore_validate_key_name_query(const char *key_name_query) { return cfstore_validate_key_name_ex(key_name_query, CFSTORE_KEY_NAME_QUERY_CHARS_ACCEPTABLE); } @@ -2794,7 +2767,7 @@ static int32_t cfstore_validate_key_name_query(const char* key_name_query) */ static CFSTORE_INLINE int32_t cfstore_validate_value_len(ARM_CFSTORE_SIZE value_len) { - if(value_len <= CFSTORE_VALUE_SIZE_MAX) { + if (value_len <= CFSTORE_VALUE_SIZE_MAX) { return ARM_DRIVER_OK; } return ARM_CFSTORE_DRIVER_ERROR_VALUE_SIZE_TOO_LARGE; @@ -2802,33 +2775,33 @@ static CFSTORE_INLINE int32_t cfstore_validate_value_len(ARM_CFSTORE_SIZE value_ /* @brief See definition in configuration_store.h for description. */ -static int32_t cfstore_get_key_name_ex(cfstore_area_hkvt_t *hkvt, char* key_name, uint8_t *key_name_len) +static int32_t cfstore_get_key_name_ex(cfstore_area_hkvt_t *hkvt, char *key_name, uint8_t *key_name_len) { int32_t ret = ARM_DRIVER_OK; int32_t max_len = 0; max_len = cfstore_hkvt_get_key_len(hkvt) + 1; max_len = max_len <= *key_name_len ? max_len : *key_name_len; - memcpy(key_name, (const char*) hkvt->key, max_len-1); - key_name[max_len-1] = '\0'; + memcpy(key_name, (const char *) hkvt->key, max_len - 1); + key_name[max_len - 1] = '\0'; *key_name_len = max_len; return ret; } /* @brief See definition in configuration_store.h for description. */ -static int32_t cfstore_get_key_name(ARM_CFSTORE_HANDLE hkey, char* key_name, uint8_t *key_name_len) +static int32_t cfstore_get_key_name(ARM_CFSTORE_HANDLE hkey, char *key_name, uint8_t *key_name_len) { int32_t ret = ARM_DRIVER_ERROR; cfstore_area_hkvt_t hkvt; cfstore_client_notify_data_t notify_data; - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); CFSTORE_ASSERT(key_name != NULL); CFSTORE_ASSERT(key_name_len != NULL); CFSTORE_FENTRYLOG("%s:entered\n", __func__); - if(!cfstore_ctx_is_initialised(ctx)) { + if (!cfstore_ctx_is_initialised(ctx)) { CFSTORE_ERRLOG("%s:Error: CFSTORE is not initialised.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_UNINITIALISED; goto out0; @@ -2836,29 +2809,29 @@ static int32_t cfstore_get_key_name(ARM_CFSTORE_HANDLE hkey, char* key_name, uin /* getting a keyname doesnt change the sram area so this can happen independently of * an oustanding async operation. its unnecessary to check the fsm state */ ret = cfstore_validate_handle(hkey); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid handle.\n", __func__); goto out0; } - if(key_name == NULL){ + if (key_name == NULL) { CFSTORE_ERRLOG("%s:Error: invalid handle.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_INVALID_KEY_NAME; goto out0; } - ret = cfstore_validate_len_ptr((ARM_CFSTORE_SIZE*)key_name_len); - if(ret < ARM_DRIVER_OK){ + ret = cfstore_validate_len_ptr((ARM_CFSTORE_SIZE *)key_name_len); + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid key_name_len argument.\n", __func__); goto out0; } memset(&hkvt, 0, sizeof(hkvt)); hkvt = cfstore_get_hkvt(hkey); - if(!cfstore_hkvt_is_valid(&hkvt, ctx->area_0_tail)){ + if (!cfstore_hkvt_is_valid(&hkvt, ctx->area_0_tail)) { CFSTORE_ERRLOG("%s:ARM_CFSTORE_DRIVER_ERROR_INVALID_HANDLE\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_INVALID_HANDLE; goto out0; } ret = cfstore_get_key_name_ex(&hkvt, key_name, key_name_len); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: cfstore_get_key_name_ex() returned error.\n", __func__); goto out0; } @@ -2874,21 +2847,18 @@ static int32_t cfstore_get_key_name(ARM_CFSTORE_HANDLE hkey, char* key_name, uin static ARM_CFSTORE_STATUS cfstore_get_status(void) { ARM_CFSTORE_STATUS status; - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); memset(&status, 0, sizeof(status)); - if(!cfstore_ctx_is_initialised(ctx)) { + if (!cfstore_ctx_is_initialised(ctx)) { CFSTORE_ERRLOG("%s:Error: CFSTORE is not initialised.\n", __func__); status.error = true; } /* getting status doesnt change the sram area so this can happen independently of * an oustanding async operation. */ - if(cfstore_flash_journal_is_async_op_pending(ctx)) - { + if (cfstore_flash_journal_is_async_op_pending(ctx)) { status.in_progress = true; - } - else - { + } else { status.in_progress = false; } return status; @@ -2900,36 +2870,36 @@ static int32_t cfstore_get_value_len(ARM_CFSTORE_HANDLE hkey, ARM_CFSTORE_SIZE * int32_t ret = ARM_CFSTORE_DRIVER_ERROR_UNINITIALISED; cfstore_area_hkvt_t hkvt; cfstore_client_notify_data_t notify_data; - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); CFSTORE_FENTRYLOG("%s:entered\n", __func__); CFSTORE_ASSERT(hkey != NULL); CFSTORE_ASSERT(value_len != NULL); - if(!cfstore_ctx_is_initialised(ctx)) { + if (!cfstore_ctx_is_initialised(ctx)) { CFSTORE_ERRLOG("%s:Error: CFSTORE is not initialised.\n", __func__); goto out0; } /* getting a value len doesnt change the sram area so this can happen independently of * an outstanding async operation. its unnecessary to check the fsm state */ ret = cfstore_validate_handle(hkey); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid handle.\n", __func__); goto out0; } ret = cfstore_validate_len_ptr(value_len); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid value len argument.\n", __func__); goto out0; } hkvt = cfstore_get_hkvt(hkey); - if(!cfstore_hkvt_is_valid(&hkvt, ctx->area_0_tail)){ + if (!cfstore_hkvt_is_valid(&hkvt, ctx->area_0_tail)) { CFSTORE_ERRLOG("%s:ARM_CFSTORE_DRIVER_ERROR_INVALID_HANDLE\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_INVALID_HANDLE; goto out0; } *value_len = cfstore_hkvt_get_value_len(&hkvt); - ret = (int32_t) *value_len; + ret = (int32_t) * value_len; out0: /* GetValueLen() always completes synchronously irrespective of flash mode, so indicate to caller */ cfstore_client_notify_data_init(¬ify_data, CFSTORE_OPCODE_GET_VALUE_LEN, ret, hkey); @@ -2940,22 +2910,22 @@ static int32_t cfstore_get_value_len(ARM_CFSTORE_HANDLE hkey, ARM_CFSTORE_SIZE * #ifdef CFSTORE_DEBUG /* @brief debug trace a struct cfstore_area_hkvt_t, providing values for key field. */ -static CFSTORE_INLINE void cfstore_hkvt_dump(cfstore_area_hkvt_t* hkvt, const char* tag) +static CFSTORE_INLINE void cfstore_hkvt_dump(cfstore_area_hkvt_t *hkvt, const char *tag) { -/* #define CFSTORE_HKVT_DUMP_ON */ + /* #define CFSTORE_HKVT_DUMP_ON */ #ifdef CFSTORE_HKVT_DUMP_ON - char kname[CFSTORE_KEY_NAME_MAX_LENGTH+1]; - char value[CFSTORE_KEY_NAME_MAX_LENGTH+1]; + char kname[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; + char value[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; uint32_t klen = 0; uint32_t vlen = 0; - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); - memset(kname, 0, CFSTORE_KEY_NAME_MAX_LENGTH+1); - memset(value, 0, CFSTORE_KEY_NAME_MAX_LENGTH+1); + memset(kname, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); + memset(value, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); klen = cfstore_hkvt_get_key_len(hkvt); vlen = cfstore_hkvt_get_value_len(hkvt); - memcpy((void*)kname, (void*) hkvt->key, klen); - memcpy((void*)value, (void*) hkvt->value, vlen); + memcpy((void *)kname, (void *) hkvt->key, klen); + memcpy((void *)value, (void *) hkvt->value, vlen); kname[klen] = '\0'; value[vlen] = '\0'; @@ -2966,10 +2936,10 @@ static CFSTORE_INLINE void cfstore_hkvt_dump(cfstore_area_hkvt_t* hkvt, const ch * col 4: the value of the pointer described in col 3 as an offset from the start of the sram area * col 5: field specified data e.g. for header, the extracted key length, value_length. */ - CFSTORE_TP(CFSTORE_TP_VERBOSE3, "%s:hkvt->head:%8p:%8p:klen=%08d:vlen=%08d:\n", tag, hkvt->head, (void*)(hkvt->head - ctx->area_0_head), (int) klen, (int) vlen); - CFSTORE_TP(CFSTORE_TP_VERBOSE3, "%s:hkvt->key :%8p:%8p:%s\n", tag, hkvt->key, (void*)(hkvt->key - ctx->area_0_head), kname); - CFSTORE_TP(CFSTORE_TP_VERBOSE3, "%s:hkvt->val :%8p:%8p:%s\n", tag, hkvt->value, (void*)(hkvt->value - ctx->area_0_head), value); - CFSTORE_TP(CFSTORE_TP_VERBOSE3, "%s:hkvt->tail:%8p:%8p:\n", tag, hkvt->tail, (void*)(hkvt->tail - ctx->area_0_head)); + CFSTORE_TP(CFSTORE_TP_VERBOSE3, "%s:hkvt->head:%8p:%8p:klen=%08d:vlen=%08d:\n", tag, hkvt->head, (void *)(hkvt->head - ctx->area_0_head), (int) klen, (int) vlen); + CFSTORE_TP(CFSTORE_TP_VERBOSE3, "%s:hkvt->key :%8p:%8p:%s\n", tag, hkvt->key, (void *)(hkvt->key - ctx->area_0_head), kname); + CFSTORE_TP(CFSTORE_TP_VERBOSE3, "%s:hkvt->val :%8p:%8p:%s\n", tag, hkvt->value, (void *)(hkvt->value - ctx->area_0_head), value); + CFSTORE_TP(CFSTORE_TP_VERBOSE3, "%s:hkvt->tail:%8p:%8p:\n", tag, hkvt->tail, (void *)(hkvt->tail - ctx->area_0_head)); return; #else (void) hkvt; @@ -2978,7 +2948,7 @@ static CFSTORE_INLINE void cfstore_hkvt_dump(cfstore_area_hkvt_t* hkvt, const ch #endif /* CFSTORE_HKVT_DUMP_ON */ } -static CFSTORE_INLINE void cfstore_flags_dump(ARM_CFSTORE_FMODE flag, const char* tag) +static CFSTORE_INLINE void cfstore_flags_dump(ARM_CFSTORE_FMODE flag, const char *tag) { int pos = 0; char flags[9]; @@ -2995,9 +2965,9 @@ static CFSTORE_INLINE void cfstore_flags_dump(ARM_CFSTORE_FMODE flag, const char return; } -static CFSTORE_INLINE void cfstore_file_dump(cfstore_file_t* file, const char* tag) +static CFSTORE_INLINE void cfstore_file_dump(cfstore_file_t *file, const char *tag) { -/*#define CFSTORE_FILE_DUMP_ON */ + /*#define CFSTORE_FILE_DUMP_ON */ #ifdef CFSTORE_FILE_DUMP_ON cfstore_area_hkvt_t hkvt; @@ -3017,25 +2987,24 @@ static CFSTORE_INLINE void cfstore_file_dump(cfstore_file_t* file, const char* t } /* dump sram contents of cfstore in a useful manner for debugging */ -static CFSTORE_INLINE void cfstore_dump_contents(const char* tag) +static CFSTORE_INLINE void cfstore_dump_contents(const char *tag) { int32_t ret = ARM_DRIVER_ERROR; cfstore_area_hkvt_t hkvt; - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); CFSTORE_TP(CFSTORE_TP_VERBOSE3, "%s:*** Dumping CFSTORE Contents : Start ***\n", tag); CFSTORE_TP(CFSTORE_TP_VERBOSE3, "%s:cfstore_ctx_g.area_0_head=%8p\n", tag, ctx->area_0_head); CFSTORE_TP(CFSTORE_TP_VERBOSE3, "%s:cfstore_ctx_g.area_0_tail=%8p\n", tag, ctx->area_0_tail); ret = cfstore_get_head_hkvt(&hkvt); - if(ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND){ + if (ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { CFSTORE_TP(CFSTORE_TP_VERBOSE1, "%s:CFSTORE has no KVs\n", tag); goto out0; - } else if(ret < ARM_DRIVER_OK){ + } else if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: could not get head of list.\n", tag); goto out0; } - while(cfstore_get_next_hkvt(&hkvt, &hkvt) != ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) - { + while (cfstore_get_next_hkvt(&hkvt, &hkvt) != ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { cfstore_hkvt_dump(&hkvt, tag); } out0: @@ -3046,10 +3015,29 @@ static CFSTORE_INLINE void cfstore_dump_contents(const char* tag) #else -static CFSTORE_INLINE void cfstore_hkvt_dump(cfstore_area_hkvt_t* hkvt, const char* tag){ (void) hkvt; (void) tag; return; } -static CFSTORE_INLINE void cfstore_file_dump(cfstore_file_t* file, const char* tag){ (void) file; (void) tag; return; } -static CFSTORE_INLINE void cfstore_dump_contents(const char* tag){ (void) tag; return; } -static CFSTORE_INLINE void cfstore_flags_dump(ARM_CFSTORE_FMODE flag, const char* tag){ (void) flag; (void) tag; return; } +static CFSTORE_INLINE void cfstore_hkvt_dump(cfstore_area_hkvt_t *hkvt, const char *tag) +{ + (void) hkvt; + (void) tag; + return; +} +static CFSTORE_INLINE void cfstore_file_dump(cfstore_file_t *file, const char *tag) +{ + (void) file; + (void) tag; + return; +} +static CFSTORE_INLINE void cfstore_dump_contents(const char *tag) +{ + (void) tag; + return; +} +static CFSTORE_INLINE void cfstore_flags_dump(ARM_CFSTORE_FMODE flag, const char *tag) +{ + (void) flag; + (void) tag; + return; +} #endif /*CFSTORE_DEBUG*/ /* @@ -3074,35 +3062,35 @@ static int32_t cfstore_delete(ARM_CFSTORE_HANDLE hkey) { int32_t ret = ARM_DRIVER_ERROR; cfstore_area_hkvt_t hkvt; - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); cfstore_client_notify_data_t notify_data; - CFSTORE_TP((CFSTORE_TP_DELETE|CFSTORE_TP_FENTRY), "%s:entered\n", __func__); - if(!cfstore_ctx_is_initialised(ctx)) { + CFSTORE_TP((CFSTORE_TP_DELETE | CFSTORE_TP_FENTRY), "%s:entered\n", __func__); + if (!cfstore_ctx_is_initialised(ctx)) { CFSTORE_TP(CFSTORE_TP_DELETE, "%s:Error: CFSTORE is not initialised.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_UNINITIALISED; goto out0; } /* deleting a key will change the sram area while a logging/flushing operation is pending, which * should not happen while an async operation is outstanding */ - if(cfstore_flash_journal_is_async_op_pending(ctx)) { + if (cfstore_flash_journal_is_async_op_pending(ctx)) { CFSTORE_TP(CFSTORE_TP_DELETE, "%s:Debug: flash journal operation pending (awaiting asynchronous notification).\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_OPERATION_PENDING; goto out0; } ret = cfstore_validate_handle(hkey); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid handle.\n", __func__); goto out0; } - if(!cfstore_is_kv_client_deletable((cfstore_file_t*) hkey)){ + if (!cfstore_is_kv_client_deletable((cfstore_file_t *) hkey)) { CFSTORE_ERRLOG("%s:Error: client is not permitted to delete KV.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_NO_PERMISSIONS; goto out0; } hkvt = cfstore_get_hkvt(hkey); /* check its a valid hkvt */ - if(!cfstore_hkvt_is_valid(&hkvt, ctx->area_0_tail)){ + if (!cfstore_hkvt_is_valid(&hkvt, ctx->area_0_tail)) { CFSTORE_ERRLOG("%s:ARM_CFSTORE_DRIVER_ERROR_INVALID_HANDLE\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_INVALID_HANDLE; goto out0; @@ -3136,27 +3124,27 @@ static int32_t cfstore_delete(ARM_CFSTORE_HANDLE hkey) * returned. If a KV is not found matching the description then * ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND is returned. */ -static int32_t cfstore_find_ex(const char* key_name_query, cfstore_area_hkvt_t *prev, cfstore_area_hkvt_t *next) +static int32_t cfstore_find_ex(const char *key_name_query, cfstore_area_hkvt_t *prev, cfstore_area_hkvt_t *next) { int32_t ret = ARM_DRIVER_ERROR; uint8_t next_key_len; - char key_name[CFSTORE_KEY_NAME_MAX_LENGTH+1]; - cfstore_ctx_t* ctx = cfstore_ctx_get(); + char key_name[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; + cfstore_ctx_t *ctx = cfstore_ctx_get(); - CFSTORE_TP((CFSTORE_TP_FIND|CFSTORE_TP_FENTRY), "%s:entered: key_name_query=\"%s\", prev=%p, next=%p\n", __func__, key_name_query, prev, next); - if(prev == NULL){ + CFSTORE_TP((CFSTORE_TP_FIND | CFSTORE_TP_FENTRY), "%s:entered: key_name_query=\"%s\", prev=%p, next=%p\n", __func__, key_name_query, prev, next); + if (prev == NULL) { ret = cfstore_get_head_hkvt(next); /* CFSTORE_TP(CFSTORE_TP_FIND, "%s:next->head=%p, next->key=%p, next->value=%p, next->tail=%p, \n", __func__, next->head, next->key, next->value, next->tail); */ - if(ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND){ + if (ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { CFSTORE_TP(CFSTORE_TP_FIND, "%s:CFSTORE has no KVs\n", __func__); return ret; - } else if(ret < ARM_DRIVER_OK) { + } else if (ret < ARM_DRIVER_OK) { CFSTORE_TP(CFSTORE_TP_FIND, "%s:failed to find the first KV in area\n", __func__); return ret; } /* check for no KVs in the store => hkvt is not valid */ - if(!cfstore_hkvt_is_valid(next, ctx->area_0_tail)){ + if (!cfstore_hkvt_is_valid(next, ctx->area_0_tail)) { /* no KVs in store */ CFSTORE_TP(CFSTORE_TP_FIND, "%s:hkvt is not valid\n", __func__); return ARM_DRIVER_OK; @@ -3165,37 +3153,36 @@ static int32_t cfstore_find_ex(const char* key_name_query, cfstore_area_hkvt_t * } else { /* CFSTORE_TP(CFSTORE_TP_FIND, "%s:getting hkvt from prev\n", __func__);*/ ret = cfstore_get_next_hkvt(prev, next); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { /* no more matching entries or error. * either way, return*/ return ret; } } - if(next->head == NULL){ + if (next->head == NULL) { /* no entry*/ CFSTORE_TP(CFSTORE_TP_FIND, "%s:No more entries found\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND; } /* CFSTORE_TP(CFSTORE_TP_FIND, "%s:cfstore_ctx_g.area_0_head=%p, cfstore_ctx_g.area_0_tail=%p\n", __func__, cfstore_ctx_g.area_0_head, cfstore_ctx_g.area_0_tail);*/ cfstore_hkvt_dump(next, __func__); - while(cfstore_hkvt_is_valid(next, ctx->area_0_tail)) - { + while (cfstore_hkvt_is_valid(next, ctx->area_0_tail)) { /* CFSTORE_TP(CFSTORE_TP_FIND, "%s:next->head=%p, next->key=%p, next->value=%p, next->tail=%p, \n", __func__, next->head, next->key, next->value, next->tail); */ cfstore_hkvt_dump(next, __func__); /* if this KV is deleting then proceed to the next item */ - if(cfstore_hkvt_get_flags_delete(next)){ + if (cfstore_hkvt_get_flags_delete(next)) { ret = cfstore_get_next_hkvt(next, next); - if(ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { + if (ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { CFSTORE_TP(CFSTORE_TP_FIND, "%s:No more KVs found\n", __func__); return ret; } continue; } /* if this KV is not readable by the client then proceed to the next item */ - if(!cfstore_is_kv_client_readable(next)){ + if (!cfstore_is_kv_client_readable(next)) { ret = cfstore_get_next_hkvt(next, next); - if(ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { + if (ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { CFSTORE_TP(CFSTORE_TP_FIND, "%s:No more KVs found\n", __func__); return ret; } @@ -3206,18 +3193,18 @@ static int32_t cfstore_find_ex(const char* key_name_query, cfstore_area_hkvt_t * next_key_len++; cfstore_get_key_name_ex(next, key_name, &next_key_len); ret = cfstore_fnmatch(key_name_query, key_name, 0); - if(ret == 0){ + if (ret == 0) { /* found the entry in the store. return handle */ CFSTORE_TP(CFSTORE_TP_FIND, "%s:Found matching key (key_name_query = \"%s\", next->key = \"%s\"),next_key_len=%d\n", __func__, key_name_query, key_name, (int) next_key_len); cfstore_hkvt_dump(next, __func__); return ARM_DRIVER_OK; - } else if(ret != CFSTORE_FNM_NOMATCH){ + } else if (ret != CFSTORE_FNM_NOMATCH) { CFSTORE_ERRLOG("%s:Error: cfstore_fnmatch() error (ret=%d).\n", __func__, (int) ret); return ARM_DRIVER_ERROR; } /* CFSTORE_FNM_NOMATCH => get the next hkvt if any */ ret = cfstore_get_next_hkvt(next, next); - if(ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { + if (ret == ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { CFSTORE_TP(CFSTORE_TP_FIND, "%s:No more KVs found\n", __func__); return ret; } @@ -3227,21 +3214,21 @@ static int32_t cfstore_find_ex(const char* key_name_query, cfstore_area_hkvt_t * /* @brief See definition in configuration_store.h for description. */ -static int32_t cfstore_find(const char* key_name_query, const ARM_CFSTORE_HANDLE previous, ARM_CFSTORE_HANDLE next) +static int32_t cfstore_find(const char *key_name_query, const ARM_CFSTORE_HANDLE previous, ARM_CFSTORE_HANDLE next) { - char key_name[CFSTORE_KEY_NAME_MAX_LENGTH+1]; + char key_name[CFSTORE_KEY_NAME_MAX_LENGTH + 1]; uint8_t key_len = 0; cfstore_area_hkvt_t hkvt_next; cfstore_area_hkvt_t hkvt_previous; cfstore_area_hkvt_t *phkvt_previous = NULL; int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_FMODE fmode; - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); cfstore_client_notify_data_t notify_data; CFSTORE_ASSERT(next != NULL); CFSTORE_FENTRYLOG("%s:entered: key_name_query=\"%s\", previous=%p, next=%p\n", __func__, key_name_query, previous, next); - if(!cfstore_ctx_is_initialised(ctx)) { + if (!cfstore_ctx_is_initialised(ctx)) { CFSTORE_ERRLOG("%s:Error: CFSTORE is not initialised.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_UNINITIALISED; goto out1; @@ -3249,21 +3236,21 @@ static int32_t cfstore_find(const char* key_name_query, const ARM_CFSTORE_HANDLE /* finding a key doesnt change the sram area so this can happen independently of * an oustanding async operation. its unnecessary to check the fsm state */ ret = cfstore_validate_key_name_query(key_name_query); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid key_name.\n", __func__); goto out1; } ret = cfstore_validate_handle(next); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid next argument.\n", __func__); goto out1; } /* note previous can be NULL if this is the first call the find */ memset(&hkvt_next, 0, sizeof(hkvt_next)); memset(&fmode, 0, sizeof(fmode)); - if(previous != NULL && cfstore_file_is_valid(previous, ctx)){ + if (previous != NULL && cfstore_file_is_valid(previous, ctx)) { ret = cfstore_validate_handle(previous); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid handle.\n", __func__); goto out1; } @@ -3271,23 +3258,23 @@ static int32_t cfstore_find(const char* key_name_query, const ARM_CFSTORE_HANDLE memset(phkvt_previous, 0, sizeof(hkvt_previous)); hkvt_previous = cfstore_get_hkvt(previous); cfstore_hkvt_dump(&hkvt_previous, __func__); - if(!cfstore_hkvt_is_valid(phkvt_previous, ctx->area_0_tail)){ + if (!cfstore_hkvt_is_valid(phkvt_previous, ctx->area_0_tail)) { ret = ARM_CFSTORE_DRIVER_ERROR_INVALID_HANDLE; goto out1; } - } else if(previous != NULL && !cfstore_file_is_empty(previous)){ + } else if (previous != NULL && !cfstore_file_is_empty(previous)) { CFSTORE_TP(CFSTORE_TP_FIND, "%s:Invalid previous hkey buffer.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_INVALID_HANDLE_BUF; goto out1; } ret = cfstore_find_ex(key_name_query, phkvt_previous, &hkvt_next); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { /* either no more entries or error but either way, return */ CFSTORE_TP(CFSTORE_TP_FIND, "%s:No more KVs found.\n", __func__); goto out2; } - if(!cfstore_hkvt_is_valid(&hkvt_next, ctx->area_0_tail)){ + if (!cfstore_hkvt_is_valid(&hkvt_next, ctx->area_0_tail)) { CFSTORE_TP(CFSTORE_TP_FIND, "%s:Did not find any matching KVs.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND; goto out2; @@ -3301,29 +3288,28 @@ static int32_t cfstore_find(const char* key_name_query, const ARM_CFSTORE_HANDLE ret = ARM_DRIVER_OK; out2: /* previous handle is being returned to CFSTORE with this call so destroy file struct */ - if(previous != NULL && cfstore_file_is_valid(previous, ctx)) - { + if (previous != NULL && cfstore_file_is_valid(previous, ctx)) { /* do not use ret in this stanza as will loose return state from above */ /* CFSTORE_TP(CFSTORE_TP_FIND, "%s:about to destroy KV, previous=%p.\n", __func__, previous); */ - cfstore_file_dump((cfstore_file_t*) previous, __func__); + cfstore_file_dump((cfstore_file_t *) previous, __func__); - key_len = CFSTORE_KEY_NAME_MAX_LENGTH+1; - memset(key_name, 0, CFSTORE_KEY_NAME_MAX_LENGTH+1); + key_len = CFSTORE_KEY_NAME_MAX_LENGTH + 1; + memset(key_name, 0, CFSTORE_KEY_NAME_MAX_LENGTH + 1); cfstore_file_destroy(cfstore_file_get(previous)); /* check hkvt is valid before trying to retrieve name*/ - if(!cfstore_hkvt_is_valid(&hkvt_next, ctx->area_0_tail)){ + if (!cfstore_hkvt_is_valid(&hkvt_next, ctx->area_0_tail)) { goto out1; } - if(cfstore_get_key_name_ex(&hkvt_next, key_name, &key_len) < ARM_DRIVER_OK){ + if (cfstore_get_key_name_ex(&hkvt_next, key_name, &key_len) < ARM_DRIVER_OK) { /* either no more entries or error but either way, return */ CFSTORE_TP(CFSTORE_TP_FIND, "%s:debug: cfstore_get_key_name_ex failed or no more kvs.\n", __func__); goto out1; } /* now get hkvt_next again based on the name to overcome the fact that the hkvt * may be invalid due to the possible deletion of the previous KV.x */ - if(cfstore_find_ex(key_name, NULL, &hkvt_next) < ARM_DRIVER_OK){ + if (cfstore_find_ex(key_name, NULL, &hkvt_next) < ARM_DRIVER_OK) { /* either no more entries or error but either way, return */ CFSTORE_TP(CFSTORE_TP_FIND, "%s:find failed key_name=%s ret=%d.\n", __func__, key_name, (int) ret); goto out1; @@ -3341,15 +3327,15 @@ static int32_t cfstore_find(const char* key_name_query, const ARM_CFSTORE_HANDLE /* @brief grow/shrink pre-existing KV. * * @note rw_lock must be held by the caller of this function rw_area0_lock */ -static int32_t cfstore_recreate(const char* key_name, ARM_CFSTORE_SIZE value_len, ARM_CFSTORE_HANDLE hkey, cfstore_area_hkvt_t* hkvt) +static int32_t cfstore_recreate(const char *key_name, ARM_CFSTORE_SIZE value_len, ARM_CFSTORE_HANDLE hkey, cfstore_area_hkvt_t *hkvt) { - uint8_t* old_area_0_head = NULL; + uint8_t *old_area_0_head = NULL; int32_t kv_size_diff = 0; int32_t ret = ARM_DRIVER_ERROR; size_t memmove_len = 0; ARM_CFSTORE_SIZE area_size = 0; ARM_CFSTORE_FMODE flags; - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); CFSTORE_FENTRYLOG("%s:entered: key_name=\"%s\", value_len=%d\n", __func__, key_name, (int) value_len); cfstore_dump_contents(__func__); @@ -3357,7 +3343,7 @@ static int32_t cfstore_recreate(const char* key_name, ARM_CFSTORE_SIZE value_len flags.read = true; flags.write = true; kv_size_diff = value_len - cfstore_hkvt_get_value_len(hkvt); - if(kv_size_diff == 0){ + if (kv_size_diff == 0) { /* nothing more to do*/ CFSTORE_TP(CFSTORE_TP_CREATE, "%s:new value length the same as the old\n", __func__); return ARM_DRIVER_OK; @@ -3370,23 +3356,23 @@ static int32_t cfstore_recreate(const char* key_name, ARM_CFSTORE_SIZE value_len memmove_len = ctx->area_0_tail - hkvt->tail; CFSTORE_TP(CFSTORE_TP_CREATE, "%s:cfstore_ctx_g.area_0_head=%p, cfstore_ctx_g.area_0_tail=%p\n", __func__, ctx->area_0_head, ctx->area_0_tail); - CFSTORE_TP(CFSTORE_TP_CREATE, "%s:sizeof(header)=%d, sizeof(key)=%d, sizeof(value)=%d, kv_size_diff=%d, area_size=%d\n", __func__, (int) sizeof(cfstore_area_header_t), (int)(strlen(key_name)), (int)value_len, (int) kv_size_diff, (int) area_size); - if (kv_size_diff < 0){ + CFSTORE_TP(CFSTORE_TP_CREATE, "%s:sizeof(header)=%d, sizeof(key)=%d, sizeof(value)=%d, kv_size_diff=%d, area_size=%d\n", __func__, (int) sizeof(cfstore_area_header_t), (int)(strlen(key_name)), (int)value_len, (int) kv_size_diff, (int) area_size); + if (kv_size_diff < 0) { /* value blob size shrinking => do memmove() before realloc() which will free memory */ memmove(hkvt->tail + kv_size_diff, hkvt->tail, memmove_len); ret = cfstore_file_update(hkvt->head, kv_size_diff); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error:file update failed\n", __func__); goto out0; } } ret = cfstore_realloc_ex(area_size + kv_size_diff, NULL); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error:file realloc failed\n", __func__); goto out0; } - if(old_area_0_head != ctx->area_0_head){ + if (old_area_0_head != ctx->area_0_head) { /* As realloc() has caused the memory to move, hkvt needs re-initialising */ hkvt->head += ctx->area_0_head - old_area_0_head; hkvt->key += ctx->area_0_head - old_area_0_head; @@ -3394,11 +3380,11 @@ static int32_t cfstore_recreate(const char* key_name, ARM_CFSTORE_SIZE value_len hkvt->tail += ctx->area_0_head - old_area_0_head; } - if(kv_size_diff > 0) { + if (kv_size_diff > 0) { /* value blob size growing requires memmove() after realloc() */ - memmove(hkvt->tail+kv_size_diff, hkvt->tail, memmove_len); + memmove(hkvt->tail + kv_size_diff, hkvt->tail, memmove_len); ret = cfstore_file_update(hkvt->head, kv_size_diff); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error:file update failed\n", __func__); goto out0; } @@ -3422,7 +3408,7 @@ static int32_t cfstore_recreate(const char* key_name, ARM_CFSTORE_SIZE value_len /* @brief See definition in configuration_store.h for description. */ -static int32_t cfstore_create(const char* key_name, ARM_CFSTORE_SIZE value_len, const ARM_CFSTORE_KEYDESC* kdesc, ARM_CFSTORE_HANDLE hkey) +static int32_t cfstore_create(const char *key_name, ARM_CFSTORE_SIZE value_len, const ARM_CFSTORE_KEYDESC *kdesc, ARM_CFSTORE_HANDLE hkey) { bool b_acl_default = false; int32_t ret = ARM_DRIVER_ERROR; @@ -3430,9 +3416,9 @@ static int32_t cfstore_create(const char* key_name, ARM_CFSTORE_SIZE value_len, ARM_CFSTORE_SIZE area_size = 0; ARM_CFSTORE_SIZE kv_size = 0; ARM_CFSTORE_SIZE realloc_size = 0; - cfstore_area_header_t* hdr; + cfstore_area_header_t *hdr; cfstore_area_hkvt_t hkvt; - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); ARM_CFSTORE_FMODE flags; cfstore_client_notify_data_t notify_data; @@ -3441,32 +3427,32 @@ static int32_t cfstore_create(const char* key_name, ARM_CFSTORE_SIZE value_len, CFSTORE_ASSERT(hkey != NULL); memset(&flags, 0, sizeof(flags)); - if(!cfstore_ctx_is_initialised(ctx)) { + if (!cfstore_ctx_is_initialised(ctx)) { CFSTORE_ERRLOG("%s:Error: CFSTORE is not initialised.\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_UNINITIALISED; } /* creating a key cannot happen while a flashJournal_log() is pending as it would change the sram area being logged*/ - if(cfstore_flash_journal_is_async_op_pending(ctx)) { + if (cfstore_flash_journal_is_async_op_pending(ctx)) { CFSTORE_TP(CFSTORE_TP_CREATE, "%s:Debug: flash journal operation pending (awaiting asynchronous notification).\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_OPERATION_PENDING; } ret = cfstore_validate_key_name(key_name); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid key_name (%s).\n", __func__, key_name); goto out0; } ret = cfstore_validate_handle(hkey); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid handle.\n", __func__); goto out0; } ret = cfstore_validate_value_len(value_len); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid key_name.\n", __func__); goto out0; } /* check uvisor security */ - if(cfstore_is_client_kv_owner(key_name, &cfstore_uvisor_box_id) != ARM_DRIVER_OK){ + if (cfstore_is_client_kv_owner(key_name, &cfstore_uvisor_box_id) != ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: Client has insufficient permissions to create KV.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_NO_PERMISSIONS; goto out0; @@ -3475,19 +3461,19 @@ static int32_t cfstore_create(const char* key_name, ARM_CFSTORE_SIZE value_len, /* A null kdesc is permitted if client is growing/shrinking pre-existing key. * Hence, find if key_name pre-exists before validating kdesc */ ret = cfstore_find_ex(key_name, NULL, &hkvt); - if(ret < ARM_DRIVER_OK && ret != ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND){ + if (ret < ARM_DRIVER_OK && ret != ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND) { CFSTORE_ERRLOG("%s:CFSTORE find() returned error (%d)\n", __func__, (int) ret); goto out1; } - if(ret != ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND && cfstore_hkvt_is_valid(&hkvt, ctx->area_0_tail)){ + if (ret != ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND && cfstore_hkvt_is_valid(&hkvt, ctx->area_0_tail)) { /* found pre-existing entry; */ - if(cfstore_hkvt_get_flags_delete(&hkvt)){ + if (cfstore_hkvt_get_flags_delete(&hkvt)) { CFSTORE_ERRLOG("%s:CFSTORE pre-existing KV with key_name=\"%s\" deleting\n", __func__, key_name); ret = ARM_CFSTORE_DRIVER_ERROR_PREEXISTING_KEY_DELETING; goto out1; } - if(kdesc != NULL) { + if (kdesc != NULL) { CFSTORE_ERRLOG("%s:CFSTORE contains pre-existing KV with key_name=\"%s\". Cannot create a new KV with the same name\n", __func__, key_name); ret = ARM_CFSTORE_DRIVER_ERROR_PREEXISTING_KEY; goto out1; @@ -3501,7 +3487,7 @@ static int32_t cfstore_create(const char* key_name, ARM_CFSTORE_SIZE value_len, /* create new key */ ret = cfstore_validate_key_desc(kdesc); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid key descriptor.\n", __func__); goto out1; } @@ -3518,19 +3504,19 @@ static int32_t cfstore_create(const char* key_name, ARM_CFSTORE_SIZE value_len, /* setup the reallocation memory size. */ realloc_size = area_size + kv_size; ret = cfstore_realloc_ex(realloc_size, NULL); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error:file realloc failed\n", __func__); goto out1; } /* determine if should adopt a default behavior for acl permission setting */ - if(cfstore_acl_is_default(kdesc->acl)){ + if (cfstore_acl_is_default(kdesc->acl)) { /* set as read-write by default default */ CFSTORE_TP(CFSTORE_TP_CREATE, "%s:Note: No ACL bits set. Adopting default permissions of owner read and write.\n", __func__); b_acl_default = true; } /* set the header up, then copy key_name into header */ - hdr = (cfstore_area_header_t*) (ctx->area_0_head + area_size); + hdr = (cfstore_area_header_t *)(ctx->area_0_head + area_size); CFSTORE_FENTRYLOG("%s:hdr=%p\n", __func__, hdr); hdr->klength = (uint8_t) strlen(key_name); hdr->vlength = value_len; @@ -3540,9 +3526,9 @@ static int32_t cfstore_create(const char* key_name, ARM_CFSTORE_SIZE value_len, hdr->perm_other_read = kdesc->acl.perm_other_read; hdr->perm_other_write = kdesc->acl.perm_other_write; hdr->perm_other_execute = kdesc->acl.perm_other_execute; - strncpy((char*)hdr + sizeof(cfstore_area_header_t), key_name, strlen(key_name)); - hkvt = cfstore_get_hkvt_from_head_ptr((uint8_t*) hdr); - if(cfstore_flags_is_default(kdesc->flags)){ + strncpy((char *)hdr + sizeof(cfstore_area_header_t), key_name, strlen(key_name)); + hkvt = cfstore_get_hkvt_from_head_ptr((uint8_t *) hdr); + if (cfstore_flags_is_default(kdesc->flags)) { /* set as read-only by default default */ flags.read = true; flags.write = true; @@ -3565,90 +3551,89 @@ static int32_t cfstore_create(const char* key_name, ARM_CFSTORE_SIZE value_len, /* @brief See definition in configuration_store.h for description. */ -static int32_t cfstore_open(const char* key_name, ARM_CFSTORE_FMODE flags, ARM_CFSTORE_HANDLE hkey) +static int32_t cfstore_open(const char *key_name, ARM_CFSTORE_FMODE flags, ARM_CFSTORE_HANDLE hkey) { int32_t ret = ARM_DRIVER_ERROR; cfstore_area_hkvt_t hkvt; cfstore_file_t *file = NULL; - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); cfstore_client_notify_data_t notify_data; CFSTORE_FENTRYLOG("%s:entered\n", __func__); cfstore_flags_dump(flags, __func__); CFSTORE_ASSERT(key_name != NULL); CFSTORE_ASSERT(hkey != NULL); - if(!cfstore_ctx_is_initialised(ctx)) { + if (!cfstore_ctx_is_initialised(ctx)) { CFSTORE_ERRLOG("%s:Error: CFSTORE is not initialised.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_UNINITIALISED; goto out1; } ret = cfstore_validate_key_name(key_name); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid key_name.\n", __func__); goto out1; } ret = cfstore_validate_fmode_flags(flags); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid flags.\n", __func__); goto out1; } - if(flags.write){ + if (flags.write) { /* opening a pre-existing key for writing can result in the sram area being changed, which * cannot happen while a flashJournal_xxx() async completion notification is outstanding */ - if(cfstore_flash_journal_is_async_op_pending(ctx)) { + if (cfstore_flash_journal_is_async_op_pending(ctx)) { CFSTORE_TP(CFSTORE_TP_OPEN, "%s:Debug: flash journal operation pending (awaiting asynchronous notification).\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_OPERATION_PENDING; goto out1; } } ret = cfstore_validate_handle(hkey); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid handle.\n", __func__); goto out1; } /* find the KV and return a handle */ cfstore_hkvt_init(&hkvt); ret = cfstore_find_ex(key_name, NULL, &hkvt); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { /* either no more entries or error but either way, return */ CFSTORE_TP(CFSTORE_TP_OPEN, "%s:debug: find failed or no more kvs.\n", __func__); goto out1; } - if(!cfstore_hkvt_is_valid(&hkvt, ctx->area_0_tail)) - { + if (!cfstore_hkvt_is_valid(&hkvt, ctx->area_0_tail)) { CFSTORE_ERRLOG("%s:Error: Could not find pre-existing key to open with key_name=(%s).\n", __func__, key_name); ret = ARM_CFSTORE_DRIVER_ERROR_KEY_NOT_FOUND; goto out1; } /* if this KV is deleting then do not allow item to be opened */ - if(cfstore_hkvt_get_flags_delete(&hkvt)){ + if (cfstore_hkvt_get_flags_delete(&hkvt)) { CFSTORE_ERRLOG("%s:Error: Pre-existing key key_name=(%s) is deleting.\n", __func__, key_name); ret = ARM_CFSTORE_DRIVER_ERROR_PREEXISTING_KEY_DELETING; goto out1; } /* key found, check permissions */ - if(cfstore_flags_is_default(flags)){ + if (cfstore_flags_is_default(flags)) { /* set as read-only by default default */ flags.read = true; } - if(flags.read == true && !cfstore_is_kv_client_readable(&hkvt)){ + if (flags.read == true && !cfstore_is_kv_client_readable(&hkvt)) { CFSTORE_ERRLOG("%s:Error: Client has no read access to KV (key_name=%s).\n", __func__, key_name); ret = ARM_CFSTORE_DRIVER_ERROR_PERM_NO_READ_ACCESS; goto out1; } - if(flags.write == true && !cfstore_is_kv_client_writable(&hkvt)){ + if (flags.write == true && !cfstore_is_kv_client_writable(&hkvt)) { CFSTORE_ERRLOG("%s:Error: Client has no write access to KV (key_name=%s).\n", __func__, key_name); ret = ARM_CFSTORE_DRIVER_ERROR_PERM_NO_WRITE_ACCESS; goto out1; } - if(flags.execute == true && !cfstore_is_kv_client_executable(&hkvt)){ + if (flags.execute == true && !cfstore_is_kv_client_executable(&hkvt)) { CFSTORE_ERRLOG("%s:Error: Client has no execute access to KV (key_name=%s).\n", __func__, key_name); ret = ARM_CFSTORE_DRIVER_ERROR_PERM_NO_EXECUTE_ACCESS; goto out1; } /* return handle to client */ file = cfstore_file_create(&hkvt, flags, hkey, &ctx->file_list); - if(file) { + if (file) { cfstore_file_dump(file, __func__); } else { CFSTORE_ERRLOG("%s:Error: failed to create file (key_name=%s).\n", __func__, key_name); @@ -3665,43 +3650,43 @@ static int32_t cfstore_open(const char* key_name, ARM_CFSTORE_FMODE flags, ARM_C static int32_t cfstore_close(ARM_CFSTORE_HANDLE hkey) { int32_t ret = ARM_DRIVER_ERROR; - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); cfstore_client_notify_data_t notify_data; cfstore_area_hkvt_t hkvt; CFSTORE_FENTRYLOG("%s:entered\n", __func__); - if(!cfstore_ctx_is_initialised(ctx)) { + if (!cfstore_ctx_is_initialised(ctx)) { CFSTORE_ERRLOG("%s:Error: CFSTORE is not initialised.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_UNINITIALISED; goto out0; } /* closing a key can lead to its deletion, which cannot happening while there are pending * async operations outstanding */ - if(cfstore_flash_journal_is_async_op_pending(ctx)) { + if (cfstore_flash_journal_is_async_op_pending(ctx)) { CFSTORE_TP(CFSTORE_TP_CLOSE, "%s:Debug: flash journal operation pending (awaiting asynchronous notification).\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_OPERATION_PENDING; goto out0; } ret = cfstore_validate_handle(hkey); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid hkey argument.\n", __func__); goto out0; } /* check the hkey is valid */ hkvt = cfstore_get_hkvt(hkey); - if(!cfstore_hkvt_is_valid(&hkvt, ctx->area_0_tail)){ + if (!cfstore_hkvt_is_valid(&hkvt, ctx->area_0_tail)) { CFSTORE_ERRLOG("%s:ARM_CFSTORE_DRIVER_ERROR_INVALID_HANDLE\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_INVALID_HANDLE; goto out0; } - if(!cfstore_is_kv_client_closable((cfstore_file_t*) hkey)){ + if (!cfstore_is_kv_client_closable((cfstore_file_t *) hkey)) { CFSTORE_ERRLOG("%s:Error: client is not permitted to close KV.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_NO_PERMISSIONS; goto out0; } /* delete the file associated with this open handle */ CFSTORE_TP(CFSTORE_TP_CLOSE, "%s:about to call cfstore_file_destroy().\n", __func__); - cfstore_file_dump((cfstore_file_t*) hkey, __func__); + cfstore_file_dump((cfstore_file_t *) hkey, __func__); ret = cfstore_file_destroy(cfstore_file_get(hkey)); out0: /* Close() always completes synchronously irrespective of flash mode, so indicate to caller */ @@ -3712,19 +3697,19 @@ static int32_t cfstore_close(ARM_CFSTORE_HANDLE hkey) /* @brief See definition in configuration_store.h for description. */ -static int32_t cfstore_read(ARM_CFSTORE_HANDLE hkey, void* data, ARM_CFSTORE_SIZE* len) +static int32_t cfstore_read(ARM_CFSTORE_HANDLE hkey, void *data, ARM_CFSTORE_SIZE *len) { int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE read_len = 0; cfstore_area_hkvt_t hkvt; - cfstore_ctx_t* ctx = cfstore_ctx_get(); - cfstore_file_t* file = cfstore_file_get(hkey); + cfstore_ctx_t *ctx = cfstore_ctx_get(); + cfstore_file_t *file = cfstore_file_get(hkey); cfstore_client_notify_data_t notify_data; CFSTORE_ASSERT(data); CFSTORE_ASSERT(len); CFSTORE_FENTRYLOG("%s:entered, hkey=%p\n", __func__, hkey); - if(!cfstore_ctx_is_initialised(ctx)) { + if (!cfstore_ctx_is_initialised(ctx)) { CFSTORE_ERRLOG("%s:Error: CFSTORE is not initialised.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_UNINITIALISED; goto out0; @@ -3732,30 +3717,30 @@ static int32_t cfstore_read(ARM_CFSTORE_HANDLE hkey, void* data, ARM_CFSTORE_SIZ /* reading KVs doesnt change the sram area so this can happen independently of * an oustanding async operation. its unnecessary to check the fsm state */ ret = cfstore_validate_handle(hkey); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid handle.\n", __func__); goto out0; } - if(data == NULL){ + if (data == NULL) { CFSTORE_ERRLOG("%s:Error: invalid read data buffer.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_INVALID_READ_BUFFER; goto out0; } ret = cfstore_validate_len_ptr(len); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid len argument.\n", __func__); goto out0; } cfstore_hkvt_init(&hkvt); hkvt = cfstore_get_hkvt(hkey); /* check the hkey is valid */ - if(!cfstore_hkvt_is_valid(&hkvt, ctx->area_0_tail)){ + if (!cfstore_hkvt_is_valid(&hkvt, ctx->area_0_tail)) { CFSTORE_ERRLOG("%s:ARM_CFSTORE_DRIVER_ERROR_INVALID_HANDLE\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_INVALID_HANDLE; goto out0; } - if(!cfstore_is_kv_client_readable(&hkvt)){ + if (!cfstore_is_kv_client_readable(&hkvt)) { CFSTORE_ERRLOG("%s:Error: client does not have permission to read KV.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_PERM_NO_READ_ACCESS; goto out0; @@ -3774,41 +3759,41 @@ static int32_t cfstore_read(ARM_CFSTORE_HANDLE hkey, void* data, ARM_CFSTORE_SIZ /* @brief See definition in configuration_store.h for description. */ -static int32_t cfstore_write(ARM_CFSTORE_HANDLE hkey, const char* data, ARM_CFSTORE_SIZE* len) +static int32_t cfstore_write(ARM_CFSTORE_HANDLE hkey, const char *data, ARM_CFSTORE_SIZE *len) { int32_t ret = ARM_DRIVER_ERROR; ARM_CFSTORE_SIZE value_len = 0; cfstore_area_hkvt_t hkvt; - cfstore_file_t* file = cfstore_file_get(hkey); - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_file_t *file = cfstore_file_get(hkey); + cfstore_ctx_t *ctx = cfstore_ctx_get(); cfstore_client_notify_data_t notify_data; CFSTORE_FENTRYLOG("%s:entered, hkey=%p\n", __func__, hkey); CFSTORE_ASSERT(hkey != NULL); CFSTORE_ASSERT(len != NULL); - if(!cfstore_ctx_is_initialised(ctx)) { + if (!cfstore_ctx_is_initialised(ctx)) { CFSTORE_ERRLOG("%s:Error: CFSTORE is not initialised.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_UNINITIALISED; goto out0; } /* writing a key cannot happen while a flashJournal_xxx() async operation is pending */ - if(cfstore_flash_journal_is_async_op_pending(ctx)) { + if (cfstore_flash_journal_is_async_op_pending(ctx)) { CFSTORE_TP(CFSTORE_TP_WRITE, "%s:Debug: flash journal operation pending (awaiting asynchronous notification).\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_OPERATION_PENDING; goto out0; } ret = cfstore_validate_handle(hkey); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid handle.\n", __func__); goto out0; } - if(data == NULL){ + if (data == NULL) { CFSTORE_ERRLOG("%s:Error: invalid write data buffer.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_INVALID_WRITE_BUFFER; goto out0; } ret = cfstore_validate_len_ptr(len); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid len argument.\n", __func__); goto out0; } @@ -3818,25 +3803,25 @@ static int32_t cfstore_write(ARM_CFSTORE_HANDLE hkey, const char* data, ARM_CFST goto out0; } /*check file has write permission set */ - if(!file->flags.write){ + if (!file->flags.write) { CFSTORE_ERRLOG("%s:Error: KV is read-only.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_KEY_READ_ONLY; goto out0; } memset(&hkvt, 0, sizeof(hkvt)); hkvt = cfstore_get_hkvt(hkey); - if(!cfstore_hkvt_is_valid(&hkvt, ctx->area_0_tail)){ + if (!cfstore_hkvt_is_valid(&hkvt, ctx->area_0_tail)) { CFSTORE_ERRLOG("%s:Error: ARM_CFSTORE_DRIVER_ERROR_INVALID_HANDLE.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_INVALID_HANDLE; goto out0; } - if(!cfstore_is_kv_client_writable(&hkvt)){ + if (!cfstore_is_kv_client_writable(&hkvt)) { CFSTORE_ERRLOG("%s:Error: client does not have permission to write KV.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_PERM_NO_WRITE_ACCESS; goto out0; } value_len = (ARM_CFSTORE_SIZE) cfstore_hkvt_get_value_len(&hkvt); - *len = *len < value_len ? *len: value_len; + *len = *len < value_len ? *len : value_len; memcpy(hkvt.value + file->wlocation, data, *len); file->wlocation += *len; cfstore_hkvt_dump(&hkvt, __func__); @@ -3855,28 +3840,28 @@ static int32_t cfstore_rseek(ARM_CFSTORE_HANDLE hkey, ARM_CFSTORE_OFFSET offset) { int32_t ret = ARM_DRIVER_ERROR; cfstore_area_hkvt_t hkvt; - cfstore_file_t* file = cfstore_file_get(hkey); - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_file_t *file = cfstore_file_get(hkey); + cfstore_ctx_t *ctx = cfstore_ctx_get(); cfstore_client_notify_data_t notify_data; CFSTORE_FENTRYLOG("%s:entered\n", __func__); - if(!cfstore_ctx_is_initialised(ctx)) { + if (!cfstore_ctx_is_initialised(ctx)) { CFSTORE_ERRLOG("%s:Error: CFSTORE is not initialised.\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_UNINITIALISED; } /* read-seeking KVs doesnt change the sram area so this can happen independently of * an oustanding async operation. its unnecessary to check the fsm state */ ret = cfstore_validate_handle(hkey); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: invalid handle.\n", __func__); return ret; } ret = cfstore_validate_value_len(offset); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: offset (%u) greater than maximum value blob size (%u).\n", __func__, (unsigned int) offset, CFSTORE_VALUE_SIZE_MAX); return ret; } - if(!file->flags.read){ + if (!file->flags.read) { CFSTORE_ERRLOG("%s:Error: KV is not readable.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_KEY_UNREADABLE; goto out0; @@ -3884,18 +3869,18 @@ static int32_t cfstore_rseek(ARM_CFSTORE_HANDLE hkey, ARM_CFSTORE_OFFSET offset) } cfstore_hkvt_init(&hkvt); hkvt = cfstore_get_hkvt(hkey); - if(!cfstore_hkvt_is_valid(&hkvt, ctx->area_0_tail)){ + if (!cfstore_hkvt_is_valid(&hkvt, ctx->area_0_tail)) { CFSTORE_ERRLOG("%s:Error: ARM_CFSTORE_DRIVER_ERROR_INVALID_HANDLE.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_INVALID_HANDLE; goto out0; } - if(!cfstore_is_kv_client_readable(&hkvt)){ + if (!cfstore_is_kv_client_readable(&hkvt)) { CFSTORE_ERRLOG("%s:Error: client does not have permission to read KV.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_PERM_NO_READ_ACCESS; goto out0; } /* check offset is in range */ - if(offset > cfstore_hkvt_get_value_len(&hkvt)){ + if (offset > cfstore_hkvt_get_value_len(&hkvt)) { CFSTORE_ERRLOG("%s:Error: seeking beyond end of value.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_INVALID_SEEK; goto out0; @@ -3914,22 +3899,22 @@ static int32_t cfstore_rseek(ARM_CFSTORE_HANDLE hkey, ARM_CFSTORE_OFFSET offset) /* @brief See definition in configuration_store.h for description. */ static int32_t cfstore_flush(void) { - int32_t ret = ARM_DRIVER_ERROR; - cfstore_ctx_t* ctx = cfstore_ctx_get(); + int32_t ret = ARM_DRIVER_ERROR; + cfstore_ctx_t *ctx = cfstore_ctx_get(); - CFSTORE_FENTRYLOG("%s:entered\n", __func__); - if(!cfstore_ctx_is_initialised(ctx)) { + CFSTORE_FENTRYLOG("%s:entered\n", __func__); + if (!cfstore_ctx_is_initialised(ctx)) { CFSTORE_ERRLOG("%s:Error: CFSTORE is not initialised.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_UNINITIALISED; goto out0; } /* only 1 flush operation can be outstanding so check whether one is already in progress */ - if(cfstore_flash_journal_is_async_op_pending(ctx)) { + if (cfstore_flash_journal_is_async_op_pending(ctx)) { CFSTORE_TP(CFSTORE_TP_FLUSH, "%s:Debug: flash journal operation pending (awaiting asynchronous notification).\n", __func__); return ARM_CFSTORE_DRIVER_ERROR_OPERATION_PENDING; } ret = cfstore_flash_flush(ctx); - if(ret < ARM_DRIVER_OK) { + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: cfstore_flash_flush() returned error (ret=%d).\n", __func__, (int) ret); goto out0; } @@ -3938,10 +3923,10 @@ static int32_t cfstore_flush(void) } /* @brief See definition in configuration_store.h for description. */ -static int32_t cfstore_initialise(ARM_CFSTORE_CALLBACK callback, void* client_context) +static int32_t cfstore_initialise(ARM_CFSTORE_CALLBACK callback, void *client_context) { - int ret = ARM_DRIVER_ERROR; - cfstore_ctx_t* ctx = cfstore_ctx_get(); + int ret = ARM_DRIVER_ERROR; + cfstore_ctx_t *ctx = cfstore_ctx_get(); #ifdef CFSTORE_CONFIG_BACKEND_FLASH_ENABLED ARM_STORAGE_CAPABILITIES storage_caps; #endif /* CFSTORE_CONFIG_BACKEND_FLASH_ENABLED */ @@ -3952,8 +3937,7 @@ static int32_t cfstore_initialise(ARM_CFSTORE_CALLBACK callback, void* client_co /* CS protection required to get into the fsm into the initing state, without another client g*/ cfstore_critical_section_lock(&ctx->rw_area0_lock, __func__); - if(ctx->init_ref_count == 0) - { + if (ctx->init_ref_count == 0) { CFSTORE_TP(CFSTORE_TP_INIT, "%s:debug: first time init\n", __func__); /* perform first time initialisation */ ctx->init_ref_count++; @@ -3964,8 +3948,8 @@ static int32_t cfstore_initialise(ARM_CFSTORE_CALLBACK callback, void* client_co ctx->area_0_tail = NULL; CFSTORE_ASSERT(sizeof(cfstore_file_t) == CFSTORE_HANDLE_BUFSIZE); - if(sizeof(cfstore_file_t) != CFSTORE_HANDLE_BUFSIZE){ - CFSTORE_ERRLOG("%s:Error: sizeof(cfstore_file_t)=(%d) != CFSTORE_HANDLE_BUFSIZE (%d)\n", __func__,(int) sizeof(cfstore_file_t), (int) CFSTORE_HANDLE_BUFSIZE); + if (sizeof(cfstore_file_t) != CFSTORE_HANDLE_BUFSIZE) { + CFSTORE_ERRLOG("%s:Error: sizeof(cfstore_file_t)=(%d) != CFSTORE_HANDLE_BUFSIZE (%d)\n", __func__, (int) sizeof(cfstore_file_t), (int) CFSTORE_HANDLE_BUFSIZE); ret = ARM_CFSTORE_DRIVER_ERROR_INTERNAL; goto out0; } @@ -3985,13 +3969,11 @@ static int32_t cfstore_initialise(ARM_CFSTORE_CALLBACK callback, void* client_co #endif /* CFSTORE_CONFIG_BACKEND_FLASH_ENABLED */ ret = cfstore_flash_init(); - if(ret < ARM_DRIVER_OK) { + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to initialise flash layer\n", __func__); goto out0; } - } - else - { + } else { CFSTORE_TP(CFSTORE_TP_INIT, "%s:debug: n-th time init\n", __func__); /* initialisation already done so only increment the ref count */ ctx->init_ref_count++; @@ -4013,49 +3995,47 @@ static int32_t cfstore_uninitialise(void) { int32_t ret = ARM_DRIVER_ERROR; ARM_STORAGE_CAPABILITIES caps; - cfstore_ctx_t* ctx = cfstore_ctx_get(); - cfstore_file_t* file; - cfstore_list_node_t* node; - cfstore_list_node_t* file_list = &ctx->file_list; + cfstore_ctx_t *ctx = cfstore_ctx_get(); + cfstore_file_t *file; + cfstore_list_node_t *node; + cfstore_list_node_t *file_list = &ctx->file_list; CFSTORE_FENTRYLOG("%s:entered\n", __func__); memset(&caps, 0, sizeof(caps)); - if(!cfstore_ctx_is_initialised(ctx)) { + if (!cfstore_ctx_is_initialised(ctx)) { CFSTORE_ERRLOG("%s:Error: CFSTORE is not initialised.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_UNINITIALISED; goto out; } /* only uninitialise when there are no flash journal async operations pending*/ - if(cfstore_flash_journal_is_async_op_pending(ctx)) { + if (cfstore_flash_journal_is_async_op_pending(ctx)) { CFSTORE_TP(CFSTORE_TP_INIT, "%s:Debug: flash journal operation pending (awaiting asynchronous notification).\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_OPERATION_PENDING; goto out; } - if(ctx->init_ref_count > 0) { + if (ctx->init_ref_count > 0) { ctx->init_ref_count--; CFSTORE_TP(CFSTORE_TP_INIT, "%s:Debug: decremented init_ref_count (%d).\n", __func__, (int) ctx->init_ref_count); } - if(ctx->init_ref_count == 0) - { + if (ctx->init_ref_count == 0) { CFSTORE_TP(CFSTORE_TP_INIT, "%s:Debug: init_ref_count == 0 (%d) so uninitialising.\n", __func__, (int) ctx->init_ref_count); /* check file list is empty and if not, free the items */ - if(ctx->file_list.next != ctx->file_list.prev) - { + if (ctx->file_list.next != ctx->file_list.prev) { /* list is not empty. walk the list and close the files, cleaning up state */ node = file_list->next; - while(node != file_list){ - file = (cfstore_file_t*) node; + while (node != file_list) { + file = (cfstore_file_t *) node; cfstore_close((ARM_CFSTORE_HANDLE) file); node = node->next; } } ret = cfstore_flash_deinit(); - if(ret < ARM_DRIVER_OK){ + if (ret < ARM_DRIVER_OK) { CFSTORE_ERRLOG("%s:Error: failed to uninitialise flash journal layer.\n", __func__); goto out; } - if(ctx->area_0_head){ + if (ctx->area_0_head) { CFSTORE_FREE(ctx->area_0_head); ctx->area_0_head = NULL; ctx->area_0_tail = NULL; @@ -4074,18 +4054,18 @@ static int32_t cfstore_uninitialise(void) static int32_t cfstore_power_control(ARM_POWER_STATE state) { int32_t ret = ARM_DRIVER_ERROR; - cfstore_ctx_t* ctx = cfstore_ctx_get(); + cfstore_ctx_t *ctx = cfstore_ctx_get(); cfstore_client_notify_data_t notify_data; CFSTORE_FENTRYLOG("%s:entered\n", __func__); - if(!cfstore_ctx_is_initialised(ctx)) { + if (!cfstore_ctx_is_initialised(ctx)) { CFSTORE_ERRLOG("%s:Error: CFSTORE is not initialised.\n", __func__); ret = ARM_CFSTORE_DRIVER_ERROR_UNINITIALISED; goto out0; } /* setting power state doesnt change the sram area so this can happen independently of * an oustanding async operation. its unnecessary to check the fsm state */ - if(state <= ARM_POWER_FULL){ + if (state <= ARM_POWER_FULL) { ctx->power_state = state; /* set return to a positive value*/ ret = (int32_t) state; @@ -4107,222 +4087,219 @@ static int32_t cfstore_power_control(ARM_POWER_STATE state) UVISOR_EXTERN int32_t __cfstore_uvisor_close(ARM_CFSTORE_HANDLE hkey) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return cfstore_close(hkey); + return cfstore_close(hkey); } static int32_t cfstore_uvisor_close(ARM_CFSTORE_HANDLE hkey) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return secure_gateway(configuration_store, __cfstore_uvisor_close, hkey); + return secure_gateway(configuration_store, __cfstore_uvisor_close, hkey); } -UVISOR_EXTERN int32_t __cfstore_uvisor_create(const char* key_name, ARM_CFSTORE_SIZE value_len, const ARM_CFSTORE_KEYDESC* kdesc, ARM_CFSTORE_HANDLE hkey) +UVISOR_EXTERN int32_t __cfstore_uvisor_create(const char *key_name, ARM_CFSTORE_SIZE value_len, const ARM_CFSTORE_KEYDESC *kdesc, ARM_CFSTORE_HANDLE hkey) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return cfstore_create(key_name, value_len, kdesc, hkey); + return cfstore_create(key_name, value_len, kdesc, hkey); } -static int32_t cfstore_uvisor_create(const char* key_name, ARM_CFSTORE_SIZE value_len, const ARM_CFSTORE_KEYDESC* kdesc, ARM_CFSTORE_HANDLE hkey) +static int32_t cfstore_uvisor_create(const char *key_name, ARM_CFSTORE_SIZE value_len, const ARM_CFSTORE_KEYDESC *kdesc, ARM_CFSTORE_HANDLE hkey) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return secure_gateway(configuration_store, __cfstore_uvisor_create, key_name, value_len, kdesc, hkey); + return secure_gateway(configuration_store, __cfstore_uvisor_create, key_name, value_len, kdesc, hkey); } UVISOR_EXTERN int32_t __cfstore_uvisor_delete(ARM_CFSTORE_HANDLE hkey) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return cfstore_delete(hkey); + return cfstore_delete(hkey); } static int32_t cfstore_uvisor_delete(ARM_CFSTORE_HANDLE hkey) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return secure_gateway(configuration_store, __cfstore_uvisor_delete, hkey); + return secure_gateway(configuration_store, __cfstore_uvisor_delete, hkey); } -UVISOR_EXTERN int32_t __cfstore_uvisor_find(const char* key_name_query, const ARM_CFSTORE_HANDLE previous, ARM_CFSTORE_HANDLE next) +UVISOR_EXTERN int32_t __cfstore_uvisor_find(const char *key_name_query, const ARM_CFSTORE_HANDLE previous, ARM_CFSTORE_HANDLE next) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return cfstore_find(key_name_query, previous, next); + return cfstore_find(key_name_query, previous, next); } -static int32_t cfstore_uvisor_find(const char* key_name_query, const ARM_CFSTORE_HANDLE previous, ARM_CFSTORE_HANDLE next) +static int32_t cfstore_uvisor_find(const char *key_name_query, const ARM_CFSTORE_HANDLE previous, ARM_CFSTORE_HANDLE next) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return secure_gateway(configuration_store, __cfstore_uvisor_find, key_name_query, previous, next); + return secure_gateway(configuration_store, __cfstore_uvisor_find, key_name_query, previous, next); } UVISOR_EXTERN int32_t __cfstore_uvisor_flush(int dummy) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - (void) dummy; - return cfstore_flush(); + (void) dummy; + return cfstore_flush(); } static int32_t cfstore_uvisor_flush(void) { - int dummy = 0; + int dummy = 0; - CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return secure_gateway(configuration_store, __cfstore_uvisor_flush, dummy); + CFSTORE_FENTRYLOG("%s:entered\n", __func__); + return secure_gateway(configuration_store, __cfstore_uvisor_flush, dummy); } -UVISOR_EXTERN int32_t __cfstore_uvisor_get_key_name(ARM_CFSTORE_HANDLE hkey, char* key_name, uint8_t *key_name_len) +UVISOR_EXTERN int32_t __cfstore_uvisor_get_key_name(ARM_CFSTORE_HANDLE hkey, char *key_name, uint8_t *key_name_len) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return cfstore_get_key_name(hkey, key_name, key_name_len); + return cfstore_get_key_name(hkey, key_name, key_name_len); } -static int32_t cfstore_uvisor_get_key_name(ARM_CFSTORE_HANDLE hkey, char* key_name, uint8_t *key_name_len) +static int32_t cfstore_uvisor_get_key_name(ARM_CFSTORE_HANDLE hkey, char *key_name, uint8_t *key_name_len) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return secure_gateway(configuration_store, __cfstore_uvisor_get_key_name, hkey, key_name, key_name_len); + return secure_gateway(configuration_store, __cfstore_uvisor_get_key_name, hkey, key_name, key_name_len); } UVISOR_EXTERN int32_t __cfstore_uvisor_get_value_len(ARM_CFSTORE_HANDLE hkey, ARM_CFSTORE_SIZE *value_len) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return cfstore_get_value_len(hkey, value_len); + return cfstore_get_value_len(hkey, value_len); } static int32_t cfstore_uvisor_get_value_len(ARM_CFSTORE_HANDLE hkey, ARM_CFSTORE_SIZE *value_len) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return secure_gateway(configuration_store, __cfstore_uvisor_get_value_len, hkey, value_len); + return secure_gateway(configuration_store, __cfstore_uvisor_get_value_len, hkey, value_len); } -UVISOR_EXTERN int32_t __cfstore_uvisor_initialize(ARM_CFSTORE_CALLBACK callback, void* client_context) +UVISOR_EXTERN int32_t __cfstore_uvisor_initialize(ARM_CFSTORE_CALLBACK callback, void *client_context) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return cfstore_initialise(callback, client_context); + return cfstore_initialise(callback, client_context); } -static int32_t cfstore_uvisor_initialise(ARM_CFSTORE_CALLBACK callback, void* client_context) +static int32_t cfstore_uvisor_initialise(ARM_CFSTORE_CALLBACK callback, void *client_context) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return secure_gateway(configuration_store, __cfstore_uvisor_initialize, callback, client_context); + return secure_gateway(configuration_store, __cfstore_uvisor_initialize, callback, client_context); } /* type to convert between ARM_CFSTORE_FMODE and uint32 for passing flags through secure gw */ -typedef union cfstore_fmode_flags_t -{ - ARM_CFSTORE_FMODE flags; - uint32_t val; +typedef union cfstore_fmode_flags_t { + ARM_CFSTORE_FMODE flags; + uint32_t val; } cfstore_fmode_flags_t; -UVISOR_EXTERN int32_t __cfstore_uvisor_open(const char* key_name, uint32_t flags, ARM_CFSTORE_HANDLE hkey) +UVISOR_EXTERN int32_t __cfstore_uvisor_open(const char *key_name, uint32_t flags, ARM_CFSTORE_HANDLE hkey) { - cfstore_fmode_flags_t uflags; + cfstore_fmode_flags_t uflags; - CFSTORE_FENTRYLOG("%s:entered\n", __func__); - uflags.val = flags; - return cfstore_open(key_name, uflags.flags, hkey); + CFSTORE_FENTRYLOG("%s:entered\n", __func__); + uflags.val = flags; + return cfstore_open(key_name, uflags.flags, hkey); } -static int32_t cfstore_uvisor_open(const char* key_name, ARM_CFSTORE_FMODE flags, ARM_CFSTORE_HANDLE hkey) +static int32_t cfstore_uvisor_open(const char *key_name, ARM_CFSTORE_FMODE flags, ARM_CFSTORE_HANDLE hkey) { - cfstore_fmode_flags_t uflags; + cfstore_fmode_flags_t uflags; CFSTORE_FENTRYLOG("%s:entered\n", __func__); uflags.flags = flags; - return secure_gateway(configuration_store, __cfstore_uvisor_open, key_name, uflags.val, hkey); + return secure_gateway(configuration_store, __cfstore_uvisor_open, key_name, uflags.val, hkey); } -UVISOR_EXTERN int32_t __cfstore_uvisor_read(ARM_CFSTORE_HANDLE hkey, void* data, ARM_CFSTORE_SIZE* len) +UVISOR_EXTERN int32_t __cfstore_uvisor_read(ARM_CFSTORE_HANDLE hkey, void *data, ARM_CFSTORE_SIZE *len) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return cfstore_read(hkey, data, len); + return cfstore_read(hkey, data, len); } -static int32_t cfstore_uvisor_read(ARM_CFSTORE_HANDLE hkey, void* data, ARM_CFSTORE_SIZE* len) +static int32_t cfstore_uvisor_read(ARM_CFSTORE_HANDLE hkey, void *data, ARM_CFSTORE_SIZE *len) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return secure_gateway(configuration_store, __cfstore_uvisor_read, hkey, data, len); + return secure_gateway(configuration_store, __cfstore_uvisor_read, hkey, data, len); } UVISOR_EXTERN int32_t __cfstore_uvisor_rseek(ARM_CFSTORE_HANDLE hkey, ARM_CFSTORE_OFFSET offset) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return cfstore_rseek(hkey, offset); + return cfstore_rseek(hkey, offset); } static int32_t cfstore_uvisor_rseek(ARM_CFSTORE_HANDLE hkey, ARM_CFSTORE_OFFSET offset) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return secure_gateway(configuration_store, __cfstore_uvisor_rseek, hkey, offset); + return secure_gateway(configuration_store, __cfstore_uvisor_rseek, hkey, offset); } UVISOR_EXTERN int32_t __cfstore_uvisor_uninitialise(int dummy) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - (void) dummy; - return cfstore_uninitialise(); + (void) dummy; + return cfstore_uninitialise(); } static int32_t cfstore_uvisor_uninitialize(void) { - int dummy = 0; + int dummy = 0; CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return secure_gateway(configuration_store, __cfstore_uvisor_uninitialise, dummy); + return secure_gateway(configuration_store, __cfstore_uvisor_uninitialise, dummy); } -UVISOR_EXTERN int32_t __cfstore_uvisor_write(ARM_CFSTORE_HANDLE hkey, const char* data, ARM_CFSTORE_SIZE* len) +UVISOR_EXTERN int32_t __cfstore_uvisor_write(ARM_CFSTORE_HANDLE hkey, const char *data, ARM_CFSTORE_SIZE *len) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return cfstore_write(hkey, data, len); + return cfstore_write(hkey, data, len); } -static int32_t cfstore_uvisor_write(ARM_CFSTORE_HANDLE hkey, const char* data, ARM_CFSTORE_SIZE* len) +static int32_t cfstore_uvisor_write(ARM_CFSTORE_HANDLE hkey, const char *data, ARM_CFSTORE_SIZE *len) { CFSTORE_FENTRYLOG("%s:entered\n", __func__); - return secure_gateway(configuration_store, __cfstore_uvisor_write, hkey, data, len); -} - - -ARM_CFSTORE_DRIVER cfstore_driver = -{ - .Close = cfstore_uvisor_close, - .Create = cfstore_uvisor_create, - .Delete= cfstore_uvisor_delete, - .Find = cfstore_uvisor_find, - .Flush = cfstore_uvisor_flush, - .GetCapabilities = cfstore_get_capabilities, - .GetKeyName = cfstore_uvisor_get_key_name, - .GetStatus = cfstore_get_status, - .GetValueLen = cfstore_uvisor_get_value_len, - .GetVersion = cfstore_get_version, - .Initialize = cfstore_uvisor_initialise, - .Open = cfstore_uvisor_open, - .PowerControl = cfstore_power_control, - .Read = cfstore_uvisor_read, - .Rseek = cfstore_uvisor_rseek, - .Uninitialize = cfstore_uvisor_uninitialize, - .Write = cfstore_uvisor_write, + return secure_gateway(configuration_store, __cfstore_uvisor_write, hkey, data, len); +} + + +ARM_CFSTORE_DRIVER cfstore_driver = { + .Close = cfstore_uvisor_close, + .Create = cfstore_uvisor_create, + .Delete = cfstore_uvisor_delete, + .Find = cfstore_uvisor_find, + .Flush = cfstore_uvisor_flush, + .GetCapabilities = cfstore_get_capabilities, + .GetKeyName = cfstore_uvisor_get_key_name, + .GetStatus = cfstore_get_status, + .GetValueLen = cfstore_uvisor_get_value_len, + .GetVersion = cfstore_get_version, + .Initialize = cfstore_uvisor_initialise, + .Open = cfstore_uvisor_open, + .PowerControl = cfstore_power_control, + .Read = cfstore_uvisor_read, + .Rseek = cfstore_uvisor_rseek, + .Uninitialize = cfstore_uvisor_uninitialize, + .Write = cfstore_uvisor_write, }; #else /* non-uvisor interface */ -ARM_CFSTORE_DRIVER cfstore_driver = -{ - .Close = cfstore_close, - .Create = cfstore_create, - .Delete= cfstore_delete, - .Find = cfstore_find, - .Flush = cfstore_flush, - .GetCapabilities = cfstore_get_capabilities, - .GetKeyName = cfstore_get_key_name, - .GetStatus = cfstore_get_status, - .GetValueLen = cfstore_get_value_len, - .GetVersion = cfstore_get_version, - .Initialize = cfstore_initialise, - .Open = cfstore_open, - .PowerControl = cfstore_power_control, - .Read = cfstore_read, - .Rseek = cfstore_rseek, - .Uninitialize = cfstore_uninitialise, - .Write = cfstore_write, +ARM_CFSTORE_DRIVER cfstore_driver = { + .Close = cfstore_close, + .Create = cfstore_create, + .Delete = cfstore_delete, + .Find = cfstore_find, + .Flush = cfstore_flush, + .GetCapabilities = cfstore_get_capabilities, + .GetKeyName = cfstore_get_key_name, + .GetStatus = cfstore_get_status, + .GetValueLen = cfstore_get_value_len, + .GetVersion = cfstore_get_version, + .Initialize = cfstore_initialise, + .Open = cfstore_open, + .PowerControl = cfstore_power_control, + .Read = cfstore_read, + .Rseek = cfstore_rseek, + .Uninitialize = cfstore_uninitialise, + .Write = cfstore_write, }; #endif /* YOTTA_CFG_CFSTORE_UVISOR */ diff --git a/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/flash_journal_crc.c b/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/flash_journal_crc.c index 41627f1c22b..e6d463c642a 100644 --- a/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/flash_journal_crc.c +++ b/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/flash_journal_crc.c @@ -76,13 +76,11 @@ reflect(uint32_t data, unsigned char nBits) /* * Reflect the data about the center bit. */ - for (bit = 0; bit < nBits; ++bit) - { + for (bit = 0; bit < nBits; ++bit) { /* * If the LSB bit is set, set the reflection of it. */ - if (data & 0x01) - { + if (data & 0x01) { reflection |= (1 << ((nBits - 1) - bit)); } @@ -121,8 +119,7 @@ flashJournalCrcInit(void) /* * Compute the remainder of each possible dividend. */ - for (dividend = 0; dividend < 256; ++dividend) - { + for (dividend = 0; dividend < 256; ++dividend) { /* * Start with the dividend followed by zeros. */ @@ -131,17 +128,13 @@ flashJournalCrcInit(void) /* * Perform modulo-2 division, a bit at a time. */ - for (bit = 8; bit > 0; --bit) - { + for (bit = 8; bit > 0; --bit) { /* * Try to divide the current data bit. */ - if (remainder & TOPBIT) - { + if (remainder & TOPBIT) { remainder = (remainder << 1) ^ POLYNOMIAL; - } - else - { + } else { remainder = (remainder << 1); } } @@ -205,8 +198,7 @@ flashJournalCrcCummulative(unsigned char const message[], int nBytes) /* * Divide the message by the polynomial, a byte at a time. */ - for (byte = 0; byte < nBytes; ++byte) - { + for (byte = 0; byte < nBytes; ++byte) { data = REFLECT_DATA(message[byte]) ^ (crcEngineRemainder >> (WIDTH - 8)); crcEngineRemainder = crcTable[data] ^ (crcEngineRemainder << 8); } diff --git a/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/flash_journal_private.h b/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/flash_journal_private.h index f2c2a9f14fb..595c5bee8c8 100644 --- a/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/flash_journal_private.h +++ b/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/flash_journal_private.h @@ -24,10 +24,12 @@ extern "C" { #include "flash-journal/flash_journal.h" -static inline uint32_t roundUp_uint32(uint32_t N, uint32_t BOUNDARY) { +static inline uint32_t roundUp_uint32(uint32_t N, uint32_t BOUNDARY) +{ return ((((N) + (BOUNDARY) - 1) / (BOUNDARY)) * (BOUNDARY)); } -static inline uint32_t roundDown_uint32(uint32_t N, uint32_t BOUNDARY) { +static inline uint32_t roundDown_uint32(uint32_t N, uint32_t BOUNDARY) +{ return (((N) / (BOUNDARY)) * (BOUNDARY)); } @@ -164,7 +166,7 @@ typedef struct _SequentialFlashJournal_t { * FlashJournal_t. The caller will only allocate a FlashJournal_t and expect the * Sequential Strategy to reuse that space for a SequentialFlashJournal_t. */ -typedef char AssertSequentialJournalSizeLessThanOrEqualToGenericJournal[sizeof(SequentialFlashJournal_t)<=sizeof(FlashJournal_t)?1:-1]; +typedef char AssertSequentialJournalSizeLessThanOrEqualToGenericJournal[sizeof(SequentialFlashJournal_t) <= sizeof(FlashJournal_t) ? 1 : -1]; #define SLOT_ADDRESS(JOURNAL, INDEX) ((JOURNAL)->mtdStartOffset + (JOURNAL)->firstSlotOffset + ((INDEX) * (JOURNAL)->sizeofSlot)) diff --git a/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/flash_journal_strategy_sequential.h b/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/flash_journal_strategy_sequential.h index 3b1c7ac38d1..04ed4ad5e9f 100644 --- a/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/flash_journal_strategy_sequential.h +++ b/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/flash_journal_strategy_sequential.h @@ -126,13 +126,13 @@ extern "C" { * +-------------------------------+ v */ int32_t flashJournalStrategySequential_format(ARM_DRIVER_STORAGE *mtd, - uint32_t numSlots, - FlashJournal_Callback_t callback); + uint32_t numSlots, + FlashJournal_Callback_t callback); int32_t flashJournalStrategySequential_initialize(FlashJournal_t *journal, - ARM_DRIVER_STORAGE *mtd, - const FlashJournal_Ops_t *ops, - FlashJournal_Callback_t callback); + ARM_DRIVER_STORAGE *mtd, + const FlashJournal_Ops_t *ops, + FlashJournal_Callback_t callback); FlashJournal_Status_t flashJournalStrategySequential_getInfo(FlashJournal_t *journal, FlashJournal_Info_t *info); int32_t flashJournalStrategySequential_read(FlashJournal_t *journal, void *blob, size_t n); int32_t flashJournalStrategySequential_readFrom(FlashJournal_t *journal, size_t offset, void *blob, size_t n); diff --git a/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/strategy.c b/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/strategy.c index 598e206da1c..84e3c7539f2 100644 --- a/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/strategy.c +++ b/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/strategy.c @@ -35,8 +35,8 @@ static inline int32_t flashJournalStrategySequential_commit_sanityChecks(Sequent int32_t flashJournalStrategySequential_format(ARM_DRIVER_STORAGE *mtd, - uint32_t numSlots, - FlashJournal_Callback_t callback) + uint32_t numSlots, + FlashJournal_Callback_t callback) { int32_t rc; if ((rc = flashJournalStrategySequential_format_sanityChecks(mtd, numSlots)) != JOURNAL_STATUS_OK) { @@ -105,10 +105,10 @@ int32_t readAndVerifyJournalHeader(SequentialFlashJournal_t *journal, Sequential } if ((headerP->genericHeader.magic != FLASH_JOURNAL_HEADER_MAGIC) || - (headerP->genericHeader.version != FLASH_JOURNAL_HEADER_VERSION) || - (headerP->genericHeader.sizeofHeader != sizeof(SequentialFlashJournalHeader_t)) || - (headerP->magic != SEQUENTIAL_FLASH_JOURNAL_HEADER_MAGIC) || - (headerP->version != SEQUENTIAL_FLASH_JOURNAL_HEADER_VERSION)) { + (headerP->genericHeader.version != FLASH_JOURNAL_HEADER_VERSION) || + (headerP->genericHeader.sizeofHeader != sizeof(SequentialFlashJournalHeader_t)) || + (headerP->magic != SEQUENTIAL_FLASH_JOURNAL_HEADER_MAGIC) || + (headerP->version != SEQUENTIAL_FLASH_JOURNAL_HEADER_VERSION)) { return JOURNAL_STATUS_NOT_FORMATTED; } @@ -125,9 +125,9 @@ int32_t readAndVerifyJournalHeader(SequentialFlashJournal_t *journal, Sequential } int32_t flashJournalStrategySequential_initialize(FlashJournal_t *_journal, - ARM_DRIVER_STORAGE *mtd, - const FlashJournal_Ops_t *ops, - FlashJournal_Callback_t callback) + ARM_DRIVER_STORAGE *mtd, + const FlashJournal_Ops_t *ops, + FlashJournal_Callback_t callback) { int32_t rc; @@ -240,7 +240,7 @@ int32_t flashJournalStrategySequential_read(FlashJournal_t *_journal, void *blob } journal->read.dataBeingRead = blob; journal->read.amountLeftToRead = ((journal->info.sizeofJournaledBlob - journal->read.logicalOffset) < sizeofBlob) ? - (journal->info.sizeofJournaledBlob - journal->read.logicalOffset) : sizeofBlob; + (journal->info.sizeofJournaledBlob - journal->read.logicalOffset) : sizeofBlob; // printf("amount left to read %u\n", journal->read.amountLeftToRead); journal->state = SEQUENTIAL_JOURNAL_STATE_READING; @@ -266,7 +266,7 @@ int32_t flashJournalStrategySequential_readFrom(FlashJournal_t *_journal, size_t journal->read.dataBeingRead = blob; journal->read.amountLeftToRead = ((journal->info.sizeofJournaledBlob - journal->read.logicalOffset) < sizeofBlob) ? - (journal->info.sizeofJournaledBlob - journal->read.logicalOffset) : sizeofBlob; + (journal->info.sizeofJournaledBlob - journal->read.logicalOffset) : sizeofBlob; // printf("amount left to read %u\n", journal->read.amountLeftToRead); journal->state = SEQUENTIAL_JOURNAL_STATE_READING; @@ -292,7 +292,7 @@ int32_t flashJournalStrategySequential_log(FlashJournal_t *_journal, const void * This is the first log in the sequence. We have to begin by identifying a new slot and erasing it. */ - /* choose the next slot */ + /* choose the next slot */ uint32_t logBlobIndex = journal->currentBlobIndex + 1; if (logBlobIndex == journal->numSlots) { logBlobIndex = 0; @@ -465,10 +465,10 @@ int32_t flashJournalStrategySequential_commit_sanityChecks(SequentialFlashJourna return JOURNAL_STATUS_ERROR; } if ((journal->log.mtdOffset == ARM_STORAGE_INVALID_OFFSET) || - (journal->log.mtdTailOffset == ARM_STORAGE_INVALID_OFFSET) || - (journal->log.mtdTailOffset < journal->log.mtdOffset) || - (journal->log.tail.sizeofBlob == 0) || - (journal->log.tail.sizeofBlob > journal->info.capacity)) { + (journal->log.mtdTailOffset == ARM_STORAGE_INVALID_OFFSET) || + (journal->log.mtdTailOffset < journal->log.mtdOffset) || + (journal->log.tail.sizeofBlob == 0) || + (journal->log.tail.sizeofBlob > journal->info.capacity)) { return JOURNAL_STATUS_ERROR; /* journal is in an un-expected state. */ } } diff --git a/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/support_funcs.c b/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/support_funcs.c index a09d6db5205..7afadcb2b78 100644 --- a/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/support_funcs.c +++ b/features/storage/FEATURE_STORAGE/flash-journal/flash-journal-strategy-sequential/support_funcs.c @@ -58,7 +58,7 @@ int32_t slotIsSane(SequentialFlashJournal_t *journal, SequentialFlashJournalLogHead_t head; /* TODO: add support for asynchronous read */ if (((rc = mtd->ReadData(slotOffset, &head, sizeof(SequentialFlashJournalLogHead_t))) < ARM_DRIVER_OK) || - (rc != sizeof(SequentialFlashJournalLogHead_t))) { + (rc != sizeof(SequentialFlashJournalLogHead_t))) { if ((rc == ARM_DRIVER_OK) && (journal->mtdCapabilities.asynchronous_ops)) { return JOURNAL_STATUS_UNSUPPORTED; } @@ -87,7 +87,7 @@ int32_t slotIsSane(SequentialFlashJournal_t *journal, /* TODO: add support for asynchronous read */ if (((rc = mtd->ReadData(tailoffset, tailP, sizeof(SequentialFlashJournalLogTail_t))) < ARM_DRIVER_OK) || - (rc != sizeof(SequentialFlashJournalLogTail_t))) { + (rc != sizeof(SequentialFlashJournalLogTail_t))) { return JOURNAL_STATUS_STORAGE_IO_ERROR; } @@ -95,7 +95,7 @@ int32_t slotIsSane(SequentialFlashJournal_t *journal, // printf("found valid tail\n"); /* iterate over the body of the slot computing CRC */ - #define CRC_CHUNK_SIZE 64 +#define CRC_CHUNK_SIZE 64 uint8_t crcBuffer[CRC_CHUNK_SIZE]; uint64_t bodyIndex = 0; uint64_t bodyOffset = slotOffset + sizeof(SequentialFlashJournalLogHead_t); @@ -193,8 +193,8 @@ int32_t discoverLatestLoggedBlob(SequentialFlashJournal_t *journal) // printf("discoverLatestLoggedBlob: start of init scan\n"); for (unsigned blobIndex = 0; - blobIndex < journal->numSlots; - blobIndex++, journal->initScan.currentOffset += journal->sizeofSlot) { + blobIndex < journal->numSlots; + blobIndex++, journal->initScan.currentOffset += journal->sizeofSlot) { // printf("discoverLatestLoggedBlob: blob index %u\n", blobIndex); /* TODO: it is possible that the header structure spans multiple blocks, needing multiple reads. */ @@ -210,14 +210,14 @@ int32_t discoverLatestLoggedBlob(SequentialFlashJournal_t *journal) /* Have we found the best of the slots seen so far? */ if ((journal->nextSequenceNumber == SEQUENTIAL_FLASH_JOURNAL_INVALD_NEXT_SEQUENCE_NUMBER) || - /* We take advantage of properties of unsigned arithmetic in the following - * expression. - * - * We want to calculate if (nextSequenceNumber > journal->nextSequenceNumber), - * instead we use the expression ((nextSequenceNumber - journal->nextSequenceNumber) > 0) - * to take wraparounds into account. - */ - ((int32_t)(nextSequenceNumber - journal->nextSequenceNumber) > 0)) { + /* We take advantage of properties of unsigned arithmetic in the following + * expression. + * + * We want to calculate if (nextSequenceNumber > journal->nextSequenceNumber), + * instead we use the expression ((nextSequenceNumber - journal->nextSequenceNumber) > 0) + * to take wraparounds into account. + */ + ((int32_t)(nextSequenceNumber - journal->nextSequenceNumber) > 0)) { journal->currentBlobIndex = blobIndex; journal->nextSequenceNumber = nextSequenceNumber; journal->info.sizeofJournaledBlob = journal->initScan.tail.sizeofBlob; @@ -231,7 +231,7 @@ int32_t discoverLatestLoggedBlob(SequentialFlashJournal_t *journal) /* Handle the case where our scan hasn't yielded any results. */ if (journal->nextSequenceNumber == SEQUENTIAL_FLASH_JOURNAL_INVALD_NEXT_SEQUENCE_NUMBER) { // printf("discoverLatestLoggedBlob: initializing to defaults\n"); - journal->currentBlobIndex = (uint32_t)-1; /* to be incremented to 0 during the first attempt to log(). */ + journal->currentBlobIndex = (uint32_t) -1; /* to be incremented to 0 during the first attempt to log(). */ journal->nextSequenceNumber = 0; } @@ -271,7 +271,7 @@ int32_t flashJournalStrategySequential_format_progress(int32_t status, ARM_STORA /* handle synchronous completion of programData */ status = rc; - /* intentional fall-through */ + /* intentional fall-through */ case ARM_STORAGE_OPERATION_ERASE: if (status != (int32_t)sizeofErase) { @@ -294,7 +294,7 @@ int32_t flashJournalStrategySequential_format_progress(int32_t status, ARM_STORA /* handle synchronous completion of programData */ status = rc; - /* intentional fall-through */ + /* intentional fall-through */ case ARM_STORAGE_OPERATION_PROGRAM_DATA: if (status != (int32_t)sizeofWrite) { @@ -328,7 +328,7 @@ int32_t flashJournalStrategySequential_reset_progress(void) /* else we fall through to handle synchronous completion */ journal->nextSequenceNumber = 0; - journal->currentBlobIndex = (uint32_t)-1; + journal->currentBlobIndex = (uint32_t) -1; journal->info.sizeofJournaledBlob = 0; journal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; return 1; @@ -347,7 +347,7 @@ int32_t flashJournalStrategySequential_read_progress(void) ARM_STORAGE_BLOCK storageBlock; if ((journal->read.amountLeftToRead) && - ((rc = journal->mtd->GetBlock(journal->read.mtdOffset, &storageBlock)) != ARM_DRIVER_OK)) { + ((rc = journal->mtd->GetBlock(journal->read.mtdOffset, &storageBlock)) != ARM_DRIVER_OK)) { journal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; /* reset state */ return JOURNAL_STATUS_STORAGE_API_ERROR; } @@ -366,7 +366,7 @@ int32_t flashJournalStrategySequential_read_progress(void) /* compute the transfer size for this iteration. */ uint32_t xfer = (journal->read.amountLeftToRead < storageBlockAvailableCapacity) ? - journal->read.amountLeftToRead : storageBlockAvailableCapacity; + journal->read.amountLeftToRead : storageBlockAvailableCapacity; /* perform the IO */ //printf("reading %lu bytes at offset %lu\n", xfer, (uint32_t)journal->read.mtdOffset); @@ -401,9 +401,9 @@ int32_t flashJournalStrategySequential_log_progress(void) SequentialFlashJournal_t *journal = activeJournal; if ((journal->state != SEQUENTIAL_JOURNAL_STATE_LOGGING_ERASE) && - (journal->state != SEQUENTIAL_JOURNAL_STATE_LOGGING_HEAD) && - (journal->state != SEQUENTIAL_JOURNAL_STATE_LOGGING_BODY) && - (journal->state != SEQUENTIAL_JOURNAL_STATE_LOGGING_TAIL)) { + (journal->state != SEQUENTIAL_JOURNAL_STATE_LOGGING_HEAD) && + (journal->state != SEQUENTIAL_JOURNAL_STATE_LOGGING_BODY) && + (journal->state != SEQUENTIAL_JOURNAL_STATE_LOGGING_TAIL)) { return JOURNAL_STATUS_ERROR; /* journal is in an un-expected state. */ } @@ -654,7 +654,7 @@ void mtdHandler(int32_t status, ARM_STORAGE_OPERATION operation) case ARM_STORAGE_OPERATION_ERASE_ALL: if (activeJournal->state == SEQUENTIAL_JOURNAL_STATE_RESETING) { activeJournal->nextSequenceNumber = 0; - activeJournal->currentBlobIndex = (uint32_t)-1; + activeJournal->currentBlobIndex = (uint32_t) -1; activeJournal->info.sizeofJournaledBlob = 0; activeJournal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; if (activeJournal->callback) { @@ -683,7 +683,7 @@ void mtdHandler(int32_t status, ARM_STORAGE_OPERATION operation) } } else if (activeJournal->state == SEQUENTIAL_JOURNAL_STATE_RESETING) { activeJournal->nextSequenceNumber = 0; - activeJournal->currentBlobIndex = (uint32_t)-1; + activeJournal->currentBlobIndex = (uint32_t) -1; activeJournal->info.sizeofJournaledBlob = 0; activeJournal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; if (activeJournal->callback) { @@ -707,7 +707,7 @@ void mtdHandler(int32_t status, ARM_STORAGE_OPERATION operation) if (activeJournal->callback) { activeJournal->callback(rc, (activeJournal->state == SEQUENTIAL_JOURNAL_STATE_LOGGING_TAIL) ? - FLASH_JOURNAL_OPCODE_COMMIT : FLASH_JOURNAL_OPCODE_LOG_BLOB); + FLASH_JOURNAL_OPCODE_COMMIT : FLASH_JOURNAL_OPCODE_LOG_BLOB); } return; } @@ -716,7 +716,7 @@ void mtdHandler(int32_t status, ARM_STORAGE_OPERATION operation) } if (activeJournal->callback) { activeJournal->callback(rc, (activeJournal->state == SEQUENTIAL_JOURNAL_STATE_INITIALIZED) ? - FLASH_JOURNAL_OPCODE_COMMIT : FLASH_JOURNAL_OPCODE_LOG_BLOB); + FLASH_JOURNAL_OPCODE_COMMIT : FLASH_JOURNAL_OPCODE_LOG_BLOB); } break; diff --git a/features/storage/FEATURE_STORAGE/flash-journal/flash_journal.h b/features/storage/FEATURE_STORAGE/flash-journal/flash_journal.h index 07a0ad68119..b11e9a1964b 100644 --- a/features/storage/FEATURE_STORAGE/flash-journal/flash_journal.h +++ b/features/storage/FEATURE_STORAGE/flash-journal/flash_journal.h @@ -30,8 +30,7 @@ extern "C" { * both error and success status returns. This enumeration contains all * possible error status values. */ -typedef enum _FlashJournal_Status -{ +typedef enum _FlashJournal_Status { JOURNAL_STATUS_OK = 0, JOURNAL_STATUS_ERROR = -1, ///< Unspecified error JOURNAL_STATUS_BUSY = -2, ///< Underlying storage is currently unavailable @@ -71,13 +70,13 @@ typedef struct _FlashJournal_Info { uint64_t capacity; ///< Maximum capacity (in octets) of the flash journal--i.e. the largest 'blob' which can be contained as payload. uint64_t sizeofJournaledBlob; ///< size (in octets) of the most recently logged blob. uint32_t program_unit; ///< Minimum programming size (in units of octets) for - ///< the current storage block--the one which will be used - ///< for the next log() operation. This value may change as we - ///< cycle through the blocks of the underlying MTD. - ///< Callers of FlashJournal_log() should refer to this field - ///< upon receiving the error JOURNAL_STATUS_SMALL_LOG_REQUEST - ///< (of when the actual amount of data logged is smaller than - ///< the requested amount). + ///< the current storage block--the one which will be used + ///< for the next log() operation. This value may change as we + ///< cycle through the blocks of the underlying MTD. + ///< Callers of FlashJournal_log() should refer to this field + ///< upon receiving the error JOURNAL_STATUS_SMALL_LOG_REQUEST + ///< (of when the actual amount of data logged is smaller than + ///< the requested amount). } FlashJournal_Info_t; @@ -148,42 +147,42 @@ typedef struct FlashJournal_Ops_t { /** * \brief Initialize the flash journal. Refer to @ref FlashJournal_initialize. */ - int32_t (*initialize)(struct FlashJournal_t *journal, - ARM_DRIVER_STORAGE *mtd, - const struct FlashJournal_Ops_t *ops, - FlashJournal_Callback_t callback); + int32_t (*initialize)(struct FlashJournal_t *journal, + ARM_DRIVER_STORAGE *mtd, + const struct FlashJournal_Ops_t *ops, + FlashJournal_Callback_t callback); /** * \brief fetch journal metadata. Refer to @ref FlashJournal_getInfo. */ - FlashJournal_Status_t (*getInfo) (struct FlashJournal_t *journal, FlashJournal_Info_t *info); + FlashJournal_Status_t (*getInfo)(struct FlashJournal_t *journal, FlashJournal_Info_t *info); /** * @brief Read from the most recently logged blob. Refer to @ref FlashJournal_read. */ - int32_t (*read) (struct FlashJournal_t *journal, void *buffer, size_t size); + int32_t (*read)(struct FlashJournal_t *journal, void *buffer, size_t size); /** * @brief Read from the most recently logged blob from a particular offset. Refer to @ref FlashJournal_readFrom. */ - int32_t (*readFrom) (struct FlashJournal_t *journal, size_t offset, void *buffer, size_t size); + int32_t (*readFrom)(struct FlashJournal_t *journal, size_t offset, void *buffer, size_t size); /** * @brief Start logging a new blob or append to the one currently being logged. Refer to @ref FlashJournal_log. */ - int32_t (*log) (struct FlashJournal_t *journal, const void *blob, size_t size); + int32_t (*log)(struct FlashJournal_t *journal, const void *blob, size_t size); /** * @brief commit a blob accumulated through a non-empty sequence of * previously successful log() operations. Refer to @ref FlashJournal_commit. */ - int32_t (*commit) (struct FlashJournal_t *journal); + int32_t (*commit)(struct FlashJournal_t *journal); /** * @brief Reset the journal. This has the effect of erasing all valid blobs. * Refer to @ref FlashJournal_reset. */ - int32_t (*reset) (struct FlashJournal_t *journal); + int32_t (*reset)(struct FlashJournal_t *journal); } FlashJournal_Ops_t; /** @@ -292,9 +291,9 @@ typedef struct FlashJournal_t { MBED_DEPRECATED_SINCE("mbed-os-5.5", "FlashJournal is deprecated. " "Use a BlockDevice or filesystem instead") static inline int32_t FlashJournal_initialize(FlashJournal_t *journal, - ARM_DRIVER_STORAGE *mtd, - const FlashJournal_Ops_t *ops, - FlashJournal_Callback_t callback) + ARM_DRIVER_STORAGE *mtd, + const FlashJournal_Ops_t *ops, + FlashJournal_Callback_t callback) { return ops->initialize(journal, mtd, ops, callback); } diff --git a/features/storage/FEATURE_STORAGE/storage-volume-manager/source/storage_volume.cpp b/features/storage/FEATURE_STORAGE/storage-volume-manager/source/storage_volume.cpp index 8d221c77c9d..43e4351a4d0 100644 --- a/features/storage/FEATURE_STORAGE/storage-volume-manager/source/storage_volume.cpp +++ b/features/storage/FEATURE_STORAGE/storage-volume-manager/source/storage_volume.cpp @@ -212,11 +212,12 @@ int32_t StorageVolume::GetInfo(ARM_STORAGE_INFO *infoP) return ARM_DRIVER_OK; } -uint32_t StorageVolume::ResolveAddress(uint64_t addr) { +uint32_t StorageVolume::ResolveAddress(uint64_t addr) +{ return (uint32_t)(volumeOffset + addr); } -int32_t StorageVolume::GetNextBlock(const ARM_STORAGE_BLOCK* prevP, ARM_STORAGE_BLOCK *nextP) +int32_t StorageVolume::GetNextBlock(const ARM_STORAGE_BLOCK *prevP, ARM_STORAGE_BLOCK *nextP) { int32_t rc; ARM_STORAGE_BLOCK tmpBlock; diff --git a/features/storage/FEATURE_STORAGE/storage-volume-manager/source/storage_volume_manager.cpp b/features/storage/FEATURE_STORAGE/storage-volume-manager/source/storage_volume_manager.cpp index 97282cda5e1..59e39cbaf0f 100644 --- a/features/storage/FEATURE_STORAGE/storage-volume-manager/source/storage_volume_manager.cpp +++ b/features/storage/FEATURE_STORAGE/storage-volume-manager/source/storage_volume_manager.cpp @@ -176,7 +176,7 @@ int32_t StorageVolumeManager::addVolume(uint64_t addr, uint64_t size, StorageVol } if ((addr < firstBlock.addr) || ((addr + size) > (firstBlock.addr + info.total_storage))) { tr_error("StorageVolumeManager_addVolume: given range [%" PRIu32 ", %" PRIu32 ") isn't entirely contained within available storage range [%" PRIu32 ", %" PRIu32 ")", - (uint32_t)addr, (uint32_t)(addr + size), (uint32_t)firstBlock.addr, (uint32_t)(firstBlock.addr + info.total_storage)); + (uint32_t)addr, (uint32_t)(addr + size), (uint32_t)firstBlock.addr, (uint32_t)(firstBlock.addr + info.total_storage)); return ARM_DRIVER_ERROR; } @@ -282,7 +282,8 @@ void StorageVolumeManager::storageCallback(int32_t status, ARM_STORAGE_OPERATION } } -size_t StorageVolumeManager::findIndexOfUnusedVolume(void) const { +size_t StorageVolumeManager::findIndexOfUnusedVolume(void) const +{ size_t index; for (index = 0; index < MAX_VOLUMES; index++) { if (!volumes[index].isAllocated()) { diff --git a/features/storage/FEATURE_STORAGE/storage-volume-manager/storage-volume-manager/storage_volume_manager.h b/features/storage/FEATURE_STORAGE/storage-volume-manager/storage-volume-manager/storage_volume_manager.h index d01376989a5..1fdb1445428 100644 --- a/features/storage/FEATURE_STORAGE/storage-volume-manager/storage-volume-manager/storage_volume_manager.h +++ b/features/storage/FEATURE_STORAGE/storage-volume-manager/storage-volume-manager/storage_volume_manager.h @@ -36,7 +36,7 @@ * Sequential Strategy to reuse that space for a SequentialFlashJournal_t. */ #ifndef __ICCARM__ -typedef char AssertStorageVolumeManagerMaxVolumesIsSane[(((MAX_VOLUMES) > 0) && ((MAX_VOLUMES) <= 8)) ? 0:-1]; +typedef char AssertStorageVolumeManagerMaxVolumesIsSane[(((MAX_VOLUMES) > 0) &&((MAX_VOLUMES) <= 8)) ? 0 : -1]; #endif #define CONCATENATE(A, B) A ## B @@ -74,8 +74,7 @@ STORAGE_API_EXTERN_C_DECLARATIONS_LIST(MAX_VOLUMES); * int32_t to allow for both error and success status returns. This enumeration * contains all possible error status values. */ -typedef enum _StorageVolumeManager_Status -{ +typedef enum _StorageVolumeManager_Status { STORAGE_VOLUME_MANAGER_STATUS_ERROR_EXHASTED_VOLUMES = -7, ///< exhausted the supply of available volumes STORAGE_VOLUME_MANAGER_STATUS_ERROR_NOT_ERASABLE = -8, ///< Part (or all) of the range provided to Erase() isn't erasable. STORAGE_VOLUME_MANAGER_STATUS_ERROR_NOT_PROGRAMMABLE = -9, ///< Part (or all) of the range provided to ProgramData() isn't programmable. @@ -112,15 +111,17 @@ class StorageVolume { ARM_STORAGE_STATUS GetStatus(void); int32_t GetInfo(ARM_STORAGE_INFO *infoP); uint32_t ResolveAddress(uint64_t addr); - int32_t GetNextBlock(const ARM_STORAGE_BLOCK* prevP, ARM_STORAGE_BLOCK *nextP); + int32_t GetNextBlock(const ARM_STORAGE_BLOCK *prevP, ARM_STORAGE_BLOCK *nextP); int32_t GetBlock(uint64_t addr, ARM_STORAGE_BLOCK *blockP); public: - bool isAllocated(void) const { + bool isAllocated(void) const + { return allocated; } - void deallocate(void) { + void deallocate(void) + { allocated = false; } @@ -128,22 +129,27 @@ class StorageVolume { * Accessor methods. */ - uint64_t getVolumeOffset(void) const { + uint64_t getVolumeOffset(void) const + { return volumeOffset; } - uint64_t getVolumeSize(void) const { + uint64_t getVolumeSize(void) const + { return volumeSize; } - const ARM_Storage_Callback_t &getCallback(void) const { + const ARM_Storage_Callback_t &getCallback(void) const + { return callback; } private: - bool overlapsWithBlock(const ARM_STORAGE_BLOCK* blockP) const { + bool overlapsWithBlock(const ARM_STORAGE_BLOCK *blockP) const + { return (((blockP->addr + blockP->size) <= volumeOffset) || ((volumeOffset + volumeSize) <= blockP->addr)) ? false : true; } - void transformBlockToVolume(ARM_STORAGE_BLOCK *blockP) const { + void transformBlockToVolume(ARM_STORAGE_BLOCK *blockP) const + { if (blockP->addr < volumeOffset) { blockP->addr = volumeOffset; } @@ -194,19 +200,24 @@ class StorageVolumeManager { * Accessor methods. */ - bool isInitialized() const { + bool isInitialized() const + { return initialized; } - ARM_DRIVER_STORAGE *getStorage(void) const { + ARM_DRIVER_STORAGE *getStorage(void) const + { return storage; } - const ARM_STORAGE_INFO &getStorageInfo(void) const { + const ARM_STORAGE_INFO &getStorageInfo(void) const + { return storageInfo; } - const ARM_STORAGE_CAPABILITIES &getStorageCapabilities(void) const { + const ARM_STORAGE_CAPABILITIES &getStorageCapabilities(void) const + { return storageCapabilities; } - StorageVolume *volumeAtIndex(size_t index) { + StorageVolume *volumeAtIndex(size_t index) + { return &volumes[index]; } @@ -248,7 +259,7 @@ class StorageVolumeManager { #define FRIEND_DECLARATIONS_FOR_STORAGE_API_INSTANCES_FOR_2 FRIEND_DECLARATIONS_FOR_STORAGE_API_INSTANCES_FOR_1 FRIEND_DECLARATIONS_FOR_VOLUME(1) #define FRIEND_DECLARATIONS_FOR_STORAGE_API_INSTANCES_FOR_3 FRIEND_DECLARATIONS_FOR_STORAGE_API_INSTANCES_FOR_2 FRIEND_DECLARATIONS_FOR_VOLUME(2) #define FRIEND_DECLARATIONS_FOR_STORAGE_API_INSTANCES_FOR_4 FRIEND_DECLARATIONS_FOR_STORAGE_API_INSTANCES_FOR_3 FRIEND_DECLARATIONS_FOR_VOLUME(3) -/* ... add more of the above if ever needed */ + /* ... add more of the above if ever needed */ #define FRIEND_DECLARATIONS_FOR_STORAGE_API_INSTANCES(N) EXPAND(CONCATENATE(FRIEND_DECLARATIONS_FOR_STORAGE_API_INSTANCES_FOR_, N)) diff --git a/hal/TARGET_FLASH_CMSIS_ALGO/flash_data.h b/hal/TARGET_FLASH_CMSIS_ALGO/flash_data.h index e905ad22a3c..f13734c4900 100644 --- a/hal/TARGET_FLASH_CMSIS_ALGO/flash_data.h +++ b/hal/TARGET_FLASH_CMSIS_ALGO/flash_data.h @@ -56,7 +56,7 @@ typedef struct { uint32_t pc; } args_t; -typedef int32_t (*flash_algo_jump_t)(args_t*); +typedef int32_t (*flash_algo_jump_t)(args_t *); // prototypes for flash algo CMSIS API diff --git a/hal/can_api.h b/hal/can_api.h index 723342f0821..7fb63905115 100644 --- a/hal/can_api.h +++ b/hal/can_api.h @@ -57,23 +57,23 @@ typedef void (*can_irq_handler)(uint32_t id, CanIrqType type); typedef struct can_s can_t; -void can_init (can_t *obj, PinName rd, PinName td); -void can_init_freq (can_t *obj, PinName rd, PinName td, int hz); -void can_free (can_t *obj); -int can_frequency (can_t *obj, int hz); - -void can_irq_init (can_t *obj, can_irq_handler handler, uint32_t id); -void can_irq_free (can_t *obj); -void can_irq_set (can_t *obj, CanIrqType irq, uint32_t enable); - -int can_write (can_t *obj, CAN_Message, int cc); -int can_read (can_t *obj, CAN_Message *msg, int handle); -int can_mode (can_t *obj, CanMode mode); +void can_init(can_t *obj, PinName rd, PinName td); +void can_init_freq(can_t *obj, PinName rd, PinName td, int hz); +void can_free(can_t *obj); +int can_frequency(can_t *obj, int hz); + +void can_irq_init(can_t *obj, can_irq_handler handler, uint32_t id); +void can_irq_free(can_t *obj); +void can_irq_set(can_t *obj, CanIrqType irq, uint32_t enable); + +int can_write(can_t *obj, CAN_Message, int cc); +int can_read(can_t *obj, CAN_Message *msg, int handle); +int can_mode(can_t *obj, CanMode mode); int can_filter(can_t *obj, uint32_t id, uint32_t mask, CANFormat format, int32_t handle); -void can_reset (can_t *obj); -unsigned char can_rderror (can_t *obj); -unsigned char can_tderror (can_t *obj); -void can_monitor (can_t *obj, int silent); +void can_reset(can_t *obj); +unsigned char can_rderror(can_t *obj); +unsigned char can_tderror(can_t *obj); +void can_monitor(can_t *obj, int silent); #ifdef __cplusplus }; diff --git a/hal/gpio_api.h b/hal/gpio_api.h index a99fdec048e..9f11937be40 100644 --- a/hal/gpio_api.h +++ b/hal/gpio_api.h @@ -86,7 +86,7 @@ int gpio_read(gpio_t *obj); * @param gpio The GPIO object * @param pin The pin name */ -void gpio_init_in(gpio_t* gpio, PinName pin); +void gpio_init_in(gpio_t *gpio, PinName pin); /** Init the input pin and set the mode * @@ -94,7 +94,7 @@ void gpio_init_in(gpio_t* gpio, PinName pin); * @param pin The pin name * @param mode The pin mode to be set */ -void gpio_init_in_ex(gpio_t* gpio, PinName pin, PinMode mode); +void gpio_init_in_ex(gpio_t *gpio, PinName pin, PinMode mode); /** Init the output pin as an output, with predefined output value 0 * @@ -102,7 +102,7 @@ void gpio_init_in_ex(gpio_t* gpio, PinName pin, PinMode mode); * @param pin The pin name * @return An integer value 1 or 0 */ -void gpio_init_out(gpio_t* gpio, PinName pin); +void gpio_init_out(gpio_t *gpio, PinName pin); /** Init the pin as an output and set the output value * @@ -110,7 +110,7 @@ void gpio_init_out(gpio_t* gpio, PinName pin); * @param pin The pin name * @param value The value to be set */ -void gpio_init_out_ex(gpio_t* gpio, PinName pin, int value); +void gpio_init_out_ex(gpio_t *gpio, PinName pin, int value); /** Init the pin to be in/out * @@ -120,7 +120,7 @@ void gpio_init_out_ex(gpio_t* gpio, PinName pin, int value); * @param mode The pin mode to be set * @param value The value to be set for an output pin */ -void gpio_init_inout(gpio_t* gpio, PinName pin, PinDirection direction, PinMode mode, int value); +void gpio_init_inout(gpio_t *gpio, PinName pin, PinDirection direction, PinMode mode, int value); /**@}*/ diff --git a/hal/i2c_api.h b/hal/i2c_api.h index 70121930fe1..18f902369e2 100644 --- a/hal/i2c_api.h +++ b/hal/i2c_api.h @@ -58,8 +58,8 @@ typedef struct i2c_s i2c_t; #endif enum { - I2C_ERROR_NO_SLAVE = -1, - I2C_ERROR_BUS_BUSY = -2 + I2C_ERROR_NO_SLAVE = -1, + I2C_ERROR_BUS_BUSY = -2 }; #ifdef __cplusplus @@ -73,7 +73,7 @@ extern "C" { /** Initialize the I2C peripheral. It sets the default parameters for I2C * peripheral, and configures its specifieds pins. - * + * * @param obj The I2C object * @param sda The sda pin * @param scl The scl pin @@ -117,7 +117,7 @@ int i2c_read(i2c_t *obj, int address, char *data, int length, int stop); * @param data The buffer for sending * @param length Number of bytes to write * @param stop Stop to be generated after the transfer is done - * @return + * @return * zero or non-zero - Number of written bytes * negative - I2C_ERROR_XXX status */ diff --git a/hal/itm_api.h b/hal/itm_api.h index 0c5a739c43d..ef77688cdef 100644 --- a/hal/itm_api.h +++ b/hal/itm_api.h @@ -44,15 +44,15 @@ enum { /** * @brief Target specific initialization function. - * This function is responsible for initializing and configuring - * the debug clock for the ITM and setting up the SWO pin for + * This function is responsible for initializing and configuring + * the debug clock for the ITM and setting up the SWO pin for * debug output. - * + * * The only Cortex-M register that should be modified is the clock * prescaler in TPI->ACPR. - * - * The generic mbed_itm_init initialization function will setup: - * + * + * The generic mbed_itm_init initialization function will setup: + * * ITM->LAR * ITM->TPR * ITM->TCR @@ -60,7 +60,7 @@ enum { * TPI->SPPR * TPI->FFCR * DWT->CTRL - * + * * for SWO output on stimulus port 0. */ void itm_init(void); diff --git a/hal/lp_ticker_api.h b/hal/lp_ticker_api.h index d1ce69a102b..ebd5c1f6a8e 100644 --- a/hal/lp_ticker_api.h +++ b/hal/lp_ticker_api.h @@ -52,7 +52,7 @@ ticker_irq_handler_type set_lp_ticker_irq_handler(ticker_irq_handler_type ticker * * @return The low power ticker data */ -const ticker_data_t* get_lp_ticker_data(void); +const ticker_data_t *get_lp_ticker_data(void); /** The wrapper for ticker_irq_handler, to pass lp ticker's data * @@ -89,7 +89,7 @@ void lp_ticker_disable_interrupt(void); void lp_ticker_clear_interrupt(void); /** Set pending interrupt that should be fired right away. - * + * * The ticker should be initialized prior calling this function. */ void lp_ticker_fire_interrupt(void); @@ -97,7 +97,7 @@ void lp_ticker_fire_interrupt(void); /** Get frequency and counter bits of this ticker. * */ -const ticker_info_t* lp_ticker_get_info(void); +const ticker_info_t *lp_ticker_get_info(void); /**@}*/ diff --git a/hal/mbed_gpio.c b/hal/mbed_gpio.c index b9dda3f1b3b..7bf52dd76d1 100644 --- a/hal/mbed_gpio.c +++ b/hal/mbed_gpio.c @@ -15,7 +15,7 @@ */ #include "hal/gpio_api.h" -static inline void _gpio_init_in(gpio_t* gpio, PinName pin, PinMode mode) +static inline void _gpio_init_in(gpio_t *gpio, PinName pin, PinMode mode) { gpio_init(gpio, pin); if (pin != NC) { @@ -24,7 +24,7 @@ static inline void _gpio_init_in(gpio_t* gpio, PinName pin, PinMode mode) } } -static inline void _gpio_init_out(gpio_t* gpio, PinName pin, PinMode mode, int value) +static inline void _gpio_init_out(gpio_t *gpio, PinName pin, PinMode mode, int value) { gpio_init(gpio, pin); if (pin != NC) { @@ -34,27 +34,33 @@ static inline void _gpio_init_out(gpio_t* gpio, PinName pin, PinMode mode, int v } } -void gpio_init_in(gpio_t* gpio, PinName pin) { +void gpio_init_in(gpio_t *gpio, PinName pin) +{ gpio_init_in_ex(gpio, pin, PullDefault); } -void gpio_init_in_ex(gpio_t* gpio, PinName pin, PinMode mode) { +void gpio_init_in_ex(gpio_t *gpio, PinName pin, PinMode mode) +{ _gpio_init_in(gpio, pin, mode); } -void gpio_init_out(gpio_t* gpio, PinName pin) { +void gpio_init_out(gpio_t *gpio, PinName pin) +{ gpio_init_out_ex(gpio, pin, 0); } -void gpio_init_out_ex(gpio_t* gpio, PinName pin, int value) { +void gpio_init_out_ex(gpio_t *gpio, PinName pin, int value) +{ _gpio_init_out(gpio, pin, PullNone, value); } -void gpio_init_inout(gpio_t* gpio, PinName pin, PinDirection direction, PinMode mode, int value) { +void gpio_init_inout(gpio_t *gpio, PinName pin, PinDirection direction, PinMode mode, int value) +{ if (direction == PIN_INPUT) { _gpio_init_in(gpio, pin, mode); - if (pin != NC) - gpio_write(gpio, value); // we prepare the value in case it is switched later + if (pin != NC) { + gpio_write(gpio, value); // we prepare the value in case it is switched later + } } else { _gpio_init_out(gpio, pin, mode, value); } diff --git a/hal/mbed_itm_api.c b/hal/mbed_itm_api.c index 5826570be21..64c116a3f6c 100644 --- a/hal/mbed_itm_api.c +++ b/hal/mbed_itm_api.c @@ -21,7 +21,7 @@ #include -#define ITM_ENABLE_WRITE 0xC5ACCE55 +#define ITM_ENABLE_WRITE 0xC5ACCE55 #define SWO_NRZ 0x02 #define SWO_STIMULUS_PORT 0x01 @@ -56,13 +56,13 @@ void mbed_itm_init(void) ITM->TPR = 0x0; /* Trace Control Register */ - ITM->TCR = (1 << ITM_TCR_TraceBusID_Pos) | - (1 << ITM_TCR_DWTENA_Pos) | + ITM->TCR = (1 << ITM_TCR_TraceBusID_Pos) | + (1 << ITM_TCR_DWTENA_Pos) | (1 << ITM_TCR_SYNCENA_Pos) | (1 << ITM_TCR_ITMENA_Pos); /* Trace Enable Register */ - ITM->TER = SWO_STIMULUS_PORT; + ITM->TER = SWO_STIMULUS_PORT; } } @@ -70,8 +70,7 @@ uint32_t mbed_itm_send(uint32_t port, uint32_t data) { /* Check if ITM and port is enabled */ if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) && /* ITM enabled */ - ((ITM->TER & (1UL << port) ) != 0UL) ) /* ITM Port enabled */ - { + ((ITM->TER & (1UL << port)) != 0UL)) { /* ITM Port enabled */ /* write data to port */ ITM->PORT[port].u32 = data; diff --git a/hal/mbed_lp_ticker_api.c b/hal/mbed_lp_ticker_api.c index 6303247568e..0c4545b3adb 100644 --- a/hal/mbed_lp_ticker_api.c +++ b/hal/mbed_lp_ticker_api.c @@ -36,7 +36,7 @@ static const ticker_data_t lp_data = { .queue = &events, }; -const ticker_data_t* get_lp_ticker_data(void) +const ticker_data_t *get_lp_ticker_data(void) { return &lp_data; } diff --git a/hal/mbed_pinmap_common.c b/hal/mbed_pinmap_common.c index 93658b27930..f1506795eec 100644 --- a/hal/mbed_pinmap_common.c +++ b/hal/mbed_pinmap_common.c @@ -16,9 +16,11 @@ #include "hal/pinmap.h" #include "platform/mbed_error.h" -void pinmap_pinout(PinName pin, const PinMap *map) { - if (pin == NC) +void pinmap_pinout(PinName pin, const PinMap *map) +{ + if (pin == NC) { return; + } while (map->pin != NC) { if (map->pin == pin) { @@ -32,58 +34,72 @@ void pinmap_pinout(PinName pin, const PinMap *map) { error("could not pinout"); } -uint32_t pinmap_merge(uint32_t a, uint32_t b) { +uint32_t pinmap_merge(uint32_t a, uint32_t b) +{ // both are the same (inc both NC) - if (a == b) + if (a == b) { return a; + } // one (or both) is not connected - if (a == (uint32_t)NC) + if (a == (uint32_t)NC) { return b; - if (b == (uint32_t)NC) + } + if (b == (uint32_t)NC) { return a; + } // mis-match error case error("pinmap mis-match"); return (uint32_t)NC; } -uint32_t pinmap_find_peripheral(PinName pin, const PinMap* map) { +uint32_t pinmap_find_peripheral(PinName pin, const PinMap *map) +{ while (map->pin != NC) { - if (map->pin == pin) + if (map->pin == pin) { return map->peripheral; + } map++; } return (uint32_t)NC; } -uint32_t pinmap_peripheral(PinName pin, const PinMap* map) { +uint32_t pinmap_peripheral(PinName pin, const PinMap *map) +{ uint32_t peripheral = (uint32_t)NC; - if (pin == (PinName)NC) + if (pin == (PinName)NC) { return (uint32_t)NC; + } peripheral = pinmap_find_peripheral(pin, map); - if ((uint32_t)NC == peripheral) // no mapping available + if ((uint32_t)NC == peripheral) { // no mapping available error("pinmap not found for peripheral"); + } return peripheral; } -uint32_t pinmap_find_function(PinName pin, const PinMap* map) { +uint32_t pinmap_find_function(PinName pin, const PinMap *map) +{ while (map->pin != NC) { - if (map->pin == pin) + if (map->pin == pin) { return map->function; + } map++; } return (uint32_t)NC; } -uint32_t pinmap_function(PinName pin, const PinMap* map) { +uint32_t pinmap_function(PinName pin, const PinMap *map) +{ uint32_t function = (uint32_t)NC; - if (pin == (PinName)NC) + if (pin == (PinName)NC) { return (uint32_t)NC; + } function = pinmap_find_function(pin, map); - if ((uint32_t)NC == function) // no mapping available + if ((uint32_t)NC == function) { // no mapping available error("pinmap not found for function"); + } return function; } diff --git a/hal/mbed_sleep_manager.c b/hal/mbed_sleep_manager.c index 79fbc58d527..d025261dea0 100644 --- a/hal/mbed_sleep_manager.c +++ b/hal/mbed_sleep_manager.c @@ -42,7 +42,7 @@ typedef struct sleep_statistic { static sleep_statistic_t sleep_stats[STATISTIC_COUNT]; -static const char* strip_path(const char* const filename) +static const char *strip_path(const char *const filename) { char *output = strrchr(filename, '/'); @@ -59,7 +59,7 @@ static const char* strip_path(const char* const filename) return filename; } -static sleep_statistic_t* sleep_tracker_find(const char *const filename) +static sleep_statistic_t *sleep_tracker_find(const char *const filename) { char temp[IDENTIFIER_WIDTH]; strncpy(temp, filename, IDENTIFIER_WIDTH); @@ -75,7 +75,7 @@ static sleep_statistic_t* sleep_tracker_find(const char *const filename) return NULL; } -static sleep_statistic_t* sleep_tracker_add(const char* const filename) +static sleep_statistic_t *sleep_tracker_add(const char *const filename) { char temp[IDENTIFIER_WIDTH]; strncpy(temp, filename, IDENTIFIER_WIDTH); @@ -109,15 +109,15 @@ static void sleep_tracker_print_stats(void) } debug("[id: %s, count: %u]\r\n", sleep_stats[i].identifier, - sleep_stats[i].count); + sleep_stats[i].count); } } -void sleep_tracker_lock(const char* const filename, int line) +void sleep_tracker_lock(const char *const filename, int line) { - const char* const stripped_path = strip_path(filename); + const char *const stripped_path = strip_path(filename); - sleep_statistic_t* stat = sleep_tracker_find(stripped_path); + sleep_statistic_t *stat = sleep_tracker_find(stripped_path); // Entry for this driver does not exist, create one. if (stat == NULL) { @@ -129,10 +129,10 @@ void sleep_tracker_lock(const char* const filename, int line) debug("LOCK: %s, ln: %i, lock count: %u\r\n", stripped_path, line, deep_sleep_lock); } -void sleep_tracker_unlock(const char* const filename, int line) +void sleep_tracker_unlock(const char *const filename, int line) { - const char* const stripped_path = strip_path(filename); - sleep_statistic_t* stat = sleep_tracker_find(stripped_path); + const char *const stripped_path = strip_path(filename); + sleep_statistic_t *stat = sleep_tracker_find(stripped_path); // Entry for this driver does not exist, something went wrong. if (stat == NULL) { diff --git a/hal/mbed_ticker_api.c b/hal/mbed_ticker_api.c index 6a200061800..adad32ff38b 100644 --- a/hal/mbed_ticker_api.c +++ b/hal/mbed_ticker_api.c @@ -23,13 +23,13 @@ static void schedule_interrupt(const ticker_data_t *const ticker); static void update_present_time(const ticker_data_t *const ticker); /* - * Initialize a ticker instance. + * Initialize a ticker instance. */ static void initialize(const ticker_data_t *ticker) { - // return if the queue has already been initialized, in that case the + // return if the queue has already been initialized, in that case the // interface used by the queue is already initialized. - if (ticker->queue->initialized) { + if (ticker->queue->initialized) { return; } @@ -49,7 +49,7 @@ static void initialize(const ticker_data_t *ticker) } uint32_t max_delta = 0x7 << (bits - 4); // 7/16th uint64_t max_delta_us = - ((uint64_t)max_delta * 1000000 + frequency - 1) / frequency; + ((uint64_t)max_delta * 1000000 + frequency - 1) / frequency; ticker->queue->event_handler = NULL; ticker->queue->head = NULL; @@ -61,13 +61,13 @@ static void initialize(const ticker_data_t *ticker) ticker->queue->max_delta_us = max_delta_us; ticker->queue->present_time = 0; ticker->queue->initialized = true; - + update_present_time(ticker); schedule_interrupt(ticker); } /** - * Set the event handler function of a ticker instance. + * Set the event handler function of a ticker instance. */ static void set_handler(const ticker_data_t *const ticker, ticker_event_handler handler) { @@ -77,18 +77,18 @@ static void set_handler(const ticker_data_t *const ticker, ticker_event_handler /* * Convert a 32 bit timestamp into a 64 bit timestamp. * - * A 64 bit timestamp is used as the point of time of reference while the - * timestamp to convert is relative to this point of time. + * A 64 bit timestamp is used as the point of time of reference while the + * timestamp to convert is relative to this point of time. + * + * The lower 32 bits of the timestamp returned will be equal to the timestamp to + * convert. * - * The lower 32 bits of the timestamp returned will be equal to the timestamp to - * convert. - * - * If the timestamp to convert is less than the lower 32 bits of the time - * reference then the timestamp to convert is seen as an overflowed value and - * the upper 32 bit of the timestamp returned will be equal to the upper 32 bit - * of the reference point + 1. - * Otherwise, the upper 32 bit returned will be equal to the upper 32 bit of the - * reference point. + * If the timestamp to convert is less than the lower 32 bits of the time + * reference then the timestamp to convert is seen as an overflowed value and + * the upper 32 bit of the timestamp returned will be equal to the upper 32 bit + * of the reference point + 1. + * Otherwise, the upper 32 bit returned will be equal to the upper 32 bit of the + * reference point. * * @param ref: The 64 bit timestamp of reference. * @param timestamp: The timestamp to convert. @@ -98,8 +98,8 @@ static us_timestamp_t convert_timestamp(us_timestamp_t ref, timestamp_t timestam bool overflow = timestamp < ((timestamp_t) ref) ? true : false; us_timestamp_t result = (ref & ~((us_timestamp_t)UINT32_MAX)) | timestamp; - if (overflow) { - result += (1ULL<<32); + if (overflow) { + result += (1ULL << 32); } return result; @@ -206,15 +206,15 @@ int _ticker_match_interval_passed(timestamp_t prev_tick, timestamp_t cur_tick, t } /** - * Compute the time when the interrupt has to be triggered and schedule it. - * - * If there is no event in the queue or the next event to execute is in more + * Compute the time when the interrupt has to be triggered and schedule it. + * + * If there is no event in the queue or the next event to execute is in more * than ticker.queue.max_delta ticks from now then the ticker irq will be * scheduled in ticker.queue.max_delta ticks. Otherwise the irq will be * scheduled to happen when the running counter reach the timestamp of the * first event in the queue. - * - * @note If there is no event in the queue then the interrupt is scheduled to + * + * @note If there is no event in the queue then the interrupt is scheduled to * in ticker.queue.max_delta. This is necessary to keep track * of the timer overflow. */ @@ -251,7 +251,7 @@ static void schedule_interrupt(const ticker_data_t *const ticker) } } else { uint32_t match_tick = - (queue->tick_last_read + queue->max_delta) & queue->bitmask; + (queue->tick_last_read + queue->max_delta) & queue->bitmask; ticker->interface->set_interrupt(match_tick); } } @@ -277,10 +277,10 @@ void ticker_irq_handler(const ticker_data_t *const ticker) break; } - // update the current timestamp used by the queue + // update the current timestamp used by the queue update_present_time(ticker); - if (ticker->queue->head->timestamp <= ticker->queue->present_time) { + if (ticker->queue->head->timestamp <= ticker->queue->present_time) { // This event was in the past: // point to the following one and execute its handler ticker_event_t *p = ticker->queue->head; @@ -292,7 +292,7 @@ void ticker_irq_handler(const ticker_data_t *const ticker) * event handler may have altered the chain of pending events. */ } else { break; - } + } } schedule_interrupt(ticker); @@ -307,13 +307,13 @@ void ticker_insert_event(const ticker_data_t *const ticker, ticker_event_t *obj, // update the current timestamp update_present_time(ticker); us_timestamp_t absolute_timestamp = convert_timestamp( - ticker->queue->present_time, - timestamp - ); + ticker->queue->present_time, + timestamp + ); // defer to ticker_insert_event_us ticker_insert_event_us( - ticker, + ticker, obj, absolute_timestamp, id ); @@ -344,7 +344,7 @@ void ticker_insert_event_us(const ticker_data_t *const ticker, ticker_event_t *o prev = p; p = p->next; } - + /* if we're at the end p will be NULL, which is correct */ obj->next = p; @@ -372,7 +372,7 @@ void ticker_remove_event(const ticker_data_t *const ticker, ticker_event_t *obj) schedule_interrupt(ticker); } else { // find the object before me, then drop me - ticker_event_t* p = ticker->queue->head; + ticker_event_t *p = ticker->queue->head; while (p != NULL) { if (p->next == obj) { p->next = obj->next; diff --git a/hal/mbed_us_ticker_api.c b/hal/mbed_us_ticker_api.c index 69b533482bd..9b025fa3f84 100644 --- a/hal/mbed_us_ticker_api.c +++ b/hal/mbed_us_ticker_api.c @@ -34,7 +34,7 @@ static const ticker_data_t us_data = { .queue = &events }; -const ticker_data_t* get_us_ticker_data(void) +const ticker_data_t *get_us_ticker_data(void) { return &us_data; } diff --git a/hal/pinmap.h b/hal/pinmap.h index 844a4cbbec1..4b3db4afa4b 100644 --- a/hal/pinmap.h +++ b/hal/pinmap.h @@ -32,14 +32,14 @@ typedef struct { } PinMap; void pin_function(PinName pin, int function); -void pin_mode (PinName pin, PinMode mode); - -uint32_t pinmap_peripheral(PinName pin, const PinMap* map); -uint32_t pinmap_function(PinName pin, const PinMap* map); -uint32_t pinmap_merge (uint32_t a, uint32_t b); -void pinmap_pinout (PinName pin, const PinMap *map); -uint32_t pinmap_find_peripheral(PinName pin, const PinMap* map); -uint32_t pinmap_find_function(PinName pin, const PinMap* map); +void pin_mode(PinName pin, PinMode mode); + +uint32_t pinmap_peripheral(PinName pin, const PinMap *map); +uint32_t pinmap_function(PinName pin, const PinMap *map); +uint32_t pinmap_merge(uint32_t a, uint32_t b); +void pinmap_pinout(PinName pin, const PinMap *map); +uint32_t pinmap_find_peripheral(PinName pin, const PinMap *map); +uint32_t pinmap_find_function(PinName pin, const PinMap *map); #ifdef __cplusplus } diff --git a/hal/storage_abstraction/Driver_Common.h b/hal/storage_abstraction/Driver_Common.h index f61ff2cc1c8..045ae931b02 100644 --- a/hal/storage_abstraction/Driver_Common.h +++ b/hal/storage_abstraction/Driver_Common.h @@ -33,8 +33,8 @@ \brief Driver Version */ typedef struct _ARM_DRIVER_VERSION { - uint16_t api; ///< API version - uint16_t drv; ///< Driver version + uint16_t api; ///< API version + uint16_t drv; ///< Driver version } ARM_DRIVER_VERSION; /* General return codes */ @@ -50,9 +50,9 @@ typedef struct _ARM_DRIVER_VERSION { \brief General power states */ typedef enum _ARM_POWER_STATE { - ARM_POWER_OFF, ///< Power off: no operation possible - ARM_POWER_LOW, ///< Low Power mode: retain state, detect and signal wake-up events - ARM_POWER_FULL ///< Power on: full operation at maximum performance + ARM_POWER_OFF, ///< Power off: no operation possible + ARM_POWER_LOW, ///< Low Power mode: retain state, detect and signal wake-up events + ARM_POWER_FULL ///< Power on: full operation at maximum performance } ARM_POWER_STATE; #endif /* __DRIVER_COMMON_H */ diff --git a/hal/storage_abstraction/Driver_Storage.h b/hal/storage_abstraction/Driver_Storage.h index 363a26541f1..3b44409ecb9 100644 --- a/hal/storage_abstraction/Driver_Storage.h +++ b/hal/storage_abstraction/Driver_Storage.h @@ -38,10 +38,10 @@ extern "C" { #define ARM_Driver_Storage_(n) _ARM_Driver_Storage_(n) #define ARM_STORAGE_INVALID_OFFSET (0xFFFFFFFFFFFFFFFFULL) ///< Invalid address (relative to a storage controller's - ///< address space). A storage block may never start at this address. +///< address space). A storage block may never start at this address. #define ARM_STORAGE_INVALID_ADDRESS (0xFFFFFFFFUL) ///< Invalid address within the processor's memory address space. - ///< Refer to memory-mapped storage, i.e. < \ref ARM_DRIVER_STORAGE::ResolveAddress(). +///< Refer to memory-mapped storage, i.e. < \ref ARM_DRIVER_STORAGE::ResolveAddress(). /****** Storage specific error codes *****/ #define ARM_STORAGE_ERROR_NOT_ERASABLE (ARM_DRIVER_ERROR_SPECIFIC - 1) ///< Part (or all) of the range provided to Erase() isn't erasable. @@ -53,26 +53,26 @@ extern "C" { * \brief Attributes of the storage range within a storage block. */ typedef struct _ARM_STORAGE_BLOCK_ATTRIBUTES { - uint32_t erasable : 1; ///< Erasing blocks is permitted with a minimum granularity of 'erase_unit'. - ///< @note: if 'erasable' is 0--i.e. the 'erase' operation isn't available--then - ///< 'erase_unit' (see below) is immaterial and should be 0. - uint32_t programmable : 1; ///< Writing to ranges is permitted with a minimum granularity of 'program_unit'. - ///< Writes are typically achieved through the ProgramData operation (following an erase); - ///< if storage isn't erasable (see 'erasable' above) but is memory-mapped - ///< (i.e. 'memory_mapped'), it can be written directly using memory-store operations. - uint32_t executable : 1; ///< This storage block can hold program data; the processor can fetch and execute code - ///< sourced from it. Often this is accompanied with the device being 'memory_mapped' (see \ref ARM_STORAGE_INFO). - uint32_t protectable : 1; ///< The entire block can be protected from program and erase operations. Once protection - ///< is enabled for a block, its 'erasable' and 'programmable' bits are turned off. - uint32_t reserved : 28; - uint32_t erase_unit; ///< Minimum erase size in bytes. - ///< The offset of the start of the erase-range should also be aligned with this value. - ///< Applicable if the 'erasable' attribute is set for the block. - ///< @note: if 'erasable' (see above) is 0--i.e. the 'erase' operation isn't available--then - ///< 'erase_unit' is immaterial and should be 0. - uint32_t protection_unit; ///< Minimum protectable size in bytes. Applicable if the 'protectable' - ///< attribute is set for the block. This should be a divisor of the block's size. A - ///< block can be considered to be made up of consecutive, individually-protectable fragments. + uint32_t erasable : 1; ///< Erasing blocks is permitted with a minimum granularity of 'erase_unit'. + ///< @note: if 'erasable' is 0--i.e. the 'erase' operation isn't available--then + ///< 'erase_unit' (see below) is immaterial and should be 0. + uint32_t programmable : 1; ///< Writing to ranges is permitted with a minimum granularity of 'program_unit'. + ///< Writes are typically achieved through the ProgramData operation (following an erase); + ///< if storage isn't erasable (see 'erasable' above) but is memory-mapped + ///< (i.e. 'memory_mapped'), it can be written directly using memory-store operations. + uint32_t executable : 1; ///< This storage block can hold program data; the processor can fetch and execute code + ///< sourced from it. Often this is accompanied with the device being 'memory_mapped' (see \ref ARM_STORAGE_INFO). + uint32_t protectable : 1; ///< The entire block can be protected from program and erase operations. Once protection + ///< is enabled for a block, its 'erasable' and 'programmable' bits are turned off. + uint32_t reserved : 28; + uint32_t erase_unit; ///< Minimum erase size in bytes. + ///< The offset of the start of the erase-range should also be aligned with this value. + ///< Applicable if the 'erasable' attribute is set for the block. + ///< @note: if 'erasable' (see above) is 0--i.e. the 'erase' operation isn't available--then + ///< 'erase_unit' is immaterial and should be 0. + uint32_t protection_unit; ///< Minimum protectable size in bytes. Applicable if the 'protectable' + ///< attribute is set for the block. This should be a divisor of the block's size. A + ///< block can be considered to be made up of consecutive, individually-protectable fragments. } ARM_STORAGE_BLOCK_ATTRIBUTES; /** @@ -80,12 +80,12 @@ typedef struct _ARM_STORAGE_BLOCK_ATTRIBUTES { * combine to make up the address map of a storage controller. */ typedef struct _ARM_STORAGE_BLOCK { - uint64_t addr; ///< This is the start address of the storage block. It is - ///< expressed as an offset from the start of the storage map - ///< maintained by the owning storage controller. - uint64_t size; ///< This is the size of the storage block, in units of bytes. - ///< Together with addr, it describes a range [addr, addr+size). - ARM_STORAGE_BLOCK_ATTRIBUTES attributes; ///< Attributes for this block. + uint64_t addr; ///< This is the start address of the storage block. It is + ///< expressed as an offset from the start of the storage map + ///< maintained by the owning storage controller. + uint64_t size; ///< This is the size of the storage block, in units of bytes. + ///< Together with addr, it describes a range [addr, addr+size). + ARM_STORAGE_BLOCK_ATTRIBUTES attributes; ///< Attributes for this block. } ARM_STORAGE_BLOCK; /** @@ -120,22 +120,22 @@ typedef struct _ARM_STORAGE_BLOCK { * Device Data Security Protection Features. Applicable mostly to EXTERNAL_NVM. */ typedef struct _ARM_STORAGE_SECURITY_FEATURES { - uint32_t acls : 1; ///< Protection against internal software attacks using ACLs. - uint32_t rollback_protection : 1; ///< Roll-back protection. Set to true if the creator of the storage - ///< can ensure that an external attacker can't force an - ///< older firmware to run or to revert back to a previous state. - uint32_t tamper_proof : 1; ///< Tamper-proof memory (will be deleted on tamper-attempts using board level or chip level sensors). - uint32_t internal_flash : 1; ///< Internal flash. - uint32_t reserved1 : 12; - - /** - * Encode support for hardening against various classes of attacks. - */ - uint32_t software_attacks : 1; ///< device software (malware running on the device). - uint32_t board_level_attacks : 1; ///< board level attacks (debug probes, copy protection fuses.) - uint32_t chip_level_attacks : 1; ///< chip level attacks (tamper-protection). - uint32_t side_channel_attacks : 1; ///< side channel attacks. - uint32_t reserved2 : 12; + uint32_t acls : 1; ///< Protection against internal software attacks using ACLs. + uint32_t rollback_protection : 1; ///< Roll-back protection. Set to true if the creator of the storage + ///< can ensure that an external attacker can't force an + ///< older firmware to run or to revert back to a previous state. + uint32_t tamper_proof : 1; ///< Tamper-proof memory (will be deleted on tamper-attempts using board level or chip level sensors). + uint32_t internal_flash : 1; ///< Internal flash. + uint32_t reserved1 : 12; + + /** + * Encode support for hardening against various classes of attacks. + */ + uint32_t software_attacks : 1; ///< device software (malware running on the device). + uint32_t board_level_attacks : 1; ///< board level attacks (debug probes, copy protection fuses.) + uint32_t chip_level_attacks : 1; ///< chip level attacks (tamper-protection). + uint32_t side_channel_attacks : 1; ///< side channel attacks. + uint32_t reserved2 : 12; } ARM_STORAGE_SECURITY_FEATURES; #define ARM_STORAGE_PROGRAM_CYCLES_INFINITE (0UL) /**< Infinite or unknown endurance for reprogramming. */ @@ -154,35 +154,35 @@ typedef struct _ARM_STORAGE_SECURITY_FEATURES { * pointers to be moved around. */ typedef struct _ARM_STORAGE_INFO { - uint64_t total_storage; ///< Total available storage, in bytes. - uint32_t program_unit; ///< Minimum programming size in bytes. - ///< The offset of the start of the program-range should also be aligned with this value. - ///< Applicable only if the 'programmable' attribute is set for a block. - ///< @note: setting program_unit to 0 has the effect of disabling the size and alignment - ///< restrictions (setting it to 1 also has the same effect). - uint32_t optimal_program_unit; ///< Optimal programming page-size in bytes. Some storage controllers - ///< have internal buffers into which to receive data. Writing in chunks of - ///< 'optimal_program_unit' would achieve maximum programming speed. - ///< Applicable only if the 'programmable' attribute is set for the underlying block(s). - uint32_t program_cycles; ///< A measure of endurance for reprogramming. - ///< Use ARM_STORAGE_PROGRAM_CYCLES_INFINITE for infinite or unknown endurance. - uint32_t erased_value : 1; ///< Contents of erased memory (usually 1 to indicate erased bytes with state 0xFF). - uint32_t memory_mapped : 1; ///< This storage device has a mapping onto the processor's memory address space. - ///< @note: For a memory-mapped block which isn't erasable but is programmable (i.e. if - ///< 'erasable' is set to 0, but 'programmable' is 1), writes should be possible directly to - ///< the memory-mapped storage without going through the ProgramData operation. - uint32_t programmability : 4; ///< A value to indicate storage programmability. - uint32_t retention_level : 4; - uint32_t reserved : 22; - ARM_STORAGE_SECURITY_FEATURES security; ///< \ref ARM_STORAGE_SECURITY_FEATURES + uint64_t total_storage; ///< Total available storage, in bytes. + uint32_t program_unit; ///< Minimum programming size in bytes. + ///< The offset of the start of the program-range should also be aligned with this value. + ///< Applicable only if the 'programmable' attribute is set for a block. + ///< @note: setting program_unit to 0 has the effect of disabling the size and alignment + ///< restrictions (setting it to 1 also has the same effect). + uint32_t optimal_program_unit; ///< Optimal programming page-size in bytes. Some storage controllers + ///< have internal buffers into which to receive data. Writing in chunks of + ///< 'optimal_program_unit' would achieve maximum programming speed. + ///< Applicable only if the 'programmable' attribute is set for the underlying block(s). + uint32_t program_cycles; ///< A measure of endurance for reprogramming. + ///< Use ARM_STORAGE_PROGRAM_CYCLES_INFINITE for infinite or unknown endurance. + uint32_t erased_value : 1; ///< Contents of erased memory (usually 1 to indicate erased bytes with state 0xFF). + uint32_t memory_mapped : 1; ///< This storage device has a mapping onto the processor's memory address space. + ///< @note: For a memory-mapped block which isn't erasable but is programmable (i.e. if + ///< 'erasable' is set to 0, but 'programmable' is 1), writes should be possible directly to + ///< the memory-mapped storage without going through the ProgramData operation. + uint32_t programmability : 4; ///< A value to indicate storage programmability. + uint32_t retention_level : 4; + uint32_t reserved : 22; + ARM_STORAGE_SECURITY_FEATURES security; ///< \ref ARM_STORAGE_SECURITY_FEATURES } ARM_STORAGE_INFO; /** \brief Operating status of the storage controller. */ typedef struct _ARM_STORAGE_STATUS { - uint32_t busy : 1; ///< Controller busy flag - uint32_t error : 1; ///< Read/Program/Erase error flag (cleared on start of next operation) + uint32_t busy : 1; ///< Controller busy flag + uint32_t error : 1; ///< Read/Program/Erase error flag (cleared on start of next operation) } ARM_STORAGE_STATUS; /** @@ -192,16 +192,16 @@ typedef struct _ARM_STORAGE_STATUS { * fetched cheaply using a call to driver->GetCapabilities(). */ typedef struct _ARM_STORAGE_CAPABILITIES { - uint32_t asynchronous_ops : 1; ///< Used to indicate if APIs like initialize, - ///< read, erase, program, etc. can operate in asynchronous mode. - ///< Setting this bit to 1 means that the driver is capable - ///< of launching asynchronous operations; command completion is - ///< signaled by the invocation of a completion callback. If - ///< set to 1, drivers may still complete asynchronous - ///< operations synchronously as necessary--in which case they - ///< return a positive error code to indicate synchronous completion. - uint32_t erase_all : 1; ///< Supports EraseAll operation. - uint32_t reserved : 30; + uint32_t asynchronous_ops : 1; ///< Used to indicate if APIs like initialize, + ///< read, erase, program, etc. can operate in asynchronous mode. + ///< Setting this bit to 1 means that the driver is capable + ///< of launching asynchronous operations; command completion is + ///< signaled by the invocation of a completion callback. If + ///< set to 1, drivers may still complete asynchronous + ///< operations synchronously as necessary--in which case they + ///< return a positive error code to indicate synchronous completion. + uint32_t erase_all : 1; ///< Supports EraseAll operation. + uint32_t reserved : 30; } ARM_STORAGE_CAPABILITIES; /** @@ -209,20 +209,20 @@ typedef struct _ARM_STORAGE_CAPABILITIES { * completing commands. Refer to \ref ARM_Storage_Callback_t. */ typedef enum _ARM_STORAGE_OPERATION { - ARM_STORAGE_OPERATION_GET_VERSION, - ARM_STORAGE_OPERATION_GET_CAPABILITIES, - ARM_STORAGE_OPERATION_INITIALIZE, - ARM_STORAGE_OPERATION_UNINITIALIZE, - ARM_STORAGE_OPERATION_POWER_CONTROL, - ARM_STORAGE_OPERATION_READ_DATA, - ARM_STORAGE_OPERATION_PROGRAM_DATA, - ARM_STORAGE_OPERATION_ERASE, - ARM_STORAGE_OPERATION_ERASE_ALL, - ARM_STORAGE_OPERATION_GET_STATUS, - ARM_STORAGE_OPERATION_GET_INFO, - ARM_STORAGE_OPERATION_RESOLVE_ADDRESS, - ARM_STORAGE_OPERATION_GET_NEXT_BLOCK, - ARM_STORAGE_OPERATION_GET_BLOCK + ARM_STORAGE_OPERATION_GET_VERSION, + ARM_STORAGE_OPERATION_GET_CAPABILITIES, + ARM_STORAGE_OPERATION_INITIALIZE, + ARM_STORAGE_OPERATION_UNINITIALIZE, + ARM_STORAGE_OPERATION_POWER_CONTROL, + ARM_STORAGE_OPERATION_READ_DATA, + ARM_STORAGE_OPERATION_PROGRAM_DATA, + ARM_STORAGE_OPERATION_ERASE, + ARM_STORAGE_OPERATION_ERASE_ALL, + ARM_STORAGE_OPERATION_GET_STATUS, + ARM_STORAGE_OPERATION_GET_INFO, + ARM_STORAGE_OPERATION_RESOLVE_ADDRESS, + ARM_STORAGE_OPERATION_GET_NEXT_BLOCK, + ARM_STORAGE_OPERATION_GET_BLOCK } ARM_STORAGE_OPERATION; /** @@ -290,480 +290,480 @@ typedef void (*ARM_Storage_Callback_t)(int32_t status, ARM_STORAGE_OPERATION ope * \endcode */ typedef struct _ARM_DRIVER_STORAGE { - /** - * \brief Get driver version. - * - * The function GetVersion() returns version information of the driver implementation in ARM_DRIVER_VERSION. - * - * - API version is the version of the CMSIS-Driver specification used to implement this driver. - * - Driver version is source code version of the actual driver implementation. - * - * Example: - * \code - * extern ARM_DRIVER_STORAGE *drv_info; - * - * void read_version (void) { - * ARM_DRIVER_VERSION version; - * - * version = drv_info->GetVersion (); - * if (version.api < 0x10A) { // requires at minimum API version 1.10 or higher - * // error handling - * return; - * } - * } - * \endcode - * - * @return \ref ARM_DRIVER_VERSION. - * - * @note This API returns synchronously--it does not result in an invocation - * of a completion callback. - * - * @note The function GetVersion() can be called any time to obtain the - * required information from the driver (even before initialization). It - * always returns the same information. - */ - ARM_DRIVER_VERSION (*GetVersion)(void); - - /** - * \brief Get driver capabilities. - * - * \details The function GetCapabilities() returns information about - * capabilities in this driver implementation. The data fields of the struct - * ARM_STORAGE_CAPABILITIES encode various capabilities, for example if the device - * is able to execute operations asynchronously. - * - * Example: - * \code - * extern ARM_DRIVER_STORAGE *drv_info; - * - * void read_capabilities (void) { - * ARM_STORAGE_CAPABILITIES drv_capabilities; - * - * drv_capabilities = drv_info->GetCapabilities (); - * // interrogate capabilities - * - * } - * \endcode - * - * @return \ref ARM_STORAGE_CAPABILITIES. - * - * @note This API returns synchronously--it does not result in an invocation - * of a completion callback. - * - * @note The function GetCapabilities() can be called any time to obtain the - * required information from the driver (even before initialization). It - * always returns the same information. - */ - ARM_STORAGE_CAPABILITIES (*GetCapabilities)(void); - - /** - * \brief Initialize the Storage Interface. - * - * The function Initialize is called when the middleware component starts - * operation. In addition to bringing the controller to a ready state, - * Initialize() receives a callback handler to be invoked upon completion of - * asynchronous operations. - * - * Initialize() needs to be called explicitly before - * powering the peripheral using PowerControl(), and before initiating other - * accesses to the storage controller. - * - * The function performs the following operations: - * - Initializes the resources needed for the Storage interface. - * - Registers the \ref ARM_Storage_Callback_t callback function. - * - * To start working with a peripheral the functions Initialize and PowerControl need to be called in this order: - * drv->Initialize (...); // Allocate I/O pins - * drv->PowerControl (ARM_POWER_FULL); // Power up peripheral, setup IRQ/DMA - * - * - Initialize() typically allocates the I/O resources (pins) for the - * peripheral. The function can be called multiple times; if the I/O resources - * are already initialized it performs no operation and just returns with - * ARM_DRIVER_OK. - * - * - PowerControl (ARM_POWER_FULL) sets the peripheral registers including - * interrupt (NVIC) and optionally DMA. The function can be called multiple - * times; if the registers are already set it performs no operation and just - * returns with ARM_DRIVER_OK. - * - * To stop working with a peripheral the functions PowerControl and Uninitialize need to be called in this order: - * drv->PowerControl (ARM_POWER_OFF); // Terminate any pending transfers, reset IRQ/DMA, power off peripheral - * drv->Uninitialize (...); // Release I/O pins - * - * The functions PowerControl and Uninitialize always execute and can be used - * to put the peripheral into a Safe State, for example after any data - * transmission errors. To restart the peripheral in an error condition, - * you should first execute the Stop Sequence and then the Start Sequence. - * - * @param [in] callback - * Caller-defined callback to be invoked upon command completion - * for asynchronous APIs (including the completion of - * initialization). Use a NULL pointer when no callback - * signals are required. - * - * @note This API may execute asynchronously if - * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous - * execution is optional even if 'asynchronous_ops' is set. - * - * @return If asynchronous activity is launched, an invocation returns - * ARM_DRIVER_OK, and the caller can expect to receive a callback in the - * future with a status value of ARM_DRIVER_OK or an error-code. In the - * case of synchronous execution, control returns after completion with a - * value of 1. Return values less than ARM_DRIVER_OK (0) signify errors. - */ - int32_t (*Initialize)(ARM_Storage_Callback_t callback); - - /** - * \brief De-initialize the Storage Interface. - * - * The function Uninitialize() de-initializes the resources of Storage interface. - * - * It is called when the middleware component stops operation, and wishes to - * release the software resources used by the interface. - * - * @note This API may execute asynchronously if - * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous - * execution is optional even if 'asynchronous_ops' is set. - * - * @return If asynchronous activity is launched, an invocation returns - * ARM_DRIVER_OK, and the caller can expect to receive a callback in the - * future with a status value of ARM_DRIVER_OK or an error-code. In the - * case of synchronous execution, control returns after completion with a - * value of 1. Return values less than ARM_DRIVER_OK (0) signify errors. - */ - int32_t (*Uninitialize)(void); - - /** - * \brief Control the Storage interface power. - * - * The function \b ARM_Storage_PowerControl operates the power modes of the Storage interface. - * - * To start working with a peripheral the functions Initialize and PowerControl need to be called in this order: - * drv->Initialize (...); // Allocate I/O pins - * drv->PowerControl (ARM_POWER_FULL); // Power up peripheral, setup IRQ/DMA - * - * - Initialize() typically allocates the I/O resources (pins) for the - * peripheral. The function can be called multiple times; if the I/O resources - * are already initialized it performs no operation and just returns with - * ARM_DRIVER_OK. - * - * - PowerControl (ARM_POWER_FULL) sets the peripheral registers including - * interrupt (NVIC) and optionally DMA. The function can be called multiple - * times; if the registers are already set it performs no operation and just - * returns with ARM_DRIVER_OK. - * - * To stop working with a peripheral the functions PowerControl and Uninitialize need to be called in this order: - * - * drv->PowerControl (ARM_POWER_OFF); // Terminate any pending transfers, reset IRQ/DMA, power off peripheral - * drv->Uninitialize (...); // Release I/O pins - * - * The functions PowerControl and Uninitialize always execute and can be used - * to put the peripheral into a Safe State, for example after any data - * transmission errors. To restart the peripheral in an error condition, - * you should first execute the Stop Sequence and then the Start Sequence. - * - * @param state - * \ref ARM_POWER_STATE. The target power-state for the storage controller. - * The parameter state can have the following values: - * - ARM_POWER_FULL : set-up peripheral for data transfers, enable interrupts - * (NVIC) and optionally DMA. Can be called multiple times. If the peripheral - * is already in this mode, then the function performs no operation and returns - * with ARM_DRIVER_OK. - * - ARM_POWER_LOW : may use power saving. Returns ARM_DRIVER_ERROR_UNSUPPORTED when not implemented. - * - ARM_POWER_OFF : terminates any pending data transfers, disables peripheral, disables related interrupts and DMA. - * - * @note This API may execute asynchronously if - * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous - * execution is optional even if 'asynchronous_ops' is set. - * - * @return If asynchronous activity is launched, an invocation returns - * ARM_DRIVER_OK, and the caller can expect to receive a callback in the - * future with a status value of ARM_DRIVER_OK or an error-code. In the - * case of synchronous execution, control returns after completion with a - * value of 1. Return values less than ARM_DRIVER_OK (0) signify errors. - */ - int32_t (*PowerControl)(ARM_POWER_STATE state); - - /** - * \brief read the contents of a given address range from the storage device. - * - * \details Read the contents of a range of storage memory into a buffer - * supplied by the caller. The buffer is owned by the caller and should - * remain accessible for the lifetime of this command. - * - * @param [in] addr - * This specifies the address from where to read data. - * - * @param [out] data - * The destination of the read operation. The buffer - * is owned by the caller and should remain accessible for the - * lifetime of this command. - * - * @param [in] size - * The number of bytes requested to read. The data buffer - * should be at least as large as this size. - * - * @note This API may execute asynchronously if - * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous - * execution is optional even if 'asynchronous_ops' is set. - * - * @return If asynchronous activity is launched, an invocation returns - * ARM_DRIVER_OK, and the caller can expect to receive a callback in the - * future with the number of successfully transferred bytes passed in as - * the 'status' parameter. In the case of synchronous execution, control - * returns after completion with a positive transfer-count. Return values - * less than ARM_DRIVER_OK (0) signify errors. - */ - int32_t (*ReadData)(uint64_t addr, void *data, uint32_t size); - - /** - * \brief program (write into) the contents of a given address range of the storage device. - * - * \details Write the contents of a given memory buffer into a range of - * storage memory. In the case of flash memory, the destination range in - * storage memory typically has its contents in an erased state from a - * preceding erase operation. The source memory buffer is owned by the - * caller and should remain accessible for the lifetime of this command. - * - * @param [in] addr - * This is the start address of the range to be written into. It - * needs to be aligned to the device's \em program_unit - * specified in \ref ARM_STORAGE_INFO. - * - * @param [in] data - * The source of the write operation. The buffer is owned by the - * caller and should remain accessible for the lifetime of this - * command. - * - * @param [in] size - * The number of bytes requested to be written. The buffer - * should be at least as large as this size. \note 'size' should - * be a multiple of the device's 'program_unit' (see \ref - * ARM_STORAGE_INFO). - * - * @note It is best for the middleware to write in units of - * 'optimal_program_unit' (\ref ARM_STORAGE_INFO) of the device. - * - * @note This API may execute asynchronously if - * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous - * execution is optional even if 'asynchronous_ops' is set. - * - * @return If asynchronous activity is launched, an invocation returns - * ARM_DRIVER_OK, and the caller can expect to receive a callback in the - * future with the number of successfully transferred bytes passed in as - * the 'status' parameter. In the case of synchronous execution, control - * returns after completion with a positive transfer-count. Return values - * less than ARM_DRIVER_OK (0) signify errors. - */ - int32_t (*ProgramData)(uint64_t addr, const void *data, uint32_t size); - - /** - * @brief Erase Storage range. - * - * @details This function erases a range of storage specified by [addr, addr + - * size). Both 'addr' and 'addr + size' should align with the - * 'erase_unit'(s) of the respective owning storage block(s) (see \ref - * ARM_STORAGE_BLOCK and \ref ARM_STORAGE_BLOCK_ATTRIBUTES). The range to - * be erased will have its contents returned to the un-programmed state-- - * i.e. to 'erased_value' (see \ref ARM_STORAGE_BLOCK_ATTRIBUTES), which - * is usually 1 to indicate the pattern of all ones: 0xFF. - * - * @param [in] addr - * This is the start-address of the range to be erased. It must - * start at an 'erase_unit' boundary of the underlying block. - * - * @param [in] size - * Size (in bytes) of the range to be erased. 'addr + size' - * must be aligned with the 'erase_unit' of the underlying - * block. - * - * @note This API may execute asynchronously if - * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous - * execution is optional even if 'asynchronous_ops' is set. - * - * @return - * If the range to be erased doesn't align with the erase_units of the - * respective start and end blocks, ARM_DRIVER_ERROR_PARAMETER is returned. - * If any part of the range is protected, ARM_STORAGE_ERROR_PROTECTED is - * returned. If any part of the range is not erasable, - * ARM_STORAGE_ERROR_NOT_ERASABLE is returned. All such sanity-check - * failures result in the error code being returned synchronously and the - * storage bytes within the range remain unaffected. - * Otherwise the function executes in the following ways: - * If asynchronous activity is launched, an invocation returns - * ARM_DRIVER_OK, and the caller can expect to receive a callback in the - * future with the number of successfully erased bytes passed in as - * the 'status' parameter. In the case of synchronous execution, control - * returns after completion with a positive erase-count. Return values - * less than ARM_DRIVER_OK (0) signify errors. - * - * @note Erase() may return a smaller (positive) value than the size of the - * requested range. The returned value indicates the actual number of bytes - * erased. It is the caller's responsibility to follow up with an appropriate - * request to complete the operation. - * - * @note in the case of a failed erase (except when - * ARM_DRIVER_ERROR_PARAMETER, ARM_STORAGE_ERROR_PROTECTED, or - * ARM_STORAGE_ERROR_NOT_ERASABLE is returned synchronously), the - * requested range should be assumed to be in an unknown state. The - * previous contents may not be retained. - */ - int32_t (*Erase)(uint64_t addr, uint32_t size); - - /** - * @brief Erase complete storage. Optional function for faster erase of the complete device. - * - * This optional function erases the complete device. If the device does not - * support global erase then the function returns the error value \ref - * ARM_DRIVER_ERROR_UNSUPPORTED. The data field \em 'erase_all' = 1 - * of the structure \ref ARM_STORAGE_CAPABILITIES encodes that - * ARM_STORAGE_EraseAll is supported. - * - * @note This API may execute asynchronously if - * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous - * execution is optional even if 'asynchronous_ops' is set. - * - * @return - * If any part of the storage range is protected, - * ARM_STORAGE_ERROR_PROTECTED is returned. If any part of the storage - * range is not erasable, ARM_STORAGE_ERROR_NOT_ERASABLE is returned. All - * such sanity-check failures result in the error code being returned - * synchronously and the storage bytes within the range remain unaffected. - * Otherwise the function executes in the following ways: - * If asynchronous activity is launched, an invocation returns - * ARM_DRIVER_OK, and the caller can expect to receive a callback in the - * future with ARM_DRIVER_OK passed in as the 'status' parameter. In the - * case of synchronous execution, control returns after completion with a - * value of 1. Return values less than ARM_DRIVER_OK (0) signify errors. - */ - int32_t (*EraseAll)(void); - - /** - * @brief Get the status of the current (or previous) command executed by the - * storage controller; stored in the structure \ref ARM_STORAGE_STATUS. - * - * @return - * The status of the underlying controller. - * - * @note This API returns synchronously--it does not result in an invocation - * of a completion callback. - */ - ARM_STORAGE_STATUS (*GetStatus)(void); - - /** - * @brief Get information about the Storage device; stored in the structure \ref ARM_STORAGE_INFO. - * - * @param [out] info - * A caller-supplied buffer capable of being filled in with an - * \ref ARM_STORAGE_INFO. - * - * @return ARM_DRIVER_OK if a ARM_STORAGE_INFO structure containing top level - * metadata about the storage controller is filled into the supplied - * buffer, else an appropriate error value. - * - * @note It is the caller's responsibility to ensure that the buffer passed in - * is able to be initialized with a \ref ARM_STORAGE_INFO. - * - * @note This API returns synchronously--it does not result in an invocation - * of a completion callback. - */ - int32_t (*GetInfo)(ARM_STORAGE_INFO *info); - - /** - * \brief For memory-mapped storage, resolve an address relative to - * the storage controller into a memory address. - * - * @param addr - * This is the address for which we want a resolution to the - * processor's physical address space. It is an offset from the - * start of the storage map maintained by the owning storage - * controller. - * - * @return - * The resolved address in the processor's address space; else - * ARM_STORAGE_INVALID_ADDRESS, if no resolution is possible. - * - * @note This API returns synchronously. The invocation should return quickly, - * and result in a resolved address. - */ - uint32_t (*ResolveAddress)(uint64_t addr); - - /** - * @brief Advance to the successor of the current block (iterator), or fetch - * the first block (if 'prev_block' is passed in as NULL). - * - * @details This helper function fetches (an iterator to) the next block (or - * the first block if 'prev_block' is passed in as NULL). In the failure - * case, a terminating, invalid block iterator is filled into the out - * parameter: 'next_block'. In combination with \ref - * ARM_STORAGE_VALID_BLOCK(), it can be used to iterate over the sequence - * of blocks within the storage map: - * - * \code - * ARM_STORAGE_BLOCK block; - * for (drv->GetNextBlock(NULL, &block); ARM_STORAGE_VALID_BLOCK(&block); drv->GetNextBlock(&block, &block)) { - * // make use of block - * } - * \endcode - * - * @param[in] prev_block - * An existing block (iterator) within the same storage - * controller. The memory buffer holding this block is owned - * by the caller. This pointer may be NULL; if so, the - * invocation fills in the first block into the out parameter: - * 'next_block'. - * - * @param[out] next_block - * A caller-owned buffer large enough to be filled in with - * the following ARM_STORAGE_BLOCK. It is legal to provide the - * same buffer using 'next_block' as was passed in with 'prev_block'. It - * is also legal to pass a NULL into this parameter if the - * caller isn't interested in populating a buffer with the next - * block--i.e. if the caller only wishes to establish the - * presence of a next block. - * - * @return ARM_DRIVER_OK if a valid next block is found (or first block, if - * prev_block is passed as NULL); upon successful operation, the contents - * of the next (or first) block are filled into the buffer pointed to by - * the parameter 'next_block' and ARM_STORAGE_VALID_BLOCK(next_block) is - * guaranteed to be true. Upon reaching the end of the sequence of blocks - * (iterators), or in case the driver is unable to fetch information about - * the next (or first) block, an error (negative) value is returned and an - * invalid StorageBlock is populated into the supplied buffer. If - * prev_block is NULL, the first block is returned. - * - * @note This API returns synchronously--it does not result in an invocation - * of a completion callback. - */ - int32_t (*GetNextBlock)(const ARM_STORAGE_BLOCK* prev_block, ARM_STORAGE_BLOCK *next_block); - - /** - * @brief Find the storage block (iterator) encompassing a given storage address. - * - * @param[in] addr - * Storage address in bytes. - * - * @param[out] block - * A caller-owned buffer large enough to be filled in with the - * ARM_STORAGE_BLOCK encapsulating the given address. This value - * can also be passed in as NULL if the caller isn't interested - * in populating a buffer with the block--if the caller only - * wishes to establish the presence of a containing storage - * block. - * - * @return ARM_DRIVER_OK if a containing storage-block is found. In this case, - * if block is non-NULL, the buffer pointed to by it is populated with - * the contents of the storage block--i.e. if block is valid and a block is - * found, ARM_STORAGE_VALID_BLOCK(block) would return true following this - * call. If there is no storage block containing the given offset, or in - * case the driver is unable to resolve an address to a storage-block, an - * error (negative) value is returned and an invalid StorageBlock is - * populated into the supplied buffer. - * - * @note This API returns synchronously--it does not result in an invocation - * of a completion callback. - */ - int32_t (*GetBlock)(uint64_t addr, ARM_STORAGE_BLOCK *block); + /** + * \brief Get driver version. + * + * The function GetVersion() returns version information of the driver implementation in ARM_DRIVER_VERSION. + * + * - API version is the version of the CMSIS-Driver specification used to implement this driver. + * - Driver version is source code version of the actual driver implementation. + * + * Example: + * \code + * extern ARM_DRIVER_STORAGE *drv_info; + * + * void read_version (void) { + * ARM_DRIVER_VERSION version; + * + * version = drv_info->GetVersion (); + * if (version.api < 0x10A) { // requires at minimum API version 1.10 or higher + * // error handling + * return; + * } + * } + * \endcode + * + * @return \ref ARM_DRIVER_VERSION. + * + * @note This API returns synchronously--it does not result in an invocation + * of a completion callback. + * + * @note The function GetVersion() can be called any time to obtain the + * required information from the driver (even before initialization). It + * always returns the same information. + */ + ARM_DRIVER_VERSION(*GetVersion)(void); + + /** + * \brief Get driver capabilities. + * + * \details The function GetCapabilities() returns information about + * capabilities in this driver implementation. The data fields of the struct + * ARM_STORAGE_CAPABILITIES encode various capabilities, for example if the device + * is able to execute operations asynchronously. + * + * Example: + * \code + * extern ARM_DRIVER_STORAGE *drv_info; + * + * void read_capabilities (void) { + * ARM_STORAGE_CAPABILITIES drv_capabilities; + * + * drv_capabilities = drv_info->GetCapabilities (); + * // interrogate capabilities + * + * } + * \endcode + * + * @return \ref ARM_STORAGE_CAPABILITIES. + * + * @note This API returns synchronously--it does not result in an invocation + * of a completion callback. + * + * @note The function GetCapabilities() can be called any time to obtain the + * required information from the driver (even before initialization). It + * always returns the same information. + */ + ARM_STORAGE_CAPABILITIES(*GetCapabilities)(void); + + /** + * \brief Initialize the Storage Interface. + * + * The function Initialize is called when the middleware component starts + * operation. In addition to bringing the controller to a ready state, + * Initialize() receives a callback handler to be invoked upon completion of + * asynchronous operations. + * + * Initialize() needs to be called explicitly before + * powering the peripheral using PowerControl(), and before initiating other + * accesses to the storage controller. + * + * The function performs the following operations: + * - Initializes the resources needed for the Storage interface. + * - Registers the \ref ARM_Storage_Callback_t callback function. + * + * To start working with a peripheral the functions Initialize and PowerControl need to be called in this order: + * drv->Initialize (...); // Allocate I/O pins + * drv->PowerControl (ARM_POWER_FULL); // Power up peripheral, setup IRQ/DMA + * + * - Initialize() typically allocates the I/O resources (pins) for the + * peripheral. The function can be called multiple times; if the I/O resources + * are already initialized it performs no operation and just returns with + * ARM_DRIVER_OK. + * + * - PowerControl (ARM_POWER_FULL) sets the peripheral registers including + * interrupt (NVIC) and optionally DMA. The function can be called multiple + * times; if the registers are already set it performs no operation and just + * returns with ARM_DRIVER_OK. + * + * To stop working with a peripheral the functions PowerControl and Uninitialize need to be called in this order: + * drv->PowerControl (ARM_POWER_OFF); // Terminate any pending transfers, reset IRQ/DMA, power off peripheral + * drv->Uninitialize (...); // Release I/O pins + * + * The functions PowerControl and Uninitialize always execute and can be used + * to put the peripheral into a Safe State, for example after any data + * transmission errors. To restart the peripheral in an error condition, + * you should first execute the Stop Sequence and then the Start Sequence. + * + * @param [in] callback + * Caller-defined callback to be invoked upon command completion + * for asynchronous APIs (including the completion of + * initialization). Use a NULL pointer when no callback + * signals are required. + * + * @note This API may execute asynchronously if + * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous + * execution is optional even if 'asynchronous_ops' is set. + * + * @return If asynchronous activity is launched, an invocation returns + * ARM_DRIVER_OK, and the caller can expect to receive a callback in the + * future with a status value of ARM_DRIVER_OK or an error-code. In the + * case of synchronous execution, control returns after completion with a + * value of 1. Return values less than ARM_DRIVER_OK (0) signify errors. + */ + int32_t (*Initialize)(ARM_Storage_Callback_t callback); + + /** + * \brief De-initialize the Storage Interface. + * + * The function Uninitialize() de-initializes the resources of Storage interface. + * + * It is called when the middleware component stops operation, and wishes to + * release the software resources used by the interface. + * + * @note This API may execute asynchronously if + * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous + * execution is optional even if 'asynchronous_ops' is set. + * + * @return If asynchronous activity is launched, an invocation returns + * ARM_DRIVER_OK, and the caller can expect to receive a callback in the + * future with a status value of ARM_DRIVER_OK or an error-code. In the + * case of synchronous execution, control returns after completion with a + * value of 1. Return values less than ARM_DRIVER_OK (0) signify errors. + */ + int32_t (*Uninitialize)(void); + + /** + * \brief Control the Storage interface power. + * + * The function \b ARM_Storage_PowerControl operates the power modes of the Storage interface. + * + * To start working with a peripheral the functions Initialize and PowerControl need to be called in this order: + * drv->Initialize (...); // Allocate I/O pins + * drv->PowerControl (ARM_POWER_FULL); // Power up peripheral, setup IRQ/DMA + * + * - Initialize() typically allocates the I/O resources (pins) for the + * peripheral. The function can be called multiple times; if the I/O resources + * are already initialized it performs no operation and just returns with + * ARM_DRIVER_OK. + * + * - PowerControl (ARM_POWER_FULL) sets the peripheral registers including + * interrupt (NVIC) and optionally DMA. The function can be called multiple + * times; if the registers are already set it performs no operation and just + * returns with ARM_DRIVER_OK. + * + * To stop working with a peripheral the functions PowerControl and Uninitialize need to be called in this order: + * + * drv->PowerControl (ARM_POWER_OFF); // Terminate any pending transfers, reset IRQ/DMA, power off peripheral + * drv->Uninitialize (...); // Release I/O pins + * + * The functions PowerControl and Uninitialize always execute and can be used + * to put the peripheral into a Safe State, for example after any data + * transmission errors. To restart the peripheral in an error condition, + * you should first execute the Stop Sequence and then the Start Sequence. + * + * @param state + * \ref ARM_POWER_STATE. The target power-state for the storage controller. + * The parameter state can have the following values: + * - ARM_POWER_FULL : set-up peripheral for data transfers, enable interrupts + * (NVIC) and optionally DMA. Can be called multiple times. If the peripheral + * is already in this mode, then the function performs no operation and returns + * with ARM_DRIVER_OK. + * - ARM_POWER_LOW : may use power saving. Returns ARM_DRIVER_ERROR_UNSUPPORTED when not implemented. + * - ARM_POWER_OFF : terminates any pending data transfers, disables peripheral, disables related interrupts and DMA. + * + * @note This API may execute asynchronously if + * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous + * execution is optional even if 'asynchronous_ops' is set. + * + * @return If asynchronous activity is launched, an invocation returns + * ARM_DRIVER_OK, and the caller can expect to receive a callback in the + * future with a status value of ARM_DRIVER_OK or an error-code. In the + * case of synchronous execution, control returns after completion with a + * value of 1. Return values less than ARM_DRIVER_OK (0) signify errors. + */ + int32_t (*PowerControl)(ARM_POWER_STATE state); + + /** + * \brief read the contents of a given address range from the storage device. + * + * \details Read the contents of a range of storage memory into a buffer + * supplied by the caller. The buffer is owned by the caller and should + * remain accessible for the lifetime of this command. + * + * @param [in] addr + * This specifies the address from where to read data. + * + * @param [out] data + * The destination of the read operation. The buffer + * is owned by the caller and should remain accessible for the + * lifetime of this command. + * + * @param [in] size + * The number of bytes requested to read. The data buffer + * should be at least as large as this size. + * + * @note This API may execute asynchronously if + * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous + * execution is optional even if 'asynchronous_ops' is set. + * + * @return If asynchronous activity is launched, an invocation returns + * ARM_DRIVER_OK, and the caller can expect to receive a callback in the + * future with the number of successfully transferred bytes passed in as + * the 'status' parameter. In the case of synchronous execution, control + * returns after completion with a positive transfer-count. Return values + * less than ARM_DRIVER_OK (0) signify errors. + */ + int32_t (*ReadData)(uint64_t addr, void *data, uint32_t size); + + /** + * \brief program (write into) the contents of a given address range of the storage device. + * + * \details Write the contents of a given memory buffer into a range of + * storage memory. In the case of flash memory, the destination range in + * storage memory typically has its contents in an erased state from a + * preceding erase operation. The source memory buffer is owned by the + * caller and should remain accessible for the lifetime of this command. + * + * @param [in] addr + * This is the start address of the range to be written into. It + * needs to be aligned to the device's \em program_unit + * specified in \ref ARM_STORAGE_INFO. + * + * @param [in] data + * The source of the write operation. The buffer is owned by the + * caller and should remain accessible for the lifetime of this + * command. + * + * @param [in] size + * The number of bytes requested to be written. The buffer + * should be at least as large as this size. \note 'size' should + * be a multiple of the device's 'program_unit' (see \ref + * ARM_STORAGE_INFO). + * + * @note It is best for the middleware to write in units of + * 'optimal_program_unit' (\ref ARM_STORAGE_INFO) of the device. + * + * @note This API may execute asynchronously if + * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous + * execution is optional even if 'asynchronous_ops' is set. + * + * @return If asynchronous activity is launched, an invocation returns + * ARM_DRIVER_OK, and the caller can expect to receive a callback in the + * future with the number of successfully transferred bytes passed in as + * the 'status' parameter. In the case of synchronous execution, control + * returns after completion with a positive transfer-count. Return values + * less than ARM_DRIVER_OK (0) signify errors. + */ + int32_t (*ProgramData)(uint64_t addr, const void *data, uint32_t size); + + /** + * @brief Erase Storage range. + * + * @details This function erases a range of storage specified by [addr, addr + + * size). Both 'addr' and 'addr + size' should align with the + * 'erase_unit'(s) of the respective owning storage block(s) (see \ref + * ARM_STORAGE_BLOCK and \ref ARM_STORAGE_BLOCK_ATTRIBUTES). The range to + * be erased will have its contents returned to the un-programmed state-- + * i.e. to 'erased_value' (see \ref ARM_STORAGE_BLOCK_ATTRIBUTES), which + * is usually 1 to indicate the pattern of all ones: 0xFF. + * + * @param [in] addr + * This is the start-address of the range to be erased. It must + * start at an 'erase_unit' boundary of the underlying block. + * + * @param [in] size + * Size (in bytes) of the range to be erased. 'addr + size' + * must be aligned with the 'erase_unit' of the underlying + * block. + * + * @note This API may execute asynchronously if + * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous + * execution is optional even if 'asynchronous_ops' is set. + * + * @return + * If the range to be erased doesn't align with the erase_units of the + * respective start and end blocks, ARM_DRIVER_ERROR_PARAMETER is returned. + * If any part of the range is protected, ARM_STORAGE_ERROR_PROTECTED is + * returned. If any part of the range is not erasable, + * ARM_STORAGE_ERROR_NOT_ERASABLE is returned. All such sanity-check + * failures result in the error code being returned synchronously and the + * storage bytes within the range remain unaffected. + * Otherwise the function executes in the following ways: + * If asynchronous activity is launched, an invocation returns + * ARM_DRIVER_OK, and the caller can expect to receive a callback in the + * future with the number of successfully erased bytes passed in as + * the 'status' parameter. In the case of synchronous execution, control + * returns after completion with a positive erase-count. Return values + * less than ARM_DRIVER_OK (0) signify errors. + * + * @note Erase() may return a smaller (positive) value than the size of the + * requested range. The returned value indicates the actual number of bytes + * erased. It is the caller's responsibility to follow up with an appropriate + * request to complete the operation. + * + * @note in the case of a failed erase (except when + * ARM_DRIVER_ERROR_PARAMETER, ARM_STORAGE_ERROR_PROTECTED, or + * ARM_STORAGE_ERROR_NOT_ERASABLE is returned synchronously), the + * requested range should be assumed to be in an unknown state. The + * previous contents may not be retained. + */ + int32_t (*Erase)(uint64_t addr, uint32_t size); + + /** + * @brief Erase complete storage. Optional function for faster erase of the complete device. + * + * This optional function erases the complete device. If the device does not + * support global erase then the function returns the error value \ref + * ARM_DRIVER_ERROR_UNSUPPORTED. The data field \em 'erase_all' = 1 + * of the structure \ref ARM_STORAGE_CAPABILITIES encodes that + * ARM_STORAGE_EraseAll is supported. + * + * @note This API may execute asynchronously if + * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous + * execution is optional even if 'asynchronous_ops' is set. + * + * @return + * If any part of the storage range is protected, + * ARM_STORAGE_ERROR_PROTECTED is returned. If any part of the storage + * range is not erasable, ARM_STORAGE_ERROR_NOT_ERASABLE is returned. All + * such sanity-check failures result in the error code being returned + * synchronously and the storage bytes within the range remain unaffected. + * Otherwise the function executes in the following ways: + * If asynchronous activity is launched, an invocation returns + * ARM_DRIVER_OK, and the caller can expect to receive a callback in the + * future with ARM_DRIVER_OK passed in as the 'status' parameter. In the + * case of synchronous execution, control returns after completion with a + * value of 1. Return values less than ARM_DRIVER_OK (0) signify errors. + */ + int32_t (*EraseAll)(void); + + /** + * @brief Get the status of the current (or previous) command executed by the + * storage controller; stored in the structure \ref ARM_STORAGE_STATUS. + * + * @return + * The status of the underlying controller. + * + * @note This API returns synchronously--it does not result in an invocation + * of a completion callback. + */ + ARM_STORAGE_STATUS(*GetStatus)(void); + + /** + * @brief Get information about the Storage device; stored in the structure \ref ARM_STORAGE_INFO. + * + * @param [out] info + * A caller-supplied buffer capable of being filled in with an + * \ref ARM_STORAGE_INFO. + * + * @return ARM_DRIVER_OK if a ARM_STORAGE_INFO structure containing top level + * metadata about the storage controller is filled into the supplied + * buffer, else an appropriate error value. + * + * @note It is the caller's responsibility to ensure that the buffer passed in + * is able to be initialized with a \ref ARM_STORAGE_INFO. + * + * @note This API returns synchronously--it does not result in an invocation + * of a completion callback. + */ + int32_t (*GetInfo)(ARM_STORAGE_INFO *info); + + /** + * \brief For memory-mapped storage, resolve an address relative to + * the storage controller into a memory address. + * + * @param addr + * This is the address for which we want a resolution to the + * processor's physical address space. It is an offset from the + * start of the storage map maintained by the owning storage + * controller. + * + * @return + * The resolved address in the processor's address space; else + * ARM_STORAGE_INVALID_ADDRESS, if no resolution is possible. + * + * @note This API returns synchronously. The invocation should return quickly, + * and result in a resolved address. + */ + uint32_t (*ResolveAddress)(uint64_t addr); + + /** + * @brief Advance to the successor of the current block (iterator), or fetch + * the first block (if 'prev_block' is passed in as NULL). + * + * @details This helper function fetches (an iterator to) the next block (or + * the first block if 'prev_block' is passed in as NULL). In the failure + * case, a terminating, invalid block iterator is filled into the out + * parameter: 'next_block'. In combination with \ref + * ARM_STORAGE_VALID_BLOCK(), it can be used to iterate over the sequence + * of blocks within the storage map: + * + * \code + * ARM_STORAGE_BLOCK block; + * for (drv->GetNextBlock(NULL, &block); ARM_STORAGE_VALID_BLOCK(&block); drv->GetNextBlock(&block, &block)) { + * // make use of block + * } + * \endcode + * + * @param[in] prev_block + * An existing block (iterator) within the same storage + * controller. The memory buffer holding this block is owned + * by the caller. This pointer may be NULL; if so, the + * invocation fills in the first block into the out parameter: + * 'next_block'. + * + * @param[out] next_block + * A caller-owned buffer large enough to be filled in with + * the following ARM_STORAGE_BLOCK. It is legal to provide the + * same buffer using 'next_block' as was passed in with 'prev_block'. It + * is also legal to pass a NULL into this parameter if the + * caller isn't interested in populating a buffer with the next + * block--i.e. if the caller only wishes to establish the + * presence of a next block. + * + * @return ARM_DRIVER_OK if a valid next block is found (or first block, if + * prev_block is passed as NULL); upon successful operation, the contents + * of the next (or first) block are filled into the buffer pointed to by + * the parameter 'next_block' and ARM_STORAGE_VALID_BLOCK(next_block) is + * guaranteed to be true. Upon reaching the end of the sequence of blocks + * (iterators), or in case the driver is unable to fetch information about + * the next (or first) block, an error (negative) value is returned and an + * invalid StorageBlock is populated into the supplied buffer. If + * prev_block is NULL, the first block is returned. + * + * @note This API returns synchronously--it does not result in an invocation + * of a completion callback. + */ + int32_t (*GetNextBlock)(const ARM_STORAGE_BLOCK *prev_block, ARM_STORAGE_BLOCK *next_block); + + /** + * @brief Find the storage block (iterator) encompassing a given storage address. + * + * @param[in] addr + * Storage address in bytes. + * + * @param[out] block + * A caller-owned buffer large enough to be filled in with the + * ARM_STORAGE_BLOCK encapsulating the given address. This value + * can also be passed in as NULL if the caller isn't interested + * in populating a buffer with the block--if the caller only + * wishes to establish the presence of a containing storage + * block. + * + * @return ARM_DRIVER_OK if a containing storage-block is found. In this case, + * if block is non-NULL, the buffer pointed to by it is populated with + * the contents of the storage block--i.e. if block is valid and a block is + * found, ARM_STORAGE_VALID_BLOCK(block) would return true following this + * call. If there is no storage block containing the given offset, or in + * case the driver is unable to resolve an address to a storage-block, an + * error (negative) value is returned and an invalid StorageBlock is + * populated into the supplied buffer. + * + * @note This API returns synchronously--it does not result in an invocation + * of a completion callback. + */ + int32_t (*GetBlock)(uint64_t addr, ARM_STORAGE_BLOCK *block); } const ARM_DRIVER_STORAGE; #ifdef __cplusplus diff --git a/hal/us_ticker_api.h b/hal/us_ticker_api.h index f880a555644..1164847f5b9 100644 --- a/hal/us_ticker_api.h +++ b/hal/us_ticker_api.h @@ -49,7 +49,7 @@ ticker_irq_handler_type set_us_ticker_irq_handler(ticker_irq_handler_type ticker * * @return The low power ticker data */ -const ticker_data_t* get_us_ticker_data(void); +const ticker_data_t *get_us_ticker_data(void); /** The wrapper for ticker_irq_handler, to pass us ticker's data @@ -87,7 +87,7 @@ void us_ticker_disable_interrupt(void); void us_ticker_clear_interrupt(void); /** Set pending interrupt that should be fired right away. - * + * * The ticker should be initialized prior calling this function. */ void us_ticker_fire_interrupt(void); @@ -95,7 +95,7 @@ void us_ticker_fire_interrupt(void); /** Get frequency and counter bits of this ticker. * */ -const ticker_info_t* us_ticker_get_info(void); +const ticker_info_t *us_ticker_get_info(void); /**@}*/ diff --git a/platform/ATCmdParser.cpp b/platform/ATCmdParser.cpp index a787b58b2a2..e2865ae6d60 100644 --- a/platform/ATCmdParser.cpp +++ b/platform/ATCmdParser.cpp @@ -79,7 +79,7 @@ void ATCmdParser::flush() int ATCmdParser::write(const char *data, int size) { int i = 0; - for ( ; i < size; i++) { + for (; i < size; i++) { if (putc(data[i]) < 0) { return -1; } @@ -90,7 +90,7 @@ int ATCmdParser::write(const char *data, int size) int ATCmdParser::read(char *data, int size) { int i = 0; - for ( ; i < size; i++) { + for (; i < size; i++) { int c = getc(); if (c < 0) { return -1; @@ -110,7 +110,7 @@ int ATCmdParser::vprintf(const char *format, va_list args) } int i = 0; - for ( ; _buffer[i]; i++) { + for (; _buffer[i]; i++) { if (putc(_buffer[i]) < 0) { return -1; } @@ -128,7 +128,7 @@ int ATCmdParser::vscanf(const char *format, va_list args) int offset = 0; while (format[i]) { - if (format[i] == '%' && format[i+1] != '%' && format[i+1] != '*') { + if (format[i] == '%' && format[i + 1] != '%' && format[i + 1] != '*') { _buffer[offset++] = '%'; _buffer[offset++] = '*'; i++; @@ -155,7 +155,7 @@ int ATCmdParser::vscanf(const char *format, va_list args) while (true) { // Ran out of space - if (j+1 >= _buffer_size - offset) { + if (j + 1 >= _buffer_size - offset) { return false; } // Recieve next character @@ -168,12 +168,12 @@ int ATCmdParser::vscanf(const char *format, va_list args) // Check for match int count = -1; - sscanf(_buffer+offset, _buffer, &count); + sscanf(_buffer + offset, _buffer, &count); // We only succeed if all characters in the response are matched if (count == j) { // Store the found results - vsscanf(_buffer+offset, format, args); + vsscanf(_buffer + offset, format, args); return j; } } @@ -220,14 +220,14 @@ bool ATCmdParser::vrecv(const char *response, va_list args) bool whole_line_wanted = false; while (response[i]) { - if (response[i] == '%' && response[i+1] != '%' && response[i+1] != '*') { + if (response[i] == '%' && response[i + 1] != '%' && response[i + 1] != '*') { _buffer[offset++] = '%'; _buffer[offset++] = '*'; i++; } else { _buffer[offset++] = response[i++]; // Find linebreaks, taking care not to be fooled if they're in a %[^\n] conversion specification - if (response[i - 1] == '\n' && !(i >= 3 && response[i-3] == '[' && response[i-2] == '^')) { + if (response[i - 1] == '\n' && !(i >= 3 && response[i - 3] == '[' && response[i - 2] == '^')) { whole_line_wanted = true; break; } @@ -260,7 +260,7 @@ bool ATCmdParser::vrecv(const char *response, va_list args) } // Simplify newlines (borrowed from retarget.cpp) if ((c == CR && _in_prev != LF) || - (c == LF && _in_prev != CR)) { + (c == LF && _in_prev != CR)) { _in_prev = c; c = '\n'; } else if ((c == CR && _in_prev == LF) || @@ -277,7 +277,7 @@ bool ATCmdParser::vrecv(const char *response, va_list args) // Check for oob data for (struct oob *oob = _oobs; oob; oob = oob->next) { if ((unsigned)j == oob->len && memcmp( - oob->prefix, _buffer+offset, oob->len) == 0) { + oob->prefix, _buffer + offset, oob->len) == 0) { debug_if(_dbg_on, "AT! %s\n", oob->prefix); oob->cb(); @@ -298,18 +298,18 @@ bool ATCmdParser::vrecv(const char *response, va_list args) // This allows recv("Foo: %s\n") to work, and not match with just the first character of a string // (scanf does not itself match whitespace in its format string, so \n is not significant to it) } else { - sscanf(_buffer+offset, _buffer, &count); + sscanf(_buffer + offset, _buffer, &count); } // We only succeed if all characters in the response are matched if (count == j) { - debug_if(_dbg_on, "AT= %s\n", _buffer+offset); + debug_if(_dbg_on, "AT= %s\n", _buffer + offset); // Reuse the front end of the buffer memcpy(_buffer, response, i); _buffer[i] = 0; // Store the found results - vsscanf(_buffer+offset, _buffer, args); + vsscanf(_buffer + offset, _buffer, args); // Jump to next line and continue parsing response += i; @@ -318,8 +318,8 @@ bool ATCmdParser::vrecv(const char *response, va_list args) // Clear the buffer when we hit a newline or ran out of space // running out of space usually means we ran into binary data - if (c == '\n' || j+1 >= _buffer_size - offset) { - debug_if(_dbg_on, "AT< %s", _buffer+offset); + if (c == '\n' || j + 1 >= _buffer_size - offset) { + debug_if(_dbg_on, "AT< %s", _buffer + offset); j = 0; } } @@ -401,18 +401,18 @@ bool ATCmdParser::process_oob() struct oob *oob = _oobs; while (oob) { if (i == (int)oob->len && memcmp( - oob->prefix, _buffer, oob->len) == 0) { + oob->prefix, _buffer, oob->len) == 0) { debug_if(_dbg_on, "AT! %s\r\n", oob->prefix); oob->cb(); return true; } oob = oob->next; } - + // Clear the buffer when we hit a newline or ran out of space // running out of space usually means we ran into binary data - if (i+1 >= _buffer_size || - strcmp(&_buffer[i-_output_delim_size], _output_delimiter) == 0) { + if (i + 1 >= _buffer_size || + strcmp(&_buffer[i - _output_delim_size], _output_delimiter) == 0) { debug_if(_dbg_on, "AT< %s", _buffer); i = 0; diff --git a/platform/ATCmdParser.h b/platform/ATCmdParser.h index c8fb0406340..31e5d50d9a1 100644 --- a/platform/ATCmdParser.h +++ b/platform/ATCmdParser.h @@ -52,8 +52,7 @@ namespace mbed { * @endcode */ -class ATCmdParser : private NonCopyable -{ +class ATCmdParser : private NonCopyable { private: // File handle // Not owned by ATCmdParser @@ -90,8 +89,8 @@ class ATCmdParser : private NonCopyable * @param debug turns on/off debug output for AT commands */ ATCmdParser(FileHandle *fh, const char *output_delimiter = "\r", - int buffer_size = 256, int timeout = 8000, bool debug = false) - : _fh(fh), _buffer_size(buffer_size), _in_prev(0), _oobs(NULL) + int buffer_size = 256, int timeout = 8000, bool debug = false) + : _fh(fh), _buffer_size(buffer_size), _in_prev(0), _oobs(NULL) { _buffer = new char[buffer_size]; set_timeout(timeout); @@ -195,7 +194,7 @@ class ATCmdParser : private NonCopyable * @param ... all printf-like arguments to insert into command * @return true only if command is successfully sent */ - bool send(const char *command, ...) MBED_PRINTF_METHOD(1,2); + bool send(const char *command, ...) MBED_PRINTF_METHOD(1, 2); bool vsend(const char *command, va_list args); @@ -213,7 +212,7 @@ class ATCmdParser : private NonCopyable * @param ... all scanf-like arguments to extract from response * @return true only if response is successfully matched */ - bool recv(const char *response, ...) MBED_SCANF_METHOD(1,2); + bool recv(const char *response, ...) MBED_SCANF_METHOD(1, 2); bool vrecv(const char *response, va_list args); @@ -258,7 +257,7 @@ class ATCmdParser : private NonCopyable * @param ... arguments to printf * @return number of bytes written or -1 on failure */ - int printf(const char *format, ...) MBED_PRINTF_METHOD(1,2); + int printf(const char *format, ...) MBED_PRINTF_METHOD(1, 2); int vprintf(const char *format, va_list args); @@ -270,7 +269,7 @@ class ATCmdParser : private NonCopyable * @param ... arguments to scanf * @return number of bytes read or -1 on failure */ - int scanf(const char *format, ...) MBED_SCANF_METHOD(1,2); + int scanf(const char *format, ...) MBED_SCANF_METHOD(1, 2); int vscanf(const char *format, va_list args); @@ -295,7 +294,7 @@ class ATCmdParser : private NonCopyable * recv operation. */ void abort(); - + /** * Process out-of-band data * diff --git a/platform/CThunk.h b/platform/CThunk.h index 5e5cccb7f08..0b4e685eaf7 100644 --- a/platform/CThunk.h +++ b/platform/CThunk.h @@ -84,165 +84,163 @@ typedef void (*CThunkEntry)(void); * @note Synchronization level: Not protected */ template -class CThunk -{ - public: - typedef void (T::*CCallbackSimple)(void); - typedef void (T::*CCallback)(void* context); - - inline CThunk(T *instance) - { - init(instance, NULL, NULL); - } - - inline CThunk(T *instance, CCallback callback) - { - init(instance, callback, NULL); - } - - ~CThunk() { - - } - - inline CThunk(T *instance, CCallbackSimple callback) - { - init(instance, (CCallback)callback, NULL); - } - - inline CThunk(T &instance, CCallback callback) - { - init(instance, callback, NULL); - } - - inline CThunk(T &instance, CCallbackSimple callback) - { - init(instance, (CCallback)callback, NULL); - } - - inline CThunk(T &instance, CCallback callback, void* context) - { - init(instance, callback, context); - } - - inline void callback(CCallback callback) - { - m_callback = callback; - } - - inline void callback(CCallbackSimple callback) - { - m_callback = (CCallback)callback; - } - - inline void context(void* context) - { - m_thunk.context = (uint32_t)context; - } - - inline void context(uint32_t context) - { - m_thunk.context = context; - } - - inline uint32_t entry(void) - { - return (((uint32_t)&m_thunk)|CTHUNK_ADDRESS); - } - - /* get thunk entry point for connecting rhunk to an IRQ table */ - inline operator CThunkEntry(void) - { - return (CThunkEntry)entry(); - } - - /* get thunk entry point for connecting rhunk to an IRQ table */ - inline operator uint32_t(void) - { - return entry(); - } - - /* simple test function */ - inline void call(void) - { - (((CThunkEntry)(entry()))()); - } - - private: - T* m_instance; - volatile CCallback m_callback; +class CThunk { +public: + typedef void (T::*CCallbackSimple)(void); + typedef void (T::*CCallback)(void *context); + + inline CThunk(T *instance) + { + init(instance, NULL, NULL); + } + + inline CThunk(T *instance, CCallback callback) + { + init(instance, callback, NULL); + } + + ~CThunk() + { + + } + + inline CThunk(T *instance, CCallbackSimple callback) + { + init(instance, (CCallback)callback, NULL); + } + + inline CThunk(T &instance, CCallback callback) + { + init(instance, callback, NULL); + } + + inline CThunk(T &instance, CCallbackSimple callback) + { + init(instance, (CCallback)callback, NULL); + } + + inline CThunk(T &instance, CCallback callback, void *context) + { + init(instance, callback, context); + } + + inline void callback(CCallback callback) + { + m_callback = callback; + } + + inline void callback(CCallbackSimple callback) + { + m_callback = (CCallback)callback; + } + + inline void context(void *context) + { + m_thunk.context = (uint32_t)context; + } + + inline void context(uint32_t context) + { + m_thunk.context = context; + } + + inline uint32_t entry(void) + { + return (((uint32_t)&m_thunk) | CTHUNK_ADDRESS); + } + + /* get thunk entry point for connecting rhunk to an IRQ table */ + inline operator CThunkEntry(void) + { + return (CThunkEntry)entry(); + } + + /* get thunk entry point for connecting rhunk to an IRQ table */ + inline operator uint32_t(void) + { + return entry(); + } + + /* simple test function */ + inline void call(void) + { + (((CThunkEntry)(entry()))()); + } + +private: + T *m_instance; + volatile CCallback m_callback; // TODO: this needs proper fix, to refactor toolchain header file and all its use // PACKED there is not defined properly for IAR #if defined (__ICCARM__) - typedef __packed struct - { - CTHUNK_VARIABLES; - volatile uint32_t instance; - volatile uint32_t context; - volatile uint32_t callback; - volatile uint32_t trampoline; - } CThunkTrampoline; + typedef __packed struct { + CTHUNK_VARIABLES; + volatile uint32_t instance; + volatile uint32_t context; + volatile uint32_t callback; + volatile uint32_t trampoline; + } CThunkTrampoline; #else - typedef struct - { - CTHUNK_VARIABLES; - volatile uint32_t instance; - volatile uint32_t context; - volatile uint32_t callback; - volatile uint32_t trampoline; - } __attribute__((__packed__)) CThunkTrampoline; + typedef struct { + CTHUNK_VARIABLES; + volatile uint32_t instance; + volatile uint32_t context; + volatile uint32_t callback; + volatile uint32_t trampoline; + } __attribute__((__packed__)) CThunkTrampoline; #endif - static void trampoline(T* instance, void* context, CCallback* callback) - { - if(instance && *callback) { - (static_cast(instance)->**callback)(context); - } + static void trampoline(T *instance, void *context, CCallback *callback) + { + if (instance && *callback) { + (static_cast(instance)->**callback)(context); } + } - volatile CThunkTrampoline m_thunk; + volatile CThunkTrampoline m_thunk; - inline void init(T *instance, CCallback callback, void* context) - { - /* remember callback - need to add this level of redirection - as pointer size for member functions differs between platforms */ - m_callback = callback; + inline void init(T *instance, CCallback callback, void *context) + { + /* remember callback - need to add this level of redirection + as pointer size for member functions differs between platforms */ + m_callback = callback; - /* populate thunking trampoline */ - CTHUNK_ASSIGMENT; - m_thunk.context = (uint32_t)context; - m_thunk.instance = (uint32_t)instance; - m_thunk.callback = (uint32_t)&m_callback; - m_thunk.trampoline = (uint32_t)&trampoline; + /* populate thunking trampoline */ + CTHUNK_ASSIGMENT; + m_thunk.context = (uint32_t)context; + m_thunk.instance = (uint32_t)instance; + m_thunk.callback = (uint32_t)&m_callback; + m_thunk.trampoline = (uint32_t)&trampoline; #if defined(__CORTEX_A9) - /* Data cache clean */ - /* Cache control */ - { - uint32_t start_addr = (uint32_t)&m_thunk & 0xFFFFFFE0; - uint32_t end_addr = (uint32_t)&m_thunk + sizeof(m_thunk); - uint32_t addr; - - /* Data cache clean and invalid */ - for (addr = start_addr; addr < end_addr; addr += 0x20) { - L1C_CleanInvalidateDCacheMVA((void *)addr); - } - /* Instruction cache invalid */ - L1C_InvalidateICacheAll(); - MMU_InvalidateTLB(); - L1C_InvalidateBTAC(); + /* Data cache clean */ + /* Cache control */ + { + uint32_t start_addr = (uint32_t)&m_thunk & 0xFFFFFFE0; + uint32_t end_addr = (uint32_t)&m_thunk + sizeof(m_thunk); + uint32_t addr; + + /* Data cache clean and invalid */ + for (addr = start_addr; addr < end_addr; addr += 0x20) { + L1C_CleanInvalidateDCacheMVA((void *)addr); } + /* Instruction cache invalid */ + L1C_InvalidateICacheAll(); + MMU_InvalidateTLB(); + L1C_InvalidateBTAC(); + } #endif #if defined(__CORTEX_M7) - /* Data cache clean and invalid */ - SCB_CleanInvalidateDCache(); + /* Data cache clean and invalid */ + SCB_CleanInvalidateDCache(); - /* Instruction cache invalid */ - SCB_InvalidateICache(); + /* Instruction cache invalid */ + SCB_InvalidateICache(); #endif - __ISB(); - __DSB(); - } + __ISB(); + __DSB(); + } }; /**@}*/ diff --git a/platform/CallChain.cpp b/platform/CallChain.cpp index ebddc0fedcb..6a72d932a40 100644 --- a/platform/CallChain.cpp +++ b/platform/CallChain.cpp @@ -13,26 +13,31 @@ namespace mbed { class CallChainLink { public: - CallChainLink(): cb(), next(NULL) { + CallChainLink(): cb(), next(NULL) + { // No work to do } - CallChainLink(Callback &callback): cb(callback), next(NULL) { + CallChainLink(Callback &callback): cb(callback), next(NULL) + { // No work to do } Callback cb; - CallChainLink * next; + CallChainLink *next; }; -CallChain::CallChain(int size) : _chain(NULL) { +CallChain::CallChain(int size) : _chain(NULL) +{ // No work to do } -CallChain::~CallChain() { +CallChain::~CallChain() +{ clear(); } -pFunctionPointer_t CallChain::add(Callback func) { +pFunctionPointer_t CallChain::add(Callback func) +{ CallChainLink *new_link = new CallChainLink(func); if (NULL == _chain) { _chain = new_link; @@ -49,14 +54,16 @@ pFunctionPointer_t CallChain::add(Callback func) { } } -pFunctionPointer_t CallChain::add_front(Callback func) { +pFunctionPointer_t CallChain::add_front(Callback func) +{ CallChainLink *link = new CallChainLink(func); link->next = _chain; _chain = link; return &link->cb; } -int CallChain::size() const { +int CallChain::size() const +{ CallChainLink *link = _chain; int elements = 0; while (link != NULL) { @@ -66,7 +73,8 @@ int CallChain::size() const { return elements; } -pFunctionPointer_t CallChain::get(int idx) const { +pFunctionPointer_t CallChain::get(int idx) const +{ CallChainLink *link = _chain; for (int i = 0; i < idx; i++) { if (NULL == link) { @@ -77,7 +85,8 @@ pFunctionPointer_t CallChain::get(int idx) const { return &link->cb; } -int CallChain::find(pFunctionPointer_t f) const { +int CallChain::find(pFunctionPointer_t f) const +{ CallChainLink *link = _chain; int i = 0; while (link != NULL) { @@ -90,7 +99,8 @@ int CallChain::find(pFunctionPointer_t f) const { return -1; } -void CallChain::clear() { +void CallChain::clear() +{ CallChainLink *link = _chain; _chain = NULL; while (link != NULL) { @@ -100,7 +110,8 @@ void CallChain::clear() { } } -bool CallChain::remove(pFunctionPointer_t f) { +bool CallChain::remove(pFunctionPointer_t f) +{ CallChainLink *link = _chain; while (link != NULL) { if (f == &link->cb) { @@ -112,7 +123,8 @@ bool CallChain::remove(pFunctionPointer_t f) { return false; } -void CallChain::call() { +void CallChain::call() +{ CallChainLink *link = _chain; while (link != NULL) { link->cb.call(); diff --git a/platform/CallChain.h b/platform/CallChain.h index 025a4a7a9eb..b2a0fb0c9b9 100644 --- a/platform/CallChain.h +++ b/platform/CallChain.h @@ -78,11 +78,11 @@ class CallChain : private NonCopyable { * @param size (optional) Initial size of the chain */ MBED_DEPRECATED_SINCE("mbed-os-5.6", "This class is not part of the " - "public API of mbed-os and is being removed in the future.") + "public API of mbed-os and is being removed in the future.") CallChain(int size = 4); MBED_DEPRECATED_SINCE("mbed-os-5.6", "This class is not part of the " - "public API of mbed-os and is being removed in the future.") + "public API of mbed-os and is being removed in the future.") virtual ~CallChain(); /** Add a function at the end of the chain @@ -93,7 +93,7 @@ class CallChain : private NonCopyable { * The function object created for 'func' */ MBED_DEPRECATED_SINCE("mbed-os-5.6", "This class is not part of the " - "public API of mbed-os and is being removed in the future.") + "public API of mbed-os and is being removed in the future.") pFunctionPointer_t add(Callback func); /** Add a function at the end of the chain @@ -110,9 +110,10 @@ class CallChain : private NonCopyable { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "The add function does not support cv-qualifiers. Replaced by " - "add(callback(obj, method)).") - pFunctionPointer_t add(T *obj, M method) { + "The add function does not support cv-qualifiers. Replaced by " + "add(callback(obj, method)).") + pFunctionPointer_t add(T *obj, M method) + { return add(callback(obj, method)); } @@ -124,7 +125,7 @@ class CallChain : private NonCopyable { * The function object created for 'func' */ MBED_DEPRECATED_SINCE("mbed-os-5.6", "This class is not part of the " - "public API of mbed-os and is being removed in the future.") + "public API of mbed-os and is being removed in the future.") pFunctionPointer_t add_front(Callback func); /** Add a function at the beginning of the chain @@ -141,16 +142,17 @@ class CallChain : private NonCopyable { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "The add_front function does not support cv-qualifiers. Replaced by " - "add_front(callback(obj, method)).") - pFunctionPointer_t add_front(T *obj, M method) { + "The add_front function does not support cv-qualifiers. Replaced by " + "add_front(callback(obj, method)).") + pFunctionPointer_t add_front(T *obj, M method) + { return add_front(callback(obj, method)); } /** Get the number of functions in the chain */ MBED_DEPRECATED_SINCE("mbed-os-5.6", "This class is not part of the " - "public API of mbed-os and is being removed in the future.") + "public API of mbed-os and is being removed in the future.") int size() const; /** Get a function object from the chain @@ -161,7 +163,7 @@ class CallChain : private NonCopyable { * The function object at position 'i' in the chain */ MBED_DEPRECATED_SINCE("mbed-os-5.6", "This class is not part of the " - "public API of mbed-os and is being removed in the future.") + "public API of mbed-os and is being removed in the future.") pFunctionPointer_t get(int i) const; /** Look for a function object in the call chain @@ -172,13 +174,13 @@ class CallChain : private NonCopyable { * The index of the function object if found, -1 otherwise. */ MBED_DEPRECATED_SINCE("mbed-os-5.6", "This class is not part of the " - "public API of mbed-os and is being removed in the future.") + "public API of mbed-os and is being removed in the future.") int find(pFunctionPointer_t f) const; /** Clear the call chain (remove all functions in the chain). */ MBED_DEPRECATED_SINCE("mbed-os-5.6", "This class is not part of the " - "public API of mbed-os and is being removed in the future.") + "public API of mbed-os and is being removed in the future.") void clear(); /** Remove a function object from the chain @@ -189,24 +191,26 @@ class CallChain : private NonCopyable { * true if the function object was found and removed, false otherwise. */ MBED_DEPRECATED_SINCE("mbed-os-5.6", "This class is not part of the " - "public API of mbed-os and is being removed in the future.") + "public API of mbed-os and is being removed in the future.") bool remove(pFunctionPointer_t f); /** Call all the functions in the chain in sequence */ MBED_DEPRECATED_SINCE("mbed-os-5.6", "This class is not part of the " - "public API of mbed-os and is being removed in the future.") + "public API of mbed-os and is being removed in the future.") void call(); MBED_DEPRECATED_SINCE("mbed-os-5.6", "This class is not part of the " - "public API of mbed-os and is being removed in the future.") - void operator ()(void) { + "public API of mbed-os and is being removed in the future.") + void operator()(void) + { call(); } MBED_DEPRECATED_SINCE("mbed-os-5.6", "This class is not part of the " - "public API of mbed-os and is being removed in the future.") - pFunctionPointer_t operator [](int i) const { + "public API of mbed-os and is being removed in the future.") + pFunctionPointer_t operator [](int i) const + { return get(i); } diff --git a/platform/Callback.h b/platform/Callback.h index b300afefadc..a4c647dcc19 100644 --- a/platform/Callback.h +++ b/platform/Callback.h @@ -47,18 +47,20 @@ class Callback; // massive and misleading error messages when confronted with an // invalid type (or worse, runtime failures) namespace detail { - struct nil {}; +struct nil {}; - template - struct enable_if { typedef R type; }; +template +struct enable_if { + typedef R type; +}; - template - struct enable_if {}; +template +struct enable_if {}; - template - struct is_type { - static const bool value = true; - }; +template +struct is_type { + static const bool value = true; +}; } #define MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, M) \ @@ -77,7 +79,8 @@ class Callback { /** Create a Callback with a static function * @param func Static function to attach */ - Callback(R (*func)() = 0) { + Callback(R(*func)() = 0) + { if (!func) { memset(this, 0, sizeof(Callback)); } else { @@ -88,7 +91,8 @@ class Callback { /** Attach a Callback * @param func The Callback to attach */ - Callback(const Callback &func) { + Callback(const Callback &func) + { if (func._ops) { func._ops->move(this, &func); } @@ -100,8 +104,9 @@ class Callback { * @param method Member function to attach */ template - Callback(U *obj, R (T::*method)()) { - generate(method_context(obj, method)); + Callback(U *obj, R(T::*method)()) + { + generate(method_context(obj, method)); } /** Create a Callback with a member function @@ -109,8 +114,9 @@ class Callback { * @param method Member function to attach */ template - Callback(const U *obj, R (T::*method)() const) { - generate(method_context(obj, method)); + Callback(const U *obj, R(T::*method)() const) + { + generate(method_context(obj, method)); } /** Create a Callback with a member function @@ -118,8 +124,9 @@ class Callback { * @param method Member function to attach */ template - Callback(volatile U *obj, R (T::*method)() volatile) { - generate(method_context(obj, method)); + Callback(volatile U *obj, R(T::*method)() volatile) + { + generate(method_context(obj, method)); } /** Create a Callback with a member function @@ -127,44 +134,49 @@ class Callback { * @param method Member function to attach */ template - Callback(const volatile U *obj, R (T::*method)() const volatile) { - generate(method_context(obj, method)); + Callback(const volatile U *obj, R(T::*method)() const volatile) + { + generate(method_context(obj, method)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(T*), U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(T *), U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(const T*), const U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(const T *), const U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(volatile T*), volatile U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(volatile T *), volatile U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(const volatile T*), const volatile U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(const volatile T *), const volatile U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a function object @@ -172,7 +184,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)())) { + Callback(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)())) + { generate(f); } @@ -181,7 +194,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)() const)) { + Callback(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)() const)) + { generate(f); } @@ -190,7 +204,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)() volatile)) { + Callback(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)() volatile)) + { generate(f); } @@ -199,7 +214,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)() const volatile)) { + Callback(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)() const volatile)) + { generate(f); } @@ -211,8 +227,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(U *obj, R (*func)(T*)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(U *obj, R(*func)(T *)) + { new (this) Callback(func, obj); } @@ -224,8 +241,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(const U *obj, R (*func)(const T*)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(const U *obj, R(*func)(const T *)) + { new (this) Callback(func, obj); } @@ -237,8 +255,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(volatile U *obj, R (*func)(volatile T*)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(volatile U *obj, R(*func)(volatile T *)) + { new (this) Callback(func, obj); } @@ -250,14 +269,16 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(const volatile U *obj, R (*func)(const volatile T*)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(const volatile U *obj, R(*func)(const volatile T *)) + { new (this) Callback(func, obj); } /** Destroy a callback */ - ~Callback() { + ~Callback() + { if (_ops) { _ops->dtor(this); } @@ -269,8 +290,9 @@ class Callback { * Replaced by simple assignment 'Callback cb = func' */ MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)()) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)()) + { this->~Callback(); new (this) Callback(func); } @@ -281,8 +303,9 @@ class Callback { * Replaced by simple assignment 'Callback cb = func' */ MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const Callback &func) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const Callback &func) + { this->~Callback(); new (this) Callback(func); } @@ -295,8 +318,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(U *obj, R (T::*method)()) { + "Replaced by simple assignment 'Callback cb = func") + void attach(U *obj, R(T::*method)()) + { this->~Callback(); new (this) Callback(obj, method); } @@ -309,8 +333,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const U *obj, R (T::*method)() const) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const U *obj, R(T::*method)() const) + { this->~Callback(); new (this) Callback(obj, method); } @@ -323,8 +348,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(volatile U *obj, R (T::*method)() volatile) { + "Replaced by simple assignment 'Callback cb = func") + void attach(volatile U *obj, R(T::*method)() volatile) + { this->~Callback(); new (this) Callback(obj, method); } @@ -337,8 +363,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const volatile U *obj, R (T::*method)() const volatile) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const volatile U *obj, R(T::*method)() const volatile) + { this->~Callback(); new (this) Callback(obj, method); } @@ -351,8 +378,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(T*), U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(T *), U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -365,8 +393,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(const T*), const U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(const T *), const U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -379,8 +408,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(volatile T*), volatile U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(volatile T *), volatile U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -393,8 +423,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(const volatile T*), const volatile U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(const volatile T *), const volatile U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -407,8 +438,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)())) { + "Replaced by simple assignment 'Callback cb = func") + void attach(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)())) + { this->~Callback(); new (this) Callback(f); } @@ -421,8 +453,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)() const)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)() const)) + { this->~Callback(); new (this) Callback(f); } @@ -435,8 +468,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)() volatile)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)() volatile)) + { this->~Callback(); new (this) Callback(f); } @@ -449,8 +483,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)() const volatile)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)() const volatile)) + { this->~Callback(); new (this) Callback(f); } @@ -463,8 +498,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(U *obj, R (*func)(T*)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(U *obj, R(*func)(T *)) + { this->~Callback(); new (this) Callback(func, obj); } @@ -477,8 +513,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(const U *obj, R (*func)(const T*)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(const U *obj, R(*func)(const T *)) + { this->~Callback(); new (this) Callback(func, obj); } @@ -491,8 +528,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(volatile U *obj, R (*func)(volatile T*)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(volatile U *obj, R(*func)(volatile T *)) + { this->~Callback(); new (this) Callback(func, obj); } @@ -505,15 +543,17 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(const volatile U *obj, R (*func)(const volatile T*)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(const volatile U *obj, R(*func)(const volatile T *)) + { this->~Callback(); new (this) Callback(func, obj); } /** Assign a callback */ - Callback &operator=(const Callback &that) { + Callback &operator=(const Callback &that) + { if (this != &that) { this->~Callback(); new (this) Callback(that); @@ -524,42 +564,48 @@ class Callback { /** Call the attached function */ - R call() const { + R call() const + { MBED_ASSERT(_ops); return _ops->call(this); } /** Call the attached function */ - R operator()() const { + R operator()() const + { return call(); } /** Test if function has been attached */ - operator bool() const { + operator bool() const + { return _ops; } /** Test for equality */ - friend bool operator==(const Callback &l, const Callback &r) { + friend bool operator==(const Callback &l, const Callback &r) + { return memcmp(&l, &r, sizeof(Callback)) == 0; } /** Test for inequality */ - friend bool operator!=(const Callback &l, const Callback &r) { + friend bool operator!=(const Callback &l, const Callback &r) + { return !(l == r); } /** Static thunk for passing as C-style function * @param func Callback to call passed as void pointer - * @return the value as determined by func which is of + * @return the value as determined by func which is of * type and determined by the signiture of func */ - static R thunk(void *func) { - return static_cast(func)->call(); + static R thunk(void *func) + { + return static_cast(func)->call(); } private: @@ -569,21 +615,22 @@ class Callback { struct _class; union { void (*_staticfunc)(); - void (*_boundfunc)(_class*); + void (*_boundfunc)(_class *); void (_class::*_methodfunc)(); } _func; void *_obj; // Dynamically dispatched operations const struct ops { - R (*call)(const void*); - void (*move)(void*, const void*); - void (*dtor)(void*); + R(*call)(const void *); + void (*move)(void *, const void *); + void (*dtor)(void *); } *_ops; // Generate operations for function object template - void generate(const F &f) { + void generate(const F &f) + { static const ops ops = { &Callback::function_call, &Callback::function_move, @@ -591,7 +638,7 @@ class Callback { }; MBED_STATIC_ASSERT(sizeof(Callback) - sizeof(_ops) >= sizeof(F), - "Type F must not exceed the size of the Callback class"); + "Type F must not exceed the size of the Callback class"); memset(this, 0, sizeof(Callback)); new (this) F(f); _ops = &ops; @@ -599,18 +646,21 @@ class Callback { // Function attributes template - static R function_call(const void *p) { - return (*(F*)p)(); + static R function_call(const void *p) + { + return (*(F *)p)(); } template - static void function_move(void *d, const void *p) { - new (d) F(*(F*)p); + static void function_move(void *d, const void *p) + { + new (d) F(*(F *)p); } template - static void function_dtor(void *p) { - ((F*)p)->~F(); + static void function_dtor(void *p) + { + ((F *)p)->~F(); } // Wrappers for functions with context @@ -622,7 +672,8 @@ class Callback { method_context(O *obj, M method) : method(method), obj(obj) {} - R operator()() const { + R operator()() const + { return (obj->*method)(); } }; @@ -635,7 +686,8 @@ class Callback { function_context(F func, A *arg) : func(func), arg(arg) {} - R operator()() const { + R operator()() const + { return func(arg); } }; @@ -651,7 +703,8 @@ class Callback { /** Create a Callback with a static function * @param func Static function to attach */ - Callback(R (*func)(A0) = 0) { + Callback(R(*func)(A0) = 0) + { if (!func) { memset(this, 0, sizeof(Callback)); } else { @@ -662,7 +715,8 @@ class Callback { /** Attach a Callback * @param func The Callback to attach */ - Callback(const Callback &func) { + Callback(const Callback &func) + { if (func._ops) { func._ops->move(this, &func); } @@ -674,8 +728,9 @@ class Callback { * @param method Member function to attach */ template - Callback(U *obj, R (T::*method)(A0)) { - generate(method_context(obj, method)); + Callback(U *obj, R(T::*method)(A0)) + { + generate(method_context(obj, method)); } /** Create a Callback with a member function @@ -683,8 +738,9 @@ class Callback { * @param method Member function to attach */ template - Callback(const U *obj, R (T::*method)(A0) const) { - generate(method_context(obj, method)); + Callback(const U *obj, R(T::*method)(A0) const) + { + generate(method_context(obj, method)); } /** Create a Callback with a member function @@ -692,8 +748,9 @@ class Callback { * @param method Member function to attach */ template - Callback(volatile U *obj, R (T::*method)(A0) volatile) { - generate(method_context(obj, method)); + Callback(volatile U *obj, R(T::*method)(A0) volatile) + { + generate(method_context(obj, method)); } /** Create a Callback with a member function @@ -701,44 +758,49 @@ class Callback { * @param method Member function to attach */ template - Callback(const volatile U *obj, R (T::*method)(A0) const volatile) { - generate(method_context(obj, method)); + Callback(const volatile U *obj, R(T::*method)(A0) const volatile) + { + generate(method_context(obj, method)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(T*, A0), U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(T *, A0), U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(const T*, A0), const U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(const T *, A0), const U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(volatile T*, A0), volatile U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(volatile T *, A0), volatile U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(const volatile T*, A0), const volatile U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(const volatile T *, A0), const volatile U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a function object @@ -746,7 +808,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0))) { + Callback(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0))) + { generate(f); } @@ -755,7 +818,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0) const)) { + Callback(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0) const)) + { generate(f); } @@ -764,7 +828,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0) volatile)) { + Callback(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0) volatile)) + { generate(f); } @@ -773,7 +838,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0) const volatile)) { + Callback(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0) const volatile)) + { generate(f); } @@ -785,8 +851,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(U *obj, R (*func)(T*, A0)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(U *obj, R(*func)(T *, A0)) + { new (this) Callback(func, obj); } @@ -798,8 +865,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(const U *obj, R (*func)(const T*, A0)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(const U *obj, R(*func)(const T *, A0)) + { new (this) Callback(func, obj); } @@ -811,8 +879,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(volatile U *obj, R (*func)(volatile T*, A0)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(volatile U *obj, R(*func)(volatile T *, A0)) + { new (this) Callback(func, obj); } @@ -824,14 +893,16 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(const volatile U *obj, R (*func)(const volatile T*, A0)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(const volatile U *obj, R(*func)(const volatile T *, A0)) + { new (this) Callback(func, obj); } /** Destroy a callback */ - ~Callback() { + ~Callback() + { if (_ops) { _ops->dtor(this); } @@ -843,8 +914,9 @@ class Callback { * Replaced by simple assignment 'Callback cb = func' */ MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(A0)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(A0)) + { this->~Callback(); new (this) Callback(func); } @@ -855,8 +927,9 @@ class Callback { * Replaced by simple assignment 'Callback cb = func' */ MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const Callback &func) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const Callback &func) + { this->~Callback(); new (this) Callback(func); } @@ -869,8 +942,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(U *obj, R (T::*method)(A0)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(U *obj, R(T::*method)(A0)) + { this->~Callback(); new (this) Callback(obj, method); } @@ -883,8 +957,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const U *obj, R (T::*method)(A0) const) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const U *obj, R(T::*method)(A0) const) + { this->~Callback(); new (this) Callback(obj, method); } @@ -897,8 +972,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(volatile U *obj, R (T::*method)(A0) volatile) { + "Replaced by simple assignment 'Callback cb = func") + void attach(volatile U *obj, R(T::*method)(A0) volatile) + { this->~Callback(); new (this) Callback(obj, method); } @@ -911,8 +987,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const volatile U *obj, R (T::*method)(A0) const volatile) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const volatile U *obj, R(T::*method)(A0) const volatile) + { this->~Callback(); new (this) Callback(obj, method); } @@ -925,8 +1002,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(T*, A0), U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(T *, A0), U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -939,8 +1017,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(const T*, A0), const U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(const T *, A0), const U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -953,8 +1032,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(volatile T*, A0), volatile U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(volatile T *, A0), volatile U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -967,8 +1047,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(const volatile T*, A0), const volatile U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(const volatile T *, A0), const volatile U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -981,8 +1062,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0))) { + "Replaced by simple assignment 'Callback cb = func") + void attach(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0))) + { this->~Callback(); new (this) Callback(f); } @@ -995,8 +1077,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0) const)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0) const)) + { this->~Callback(); new (this) Callback(f); } @@ -1009,8 +1092,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0) volatile)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0) volatile)) + { this->~Callback(); new (this) Callback(f); } @@ -1023,8 +1107,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0) const volatile)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0) const volatile)) + { this->~Callback(); new (this) Callback(f); } @@ -1037,8 +1122,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(U *obj, R (*func)(T*, A0)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(U *obj, R(*func)(T *, A0)) + { this->~Callback(); new (this) Callback(func, obj); } @@ -1051,8 +1137,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(const U *obj, R (*func)(const T*, A0)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(const U *obj, R(*func)(const T *, A0)) + { this->~Callback(); new (this) Callback(func, obj); } @@ -1065,8 +1152,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(volatile U *obj, R (*func)(volatile T*, A0)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(volatile U *obj, R(*func)(volatile T *, A0)) + { this->~Callback(); new (this) Callback(func, obj); } @@ -1079,15 +1167,17 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(const volatile U *obj, R (*func)(const volatile T*, A0)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(const volatile U *obj, R(*func)(const volatile T *, A0)) + { this->~Callback(); new (this) Callback(func, obj); } /** Assign a callback */ - Callback &operator=(const Callback &that) { + Callback &operator=(const Callback &that) + { if (this != &that) { this->~Callback(); new (this) Callback(that); @@ -1098,43 +1188,49 @@ class Callback { /** Call the attached function */ - R call(A0 a0) const { + R call(A0 a0) const + { MBED_ASSERT(_ops); return _ops->call(this, a0); } /** Call the attached function */ - R operator()(A0 a0) const { + R operator()(A0 a0) const + { return call(a0); } /** Test if function has been attached */ - operator bool() const { + operator bool() const + { return _ops; } /** Test for equality */ - friend bool operator==(const Callback &l, const Callback &r) { + friend bool operator==(const Callback &l, const Callback &r) + { return memcmp(&l, &r, sizeof(Callback)) == 0; } /** Test for inequality */ - friend bool operator!=(const Callback &l, const Callback &r) { + friend bool operator!=(const Callback &l, const Callback &r) + { return !(l == r); } /** Static thunk for passing as C-style function * @param func Callback to call passed as void pointer * @param a0 An argument to be called with function func - * @return the value as determined by func which is of + * @return the value as determined by func which is of * type and determined by the signiture of func */ - static R thunk(void *func, A0 a0) { - return static_cast(func)->call(a0); + static R thunk(void *func, A0 a0) + { + return static_cast(func)->call(a0); } private: @@ -1144,21 +1240,22 @@ class Callback { struct _class; union { void (*_staticfunc)(A0); - void (*_boundfunc)(_class*, A0); + void (*_boundfunc)(_class *, A0); void (_class::*_methodfunc)(A0); } _func; void *_obj; // Dynamically dispatched operations const struct ops { - R (*call)(const void*, A0); - void (*move)(void*, const void*); - void (*dtor)(void*); + R(*call)(const void *, A0); + void (*move)(void *, const void *); + void (*dtor)(void *); } *_ops; // Generate operations for function object template - void generate(const F &f) { + void generate(const F &f) + { static const ops ops = { &Callback::function_call, &Callback::function_move, @@ -1166,7 +1263,7 @@ class Callback { }; MBED_STATIC_ASSERT(sizeof(Callback) - sizeof(_ops) >= sizeof(F), - "Type F must not exceed the size of the Callback class"); + "Type F must not exceed the size of the Callback class"); memset(this, 0, sizeof(Callback)); new (this) F(f); _ops = &ops; @@ -1174,18 +1271,21 @@ class Callback { // Function attributes template - static R function_call(const void *p, A0 a0) { - return (*(F*)p)(a0); + static R function_call(const void *p, A0 a0) + { + return (*(F *)p)(a0); } template - static void function_move(void *d, const void *p) { - new (d) F(*(F*)p); + static void function_move(void *d, const void *p) + { + new (d) F(*(F *)p); } template - static void function_dtor(void *p) { - ((F*)p)->~F(); + static void function_dtor(void *p) + { + ((F *)p)->~F(); } // Wrappers for functions with context @@ -1197,7 +1297,8 @@ class Callback { method_context(O *obj, M method) : method(method), obj(obj) {} - R operator()(A0 a0) const { + R operator()(A0 a0) const + { return (obj->*method)(a0); } }; @@ -1210,7 +1311,8 @@ class Callback { function_context(F func, A *arg) : func(func), arg(arg) {} - R operator()(A0 a0) const { + R operator()(A0 a0) const + { return func(arg, a0); } }; @@ -1226,7 +1328,8 @@ class Callback { /** Create a Callback with a static function * @param func Static function to attach */ - Callback(R (*func)(A0, A1) = 0) { + Callback(R(*func)(A0, A1) = 0) + { if (!func) { memset(this, 0, sizeof(Callback)); } else { @@ -1237,7 +1340,8 @@ class Callback { /** Attach a Callback * @param func The Callback to attach */ - Callback(const Callback &func) { + Callback(const Callback &func) + { if (func._ops) { func._ops->move(this, &func); } @@ -1249,8 +1353,9 @@ class Callback { * @param method Member function to attach */ template - Callback(U *obj, R (T::*method)(A0, A1)) { - generate(method_context(obj, method)); + Callback(U *obj, R(T::*method)(A0, A1)) + { + generate(method_context(obj, method)); } /** Create a Callback with a member function @@ -1258,8 +1363,9 @@ class Callback { * @param method Member function to attach */ template - Callback(const U *obj, R (T::*method)(A0, A1) const) { - generate(method_context(obj, method)); + Callback(const U *obj, R(T::*method)(A0, A1) const) + { + generate(method_context(obj, method)); } /** Create a Callback with a member function @@ -1267,8 +1373,9 @@ class Callback { * @param method Member function to attach */ template - Callback(volatile U *obj, R (T::*method)(A0, A1) volatile) { - generate(method_context(obj, method)); + Callback(volatile U *obj, R(T::*method)(A0, A1) volatile) + { + generate(method_context(obj, method)); } /** Create a Callback with a member function @@ -1276,44 +1383,49 @@ class Callback { * @param method Member function to attach */ template - Callback(const volatile U *obj, R (T::*method)(A0, A1) const volatile) { - generate(method_context(obj, method)); + Callback(const volatile U *obj, R(T::*method)(A0, A1) const volatile) + { + generate(method_context(obj, method)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(T*, A0, A1), U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(T *, A0, A1), U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(const T*, A0, A1), const U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(const T *, A0, A1), const U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(volatile T*, A0, A1), volatile U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(volatile T *, A0, A1), volatile U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(const volatile T*, A0, A1), const volatile U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(const volatile T *, A0, A1), const volatile U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a function object @@ -1321,7 +1433,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1))) { + Callback(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1))) + { generate(f); } @@ -1330,7 +1443,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1) const)) { + Callback(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1) const)) + { generate(f); } @@ -1339,7 +1453,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1) volatile)) { + Callback(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1) volatile)) + { generate(f); } @@ -1348,7 +1463,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1) const volatile)) { + Callback(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1) const volatile)) + { generate(f); } @@ -1360,8 +1476,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(U *obj, R (*func)(T*, A0, A1)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(U *obj, R(*func)(T *, A0, A1)) + { new (this) Callback(func, obj); } @@ -1373,8 +1490,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(const U *obj, R (*func)(const T*, A0, A1)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(const U *obj, R(*func)(const T *, A0, A1)) + { new (this) Callback(func, obj); } @@ -1386,8 +1504,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(volatile U *obj, R (*func)(volatile T*, A0, A1)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(volatile U *obj, R(*func)(volatile T *, A0, A1)) + { new (this) Callback(func, obj); } @@ -1399,14 +1518,16 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(const volatile U *obj, R (*func)(const volatile T*, A0, A1)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(const volatile U *obj, R(*func)(const volatile T *, A0, A1)) + { new (this) Callback(func, obj); } /** Destroy a callback */ - ~Callback() { + ~Callback() + { if (_ops) { _ops->dtor(this); } @@ -1418,8 +1539,9 @@ class Callback { * Replaced by simple assignment 'Callback cb = func' */ MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(A0, A1)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(A0, A1)) + { this->~Callback(); new (this) Callback(func); } @@ -1430,8 +1552,9 @@ class Callback { * Replaced by simple assignment 'Callback cb = func' */ MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const Callback &func) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const Callback &func) + { this->~Callback(); new (this) Callback(func); } @@ -1444,8 +1567,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(U *obj, R (T::*method)(A0, A1)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(U *obj, R(T::*method)(A0, A1)) + { this->~Callback(); new (this) Callback(obj, method); } @@ -1458,8 +1582,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const U *obj, R (T::*method)(A0, A1) const) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const U *obj, R(T::*method)(A0, A1) const) + { this->~Callback(); new (this) Callback(obj, method); } @@ -1472,8 +1597,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(volatile U *obj, R (T::*method)(A0, A1) volatile) { + "Replaced by simple assignment 'Callback cb = func") + void attach(volatile U *obj, R(T::*method)(A0, A1) volatile) + { this->~Callback(); new (this) Callback(obj, method); } @@ -1486,8 +1612,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const volatile U *obj, R (T::*method)(A0, A1) const volatile) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const volatile U *obj, R(T::*method)(A0, A1) const volatile) + { this->~Callback(); new (this) Callback(obj, method); } @@ -1500,8 +1627,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(T*, A0, A1), U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(T *, A0, A1), U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -1514,8 +1642,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(const T*, A0, A1), const U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(const T *, A0, A1), const U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -1528,8 +1657,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(volatile T*, A0, A1), volatile U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(volatile T *, A0, A1), volatile U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -1542,8 +1672,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(const volatile T*, A0, A1), const volatile U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(const volatile T *, A0, A1), const volatile U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -1556,8 +1687,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1))) { + "Replaced by simple assignment 'Callback cb = func") + void attach(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1))) + { this->~Callback(); new (this) Callback(f); } @@ -1570,8 +1702,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1) const)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1) const)) + { this->~Callback(); new (this) Callback(f); } @@ -1584,8 +1717,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1) volatile)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1) volatile)) + { this->~Callback(); new (this) Callback(f); } @@ -1598,8 +1732,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1) const volatile)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1) const volatile)) + { this->~Callback(); new (this) Callback(f); } @@ -1612,8 +1747,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(U *obj, R (*func)(T*, A0, A1)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(U *obj, R(*func)(T *, A0, A1)) + { this->~Callback(); new (this) Callback(func, obj); } @@ -1626,8 +1762,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(const U *obj, R (*func)(const T*, A0, A1)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(const U *obj, R(*func)(const T *, A0, A1)) + { this->~Callback(); new (this) Callback(func, obj); } @@ -1640,8 +1777,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(volatile U *obj, R (*func)(volatile T*, A0, A1)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(volatile U *obj, R(*func)(volatile T *, A0, A1)) + { this->~Callback(); new (this) Callback(func, obj); } @@ -1654,15 +1792,17 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(const volatile U *obj, R (*func)(const volatile T*, A0, A1)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(const volatile U *obj, R(*func)(const volatile T *, A0, A1)) + { this->~Callback(); new (this) Callback(func, obj); } /** Assign a callback */ - Callback &operator=(const Callback &that) { + Callback &operator=(const Callback &that) + { if (this != &that) { this->~Callback(); new (this) Callback(that); @@ -1673,32 +1813,37 @@ class Callback { /** Call the attached function */ - R call(A0 a0, A1 a1) const { + R call(A0 a0, A1 a1) const + { MBED_ASSERT(_ops); return _ops->call(this, a0, a1); } /** Call the attached function */ - R operator()(A0 a0, A1 a1) const { + R operator()(A0 a0, A1 a1) const + { return call(a0, a1); } /** Test if function has been attached */ - operator bool() const { + operator bool() const + { return _ops; } /** Test for equality */ - friend bool operator==(const Callback &l, const Callback &r) { + friend bool operator==(const Callback &l, const Callback &r) + { return memcmp(&l, &r, sizeof(Callback)) == 0; } /** Test for inequality */ - friend bool operator!=(const Callback &l, const Callback &r) { + friend bool operator!=(const Callback &l, const Callback &r) + { return !(l == r); } @@ -1706,11 +1851,12 @@ class Callback { * @param func Callback to call passed as void pointer * @param a0 An argument to be called with function func * @param a1 An argument to be called with function func - * @return the value as determined by func which is of + * @return the value as determined by func which is of * type and determined by the signiture of func */ - static R thunk(void *func, A0 a0, A1 a1) { - return static_cast(func)->call(a0, a1); + static R thunk(void *func, A0 a0, A1 a1) + { + return static_cast(func)->call(a0, a1); } private: @@ -1720,21 +1866,22 @@ class Callback { struct _class; union { void (*_staticfunc)(A0, A1); - void (*_boundfunc)(_class*, A0, A1); + void (*_boundfunc)(_class *, A0, A1); void (_class::*_methodfunc)(A0, A1); } _func; void *_obj; // Dynamically dispatched operations const struct ops { - R (*call)(const void*, A0, A1); - void (*move)(void*, const void*); - void (*dtor)(void*); + R(*call)(const void *, A0, A1); + void (*move)(void *, const void *); + void (*dtor)(void *); } *_ops; // Generate operations for function object template - void generate(const F &f) { + void generate(const F &f) + { static const ops ops = { &Callback::function_call, &Callback::function_move, @@ -1742,7 +1889,7 @@ class Callback { }; MBED_STATIC_ASSERT(sizeof(Callback) - sizeof(_ops) >= sizeof(F), - "Type F must not exceed the size of the Callback class"); + "Type F must not exceed the size of the Callback class"); memset(this, 0, sizeof(Callback)); new (this) F(f); _ops = &ops; @@ -1750,18 +1897,21 @@ class Callback { // Function attributes template - static R function_call(const void *p, A0 a0, A1 a1) { - return (*(F*)p)(a0, a1); + static R function_call(const void *p, A0 a0, A1 a1) + { + return (*(F *)p)(a0, a1); } template - static void function_move(void *d, const void *p) { - new (d) F(*(F*)p); + static void function_move(void *d, const void *p) + { + new (d) F(*(F *)p); } template - static void function_dtor(void *p) { - ((F*)p)->~F(); + static void function_dtor(void *p) + { + ((F *)p)->~F(); } // Wrappers for functions with context @@ -1773,7 +1923,8 @@ class Callback { method_context(O *obj, M method) : method(method), obj(obj) {} - R operator()(A0 a0, A1 a1) const { + R operator()(A0 a0, A1 a1) const + { return (obj->*method)(a0, a1); } }; @@ -1786,7 +1937,8 @@ class Callback { function_context(F func, A *arg) : func(func), arg(arg) {} - R operator()(A0 a0, A1 a1) const { + R operator()(A0 a0, A1 a1) const + { return func(arg, a0, a1); } }; @@ -1802,7 +1954,8 @@ class Callback { /** Create a Callback with a static function * @param func Static function to attach */ - Callback(R (*func)(A0, A1, A2) = 0) { + Callback(R(*func)(A0, A1, A2) = 0) + { if (!func) { memset(this, 0, sizeof(Callback)); } else { @@ -1813,7 +1966,8 @@ class Callback { /** Attach a Callback * @param func The Callback to attach */ - Callback(const Callback &func) { + Callback(const Callback &func) + { if (func._ops) { func._ops->move(this, &func); } @@ -1825,8 +1979,9 @@ class Callback { * @param method Member function to attach */ template - Callback(U *obj, R (T::*method)(A0, A1, A2)) { - generate(method_context(obj, method)); + Callback(U *obj, R(T::*method)(A0, A1, A2)) + { + generate(method_context(obj, method)); } /** Create a Callback with a member function @@ -1834,8 +1989,9 @@ class Callback { * @param method Member function to attach */ template - Callback(const U *obj, R (T::*method)(A0, A1, A2) const) { - generate(method_context(obj, method)); + Callback(const U *obj, R(T::*method)(A0, A1, A2) const) + { + generate(method_context(obj, method)); } /** Create a Callback with a member function @@ -1843,8 +1999,9 @@ class Callback { * @param method Member function to attach */ template - Callback(volatile U *obj, R (T::*method)(A0, A1, A2) volatile) { - generate(method_context(obj, method)); + Callback(volatile U *obj, R(T::*method)(A0, A1, A2) volatile) + { + generate(method_context(obj, method)); } /** Create a Callback with a member function @@ -1852,44 +2009,49 @@ class Callback { * @param method Member function to attach */ template - Callback(const volatile U *obj, R (T::*method)(A0, A1, A2) const volatile) { - generate(method_context(obj, method)); + Callback(const volatile U *obj, R(T::*method)(A0, A1, A2) const volatile) + { + generate(method_context(obj, method)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(T*, A0, A1, A2), U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(T *, A0, A1, A2), U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(const T*, A0, A1, A2), const U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(const T *, A0, A1, A2), const U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(volatile T*, A0, A1, A2), volatile U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(volatile T *, A0, A1, A2), volatile U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(const volatile T*, A0, A1, A2), const volatile U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(const volatile T *, A0, A1, A2), const volatile U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a function object @@ -1897,7 +2059,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2))) { + Callback(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2))) + { generate(f); } @@ -1906,7 +2069,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2) const)) { + Callback(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2) const)) + { generate(f); } @@ -1915,7 +2079,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2) volatile)) { + Callback(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2) volatile)) + { generate(f); } @@ -1924,7 +2089,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2) const volatile)) { + Callback(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2) const volatile)) + { generate(f); } @@ -1936,8 +2102,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(U *obj, R (*func)(T*, A0, A1, A2)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(U *obj, R(*func)(T *, A0, A1, A2)) + { new (this) Callback(func, obj); } @@ -1949,8 +2116,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(const U *obj, R (*func)(const T*, A0, A1, A2)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(const U *obj, R(*func)(const T *, A0, A1, A2)) + { new (this) Callback(func, obj); } @@ -1962,8 +2130,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(volatile U *obj, R (*func)(volatile T*, A0, A1, A2)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(volatile U *obj, R(*func)(volatile T *, A0, A1, A2)) + { new (this) Callback(func, obj); } @@ -1975,14 +2144,16 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(const volatile U *obj, R (*func)(const volatile T*, A0, A1, A2)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(const volatile U *obj, R(*func)(const volatile T *, A0, A1, A2)) + { new (this) Callback(func, obj); } /** Destroy a callback */ - ~Callback() { + ~Callback() + { if (_ops) { _ops->dtor(this); } @@ -1994,8 +2165,9 @@ class Callback { * Replaced by simple assignment 'Callback cb = func' */ MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(A0, A1, A2)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(A0, A1, A2)) + { this->~Callback(); new (this) Callback(func); } @@ -2006,8 +2178,9 @@ class Callback { * Replaced by simple assignment 'Callback cb = func' */ MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const Callback &func) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const Callback &func) + { this->~Callback(); new (this) Callback(func); } @@ -2020,8 +2193,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(U *obj, R (T::*method)(A0, A1, A2)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(U *obj, R(T::*method)(A0, A1, A2)) + { this->~Callback(); new (this) Callback(obj, method); } @@ -2034,8 +2208,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const U *obj, R (T::*method)(A0, A1, A2) const) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const U *obj, R(T::*method)(A0, A1, A2) const) + { this->~Callback(); new (this) Callback(obj, method); } @@ -2048,8 +2223,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(volatile U *obj, R (T::*method)(A0, A1, A2) volatile) { + "Replaced by simple assignment 'Callback cb = func") + void attach(volatile U *obj, R(T::*method)(A0, A1, A2) volatile) + { this->~Callback(); new (this) Callback(obj, method); } @@ -2062,8 +2238,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const volatile U *obj, R (T::*method)(A0, A1, A2) const volatile) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const volatile U *obj, R(T::*method)(A0, A1, A2) const volatile) + { this->~Callback(); new (this) Callback(obj, method); } @@ -2076,8 +2253,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(T*, A0, A1, A2), U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(T *, A0, A1, A2), U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -2090,8 +2268,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(const T*, A0, A1, A2), const U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(const T *, A0, A1, A2), const U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -2104,8 +2283,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(volatile T*, A0, A1, A2), volatile U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(volatile T *, A0, A1, A2), volatile U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -2118,8 +2298,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(const volatile T*, A0, A1, A2), const volatile U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(const volatile T *, A0, A1, A2), const volatile U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -2132,8 +2313,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2))) { + "Replaced by simple assignment 'Callback cb = func") + void attach(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2))) + { this->~Callback(); new (this) Callback(f); } @@ -2146,8 +2328,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2) const)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2) const)) + { this->~Callback(); new (this) Callback(f); } @@ -2160,8 +2343,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2) volatile)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2) volatile)) + { this->~Callback(); new (this) Callback(f); } @@ -2174,8 +2358,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2) const volatile)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2) const volatile)) + { this->~Callback(); new (this) Callback(f); } @@ -2188,8 +2373,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(U *obj, R (*func)(T*, A0, A1, A2)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(U *obj, R(*func)(T *, A0, A1, A2)) + { this->~Callback(); new (this) Callback(func, obj); } @@ -2202,8 +2388,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(const U *obj, R (*func)(const T*, A0, A1, A2)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(const U *obj, R(*func)(const T *, A0, A1, A2)) + { this->~Callback(); new (this) Callback(func, obj); } @@ -2216,8 +2403,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(volatile U *obj, R (*func)(volatile T*, A0, A1, A2)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(volatile U *obj, R(*func)(volatile T *, A0, A1, A2)) + { this->~Callback(); new (this) Callback(func, obj); } @@ -2230,15 +2418,17 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(const volatile U *obj, R (*func)(const volatile T*, A0, A1, A2)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(const volatile U *obj, R(*func)(const volatile T *, A0, A1, A2)) + { this->~Callback(); new (this) Callback(func, obj); } /** Assign a callback */ - Callback &operator=(const Callback &that) { + Callback &operator=(const Callback &that) + { if (this != &that) { this->~Callback(); new (this) Callback(that); @@ -2249,32 +2439,37 @@ class Callback { /** Call the attached function */ - R call(A0 a0, A1 a1, A2 a2) const { + R call(A0 a0, A1 a1, A2 a2) const + { MBED_ASSERT(_ops); return _ops->call(this, a0, a1, a2); } /** Call the attached function */ - R operator()(A0 a0, A1 a1, A2 a2) const { + R operator()(A0 a0, A1 a1, A2 a2) const + { return call(a0, a1, a2); } /** Test if function has been attached */ - operator bool() const { + operator bool() const + { return _ops; } /** Test for equality */ - friend bool operator==(const Callback &l, const Callback &r) { + friend bool operator==(const Callback &l, const Callback &r) + { return memcmp(&l, &r, sizeof(Callback)) == 0; } /** Test for inequality */ - friend bool operator!=(const Callback &l, const Callback &r) { + friend bool operator!=(const Callback &l, const Callback &r) + { return !(l == r); } @@ -2283,11 +2478,12 @@ class Callback { * @param a0 An argument to be called with function func * @param a1 An argument to be called with function func * @param a2 An argument to be called with function func - * @return the value as determined by func which is of + * @return the value as determined by func which is of * type and determined by the signiture of func */ - static R thunk(void *func, A0 a0, A1 a1, A2 a2) { - return static_cast(func)->call(a0, a1, a2); + static R thunk(void *func, A0 a0, A1 a1, A2 a2) + { + return static_cast(func)->call(a0, a1, a2); } private: @@ -2297,21 +2493,22 @@ class Callback { struct _class; union { void (*_staticfunc)(A0, A1, A2); - void (*_boundfunc)(_class*, A0, A1, A2); + void (*_boundfunc)(_class *, A0, A1, A2); void (_class::*_methodfunc)(A0, A1, A2); } _func; void *_obj; // Dynamically dispatched operations const struct ops { - R (*call)(const void*, A0, A1, A2); - void (*move)(void*, const void*); - void (*dtor)(void*); + R(*call)(const void *, A0, A1, A2); + void (*move)(void *, const void *); + void (*dtor)(void *); } *_ops; // Generate operations for function object template - void generate(const F &f) { + void generate(const F &f) + { static const ops ops = { &Callback::function_call, &Callback::function_move, @@ -2319,7 +2516,7 @@ class Callback { }; MBED_STATIC_ASSERT(sizeof(Callback) - sizeof(_ops) >= sizeof(F), - "Type F must not exceed the size of the Callback class"); + "Type F must not exceed the size of the Callback class"); memset(this, 0, sizeof(Callback)); new (this) F(f); _ops = &ops; @@ -2327,18 +2524,21 @@ class Callback { // Function attributes template - static R function_call(const void *p, A0 a0, A1 a1, A2 a2) { - return (*(F*)p)(a0, a1, a2); + static R function_call(const void *p, A0 a0, A1 a1, A2 a2) + { + return (*(F *)p)(a0, a1, a2); } template - static void function_move(void *d, const void *p) { - new (d) F(*(F*)p); + static void function_move(void *d, const void *p) + { + new (d) F(*(F *)p); } template - static void function_dtor(void *p) { - ((F*)p)->~F(); + static void function_dtor(void *p) + { + ((F *)p)->~F(); } // Wrappers for functions with context @@ -2350,7 +2550,8 @@ class Callback { method_context(O *obj, M method) : method(method), obj(obj) {} - R operator()(A0 a0, A1 a1, A2 a2) const { + R operator()(A0 a0, A1 a1, A2 a2) const + { return (obj->*method)(a0, a1, a2); } }; @@ -2363,7 +2564,8 @@ class Callback { function_context(F func, A *arg) : func(func), arg(arg) {} - R operator()(A0 a0, A1 a1, A2 a2) const { + R operator()(A0 a0, A1 a1, A2 a2) const + { return func(arg, a0, a1, a2); } }; @@ -2379,7 +2581,8 @@ class Callback { /** Create a Callback with a static function * @param func Static function to attach */ - Callback(R (*func)(A0, A1, A2, A3) = 0) { + Callback(R(*func)(A0, A1, A2, A3) = 0) + { if (!func) { memset(this, 0, sizeof(Callback)); } else { @@ -2390,7 +2593,8 @@ class Callback { /** Attach a Callback * @param func The Callback to attach */ - Callback(const Callback &func) { + Callback(const Callback &func) + { if (func._ops) { func._ops->move(this, &func); } @@ -2402,8 +2606,9 @@ class Callback { * @param method Member function to attach */ template - Callback(U *obj, R (T::*method)(A0, A1, A2, A3)) { - generate(method_context(obj, method)); + Callback(U *obj, R(T::*method)(A0, A1, A2, A3)) + { + generate(method_context(obj, method)); } /** Create a Callback with a member function @@ -2411,8 +2616,9 @@ class Callback { * @param method Member function to attach */ template - Callback(const U *obj, R (T::*method)(A0, A1, A2, A3) const) { - generate(method_context(obj, method)); + Callback(const U *obj, R(T::*method)(A0, A1, A2, A3) const) + { + generate(method_context(obj, method)); } /** Create a Callback with a member function @@ -2420,8 +2626,9 @@ class Callback { * @param method Member function to attach */ template - Callback(volatile U *obj, R (T::*method)(A0, A1, A2, A3) volatile) { - generate(method_context(obj, method)); + Callback(volatile U *obj, R(T::*method)(A0, A1, A2, A3) volatile) + { + generate(method_context(obj, method)); } /** Create a Callback with a member function @@ -2429,44 +2636,49 @@ class Callback { * @param method Member function to attach */ template - Callback(const volatile U *obj, R (T::*method)(A0, A1, A2, A3) const volatile) { - generate(method_context(obj, method)); + Callback(const volatile U *obj, R(T::*method)(A0, A1, A2, A3) const volatile) + { + generate(method_context(obj, method)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(T*, A0, A1, A2, A3), U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(T *, A0, A1, A2, A3), U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(const T*, A0, A1, A2, A3), const U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(const T *, A0, A1, A2, A3), const U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(volatile T*, A0, A1, A2, A3), volatile U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(volatile T *, A0, A1, A2, A3), volatile U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(const volatile T*, A0, A1, A2, A3), const volatile U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(const volatile T *, A0, A1, A2, A3), const volatile U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a function object @@ -2474,7 +2686,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3))) { + Callback(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2, A3))) + { generate(f); } @@ -2483,7 +2696,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3) const)) { + Callback(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2, A3) const)) + { generate(f); } @@ -2492,7 +2706,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3) volatile)) { + Callback(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2, A3) volatile)) + { generate(f); } @@ -2501,7 +2716,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3) const volatile)) { + Callback(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2, A3) const volatile)) + { generate(f); } @@ -2513,8 +2729,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(U *obj, R (*func)(T*, A0, A1, A2, A3)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(U *obj, R(*func)(T *, A0, A1, A2, A3)) + { new (this) Callback(func, obj); } @@ -2526,8 +2743,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(const U *obj, R (*func)(const T*, A0, A1, A2, A3)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(const U *obj, R(*func)(const T *, A0, A1, A2, A3)) + { new (this) Callback(func, obj); } @@ -2539,8 +2757,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(volatile U *obj, R (*func)(volatile T*, A0, A1, A2, A3)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(volatile U *obj, R(*func)(volatile T *, A0, A1, A2, A3)) + { new (this) Callback(func, obj); } @@ -2552,14 +2771,16 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(const volatile U *obj, R (*func)(const volatile T*, A0, A1, A2, A3)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(const volatile U *obj, R(*func)(const volatile T *, A0, A1, A2, A3)) + { new (this) Callback(func, obj); } /** Destroy a callback */ - ~Callback() { + ~Callback() + { if (_ops) { _ops->dtor(this); } @@ -2571,8 +2792,9 @@ class Callback { * Replaced by simple assignment 'Callback cb = func' */ MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(A0, A1, A2, A3)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(A0, A1, A2, A3)) + { this->~Callback(); new (this) Callback(func); } @@ -2583,8 +2805,9 @@ class Callback { * Replaced by simple assignment 'Callback cb = func' */ MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const Callback &func) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const Callback &func) + { this->~Callback(); new (this) Callback(func); } @@ -2597,8 +2820,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(U *obj, R (T::*method)(A0, A1, A2, A3)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(U *obj, R(T::*method)(A0, A1, A2, A3)) + { this->~Callback(); new (this) Callback(obj, method); } @@ -2611,8 +2835,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const U *obj, R (T::*method)(A0, A1, A2, A3) const) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const U *obj, R(T::*method)(A0, A1, A2, A3) const) + { this->~Callback(); new (this) Callback(obj, method); } @@ -2625,8 +2850,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(volatile U *obj, R (T::*method)(A0, A1, A2, A3) volatile) { + "Replaced by simple assignment 'Callback cb = func") + void attach(volatile U *obj, R(T::*method)(A0, A1, A2, A3) volatile) + { this->~Callback(); new (this) Callback(obj, method); } @@ -2639,8 +2865,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const volatile U *obj, R (T::*method)(A0, A1, A2, A3) const volatile) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const volatile U *obj, R(T::*method)(A0, A1, A2, A3) const volatile) + { this->~Callback(); new (this) Callback(obj, method); } @@ -2653,8 +2880,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(T*, A0, A1, A2, A3), U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(T *, A0, A1, A2, A3), U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -2667,8 +2895,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(const T*, A0, A1, A2, A3), const U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(const T *, A0, A1, A2, A3), const U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -2681,8 +2910,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(volatile T*, A0, A1, A2, A3), volatile U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(volatile T *, A0, A1, A2, A3), volatile U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -2695,8 +2925,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(const volatile T*, A0, A1, A2, A3), const volatile U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(const volatile T *, A0, A1, A2, A3), const volatile U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -2709,8 +2940,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3))) { + "Replaced by simple assignment 'Callback cb = func") + void attach(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2, A3))) + { this->~Callback(); new (this) Callback(f); } @@ -2723,8 +2955,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3) const)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2, A3) const)) + { this->~Callback(); new (this) Callback(f); } @@ -2737,8 +2970,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3) volatile)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2, A3) volatile)) + { this->~Callback(); new (this) Callback(f); } @@ -2751,8 +2985,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3) const volatile)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2, A3) const volatile)) + { this->~Callback(); new (this) Callback(f); } @@ -2765,8 +3000,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(U *obj, R (*func)(T*, A0, A1, A2, A3)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(U *obj, R(*func)(T *, A0, A1, A2, A3)) + { this->~Callback(); new (this) Callback(func, obj); } @@ -2779,8 +3015,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(const U *obj, R (*func)(const T*, A0, A1, A2, A3)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(const U *obj, R(*func)(const T *, A0, A1, A2, A3)) + { this->~Callback(); new (this) Callback(func, obj); } @@ -2793,8 +3030,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(volatile U *obj, R (*func)(volatile T*, A0, A1, A2, A3)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(volatile U *obj, R(*func)(volatile T *, A0, A1, A2, A3)) + { this->~Callback(); new (this) Callback(func, obj); } @@ -2807,15 +3045,17 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(const volatile U *obj, R (*func)(const volatile T*, A0, A1, A2, A3)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(const volatile U *obj, R(*func)(const volatile T *, A0, A1, A2, A3)) + { this->~Callback(); new (this) Callback(func, obj); } /** Assign a callback */ - Callback &operator=(const Callback &that) { + Callback &operator=(const Callback &that) + { if (this != &that) { this->~Callback(); new (this) Callback(that); @@ -2826,32 +3066,37 @@ class Callback { /** Call the attached function */ - R call(A0 a0, A1 a1, A2 a2, A3 a3) const { + R call(A0 a0, A1 a1, A2 a2, A3 a3) const + { MBED_ASSERT(_ops); return _ops->call(this, a0, a1, a2, a3); } /** Call the attached function */ - R operator()(A0 a0, A1 a1, A2 a2, A3 a3) const { + R operator()(A0 a0, A1 a1, A2 a2, A3 a3) const + { return call(a0, a1, a2, a3); } /** Test if function has been attached */ - operator bool() const { + operator bool() const + { return _ops; } /** Test for equality */ - friend bool operator==(const Callback &l, const Callback &r) { + friend bool operator==(const Callback &l, const Callback &r) + { return memcmp(&l, &r, sizeof(Callback)) == 0; } /** Test for inequality */ - friend bool operator!=(const Callback &l, const Callback &r) { + friend bool operator!=(const Callback &l, const Callback &r) + { return !(l == r); } @@ -2861,11 +3106,12 @@ class Callback { * @param a1 An argument to be called with function func * @param a2 An argument to be called with function func * @param a3 An argument to be called with function func - * @return the value as determined by func which is of + * @return the value as determined by func which is of * type and determined by the signiture of func */ - static R thunk(void *func, A0 a0, A1 a1, A2 a2, A3 a3) { - return static_cast(func)->call(a0, a1, a2, a3); + static R thunk(void *func, A0 a0, A1 a1, A2 a2, A3 a3) + { + return static_cast(func)->call(a0, a1, a2, a3); } private: @@ -2875,21 +3121,22 @@ class Callback { struct _class; union { void (*_staticfunc)(A0, A1, A2, A3); - void (*_boundfunc)(_class*, A0, A1, A2, A3); + void (*_boundfunc)(_class *, A0, A1, A2, A3); void (_class::*_methodfunc)(A0, A1, A2, A3); } _func; void *_obj; // Dynamically dispatched operations const struct ops { - R (*call)(const void*, A0, A1, A2, A3); - void (*move)(void*, const void*); - void (*dtor)(void*); + R(*call)(const void *, A0, A1, A2, A3); + void (*move)(void *, const void *); + void (*dtor)(void *); } *_ops; // Generate operations for function object template - void generate(const F &f) { + void generate(const F &f) + { static const ops ops = { &Callback::function_call, &Callback::function_move, @@ -2897,7 +3144,7 @@ class Callback { }; MBED_STATIC_ASSERT(sizeof(Callback) - sizeof(_ops) >= sizeof(F), - "Type F must not exceed the size of the Callback class"); + "Type F must not exceed the size of the Callback class"); memset(this, 0, sizeof(Callback)); new (this) F(f); _ops = &ops; @@ -2905,18 +3152,21 @@ class Callback { // Function attributes template - static R function_call(const void *p, A0 a0, A1 a1, A2 a2, A3 a3) { - return (*(F*)p)(a0, a1, a2, a3); + static R function_call(const void *p, A0 a0, A1 a1, A2 a2, A3 a3) + { + return (*(F *)p)(a0, a1, a2, a3); } template - static void function_move(void *d, const void *p) { - new (d) F(*(F*)p); + static void function_move(void *d, const void *p) + { + new (d) F(*(F *)p); } template - static void function_dtor(void *p) { - ((F*)p)->~F(); + static void function_dtor(void *p) + { + ((F *)p)->~F(); } // Wrappers for functions with context @@ -2928,7 +3178,8 @@ class Callback { method_context(O *obj, M method) : method(method), obj(obj) {} - R operator()(A0 a0, A1 a1, A2 a2, A3 a3) const { + R operator()(A0 a0, A1 a1, A2 a2, A3 a3) const + { return (obj->*method)(a0, a1, a2, a3); } }; @@ -2941,7 +3192,8 @@ class Callback { function_context(F func, A *arg) : func(func), arg(arg) {} - R operator()(A0 a0, A1 a1, A2 a2, A3 a3) const { + R operator()(A0 a0, A1 a1, A2 a2, A3 a3) const + { return func(arg, a0, a1, a2, a3); } }; @@ -2957,7 +3209,8 @@ class Callback { /** Create a Callback with a static function * @param func Static function to attach */ - Callback(R (*func)(A0, A1, A2, A3, A4) = 0) { + Callback(R(*func)(A0, A1, A2, A3, A4) = 0) + { if (!func) { memset(this, 0, sizeof(Callback)); } else { @@ -2968,7 +3221,8 @@ class Callback { /** Attach a Callback * @param func The Callback to attach */ - Callback(const Callback &func) { + Callback(const Callback &func) + { if (func._ops) { func._ops->move(this, &func); } @@ -2980,8 +3234,9 @@ class Callback { * @param method Member function to attach */ template - Callback(U *obj, R (T::*method)(A0, A1, A2, A3, A4)) { - generate(method_context(obj, method)); + Callback(U *obj, R(T::*method)(A0, A1, A2, A3, A4)) + { + generate(method_context(obj, method)); } /** Create a Callback with a member function @@ -2989,8 +3244,9 @@ class Callback { * @param method Member function to attach */ template - Callback(const U *obj, R (T::*method)(A0, A1, A2, A3, A4) const) { - generate(method_context(obj, method)); + Callback(const U *obj, R(T::*method)(A0, A1, A2, A3, A4) const) + { + generate(method_context(obj, method)); } /** Create a Callback with a member function @@ -2998,8 +3254,9 @@ class Callback { * @param method Member function to attach */ template - Callback(volatile U *obj, R (T::*method)(A0, A1, A2, A3, A4) volatile) { - generate(method_context(obj, method)); + Callback(volatile U *obj, R(T::*method)(A0, A1, A2, A3, A4) volatile) + { + generate(method_context(obj, method)); } /** Create a Callback with a member function @@ -3007,44 +3264,49 @@ class Callback { * @param method Member function to attach */ template - Callback(const volatile U *obj, R (T::*method)(A0, A1, A2, A3, A4) const volatile) { - generate(method_context(obj, method)); + Callback(const volatile U *obj, R(T::*method)(A0, A1, A2, A3, A4) const volatile) + { + generate(method_context(obj, method)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(T*, A0, A1, A2, A3, A4), U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(T *, A0, A1, A2, A3, A4), U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(const T*, A0, A1, A2, A3, A4), const U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(const T *, A0, A1, A2, A3, A4), const U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(volatile T*, A0, A1, A2, A3, A4), volatile U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(volatile T *, A0, A1, A2, A3, A4), volatile U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a static function and bound pointer * @param func Static function to attach - * @param arg Pointer argument to function + * @param arg Pointer argument to function */ template - Callback(R (*func)(const volatile T*, A0, A1, A2, A3, A4), const volatile U *arg) { - generate(function_context(func, arg)); + Callback(R(*func)(const volatile T *, A0, A1, A2, A3, A4), const volatile U *arg) + { + generate(function_context(func, arg)); } /** Create a Callback with a function object @@ -3052,7 +3314,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3, A4))) { + Callback(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2, A3, A4))) + { generate(f); } @@ -3061,7 +3324,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3, A4) const)) { + Callback(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2, A3, A4) const)) + { generate(f); } @@ -3070,7 +3334,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3, A4) volatile)) { + Callback(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2, A3, A4) volatile)) + { generate(f); } @@ -3079,7 +3344,8 @@ class Callback { * @note The function object is limited to a single word of storage */ template - Callback(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3, A4) const volatile)) { + Callback(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2, A3, A4) const volatile)) + { generate(f); } @@ -3091,8 +3357,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(U *obj, R (*func)(T*, A0, A1, A2, A3, A4)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(U *obj, R(*func)(T *, A0, A1, A2, A3, A4)) + { new (this) Callback(func, obj); } @@ -3104,8 +3371,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(const U *obj, R (*func)(const T*, A0, A1, A2, A3, A4)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(const U *obj, R(*func)(const T *, A0, A1, A2, A3, A4)) + { new (this) Callback(func, obj); } @@ -3117,8 +3385,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(volatile U *obj, R (*func)(volatile T*, A0, A1, A2, A3, A4)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(volatile U *obj, R(*func)(volatile T *, A0, A1, A2, A3, A4)) + { new (this) Callback(func, obj); } @@ -3130,14 +3399,16 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to Callback(func, arg)") - Callback(const volatile U *obj, R (*func)(const volatile T*, A0, A1, A2, A3, A4)) { + "Arguments to callback have been reordered to Callback(func, arg)") + Callback(const volatile U *obj, R(*func)(const volatile T *, A0, A1, A2, A3, A4)) + { new (this) Callback(func, obj); } /** Destroy a callback */ - ~Callback() { + ~Callback() + { if (_ops) { _ops->dtor(this); } @@ -3149,8 +3420,9 @@ class Callback { * Replaced by simple assignment 'Callback cb = func' */ MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(A0, A1, A2, A3, A4)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(A0, A1, A2, A3, A4)) + { this->~Callback(); new (this) Callback(func); } @@ -3161,8 +3433,9 @@ class Callback { * Replaced by simple assignment 'Callback cb = func' */ MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const Callback &func) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const Callback &func) + { this->~Callback(); new (this) Callback(func); } @@ -3175,8 +3448,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(U *obj, R (T::*method)(A0, A1, A2, A3, A4)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(U *obj, R(T::*method)(A0, A1, A2, A3, A4)) + { this->~Callback(); new (this) Callback(obj, method); } @@ -3189,8 +3463,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const U *obj, R (T::*method)(A0, A1, A2, A3, A4) const) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const U *obj, R(T::*method)(A0, A1, A2, A3, A4) const) + { this->~Callback(); new (this) Callback(obj, method); } @@ -3203,8 +3478,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(volatile U *obj, R (T::*method)(A0, A1, A2, A3, A4) volatile) { + "Replaced by simple assignment 'Callback cb = func") + void attach(volatile U *obj, R(T::*method)(A0, A1, A2, A3, A4) volatile) + { this->~Callback(); new (this) Callback(obj, method); } @@ -3217,8 +3493,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const volatile U *obj, R (T::*method)(A0, A1, A2, A3, A4) const volatile) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const volatile U *obj, R(T::*method)(A0, A1, A2, A3, A4) const volatile) + { this->~Callback(); new (this) Callback(obj, method); } @@ -3231,8 +3508,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(T*, A0, A1, A2, A3, A4), U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(T *, A0, A1, A2, A3, A4), U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -3245,8 +3523,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(const T*, A0, A1, A2, A3, A4), const U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(const T *, A0, A1, A2, A3, A4), const U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -3259,8 +3538,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(volatile T*, A0, A1, A2, A3, A4), volatile U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(volatile T *, A0, A1, A2, A3, A4), volatile U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -3273,8 +3553,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(R (*func)(const volatile T*, A0, A1, A2, A3, A4), const volatile U *arg) { + "Replaced by simple assignment 'Callback cb = func") + void attach(R(*func)(const volatile T *, A0, A1, A2, A3, A4), const volatile U *arg) + { this->~Callback(); new (this) Callback(func, arg); } @@ -3287,8 +3568,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3, A4))) { + "Replaced by simple assignment 'Callback cb = func") + void attach(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2, A3, A4))) + { this->~Callback(); new (this) Callback(f); } @@ -3301,8 +3583,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3, A4) const)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2, A3, A4) const)) + { this->~Callback(); new (this) Callback(f); } @@ -3315,8 +3598,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3, A4) volatile)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2, A3, A4) volatile)) + { this->~Callback(); new (this) Callback(f); } @@ -3329,8 +3613,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.4", - "Replaced by simple assignment 'Callback cb = func") - void attach(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3, A4) const volatile)) { + "Replaced by simple assignment 'Callback cb = func") + void attach(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R(F::*)(A0, A1, A2, A3, A4) const volatile)) + { this->~Callback(); new (this) Callback(f); } @@ -3343,8 +3628,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(U *obj, R (*func)(T*, A0, A1, A2, A3, A4)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(U *obj, R(*func)(T *, A0, A1, A2, A3, A4)) + { this->~Callback(); new (this) Callback(func, obj); } @@ -3357,8 +3643,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(const U *obj, R (*func)(const T*, A0, A1, A2, A3, A4)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(const U *obj, R(*func)(const T *, A0, A1, A2, A3, A4)) + { this->~Callback(); new (this) Callback(func, obj); } @@ -3371,8 +3658,9 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(volatile U *obj, R (*func)(volatile T*, A0, A1, A2, A3, A4)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(volatile U *obj, R(*func)(volatile T *, A0, A1, A2, A3, A4)) + { this->~Callback(); new (this) Callback(func, obj); } @@ -3385,15 +3673,17 @@ class Callback { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to attach(func, arg)") - void attach(const volatile U *obj, R (*func)(const volatile T*, A0, A1, A2, A3, A4)) { + "Arguments to callback have been reordered to attach(func, arg)") + void attach(const volatile U *obj, R(*func)(const volatile T *, A0, A1, A2, A3, A4)) + { this->~Callback(); new (this) Callback(func, obj); } /** Assign a callback */ - Callback &operator=(const Callback &that) { + Callback &operator=(const Callback &that) + { if (this != &that) { this->~Callback(); new (this) Callback(that); @@ -3404,32 +3694,37 @@ class Callback { /** Call the attached function */ - R call(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) const { + R call(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) const + { MBED_ASSERT(_ops); return _ops->call(this, a0, a1, a2, a3, a4); } /** Call the attached function */ - R operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) const { + R operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) const + { return call(a0, a1, a2, a3, a4); } /** Test if function has been attached */ - operator bool() const { + operator bool() const + { return _ops; } /** Test for equality */ - friend bool operator==(const Callback &l, const Callback &r) { + friend bool operator==(const Callback &l, const Callback &r) + { return memcmp(&l, &r, sizeof(Callback)) == 0; } /** Test for inequality */ - friend bool operator!=(const Callback &l, const Callback &r) { + friend bool operator!=(const Callback &l, const Callback &r) + { return !(l == r); } @@ -3440,11 +3735,12 @@ class Callback { * @param a2 An argument to be called with function func * @param a3 An argument to be called with function func * @param a4 An argument to be called with function func - * @return the value as determined by func which is of + * @return the value as determined by func which is of * type and determined by the signiture of func */ - static R thunk(void *func, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { - return static_cast(func)->call(a0, a1, a2, a3, a4); + static R thunk(void *func, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { + return static_cast(func)->call(a0, a1, a2, a3, a4); } private: @@ -3454,21 +3750,22 @@ class Callback { struct _class; union { void (*_staticfunc)(A0, A1, A2, A3, A4); - void (*_boundfunc)(_class*, A0, A1, A2, A3, A4); + void (*_boundfunc)(_class *, A0, A1, A2, A3, A4); void (_class::*_methodfunc)(A0, A1, A2, A3, A4); } _func; void *_obj; // Dynamically dispatched operations const struct ops { - R (*call)(const void*, A0, A1, A2, A3, A4); - void (*move)(void*, const void*); - void (*dtor)(void*); + R(*call)(const void *, A0, A1, A2, A3, A4); + void (*move)(void *, const void *); + void (*dtor)(void *); } *_ops; // Generate operations for function object template - void generate(const F &f) { + void generate(const F &f) + { static const ops ops = { &Callback::function_call, &Callback::function_move, @@ -3476,7 +3773,7 @@ class Callback { }; MBED_STATIC_ASSERT(sizeof(Callback) - sizeof(_ops) >= sizeof(F), - "Type F must not exceed the size of the Callback class"); + "Type F must not exceed the size of the Callback class"); memset(this, 0, sizeof(Callback)); new (this) F(f); _ops = &ops; @@ -3484,18 +3781,21 @@ class Callback { // Function attributes template - static R function_call(const void *p, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { - return (*(F*)p)(a0, a1, a2, a3, a4); + static R function_call(const void *p, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) + { + return (*(F *)p)(a0, a1, a2, a3, a4); } template - static void function_move(void *d, const void *p) { - new (d) F(*(F*)p); + static void function_move(void *d, const void *p) + { + new (d) F(*(F *)p); } template - static void function_dtor(void *p) { - ((F*)p)->~F(); + static void function_dtor(void *p) + { + ((F *)p)->~F(); } // Wrappers for functions with context @@ -3507,7 +3807,8 @@ class Callback { method_context(O *obj, M method) : method(method), obj(obj) {} - R operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) const { + R operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) const + { return (obj->*method)(a0, a1, a2, a3, a4); } }; @@ -3520,7 +3821,8 @@ class Callback { function_context(F func, A *arg) : func(func), arg(arg) {} - R operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) const { + R operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) const + { return func(arg, a0, a1, a2, a3, a4); } }; @@ -3536,7 +3838,8 @@ typedef Callback event_callback_t; * @return Callback with infered type */ template -Callback callback(R (*func)() = 0) { +Callback callback(R(*func)() = 0) +{ return Callback(func); } @@ -3546,7 +3849,8 @@ Callback callback(R (*func)() = 0) { * @return Callback with infered type */ template -Callback callback(const Callback &func) { +Callback callback(const Callback &func) +{ return Callback(func); } @@ -3557,7 +3861,8 @@ Callback callback(const Callback &func) { * @return Callback with infered type */ template -Callback callback(U *obj, R (T::*method)()) { +Callback callback(U *obj, R(T::*method)()) +{ return Callback(obj, method); } @@ -3568,7 +3873,8 @@ Callback callback(U *obj, R (T::*method)()) { * @return Callback with infered type */ template -Callback callback(const U *obj, R (T::*method)() const) { +Callback callback(const U *obj, R(T::*method)() const) +{ return Callback(obj, method); } @@ -3579,7 +3885,8 @@ Callback callback(const U *obj, R (T::*method)() const) { * @return Callback with infered type */ template -Callback callback(volatile U *obj, R (T::*method)() volatile) { +Callback callback(volatile U *obj, R(T::*method)() volatile) +{ return Callback(obj, method); } @@ -3590,7 +3897,8 @@ Callback callback(volatile U *obj, R (T::*method)() volatile) { * @return Callback with infered type */ template -Callback callback(const volatile U *obj, R (T::*method)() const volatile) { +Callback callback(const volatile U *obj, R(T::*method)() const volatile) +{ return Callback(obj, method); } @@ -3601,7 +3909,8 @@ Callback callback(const volatile U *obj, R (T::*method)() const volatile) { * @return Callback with infered type */ template -Callback callback(R (*func)(T*), U *arg) { +Callback callback(R(*func)(T *), U *arg) +{ return Callback(func, arg); } @@ -3612,7 +3921,8 @@ Callback callback(R (*func)(T*), U *arg) { * @return Callback with infered type */ template -Callback callback(R (*func)(const T*), const U *arg) { +Callback callback(R(*func)(const T *), const U *arg) +{ return Callback(func, arg); } @@ -3623,7 +3933,8 @@ Callback callback(R (*func)(const T*), const U *arg) { * @return Callback with infered type */ template -Callback callback(R (*func)(volatile T*), volatile U *arg) { +Callback callback(R(*func)(volatile T *), volatile U *arg) +{ return Callback(func, arg); } @@ -3634,7 +3945,8 @@ Callback callback(R (*func)(volatile T*), volatile U *arg) { * @return Callback with infered type */ template -Callback callback(R (*func)(const volatile T*), const volatile U *arg) { +Callback callback(R(*func)(const volatile T *), const volatile U *arg) +{ return Callback(func, arg); } @@ -3648,8 +3960,9 @@ Callback callback(R (*func)(const volatile T*), const volatile U *arg) { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(U *obj, R (*func)(T*)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(U *obj, R(*func)(T *)) +{ return Callback(func, obj); } @@ -3663,8 +3976,9 @@ Callback callback(U *obj, R (*func)(T*)) { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(const U *obj, R (*func)(const T*)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(const U *obj, R(*func)(const T *)) +{ return Callback(func, obj); } @@ -3678,8 +3992,9 @@ Callback callback(const U *obj, R (*func)(const T*)) { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(volatile U *obj, R (*func)(volatile T*)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(volatile U *obj, R(*func)(volatile T *)) +{ return Callback(func, obj); } @@ -3693,8 +4008,9 @@ Callback callback(volatile U *obj, R (*func)(volatile T*)) { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(const volatile U *obj, R (*func)(const volatile T*)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(const volatile U *obj, R(*func)(const volatile T *)) +{ return Callback(func, obj); } @@ -3705,7 +4021,8 @@ Callback callback(const volatile U *obj, R (*func)(const volatile T*)) { * @return Callback with infered type */ template -Callback callback(R (*func)(A0) = 0) { +Callback callback(R(*func)(A0) = 0) +{ return Callback(func); } @@ -3715,7 +4032,8 @@ Callback callback(R (*func)(A0) = 0) { * @return Callback with infered type */ template -Callback callback(const Callback &func) { +Callback callback(const Callback &func) +{ return Callback(func); } @@ -3726,7 +4044,8 @@ Callback callback(const Callback &func) { * @return Callback with infered type */ template -Callback callback(U *obj, R (T::*method)(A0)) { +Callback callback(U *obj, R(T::*method)(A0)) +{ return Callback(obj, method); } @@ -3737,7 +4056,8 @@ Callback callback(U *obj, R (T::*method)(A0)) { * @return Callback with infered type */ template -Callback callback(const U *obj, R (T::*method)(A0) const) { +Callback callback(const U *obj, R(T::*method)(A0) const) +{ return Callback(obj, method); } @@ -3748,7 +4068,8 @@ Callback callback(const U *obj, R (T::*method)(A0) const) { * @return Callback with infered type */ template -Callback callback(volatile U *obj, R (T::*method)(A0) volatile) { +Callback callback(volatile U *obj, R(T::*method)(A0) volatile) +{ return Callback(obj, method); } @@ -3759,7 +4080,8 @@ Callback callback(volatile U *obj, R (T::*method)(A0) volatile) { * @return Callback with infered type */ template -Callback callback(const volatile U *obj, R (T::*method)(A0) const volatile) { +Callback callback(const volatile U *obj, R(T::*method)(A0) const volatile) +{ return Callback(obj, method); } @@ -3770,7 +4092,8 @@ Callback callback(const volatile U *obj, R (T::*method)(A0) const volatil * @return Callback with infered type */ template -Callback callback(R (*func)(T*, A0), U *arg) { +Callback callback(R(*func)(T *, A0), U *arg) +{ return Callback(func, arg); } @@ -3781,7 +4104,8 @@ Callback callback(R (*func)(T*, A0), U *arg) { * @return Callback with infered type */ template -Callback callback(R (*func)(const T*, A0), const U *arg) { +Callback callback(R(*func)(const T *, A0), const U *arg) +{ return Callback(func, arg); } @@ -3792,7 +4116,8 @@ Callback callback(R (*func)(const T*, A0), const U *arg) { * @return Callback with infered type */ template -Callback callback(R (*func)(volatile T*, A0), volatile U *arg) { +Callback callback(R(*func)(volatile T *, A0), volatile U *arg) +{ return Callback(func, arg); } @@ -3803,7 +4128,8 @@ Callback callback(R (*func)(volatile T*, A0), volatile U *arg) { * @return Callback with infered type */ template -Callback callback(R (*func)(const volatile T*, A0), const volatile U *arg) { +Callback callback(R(*func)(const volatile T *, A0), const volatile U *arg) +{ return Callback(func, arg); } @@ -3817,8 +4143,9 @@ Callback callback(R (*func)(const volatile T*, A0), const volatile U *arg */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(U *obj, R (*func)(T*, A0)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(U *obj, R(*func)(T *, A0)) +{ return Callback(func, obj); } @@ -3832,8 +4159,9 @@ Callback callback(U *obj, R (*func)(T*, A0)) { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(const U *obj, R (*func)(const T*, A0)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(const U *obj, R(*func)(const T *, A0)) +{ return Callback(func, obj); } @@ -3847,8 +4175,9 @@ Callback callback(const U *obj, R (*func)(const T*, A0)) { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(volatile U *obj, R (*func)(volatile T*, A0)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(volatile U *obj, R(*func)(volatile T *, A0)) +{ return Callback(func, obj); } @@ -3862,8 +4191,9 @@ Callback callback(volatile U *obj, R (*func)(volatile T*, A0)) { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(const volatile U *obj, R (*func)(const volatile T*, A0)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(const volatile U *obj, R(*func)(const volatile T *, A0)) +{ return Callback(func, obj); } @@ -3874,7 +4204,8 @@ Callback callback(const volatile U *obj, R (*func)(const volatile T*, A0) * @return Callback with infered type */ template -Callback callback(R (*func)(A0, A1) = 0) { +Callback callback(R(*func)(A0, A1) = 0) +{ return Callback(func); } @@ -3884,7 +4215,8 @@ Callback callback(R (*func)(A0, A1) = 0) { * @return Callback with infered type */ template -Callback callback(const Callback &func) { +Callback callback(const Callback &func) +{ return Callback(func); } @@ -3895,7 +4227,8 @@ Callback callback(const Callback &func) { * @return Callback with infered type */ template -Callback callback(U *obj, R (T::*method)(A0, A1)) { +Callback callback(U *obj, R(T::*method)(A0, A1)) +{ return Callback(obj, method); } @@ -3906,7 +4239,8 @@ Callback callback(U *obj, R (T::*method)(A0, A1)) { * @return Callback with infered type */ template -Callback callback(const U *obj, R (T::*method)(A0, A1) const) { +Callback callback(const U *obj, R(T::*method)(A0, A1) const) +{ return Callback(obj, method); } @@ -3917,7 +4251,8 @@ Callback callback(const U *obj, R (T::*method)(A0, A1) const) { * @return Callback with infered type */ template -Callback callback(volatile U *obj, R (T::*method)(A0, A1) volatile) { +Callback callback(volatile U *obj, R(T::*method)(A0, A1) volatile) +{ return Callback(obj, method); } @@ -3928,7 +4263,8 @@ Callback callback(volatile U *obj, R (T::*method)(A0, A1) volatile) { * @return Callback with infered type */ template -Callback callback(const volatile U *obj, R (T::*method)(A0, A1) const volatile) { +Callback callback(const volatile U *obj, R(T::*method)(A0, A1) const volatile) +{ return Callback(obj, method); } @@ -3939,7 +4275,8 @@ Callback callback(const volatile U *obj, R (T::*method)(A0, A1) const * @return Callback with infered type */ template -Callback callback(R (*func)(T*, A0, A1), U *arg) { +Callback callback(R(*func)(T *, A0, A1), U *arg) +{ return Callback(func, arg); } @@ -3950,7 +4287,8 @@ Callback callback(R (*func)(T*, A0, A1), U *arg) { * @return Callback with infered type */ template -Callback callback(R (*func)(const T*, A0, A1), const U *arg) { +Callback callback(R(*func)(const T *, A0, A1), const U *arg) +{ return Callback(func, arg); } @@ -3961,7 +4299,8 @@ Callback callback(R (*func)(const T*, A0, A1), const U *arg) { * @return Callback with infered type */ template -Callback callback(R (*func)(volatile T*, A0, A1), volatile U *arg) { +Callback callback(R(*func)(volatile T *, A0, A1), volatile U *arg) +{ return Callback(func, arg); } @@ -3972,7 +4311,8 @@ Callback callback(R (*func)(volatile T*, A0, A1), volatile U *arg) { * @return Callback with infered type */ template -Callback callback(R (*func)(const volatile T*, A0, A1), const volatile U *arg) { +Callback callback(R(*func)(const volatile T *, A0, A1), const volatile U *arg) +{ return Callback(func, arg); } @@ -3986,8 +4326,9 @@ Callback callback(R (*func)(const volatile T*, A0, A1), const volatil */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(U *obj, R (*func)(T*, A0, A1)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(U *obj, R(*func)(T *, A0, A1)) +{ return Callback(func, obj); } @@ -4001,8 +4342,9 @@ Callback callback(U *obj, R (*func)(T*, A0, A1)) { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(const U *obj, R (*func)(const T*, A0, A1)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(const U *obj, R(*func)(const T *, A0, A1)) +{ return Callback(func, obj); } @@ -4016,8 +4358,9 @@ Callback callback(const U *obj, R (*func)(const T*, A0, A1)) { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(volatile U *obj, R (*func)(volatile T*, A0, A1)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(volatile U *obj, R(*func)(volatile T *, A0, A1)) +{ return Callback(func, obj); } @@ -4031,8 +4374,9 @@ Callback callback(volatile U *obj, R (*func)(volatile T*, A0, A1)) { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(const volatile U *obj, R (*func)(const volatile T*, A0, A1)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(const volatile U *obj, R(*func)(const volatile T *, A0, A1)) +{ return Callback(func, obj); } @@ -4043,7 +4387,8 @@ Callback callback(const volatile U *obj, R (*func)(const volatile T*, * @return Callback with infered type */ template -Callback callback(R (*func)(A0, A1, A2) = 0) { +Callback callback(R(*func)(A0, A1, A2) = 0) +{ return Callback(func); } @@ -4053,7 +4398,8 @@ Callback callback(R (*func)(A0, A1, A2) = 0) { * @return Callback with infered type */ template -Callback callback(const Callback &func) { +Callback callback(const Callback &func) +{ return Callback(func); } @@ -4064,7 +4410,8 @@ Callback callback(const Callback &func) { * @return Callback with infered type */ template -Callback callback(U *obj, R (T::*method)(A0, A1, A2)) { +Callback callback(U *obj, R(T::*method)(A0, A1, A2)) +{ return Callback(obj, method); } @@ -4075,7 +4422,8 @@ Callback callback(U *obj, R (T::*method)(A0, A1, A2)) { * @return Callback with infered type */ template -Callback callback(const U *obj, R (T::*method)(A0, A1, A2) const) { +Callback callback(const U *obj, R(T::*method)(A0, A1, A2) const) +{ return Callback(obj, method); } @@ -4086,7 +4434,8 @@ Callback callback(const U *obj, R (T::*method)(A0, A1, A2) const) * @return Callback with infered type */ template -Callback callback(volatile U *obj, R (T::*method)(A0, A1, A2) volatile) { +Callback callback(volatile U *obj, R(T::*method)(A0, A1, A2) volatile) +{ return Callback(obj, method); } @@ -4097,7 +4446,8 @@ Callback callback(volatile U *obj, R (T::*method)(A0, A1, A2) vol * @return Callback with infered type */ template -Callback callback(const volatile U *obj, R (T::*method)(A0, A1, A2) const volatile) { +Callback callback(const volatile U *obj, R(T::*method)(A0, A1, A2) const volatile) +{ return Callback(obj, method); } @@ -4108,7 +4458,8 @@ Callback callback(const volatile U *obj, R (T::*method)(A0, A1, A * @return Callback with infered type */ template -Callback callback(R (*func)(T*, A0, A1, A2), U *arg) { +Callback callback(R(*func)(T *, A0, A1, A2), U *arg) +{ return Callback(func, arg); } @@ -4119,7 +4470,8 @@ Callback callback(R (*func)(T*, A0, A1, A2), U *arg) { * @return Callback with infered type */ template -Callback callback(R (*func)(const T*, A0, A1, A2), const U *arg) { +Callback callback(R(*func)(const T *, A0, A1, A2), const U *arg) +{ return Callback(func, arg); } @@ -4130,7 +4482,8 @@ Callback callback(R (*func)(const T*, A0, A1, A2), const U *arg) * @return Callback with infered type */ template -Callback callback(R (*func)(volatile T*, A0, A1, A2), volatile U *arg) { +Callback callback(R(*func)(volatile T *, A0, A1, A2), volatile U *arg) +{ return Callback(func, arg); } @@ -4141,7 +4494,8 @@ Callback callback(R (*func)(volatile T*, A0, A1, A2), volatile U * @return Callback with infered type */ template -Callback callback(R (*func)(const volatile T*, A0, A1, A2), const volatile U *arg) { +Callback callback(R(*func)(const volatile T *, A0, A1, A2), const volatile U *arg) +{ return Callback(func, arg); } @@ -4155,8 +4509,9 @@ Callback callback(R (*func)(const volatile T*, A0, A1, A2), const */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(U *obj, R (*func)(T*, A0, A1, A2)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(U *obj, R(*func)(T *, A0, A1, A2)) +{ return Callback(func, obj); } @@ -4170,8 +4525,9 @@ Callback callback(U *obj, R (*func)(T*, A0, A1, A2)) { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(const U *obj, R (*func)(const T*, A0, A1, A2)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(const U *obj, R(*func)(const T *, A0, A1, A2)) +{ return Callback(func, obj); } @@ -4185,8 +4541,9 @@ Callback callback(const U *obj, R (*func)(const T*, A0, A1, A2)) */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(volatile U *obj, R (*func)(volatile T*, A0, A1, A2)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(volatile U *obj, R(*func)(volatile T *, A0, A1, A2)) +{ return Callback(func, obj); } @@ -4200,8 +4557,9 @@ Callback callback(volatile U *obj, R (*func)(volatile T*, A0, A1, */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(const volatile U *obj, R (*func)(const volatile T*, A0, A1, A2)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(const volatile U *obj, R(*func)(const volatile T *, A0, A1, A2)) +{ return Callback(func, obj); } @@ -4212,7 +4570,8 @@ Callback callback(const volatile U *obj, R (*func)(const volatile * @return Callback with infered type */ template -Callback callback(R (*func)(A0, A1, A2, A3) = 0) { +Callback callback(R(*func)(A0, A1, A2, A3) = 0) +{ return Callback(func); } @@ -4222,7 +4581,8 @@ Callback callback(R (*func)(A0, A1, A2, A3) = 0) { * @return Callback with infered type */ template -Callback callback(const Callback &func) { +Callback callback(const Callback &func) +{ return Callback(func); } @@ -4233,7 +4593,8 @@ Callback callback(const Callback &func) { * @return Callback with infered type */ template -Callback callback(U *obj, R (T::*method)(A0, A1, A2, A3)) { +Callback callback(U *obj, R(T::*method)(A0, A1, A2, A3)) +{ return Callback(obj, method); } @@ -4244,7 +4605,8 @@ Callback callback(U *obj, R (T::*method)(A0, A1, A2, A3)) { * @return Callback with infered type */ template -Callback callback(const U *obj, R (T::*method)(A0, A1, A2, A3) const) { +Callback callback(const U *obj, R(T::*method)(A0, A1, A2, A3) const) +{ return Callback(obj, method); } @@ -4255,7 +4617,8 @@ Callback callback(const U *obj, R (T::*method)(A0, A1, A2, A3 * @return Callback with infered type */ template -Callback callback(volatile U *obj, R (T::*method)(A0, A1, A2, A3) volatile) { +Callback callback(volatile U *obj, R(T::*method)(A0, A1, A2, A3) volatile) +{ return Callback(obj, method); } @@ -4266,7 +4629,8 @@ Callback callback(volatile U *obj, R (T::*method)(A0, A1, A2, * @return Callback with infered type */ template -Callback callback(const volatile U *obj, R (T::*method)(A0, A1, A2, A3) const volatile) { +Callback callback(const volatile U *obj, R(T::*method)(A0, A1, A2, A3) const volatile) +{ return Callback(obj, method); } @@ -4277,7 +4641,8 @@ Callback callback(const volatile U *obj, R (T::*method)(A0, A * @return Callback with infered type */ template -Callback callback(R (*func)(T*, A0, A1, A2, A3), U *arg) { +Callback callback(R(*func)(T *, A0, A1, A2, A3), U *arg) +{ return Callback(func, arg); } @@ -4288,7 +4653,8 @@ Callback callback(R (*func)(T*, A0, A1, A2, A3), U *arg) { * @return Callback with infered type */ template -Callback callback(R (*func)(const T*, A0, A1, A2, A3), const U *arg) { +Callback callback(R(*func)(const T *, A0, A1, A2, A3), const U *arg) +{ return Callback(func, arg); } @@ -4299,7 +4665,8 @@ Callback callback(R (*func)(const T*, A0, A1, A2, A3), const * @return Callback with infered type */ template -Callback callback(R (*func)(volatile T*, A0, A1, A2, A3), volatile U *arg) { +Callback callback(R(*func)(volatile T *, A0, A1, A2, A3), volatile U *arg) +{ return Callback(func, arg); } @@ -4310,7 +4677,8 @@ Callback callback(R (*func)(volatile T*, A0, A1, A2, A3), vol * @return Callback with infered type */ template -Callback callback(R (*func)(const volatile T*, A0, A1, A2, A3), const volatile U *arg) { +Callback callback(R(*func)(const volatile T *, A0, A1, A2, A3), const volatile U *arg) +{ return Callback(func, arg); } @@ -4324,8 +4692,9 @@ Callback callback(R (*func)(const volatile T*, A0, A1, A2, A3 */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(U *obj, R (*func)(T*, A0, A1, A2, A3)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(U *obj, R(*func)(T *, A0, A1, A2, A3)) +{ return Callback(func, obj); } @@ -4339,8 +4708,9 @@ Callback callback(U *obj, R (*func)(T*, A0, A1, A2, A3)) { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(const U *obj, R (*func)(const T*, A0, A1, A2, A3)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(const U *obj, R(*func)(const T *, A0, A1, A2, A3)) +{ return Callback(func, obj); } @@ -4354,8 +4724,9 @@ Callback callback(const U *obj, R (*func)(const T*, A0, A1, A */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(volatile U *obj, R (*func)(volatile T*, A0, A1, A2, A3)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(volatile U *obj, R(*func)(volatile T *, A0, A1, A2, A3)) +{ return Callback(func, obj); } @@ -4369,8 +4740,9 @@ Callback callback(volatile U *obj, R (*func)(volatile T*, A0, */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(const volatile U *obj, R (*func)(const volatile T*, A0, A1, A2, A3)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(const volatile U *obj, R(*func)(const volatile T *, A0, A1, A2, A3)) +{ return Callback(func, obj); } @@ -4381,7 +4753,8 @@ Callback callback(const volatile U *obj, R (*func)(const vola * @return Callback with infered type */ template -Callback callback(R (*func)(A0, A1, A2, A3, A4) = 0) { +Callback callback(R(*func)(A0, A1, A2, A3, A4) = 0) +{ return Callback(func); } @@ -4391,7 +4764,8 @@ Callback callback(R (*func)(A0, A1, A2, A3, A4) = 0) { * @return Callback with infered type */ template -Callback callback(const Callback &func) { +Callback callback(const Callback &func) +{ return Callback(func); } @@ -4402,7 +4776,8 @@ Callback callback(const Callback & * @return Callback with infered type */ template -Callback callback(U *obj, R (T::*method)(A0, A1, A2, A3, A4)) { +Callback callback(U *obj, R(T::*method)(A0, A1, A2, A3, A4)) +{ return Callback(obj, method); } @@ -4413,7 +4788,8 @@ Callback callback(U *obj, R (T::*method)(A0, A1, A2, A3, * @return Callback with infered type */ template -Callback callback(const U *obj, R (T::*method)(A0, A1, A2, A3, A4) const) { +Callback callback(const U *obj, R(T::*method)(A0, A1, A2, A3, A4) const) +{ return Callback(obj, method); } @@ -4424,7 +4800,8 @@ Callback callback(const U *obj, R (T::*method)(A0, A1, A2 * @return Callback with infered type */ template -Callback callback(volatile U *obj, R (T::*method)(A0, A1, A2, A3, A4) volatile) { +Callback callback(volatile U *obj, R(T::*method)(A0, A1, A2, A3, A4) volatile) +{ return Callback(obj, method); } @@ -4435,7 +4812,8 @@ Callback callback(volatile U *obj, R (T::*method)(A0, A1, * @return Callback with infered type */ template -Callback callback(const volatile U *obj, R (T::*method)(A0, A1, A2, A3, A4) const volatile) { +Callback callback(const volatile U *obj, R(T::*method)(A0, A1, A2, A3, A4) const volatile) +{ return Callback(obj, method); } @@ -4446,7 +4824,8 @@ Callback callback(const volatile U *obj, R (T::*method)(A * @return Callback with infered type */ template -Callback callback(R (*func)(T*, A0, A1, A2, A3, A4), U *arg) { +Callback callback(R(*func)(T *, A0, A1, A2, A3, A4), U *arg) +{ return Callback(func, arg); } @@ -4457,7 +4836,8 @@ Callback callback(R (*func)(T*, A0, A1, A2, A3, A4), U *a * @return Callback with infered type */ template -Callback callback(R (*func)(const T*, A0, A1, A2, A3, A4), const U *arg) { +Callback callback(R(*func)(const T *, A0, A1, A2, A3, A4), const U *arg) +{ return Callback(func, arg); } @@ -4468,7 +4848,8 @@ Callback callback(R (*func)(const T*, A0, A1, A2, A3, A4) * @return Callback with infered type */ template -Callback callback(R (*func)(volatile T*, A0, A1, A2, A3, A4), volatile U *arg) { +Callback callback(R(*func)(volatile T *, A0, A1, A2, A3, A4), volatile U *arg) +{ return Callback(func, arg); } @@ -4479,7 +4860,8 @@ Callback callback(R (*func)(volatile T*, A0, A1, A2, A3, * @return Callback with infered type */ template -Callback callback(R (*func)(const volatile T*, A0, A1, A2, A3, A4), const volatile U *arg) { +Callback callback(R(*func)(const volatile T *, A0, A1, A2, A3, A4), const volatile U *arg) +{ return Callback(func, arg); } @@ -4493,8 +4875,9 @@ Callback callback(R (*func)(const volatile T*, A0, A1, A2 */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(U *obj, R (*func)(T*, A0, A1, A2, A3, A4)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(U *obj, R(*func)(T *, A0, A1, A2, A3, A4)) +{ return Callback(func, obj); } @@ -4508,8 +4891,9 @@ Callback callback(U *obj, R (*func)(T*, A0, A1, A2, A3, A */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(const U *obj, R (*func)(const T*, A0, A1, A2, A3, A4)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(const U *obj, R(*func)(const T *, A0, A1, A2, A3, A4)) +{ return Callback(func, obj); } @@ -4523,8 +4907,9 @@ Callback callback(const U *obj, R (*func)(const T*, A0, A */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(volatile U *obj, R (*func)(volatile T*, A0, A1, A2, A3, A4)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(volatile U *obj, R(*func)(volatile T *, A0, A1, A2, A3, A4)) +{ return Callback(func, obj); } @@ -4538,8 +4923,9 @@ Callback callback(volatile U *obj, R (*func)(volatile T*, */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Arguments to callback have been reordered to callback(func, arg)") -Callback callback(const volatile U *obj, R (*func)(const volatile T*, A0, A1, A2, A3, A4)) { + "Arguments to callback have been reordered to callback(func, arg)") +Callback callback(const volatile U *obj, R(*func)(const volatile T *, A0, A1, A2, A3, A4)) +{ return Callback(func, obj); } diff --git a/platform/CircularBuffer.h b/platform/CircularBuffer.h index abf24c40ac9..4ec56ea7862 100644 --- a/platform/CircularBuffer.h +++ b/platform/CircularBuffer.h @@ -24,17 +24,29 @@ namespace mbed { namespace internal { /* Detect if CounterType of the Circular buffer is of unsigned type. */ template -struct is_unsigned { static const bool value = false; }; +struct is_unsigned { + static const bool value = false; +}; template<> -struct is_unsigned { static const bool value = true; }; +struct is_unsigned { + static const bool value = true; +}; template<> -struct is_unsigned { static const bool value = true; }; +struct is_unsigned { + static const bool value = true; +}; template<> -struct is_unsigned { static const bool value = true; }; +struct is_unsigned { + static const bool value = true; +}; template<> -struct is_unsigned { static const bool value = true; }; +struct is_unsigned { + static const bool value = true; +}; template<> -struct is_unsigned { static const bool value = true; }; +struct is_unsigned { + static const bool value = true; +}; }; /** \addtogroup platform */ @@ -52,7 +64,8 @@ struct is_unsigned { static const bool value = true; }; template class CircularBuffer { public: - CircularBuffer() : _head(0), _tail(0), _full(false) { + CircularBuffer() : _head(0), _tail(0), _full(false) + { MBED_STATIC_ASSERT( internal::is_unsigned::value, "CounterType must be unsigned" @@ -65,7 +78,8 @@ class CircularBuffer { ); } - ~CircularBuffer() { + ~CircularBuffer() + { } /** Push the transaction to the buffer. This overwrites the buffer if it's @@ -73,7 +87,8 @@ class CircularBuffer { * * @param data Data to be pushed to the buffer */ - void push(const T& data) { + void push(const T &data) + { core_util_critical_section_enter(); if (full()) { _tail++; @@ -92,7 +107,8 @@ class CircularBuffer { * @param data Data to be pushed to the buffer * @return True if the buffer is not empty and data contains a transaction, false otherwise */ - bool pop(T& data) { + bool pop(T &data) + { bool data_popped = false; core_util_critical_section_enter(); if (!empty()) { @@ -109,7 +125,8 @@ class CircularBuffer { * * @return True if the buffer is empty, false if not */ - bool empty() const { + bool empty() const + { core_util_critical_section_enter(); bool is_empty = (_head == _tail) && !_full; core_util_critical_section_exit(); @@ -120,7 +137,8 @@ class CircularBuffer { * * @return True if the buffer is full, false if not */ - bool full() const { + bool full() const + { core_util_critical_section_enter(); bool full = _full; core_util_critical_section_exit(); @@ -130,7 +148,8 @@ class CircularBuffer { /** Reset the buffer * */ - void reset() { + void reset() + { core_util_critical_section_enter(); _head = 0; _tail = 0; @@ -139,7 +158,8 @@ class CircularBuffer { } /** Get the number of elements currently stored in the circular_buffer */ - CounterType size() const { + CounterType size() const + { core_util_critical_section_enter(); CounterType elements; if (!_full) { @@ -154,7 +174,7 @@ class CircularBuffer { core_util_critical_section_exit(); return elements; } - + private: T _pool[BufferSize]; volatile CounterType _head; diff --git a/platform/CriticalSectionLock.h b/platform/CriticalSectionLock.h index f20be85ad79..3373b5eea0e 100644 --- a/platform/CriticalSectionLock.h +++ b/platform/CriticalSectionLock.h @@ -57,12 +57,12 @@ namespace mbed { */ class CriticalSectionLock { public: - CriticalSectionLock() + CriticalSectionLock() { core_util_critical_section_enter(); } - ~CriticalSectionLock() + ~CriticalSectionLock() { core_util_critical_section_exit(); } @@ -71,8 +71,8 @@ class CriticalSectionLock { * */ MBED_DEPRECATED_SINCE("mbed-os-5.8", - "This function is inconsistent with RAII and is being removed in the future." - "Replaced by static function CriticalSectionLock::enable.") + "This function is inconsistent with RAII and is being removed in the future." + "Replaced by static function CriticalSectionLock::enable.") void lock() { core_util_critical_section_enter(); @@ -82,8 +82,8 @@ class CriticalSectionLock { * */ MBED_DEPRECATED_SINCE("mbed-os-5.8", - "This function is inconsistent with RAII and is being removed in the future." - "Replaced by static function CriticalSectionLock::disable.") + "This function is inconsistent with RAII and is being removed in the future." + "Replaced by static function CriticalSectionLock::disable.") void unlock() { core_util_critical_section_exit(); diff --git a/platform/DirHandle.h b/platform/DirHandle.h index 116ebf581dc..e2e85ad00df 100644 --- a/platform/DirHandle.h +++ b/platform/DirHandle.h @@ -80,7 +80,7 @@ class DirHandle : private NonCopyable { */ virtual void rewind() = 0; - /** Get the sizeof the directory + /** Get the sizeof the directory * * @return Number of files in the directory */ @@ -107,7 +107,10 @@ class DirHandle : private NonCopyable { * -1 on error. */ MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by DirHandle::close") - virtual int closedir() { return close(); }; + virtual int closedir() + { + return close(); + }; /** Return the directory entry at the current position, and * advances the position to the next entry. @@ -127,7 +130,10 @@ class DirHandle : private NonCopyable { /** Resets the position to the beginning of the directory. */ MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by DirHandle::rewind") - virtual void rewinddir() { rewind(); } + virtual void rewinddir() + { + rewind(); + } /** Returns the current position of the DirHandle. * @@ -136,14 +142,20 @@ class DirHandle : private NonCopyable { * -1 on error. */ MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by DirHandle::tell") - virtual off_t telldir() { return tell(); } + virtual off_t telldir() + { + return tell(); + } /** Sets the position of the DirHandle. * * @param location The location to seek to. Must be a value returned by telldir. */ MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by DirHandle::seek") - virtual void seekdir(off_t location) { seek(location); } + virtual void seekdir(off_t location) + { + seek(location); + } }; /**@}*/ diff --git a/platform/FileBase.cpp b/platform/FileBase.cpp index 4458f584b48..a6ca848a82b 100644 --- a/platform/FileBase.cpp +++ b/platform/FileBase.cpp @@ -23,8 +23,9 @@ FileBase *FileBase::_head = NULL; SingletonPtr FileBase::_mutex; FileBase::FileBase(const char *name, PathType t) : _next(NULL), - _name(name), - _path_type(t) { + _name(name), + _path_type(t) +{ _mutex->lock(); if (name != NULL) { // put this object at head of the list @@ -36,7 +37,8 @@ FileBase::FileBase(const char *name, PathType t) : _next(NULL), _mutex->unlock(); } -FileBase::~FileBase() { +FileBase::~FileBase() +{ _mutex->lock(); if (_name != NULL) { // remove this object from the list @@ -53,12 +55,13 @@ FileBase::~FileBase() { _mutex->unlock(); if (getPathType() == FilePathType) { - extern void remove_filehandle(FileHandle *file); - remove_filehandle(static_cast(static_cast(this))); + extern void remove_filehandle(FileHandle * file); + remove_filehandle(static_cast(static_cast(this))); } } -FileBase *FileBase::lookup(const char *name, unsigned int len) { +FileBase *FileBase::lookup(const char *name, unsigned int len) +{ _mutex->lock(); FileBase *p = _head; while (p != NULL) { @@ -73,7 +76,8 @@ FileBase *FileBase::lookup(const char *name, unsigned int len) { return NULL; } -FileBase *FileBase::get(int n) { +FileBase *FileBase::get(int n) +{ _mutex->lock(); FileBase *p = _head; int m = 0; @@ -90,12 +94,14 @@ FileBase *FileBase::get(int n) { return NULL; } -const char* FileBase::getName(void) { +const char *FileBase::getName(void) +{ // Constant read so no lock needed return _name; } -PathType FileBase::getPathType(void) { +PathType FileBase::getPathType(void) +{ // Constant read so no lock needed return _path_type; } diff --git a/platform/FileBase.h b/platform/FileBase.h index 4f6371923b2..0ef63b40af1 100644 --- a/platform/FileBase.h +++ b/platform/FileBase.h @@ -27,7 +27,7 @@ typedef int FILEHANDLE; #include "platform/NonCopyable.h" namespace mbed { - + typedef enum { FilePathType, FileSystemPathType @@ -42,13 +42,13 @@ typedef enum { /** Class FileBase * */ - + class FileBase : private NonCopyable { public: FileBase(const char *name, PathType t); virtual ~FileBase(); - const char* getName(void); + const char *getName(void); PathType getPathType(void); static FileBase *lookup(const char *name, unsigned int len); @@ -61,7 +61,7 @@ class FileBase : private NonCopyable { static SingletonPtr _mutex; FileBase *_next; - const char * const _name; + const char *const _name; const PathType _path_type; }; diff --git a/platform/FileHandle.h b/platform/FileHandle.h index 5ce64566ab1..13d6b88f0ab 100644 --- a/platform/FileHandle.h +++ b/platform/FileHandle.h @@ -69,7 +69,7 @@ class FileHandle : private NonCopyable { * * if some data can be written, and non-blocking set, write partial * * @param buffer The buffer to write from - * @param size The number of bytes to write + * @param size The number of bytes to write * @return The number of bytes written, negative error on failure */ virtual ssize_t write(const void *buffer, size_t size) = 0; diff --git a/platform/FilePath.cpp b/platform/FilePath.cpp index ee348993f50..92511d1b687 100644 --- a/platform/FilePath.cpp +++ b/platform/FilePath.cpp @@ -17,11 +17,12 @@ namespace mbed { -FilePath::FilePath(const char* file_path) : file_name(NULL), fb(NULL) { +FilePath::FilePath(const char *file_path) : file_name(NULL), fb(NULL) +{ // skip slashes file_path += strspn(file_path, "/"); - const char* file_system = file_path; + const char *file_system = file_path; file_name = file_system; int len = 0; while (true) { @@ -41,37 +42,45 @@ FilePath::FilePath(const char* file_path) : file_name(NULL), fb(NULL) { fb = FileBase::lookup(file_system, len); } -const char* FilePath::fileName(void) { +const char *FilePath::fileName(void) +{ return file_name; } -bool FilePath::isFileSystem(void) { - if (NULL == fb) +bool FilePath::isFileSystem(void) +{ + if (NULL == fb) { return false; + } return (fb->getPathType() == FileSystemPathType); } -FileSystemLike* FilePath::fileSystem(void) { +FileSystemLike *FilePath::fileSystem(void) +{ if (isFileSystem()) { - return static_cast(fb); + return static_cast(fb); } return NULL; } -bool FilePath::isFile(void) { - if (NULL == fb) +bool FilePath::isFile(void) +{ + if (NULL == fb) { return false; + } return (fb->getPathType() == FilePathType); } -FileLike* FilePath::file(void) { +FileLike *FilePath::file(void) +{ if (isFile()) { - return (FileLike*)fb; + return (FileLike *)fb; } return NULL; } -bool FilePath::exists(void) { +bool FilePath::exists(void) +{ return fb != NULL; } diff --git a/platform/FilePath.h b/platform/FilePath.h index d380041ca05..6183ffbcefe 100644 --- a/platform/FilePath.h +++ b/platform/FilePath.h @@ -33,27 +33,27 @@ class FileSystem; /** Class FilePath * */ - + class FilePath { public: /** Constructor FilePath * * @param file_path The path of file. - */ - FilePath(const char* file_path); + */ + FilePath(const char *file_path); - const char* fileName(void); + const char *fileName(void); bool isFileSystem(void); - FileSystemLike* fileSystem(void); + FileSystemLike *fileSystem(void); bool isFile(void); - FileLike* file(void); + FileLike *file(void); bool exists(void); private: - const char* file_name; - FileBase* fb; + const char *file_name; + FileBase *fb; }; /**@}*/ diff --git a/platform/FileSystemHandle.h b/platform/FileSystemHandle.h index 349e25855ee..750dab056a5 100644 --- a/platform/FileSystemHandle.h +++ b/platform/FileSystemHandle.h @@ -101,7 +101,7 @@ class FileSystemHandle : private NonCopyable { * @param buf The stat buffer to write to * @return 0 on success, negative error code on failure */ - virtual int statvfs(const char *path, struct statvfs *buf); + virtual int statvfs(const char *path, struct statvfs *buf); }; /**@}*/ diff --git a/platform/FileSystemLike.h b/platform/FileSystemLike.h index aef7913cf67..abcd6358d39 100644 --- a/platform/FileSystemLike.h +++ b/platform/FileSystemLike.h @@ -59,7 +59,7 @@ class FileSystemLike : public FileSystemHandle, public FileBase, private NonCopy * @deprecated Replaced by `int open(FileHandle **, ...)` for propagating error codes */ MBED_DEPRECATED_SINCE("mbed-os-5.5", - "Replaced by `int open(FileHandle **, ...)` for propagating error codes") + "Replaced by `int open(FileHandle **, ...)` for propagating error codes") FileHandle *open(const char *path, int flags) { FileHandle *file; @@ -74,7 +74,7 @@ class FileSystemLike : public FileSystemHandle, public FileBase, private NonCopy * @deprecated Replaced by `int open(DirHandle **, ...)` for propagating error codes */ MBED_DEPRECATED_SINCE("mbed-os-5.5", - "Replaced by `int open(DirHandle **, ...)` for propagating error codes") + "Replaced by `int open(DirHandle **, ...)` for propagating error codes") DirHandle *opendir(const char *path) { DirHandle *dir; diff --git a/platform/FunctionPointer.h b/platform/FunctionPointer.h index 18c34c2106e..c17f53a9a96 100644 --- a/platform/FunctionPointer.h +++ b/platform/FunctionPointer.h @@ -35,21 +35,23 @@ template class FunctionPointerArg1 : public Callback { public: MBED_DEPRECATED_SINCE("mbed-os-5.1", - "FunctionPointerArg1 has been replaced by Callback") - FunctionPointerArg1(R (*function)(A1) = 0) + "FunctionPointerArg1 has been replaced by Callback") + FunctionPointerArg1(R(*function)(A1) = 0) : Callback(function) {} template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "FunctionPointerArg1 has been replaced by Callback") - FunctionPointerArg1(T *object, R (T::*member)(A1)) + "FunctionPointerArg1 has been replaced by Callback") + FunctionPointerArg1(T *object, R(T::*member)(A1)) : Callback(object, member) {} - R (*get_function())(A1) { - return *reinterpret_cast(this); + R(*get_function())(A1) + { + return *reinterpret_cast(this); } - R call(A1 a1) const { + R call(A1 a1) const + { if (!Callback::operator bool()) { return (R)0; } @@ -57,7 +59,8 @@ class FunctionPointerArg1 : public Callback { return Callback::call(a1); } - R operator()(A1 a1) const { + R operator()(A1 a1) const + { return Callback::call(a1); } }; @@ -66,21 +69,23 @@ template class FunctionPointerArg1 : public Callback { public: MBED_DEPRECATED_SINCE("mbed-os-5.1", - "FunctionPointer has been replaced by Callback") - FunctionPointerArg1(R (*function)() = 0) + "FunctionPointer has been replaced by Callback") + FunctionPointerArg1(R(*function)() = 0) : Callback(function) {} template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "FunctionPointer has been replaced by Callback") - FunctionPointerArg1(T *object, R (T::*member)()) + "FunctionPointer has been replaced by Callback") + FunctionPointerArg1(T *object, R(T::*member)()) : Callback(object, member) {} - R (*get_function())() { - return *reinterpret_cast(this); + R(*get_function())() + { + return *reinterpret_cast(this); } - R call() const { + R call() const + { if (!Callback::operator bool()) { return (R)0; } @@ -88,7 +93,8 @@ class FunctionPointerArg1 : public Callback { return Callback::call(); } - R operator()() const { + R operator()() const + { return Callback::call(); } }; diff --git a/platform/LocalFileSystem.cpp b/platform/LocalFileSystem.cpp index 13daee31c26..c5c7d33dff7 100644 --- a/platform/LocalFileSystem.cpp +++ b/platform/LocalFileSystem.cpp @@ -45,7 +45,8 @@ typedef struct { /* File Search info record */ #define RESERVED_FOR_USER_APPLICATIONS (0x100) /* 0x100 - 0x1ff */ #define USR_XFFIND (RESERVED_FOR_USER_APPLICATIONS + 0) -static int xffind (const char *pattern, XFINFO *info) { +static int xffind(const char *pattern, XFINFO *info) +{ unsigned param[4]; param[0] = (unsigned long)pattern; @@ -63,7 +64,8 @@ static int xffind (const char *pattern, XFINFO *info) { #define OPEN_A 8 #define OPEN_INVALID -1 -int posix_to_semihost_open_flags(int flags) { +int posix_to_semihost_open_flags(int flags) +{ /* POSIX flags -> semihosting open mode */ int openmode; if (flags & O_RDWR) { @@ -94,7 +96,8 @@ int posix_to_semihost_open_flags(int flags) { return openmode; } -FILEHANDLE local_file_open(const char* name, int flags) { +FILEHANDLE local_file_open(const char *name, int flags) +{ int openmode = posix_to_semihost_open_flags(flags); if (openmode == OPEN_INVALID) { return (FILEHANDLE)NULL; @@ -108,42 +111,48 @@ FILEHANDLE local_file_open(const char* name, int flags) { return fh; } -LocalFileHandle::LocalFileHandle(FILEHANDLE fh) : _fh(fh), pos(0) { +LocalFileHandle::LocalFileHandle(FILEHANDLE fh) : _fh(fh), pos(0) +{ // No lock needed in constructor } -int LocalFileHandle::close() { +int LocalFileHandle::close() +{ int retval = semihost_close(_fh); delete this; return retval; } -ssize_t LocalFileHandle::write(const void *buffer, size_t length) { +ssize_t LocalFileHandle::write(const void *buffer, size_t length) +{ lock(); - ssize_t n = semihost_write(_fh, (const unsigned char*)buffer, length, 0); // number of characters not written + ssize_t n = semihost_write(_fh, (const unsigned char *)buffer, length, 0); // number of characters not written n = length - n; // number of characters written pos += n; unlock(); return n; } -ssize_t LocalFileHandle::read(void *buffer, size_t length) { +ssize_t LocalFileHandle::read(void *buffer, size_t length) +{ lock(); - ssize_t n = semihost_read(_fh, (unsigned char*)buffer, length, 0); // number of characters not read + ssize_t n = semihost_read(_fh, (unsigned char *)buffer, length, 0); // number of characters not read n = length - n; // number of characters read pos += n; unlock(); return n; } -int LocalFileHandle::isatty() { +int LocalFileHandle::isatty() +{ lock(); int ret = semihost_istty(_fh); unlock(); return ret; } -off_t LocalFileHandle::seek(off_t position, int whence) { +off_t LocalFileHandle::seek(off_t position, int whence) +{ lock(); if (whence == SEEK_CUR) { position += pos; @@ -158,25 +167,29 @@ off_t LocalFileHandle::seek(off_t position, int whence) { return position; } -int LocalFileHandle::sync() { +int LocalFileHandle::sync() +{ lock(); int ret = semihost_ensure(_fh); unlock(); return ret; } -off_t LocalFileHandle::size() { +off_t LocalFileHandle::size() +{ lock(); off_t off = semihost_flen(_fh); unlock(); return off; } -void LocalFileHandle::lock() { +void LocalFileHandle::lock() +{ _mutex.lock(); } -void LocalFileHandle::unlock() { +void LocalFileHandle::unlock() +{ _mutex.unlock(); } @@ -185,18 +198,21 @@ class LocalDirHandle : public DirHandle { public: XFINFO info; - LocalDirHandle() : info() { + LocalDirHandle() : info() + { } - virtual int close() { + virtual int close() + { // No lock can be used in destructor delete this; return 0; } - virtual int read(struct dirent *ent) { + virtual int read(struct dirent *ent) + { lock(); - if (xffind("*", &info)!=0) { + if (xffind("*", &info) != 0) { unlock(); return 0; } @@ -205,20 +221,23 @@ class LocalDirHandle : public DirHandle { return 1; } - virtual void rewind() { + virtual void rewind() + { lock(); info.fileID = 0; unlock(); } - virtual off_t tell() { + virtual off_t tell() + { lock(); int fileId = info.fileID; unlock(); return fileId; } - virtual void seek(off_t offset) { + virtual void seek(off_t offset) + { lock(); info.fileID = offset; unlock(); @@ -227,16 +246,19 @@ class LocalDirHandle : public DirHandle { protected: PlatformMutex _mutex; - virtual void lock() { + virtual void lock() + { _mutex.lock(); } - virtual void unlock() { + virtual void unlock() + { _mutex.unlock(); } }; -int LocalFileSystem::open(FileHandle **file, const char* name, int flags) { +int LocalFileSystem::open(FileHandle **file, const char *name, int flags) +{ // No global state modified so function is thread safe /* reject filenames with / in them */ @@ -260,13 +282,15 @@ int LocalFileSystem::open(FileHandle **file, const char* name, int flags) { return 0; } -int LocalFileSystem::remove(const char *filename) { +int LocalFileSystem::remove(const char *filename) +{ // No global state modified so function is thread safe return semihost_remove(filename); } -int LocalFileSystem::open(DirHandle **dir, const char *name) { +int LocalFileSystem::open(DirHandle **dir, const char *name) +{ // No global state modified so function is thread safe *dir = new LocalDirHandle(); diff --git a/platform/LocalFileSystem.h b/platform/LocalFileSystem.h index ce0baafaf07..78ca4993750 100644 --- a/platform/LocalFileSystem.h +++ b/platform/LocalFileSystem.h @@ -32,7 +32,7 @@ namespace mbed { * @{ */ -FILEHANDLE local_file_open(const char* name, int flags); +FILEHANDLE local_file_open(const char *name, int flags); /** * @class LocalFileHandle @@ -106,7 +106,8 @@ class LocalFileSystem : public FileSystemLike, private NonCopyable { public: - PlatformMutex() { + PlatformMutex() + { // Stub } - ~PlatformMutex() { + ~PlatformMutex() + { // Stub } - void lock() { + void lock() + { // Do nothing } - void unlock() { + void unlock() + { // Do nothing } }; diff --git a/platform/ScopedLock.h b/platform/ScopedLock.h index 674462f2554..8f79fbf7ddd 100644 --- a/platform/ScopedLock.h +++ b/platform/ScopedLock.h @@ -65,7 +65,7 @@ class ScopedLock : private NonCopyable > { * @param lockable reference to the instance of Lockable object * @note lockable object should outlive the ScopedLock object */ - ScopedLock(Lockable& lockable): _lockable(lockable) + ScopedLock(Lockable &lockable): _lockable(lockable) { _lockable.lock(); } @@ -75,7 +75,7 @@ class ScopedLock : private NonCopyable > { _lockable.unlock(); } private: - Lockable& _lockable; + Lockable &_lockable; }; /**@}*/ diff --git a/platform/SingletonPtr.h b/platform/SingletonPtr.h index 848fd099f46..a7f5f6bde5b 100644 --- a/platform/SingletonPtr.h +++ b/platform/SingletonPtr.h @@ -56,7 +56,7 @@ inline static void singleton_lock(void) inline static void singleton_unlock(void) { #ifdef MBED_CONF_RTOS_PRESENT - osMutexRelease (singleton_mutex_id); + osMutexRelease(singleton_mutex_id); #endif } @@ -80,7 +80,8 @@ struct SingletonPtr { * @returns * A pointer to the singleton */ - T* get() { + T *get() + { if (NULL == _ptr) { singleton_lock(); if (NULL == _ptr) { @@ -99,7 +100,8 @@ struct SingletonPtr { * @returns * A pointer to the singleton */ - T* operator->() { + T *operator->() + { return get(); } diff --git a/platform/Stream.cpp b/platform/Stream.cpp index 61054d65bc3..868da89a126 100644 --- a/platform/Stream.cpp +++ b/platform/Stream.cpp @@ -19,13 +19,14 @@ namespace mbed { -Stream::Stream(const char *name) : FileLike(name), _file(NULL) { +Stream::Stream(const char *name) : FileLike(name), _file(NULL) +{ // No lock needed in constructor /* open ourselves */ _file = fdopen(this, "w+"); // fdopen() will make us buffered because Stream::isatty() // wrongly returns zero which is not being changed for - // backward compatibility + // backward compatibility if (_file) { mbed_set_unbuffered_stream(_file); } else { @@ -33,47 +34,54 @@ Stream::Stream(const char *name) : FileLike(name), _file(NULL) { } } -Stream::~Stream() { +Stream::~Stream() +{ // No lock can be used in destructor fclose(_file); } -int Stream::putc(int c) { +int Stream::putc(int c) +{ lock(); fflush(_file); int ret = std::fputc(c, _file); unlock(); return ret; } -int Stream::puts(const char *s) { +int Stream::puts(const char *s) +{ lock(); fflush(_file); int ret = std::fputs(s, _file); unlock(); return ret; } -int Stream::getc() { +int Stream::getc() +{ lock(); fflush(_file); int ret = mbed_getc(_file); unlock(); return ret; } -char* Stream::gets(char *s, int size) { +char *Stream::gets(char *s, int size) +{ lock(); fflush(_file); - char *ret = mbed_gets(s,size,_file); + char *ret = mbed_gets(s, size, _file); unlock(); return ret; } -int Stream::close() { +int Stream::close() +{ return 0; } -ssize_t Stream::write(const void* buffer, size_t length) { - const char* ptr = (const char*)buffer; - const char* end = ptr + length; +ssize_t Stream::write(const void *buffer, size_t length) +{ + const char *ptr = (const char *)buffer; + const char *end = ptr + length; lock(); while (ptr != end) { @@ -83,48 +91,58 @@ ssize_t Stream::write(const void* buffer, size_t length) { } unlock(); - return ptr - (const char*)buffer; + return ptr - (const char *)buffer; } -ssize_t Stream::read(void* buffer, size_t length) { - char* ptr = (char*)buffer; - char* end = ptr + length; +ssize_t Stream::read(void *buffer, size_t length) +{ + char *ptr = (char *)buffer; + char *end = ptr + length; lock(); while (ptr != end) { int c = _getc(); - if (c==EOF) break; + if (c == EOF) { + break; + } *ptr++ = c; } unlock(); - return ptr - (const char*)buffer; + return ptr - (const char *)buffer; } -off_t Stream::seek(off_t offset, int whence) { +off_t Stream::seek(off_t offset, int whence) +{ return 0; } -off_t Stream::tell() { +off_t Stream::tell() +{ return 0; } -void Stream::rewind() { +void Stream::rewind() +{ } -int Stream::isatty() { +int Stream::isatty() +{ return 0; } -int Stream::sync() { +int Stream::sync() +{ return 0; } -off_t Stream::size() { +off_t Stream::size() +{ return 0; } -int Stream::printf(const char* format, ...) { +int Stream::printf(const char *format, ...) +{ lock(); std::va_list arg; va_start(arg, format); @@ -135,7 +153,8 @@ int Stream::printf(const char* format, ...) { return r; } -int Stream::scanf(const char* format, ...) { +int Stream::scanf(const char *format, ...) +{ lock(); std::va_list arg; va_start(arg, format); @@ -146,7 +165,8 @@ int Stream::scanf(const char* format, ...) { return r; } -int Stream::vprintf(const char* format, std::va_list args) { +int Stream::vprintf(const char *format, std::va_list args) +{ lock(); fflush(_file); int r = vfprintf(_file, format, args); @@ -154,7 +174,8 @@ int Stream::vprintf(const char* format, std::va_list args) { return r; } -int Stream::vscanf(const char* format, std::va_list args) { +int Stream::vscanf(const char *format, std::va_list args) +{ lock(); fflush(_file); int r = vfscanf(_file, format, args); diff --git a/platform/Stream.h b/platform/Stream.h index 20b7e44afcb..bb761a59790 100644 --- a/platform/Stream.h +++ b/platform/Stream.h @@ -33,7 +33,7 @@ namespace mbed { extern void mbed_set_unbuffered_stream(std::FILE *_file); extern int mbed_getc(std::FILE *_file); -extern char* mbed_gets(char *s, int size, std::FILE *_file); +extern char *mbed_gets(char *s, int size, std::FILE *_file); /** File stream * @@ -42,24 +42,27 @@ extern char* mbed_gets(char *s, int size, std::FILE *_file); class Stream : public FileLike, private NonCopyable { public: - Stream(const char *name=NULL); + Stream(const char *name = NULL); virtual ~Stream(); int putc(int c); int puts(const char *s); int getc(); char *gets(char *s, int size); - int printf(const char* format, ...); - int scanf(const char* format, ...); - int vprintf(const char* format, std::va_list args); - int vscanf(const char* format, std::va_list args); + int printf(const char *format, ...); + int scanf(const char *format, ...); + int vprintf(const char *format, std::va_list args); + int vscanf(const char *format, std::va_list args); - operator std::FILE*() {return _file;} + operator std::FILE *() + { + return _file; + } protected: virtual int close(); - virtual ssize_t write(const void* buffer, size_t length); - virtual ssize_t read(void* buffer, size_t length); + virtual ssize_t write(const void *buffer, size_t length); + virtual ssize_t read(void *buffer, size_t length); virtual off_t seek(off_t offset, int whence); virtual off_t tell(); virtual void rewind(); @@ -74,13 +77,15 @@ class Stream : public FileLike, private NonCopyable { /** Acquire exclusive access to this object. */ - virtual void lock() { + virtual void lock() + { // Stub } /** Release exclusive access to this object. */ - virtual void unlock() { + virtual void unlock() + { // Stub } }; diff --git a/platform/Transaction.h b/platform/Transaction.h index 23f03e07f22..1d8d6ff9de5 100644 --- a/platform/Transaction.h +++ b/platform/Transaction.h @@ -46,20 +46,24 @@ typedef struct { template class Transaction { public: - Transaction(Class *tpointer, const transaction_t& transaction) : _obj(tpointer), _data(transaction) { + Transaction(Class *tpointer, const transaction_t &transaction) : _obj(tpointer), _data(transaction) + { } - Transaction() : _obj(), _data() { + Transaction() : _obj(), _data() + { } - ~Transaction() { + ~Transaction() + { } /** Get object's instance for the transaction * * @return The object which was stored */ - Class* get_object() { + Class *get_object() + { return _obj; } @@ -67,12 +71,13 @@ class Transaction { * * @return The transaction which was stored */ - transaction_t* get_transaction() { + transaction_t *get_transaction() + { return &_data; } private: - Class* _obj; + Class *_obj; transaction_t _data; }; /**@}*/ diff --git a/platform/mbed_alloc_wrappers.cpp b/platform/mbed_alloc_wrappers.cpp index 58f153c70d0..87fcd95f142 100644 --- a/platform/mbed_alloc_wrappers.cpp +++ b/platform/mbed_alloc_wrappers.cpp @@ -76,33 +76,35 @@ void mbed_stats_heap_get(mbed_stats_heap_t *stats) #endif/* FEATURE_UVISOR */ extern "C" { - void * __real__malloc_r(struct _reent * r, size_t size); - void * __real__memalign_r(struct _reent * r, size_t alignment, size_t bytes); - void * __real__realloc_r(struct _reent * r, void * ptr, size_t size); - void __real__free_r(struct _reent * r, void * ptr); - void* __real__calloc_r(struct _reent * r, size_t nmemb, size_t size); - void* malloc_wrapper(struct _reent * r, size_t size, void * caller); - void free_wrapper(struct _reent * r, void * ptr, void* caller); + void *__real__malloc_r(struct _reent *r, size_t size); + void *__real__memalign_r(struct _reent *r, size_t alignment, size_t bytes); + void *__real__realloc_r(struct _reent *r, void *ptr, size_t size); + void __real__free_r(struct _reent *r, void *ptr); + void *__real__calloc_r(struct _reent *r, size_t nmemb, size_t size); + void *malloc_wrapper(struct _reent *r, size_t size, void *caller); + void free_wrapper(struct _reent *r, void *ptr, void *caller); } // TODO: memory tracing doesn't work with uVisor enabled. #if !defined(FEATURE_UVISOR) -extern "C" void * __wrap__malloc_r(struct _reent * r, size_t size) { +extern "C" void *__wrap__malloc_r(struct _reent *r, size_t size) +{ return malloc_wrapper(r, size, MBED_CALLER_ADDR()); } -extern "C" void * malloc_wrapper(struct _reent * r, size_t size, void * caller) { +extern "C" void *malloc_wrapper(struct _reent *r, size_t size, void *caller) +{ void *ptr = NULL; #ifdef MBED_MEM_TRACING_ENABLED mbed_mem_trace_lock(); #endif #ifdef MBED_HEAP_STATS_ENABLED malloc_stats_mutex->lock(); - alloc_info_t *alloc_info = (alloc_info_t*)__real__malloc_r(r, size + sizeof(alloc_info_t)); + alloc_info_t *alloc_info = (alloc_info_t *)__real__malloc_r(r, size + sizeof(alloc_info_t)); if (alloc_info != NULL) { alloc_info->size = size; - ptr = (void*)(alloc_info + 1); + ptr = (void *)(alloc_info + 1); heap_stats.current_size += size; heap_stats.total_size += size; heap_stats.alloc_cnt += 1; @@ -123,7 +125,8 @@ extern "C" void * malloc_wrapper(struct _reent * r, size_t size, void * caller) return ptr; } -extern "C" void * __wrap__realloc_r(struct _reent * r, void * ptr, size_t size) { +extern "C" void *__wrap__realloc_r(struct _reent *r, void *ptr, size_t size) +{ void *new_ptr = NULL; #ifdef MBED_MEM_TRACING_ENABLED mbed_mem_trace_lock(); @@ -139,7 +142,7 @@ extern "C" void * __wrap__realloc_r(struct _reent * r, void * ptr, size_t size) // Get old size uint32_t old_size = 0; if (ptr != NULL) { - alloc_info_t *alloc_info = ((alloc_info_t*)ptr) - 1; + alloc_info_t *alloc_info = ((alloc_info_t *)ptr) - 1; old_size = alloc_info->size; } @@ -152,7 +155,7 @@ extern "C" void * __wrap__realloc_r(struct _reent * r, void * ptr, size_t size) // and free the old buffer if (new_ptr != NULL) { uint32_t copy_size = (old_size < size) ? old_size : size; - memcpy(new_ptr, (void*)ptr, copy_size); + memcpy(new_ptr, (void *)ptr, copy_size); free(ptr); } #else // #ifdef MBED_HEAP_STATS_ENABLED @@ -165,11 +168,13 @@ extern "C" void * __wrap__realloc_r(struct _reent * r, void * ptr, size_t size) return new_ptr; } -extern "C" void __wrap__free_r(struct _reent * r, void * ptr) { +extern "C" void __wrap__free_r(struct _reent *r, void *ptr) +{ free_wrapper(r, ptr, MBED_CALLER_ADDR()); } -extern "C" void free_wrapper(struct _reent * r, void * ptr, void * caller) { +extern "C" void free_wrapper(struct _reent *r, void *ptr, void *caller) +{ #ifdef MBED_MEM_TRACING_ENABLED mbed_mem_trace_lock(); #endif @@ -177,11 +182,11 @@ extern "C" void free_wrapper(struct _reent * r, void * ptr, void * caller) { malloc_stats_mutex->lock(); alloc_info_t *alloc_info = NULL; if (ptr != NULL) { - alloc_info = ((alloc_info_t*)ptr) - 1; + alloc_info = ((alloc_info_t *)ptr) - 1; heap_stats.current_size -= alloc_info->size; heap_stats.alloc_cnt -= 1; } - __real__free_r(r, (void*)alloc_info); + __real__free_r(r, (void *)alloc_info); malloc_stats_mutex->unlock(); #else // #ifdef MBED_HEAP_STATS_ENABLED __real__free_r(r, ptr); @@ -192,7 +197,8 @@ extern "C" void free_wrapper(struct _reent * r, void * ptr, void * caller) { #endif // #ifdef MBED_MEM_TRACING_ENABLED } -extern "C" void * __wrap__calloc_r(struct _reent * r, size_t nmemb, size_t size) { +extern "C" void *__wrap__calloc_r(struct _reent *r, size_t nmemb, size_t size) +{ void *ptr = NULL; #ifdef MBED_MEM_TRACING_ENABLED mbed_mem_trace_lock(); @@ -214,7 +220,8 @@ extern "C" void * __wrap__calloc_r(struct _reent * r, size_t nmemb, size_t size) return ptr; } -extern "C" void * __wrap__memalign_r(struct _reent * r, size_t alignment, size_t bytes) { +extern "C" void *__wrap__memalign_r(struct _reent *r, size_t alignment, size_t bytes) +{ return __real__memalign_r(r, alignment, bytes); } @@ -255,26 +262,28 @@ extern "C" { void *SUPER_REALLOC(void *ptr, size_t size); void *SUPER_CALLOC(size_t nmemb, size_t size); void SUPER_FREE(void *ptr); - void *malloc_wrapper(size_t size, void* caller); - void free_wrapper(void *ptr, void* caller); + void *malloc_wrapper(size_t size, void *caller); + void free_wrapper(void *ptr, void *caller); } -extern "C" void* SUB_MALLOC(size_t size) { +extern "C" void *SUB_MALLOC(size_t size) +{ return malloc_wrapper(size, MBED_CALLER_ADDR()); } -extern "C" void* malloc_wrapper(size_t size, void* caller) { +extern "C" void *malloc_wrapper(size_t size, void *caller) +{ void *ptr = NULL; #ifdef MBED_MEM_TRACING_ENABLED mbed_mem_trace_lock(); #endif #ifdef MBED_HEAP_STATS_ENABLED malloc_stats_mutex->lock(); - alloc_info_t *alloc_info = (alloc_info_t*)SUPER_MALLOC(size + sizeof(alloc_info_t)); + alloc_info_t *alloc_info = (alloc_info_t *)SUPER_MALLOC(size + sizeof(alloc_info_t)); if (alloc_info != NULL) { alloc_info->size = size; - ptr = (void*)(alloc_info + 1); + ptr = (void *)(alloc_info + 1); heap_stats.current_size += size; heap_stats.total_size += size; heap_stats.alloc_cnt += 1; @@ -296,7 +305,8 @@ extern "C" void* malloc_wrapper(size_t size, void* caller) { } -extern "C" void* SUB_REALLOC(void *ptr, size_t size) { +extern "C" void *SUB_REALLOC(void *ptr, size_t size) +{ void *new_ptr = NULL; #ifdef MBED_MEM_TRACING_ENABLED mbed_mem_trace_lock(); @@ -307,7 +317,7 @@ extern "C" void* SUB_REALLOC(void *ptr, size_t size) { // Get old size uint32_t old_size = 0; if (ptr != NULL) { - alloc_info_t *alloc_info = ((alloc_info_t*)ptr) - 1; + alloc_info_t *alloc_info = ((alloc_info_t *)ptr) - 1; old_size = alloc_info->size; } @@ -320,7 +330,7 @@ extern "C" void* SUB_REALLOC(void *ptr, size_t size) { // and free the old buffer if (new_ptr != NULL) { uint32_t copy_size = (old_size < size) ? old_size : size; - memcpy(new_ptr, (void*)ptr, copy_size); + memcpy(new_ptr, (void *)ptr, copy_size); free(ptr); } #else // #ifdef MBED_HEAP_STATS_ENABLED @@ -333,7 +343,8 @@ extern "C" void* SUB_REALLOC(void *ptr, size_t size) { return new_ptr; } -extern "C" void *SUB_CALLOC(size_t nmemb, size_t size) { +extern "C" void *SUB_CALLOC(size_t nmemb, size_t size) +{ void *ptr = NULL; #ifdef MBED_MEM_TRACING_ENABLED mbed_mem_trace_lock(); @@ -354,11 +365,13 @@ extern "C" void *SUB_CALLOC(size_t nmemb, size_t size) { return ptr; } -extern "C" void SUB_FREE(void *ptr) { +extern "C" void SUB_FREE(void *ptr) +{ free_wrapper(ptr, MBED_CALLER_ADDR()); } -extern "C" void free_wrapper(void *ptr, void* caller) { +extern "C" void free_wrapper(void *ptr, void *caller) +{ #ifdef MBED_MEM_TRACING_ENABLED mbed_mem_trace_lock(); #endif @@ -366,11 +379,11 @@ extern "C" void free_wrapper(void *ptr, void* caller) { malloc_stats_mutex->lock(); alloc_info_t *alloc_info = NULL; if (ptr != NULL) { - alloc_info = ((alloc_info_t*)ptr) - 1; + alloc_info = ((alloc_info_t *)ptr) - 1; heap_stats.current_size -= alloc_info->size; heap_stats.alloc_cnt -= 1; } - SUPER_FREE((void*)alloc_info); + SUPER_FREE((void *)alloc_info); malloc_stats_mutex->unlock(); #else // #ifdef MBED_HEAP_STATS_ENABLED SUPER_FREE(ptr); diff --git a/platform/mbed_application.c b/platform/mbed_application.c index 75657f69e7f..dce8745116e 100644 --- a/platform/mbed_application.c +++ b/platform/mbed_application.c @@ -37,8 +37,8 @@ void mbed_start_application(uintptr_t address) powerdown_nvic(); powerdown_scb(address); - sp = *((void**)address + 0); - pc = *((void**)address + 1); + sp = *((void **)address + 0); + pc = *((void **)address + 1); start_new_application(sp, pc); } @@ -106,14 +106,14 @@ __asm static void start_new_application(void *sp, void *pc) void start_new_application(void *sp, void *pc) { - __asm volatile ( + __asm volatile( "mov r2, #0 \n" "msr control, r2 \n" // Switch to main stack "mov sp, %0 \n" "msr primask, r2 \n" // Enable interrupts "bx %1 \n" : - : "l" (sp), "l" (pc) + : "l"(sp), "l"(pc) : "r2", "cc", "memory" ); } diff --git a/platform/mbed_board.c b/platform/mbed_board.c index 227c774c8b2..0c837cfb32f 100644 --- a/platform/mbed_board.c +++ b/platform/mbed_board.c @@ -26,11 +26,13 @@ extern int stdio_uart_inited; extern serial_t stdio_uart; #endif -WEAK void mbed_die(void) { +WEAK void mbed_die(void) +{ #if !defined (NRF51_H) && !defined(TARGET_EFM32) core_util_critical_section_enter(); #endif - gpio_t led_err; gpio_init_out(&led_err, LED1); + gpio_t led_err; + gpio_init_out(&led_err, LED1); while (1) { for (int i = 0; i < 4; ++i) { @@ -49,14 +51,16 @@ WEAK void mbed_die(void) { } } -void mbed_error_printf(const char* format, ...) { +void mbed_error_printf(const char *format, ...) +{ va_list arg; va_start(arg, format); mbed_error_vfprintf(format, arg); va_end(arg); } -void mbed_error_vfprintf(const char * format, va_list arg) { +void mbed_error_vfprintf(const char *format, va_list arg) +{ #if DEVICE_SERIAL #define ERROR_BUF_SIZE (128) core_util_critical_section_enter(); @@ -70,7 +74,7 @@ void mbed_error_vfprintf(const char * format, va_list arg) { char stdio_out_prev = '\0'; for (int i = 0; i < size; i++) { if (buffer[i] == '\n' && stdio_out_prev != '\r') { - serial_putc(&stdio_uart, '\r'); + serial_putc(&stdio_uart, '\r'); } serial_putc(&stdio_uart, buffer[i]); stdio_out_prev = buffer[i]; diff --git a/platform/mbed_critical.c b/platform/mbed_critical.c index 98f14785205..497488372bc 100644 --- a/platform/mbed_critical.c +++ b/platform/mbed_critical.c @@ -38,7 +38,7 @@ #else #error "Unknown architecture for exclusive access" #endif -#else +#else #define MBED_EXCLUSIVE_ACCESS __EXCLUSIVE_ACCESS #endif #endif @@ -57,7 +57,7 @@ bool core_util_are_interrupts_enabled(void) bool core_util_is_isr_active(void) { #if defined(__CORTEX_A9) - switch(__get_CPSR() & 0x1FU) { + switch (__get_CPSR() & 0x1FU) { case CPSR_M_USR: case CPSR_M_SYS: return false; @@ -79,7 +79,7 @@ void core_util_critical_section_enter(void) { // FIXME #ifdef FEATURE_UVISOR - #warning "core_util_critical_section_enter needs fixing to work from unprivileged code" +#warning "core_util_critical_section_enter needs fixing to work from unprivileged code" #else // If the reentrancy counter overflows something has gone badly wrong. MBED_ASSERT(critical_section_reentrancy_counter < UINT32_MAX); @@ -94,7 +94,7 @@ void core_util_critical_section_exit(void) { // FIXME #ifdef FEATURE_UVISOR - #warning "core_util_critical_section_exit needs fixing to work from unprivileged code" +#warning "core_util_critical_section_exit needs fixing to work from unprivileged code" #endif /* FEATURE_UVISOR */ // If critical_section_enter has not previously been called, do nothing @@ -112,33 +112,33 @@ void core_util_critical_section_exit(void) #if MBED_EXCLUSIVE_ACCESS /* Supress __ldrex and __strex deprecated warnings - "#3731-D: intrinsic is deprecated" */ -#if defined (__CC_ARM) +#if defined (__CC_ARM) #pragma diag_suppress 3731 #endif bool core_util_atomic_cas_u8(uint8_t *ptr, uint8_t *expectedCurrentValue, uint8_t desiredValue) { do { - uint8_t currentValue = __LDREXB((volatile uint8_t*)ptr); + uint8_t currentValue = __LDREXB((volatile uint8_t *)ptr); if (currentValue != *expectedCurrentValue) { *expectedCurrentValue = currentValue; __CLREX(); return false; } - } while (__STREXB(desiredValue, (volatile uint8_t*)ptr)); + } while (__STREXB(desiredValue, (volatile uint8_t *)ptr)); return true; } bool core_util_atomic_cas_u16(uint16_t *ptr, uint16_t *expectedCurrentValue, uint16_t desiredValue) { do { - uint16_t currentValue = __LDREXH((volatile uint16_t*)ptr); + uint16_t currentValue = __LDREXH((volatile uint16_t *)ptr); if (currentValue != *expectedCurrentValue) { *expectedCurrentValue = currentValue; __CLREX(); return false; } - } while (__STREXH(desiredValue, (volatile uint16_t*)ptr)); + } while (__STREXH(desiredValue, (volatile uint16_t *)ptr)); return true; } @@ -146,13 +146,13 @@ bool core_util_atomic_cas_u16(uint16_t *ptr, uint16_t *expectedCurrentValue, uin bool core_util_atomic_cas_u32(uint32_t *ptr, uint32_t *expectedCurrentValue, uint32_t desiredValue) { do { - uint32_t currentValue = __LDREXW((volatile uint32_t*)ptr); + uint32_t currentValue = __LDREXW((volatile uint32_t *)ptr); if (currentValue != *expectedCurrentValue) { *expectedCurrentValue = currentValue; __CLREX(); return false; } - } while (__STREXW(desiredValue, (volatile uint32_t*)ptr)); + } while (__STREXW(desiredValue, (volatile uint32_t *)ptr)); return true; } @@ -160,8 +160,8 @@ uint8_t core_util_atomic_incr_u8(uint8_t *valuePtr, uint8_t delta) { uint8_t newValue; do { - newValue = __LDREXB((volatile uint8_t*)valuePtr) + delta; - } while (__STREXB(newValue, (volatile uint8_t*)valuePtr)); + newValue = __LDREXB((volatile uint8_t *)valuePtr) + delta; + } while (__STREXB(newValue, (volatile uint8_t *)valuePtr)); return newValue; } @@ -169,8 +169,8 @@ uint16_t core_util_atomic_incr_u16(uint16_t *valuePtr, uint16_t delta) { uint16_t newValue; do { - newValue = __LDREXH((volatile uint16_t*)valuePtr) + delta; - } while (__STREXH(newValue, (volatile uint16_t*)valuePtr)); + newValue = __LDREXH((volatile uint16_t *)valuePtr) + delta; + } while (__STREXH(newValue, (volatile uint16_t *)valuePtr)); return newValue; } @@ -178,8 +178,8 @@ uint32_t core_util_atomic_incr_u32(uint32_t *valuePtr, uint32_t delta) { uint32_t newValue; do { - newValue = __LDREXW((volatile uint32_t*)valuePtr) + delta; - } while (__STREXW(newValue, (volatile uint32_t*)valuePtr)); + newValue = __LDREXW((volatile uint32_t *)valuePtr) + delta; + } while (__STREXW(newValue, (volatile uint32_t *)valuePtr)); return newValue; } @@ -188,8 +188,8 @@ uint8_t core_util_atomic_decr_u8(uint8_t *valuePtr, uint8_t delta) { uint8_t newValue; do { - newValue = __LDREXB((volatile uint8_t*)valuePtr) - delta; - } while (__STREXB(newValue, (volatile uint8_t*)valuePtr)); + newValue = __LDREXB((volatile uint8_t *)valuePtr) - delta; + } while (__STREXB(newValue, (volatile uint8_t *)valuePtr)); return newValue; } @@ -197,8 +197,8 @@ uint16_t core_util_atomic_decr_u16(uint16_t *valuePtr, uint16_t delta) { uint16_t newValue; do { - newValue = __LDREXH((volatile uint16_t*)valuePtr) - delta; - } while (__STREXH(newValue, (volatile uint16_t*)valuePtr)); + newValue = __LDREXH((volatile uint16_t *)valuePtr) - delta; + } while (__STREXH(newValue, (volatile uint16_t *)valuePtr)); return newValue; } @@ -206,8 +206,8 @@ uint32_t core_util_atomic_decr_u32(uint32_t *valuePtr, uint32_t delta) { uint32_t newValue; do { - newValue = __LDREXW((volatile uint32_t*)valuePtr) - delta; - } while (__STREXW(newValue, (volatile uint32_t*)valuePtr)); + newValue = __LDREXW((volatile uint32_t *)valuePtr) - delta; + } while (__STREXW(newValue, (volatile uint32_t *)valuePtr)); return newValue; } @@ -330,18 +330,21 @@ uint32_t core_util_atomic_decr_u32(uint32_t *valuePtr, uint32_t delta) #endif -bool core_util_atomic_cas_ptr(void **ptr, void **expectedCurrentValue, void *desiredValue) { +bool core_util_atomic_cas_ptr(void **ptr, void **expectedCurrentValue, void *desiredValue) +{ return core_util_atomic_cas_u32( - (uint32_t *)ptr, - (uint32_t *)expectedCurrentValue, - (uint32_t)desiredValue); + (uint32_t *)ptr, + (uint32_t *)expectedCurrentValue, + (uint32_t)desiredValue); } -void *core_util_atomic_incr_ptr(void **valuePtr, ptrdiff_t delta) { +void *core_util_atomic_incr_ptr(void **valuePtr, ptrdiff_t delta) +{ return (void *)core_util_atomic_incr_u32((uint32_t *)valuePtr, (uint32_t)delta); } -void *core_util_atomic_decr_ptr(void **valuePtr, ptrdiff_t delta) { +void *core_util_atomic_decr_ptr(void **valuePtr, ptrdiff_t delta) +{ return (void *)core_util_atomic_decr_u32((uint32_t *)valuePtr, (uint32_t)delta); } diff --git a/platform/mbed_debug.h b/platform/mbed_debug.h index 5f9a19805d6..5ccc123bb07 100644 --- a/platform/mbed_debug.h +++ b/platform/mbed_debug.h @@ -5,7 +5,7 @@ * \defgroup platform_debug Debug functions * @{ */ - + /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * @@ -37,7 +37,8 @@ extern "C" { * * @param format printf-style format string, followed by variables */ -static inline void debug(const char *format, ...) { +static inline void debug(const char *format, ...) +{ #if DEVICE_STDIO_MESSAGES && !defined(NDEBUG) va_list args; va_start(args, format); @@ -55,7 +56,8 @@ static inline void debug(const char *format, ...) { * @param condition output only if condition is true (!= 0) * @param format printf-style format string, followed by variables */ -static inline void debug_if(int condition, const char *format, ...) { +static inline void debug_if(int condition, const char *format, ...) +{ #if DEVICE_STDIO_MESSAGES && !defined(NDEBUG) if (condition) { va_list args; diff --git a/platform/mbed_error.c b/platform/mbed_error.c index 37422033c00..10291cbf348 100644 --- a/platform/mbed_error.c +++ b/platform/mbed_error.c @@ -25,7 +25,8 @@ static uint8_t error_in_progress = 0; -WEAK void error(const char* format, ...) { +WEAK void error(const char *format, ...) +{ // Prevent recursion if error is called again if (error_in_progress) { diff --git a/platform/mbed_error.h b/platform/mbed_error.h index 8f5cd9baff1..119d12d3218 100644 --- a/platform/mbed_error.h +++ b/platform/mbed_error.h @@ -70,7 +70,7 @@ #ifdef __cplusplus extern "C" { #endif -void error(const char* format, ...); +void error(const char *format, ...); #ifdef __cplusplus } diff --git a/platform/mbed_interface.c b/platform/mbed_interface.c index 99c7c4891b1..b1a43697e9b 100644 --- a/platform/mbed_interface.c +++ b/platform/mbed_interface.c @@ -25,11 +25,13 @@ #if DEVICE_SEMIHOST // return true if a debugger is attached, indicating mbed interface is connected -int mbed_interface_connected(void) { +int mbed_interface_connected(void) +{ return semihost_connected(); } -int mbed_interface_reset(void) { +int mbed_interface_reset(void) +{ if (mbed_interface_connected()) { semihost_reset(); return 0; @@ -38,7 +40,8 @@ int mbed_interface_reset(void) { } } -WEAK int mbed_interface_uid(char *uid) { +WEAK int mbed_interface_uid(char *uid) +{ if (mbed_interface_connected()) { return semihost_uid(uid); // Returns 0 if successful, -1 on failure } else { @@ -47,11 +50,13 @@ WEAK int mbed_interface_uid(char *uid) { } } -int mbed_interface_disconnect(void) { +int mbed_interface_disconnect(void) +{ int res; if (mbed_interface_connected()) { - if ((res = semihost_disabledebug()) != 0) + if ((res = semihost_disabledebug()) != 0) { return res; + } while (mbed_interface_connected()); return 0; } else { @@ -59,11 +64,13 @@ int mbed_interface_disconnect(void) { } } -int mbed_interface_powerdown(void) { +int mbed_interface_powerdown(void) +{ int res; if (mbed_interface_connected()) { - if ((res = semihost_powerdown()) != 0) + if ((res = semihost_powerdown()) != 0) { return res; + } while (mbed_interface_connected()); return 0; } else { @@ -72,17 +79,20 @@ int mbed_interface_powerdown(void) { } MBED_DEPRECATED_SINCE("mbed-os-5.9", "This function shouldn't be used in new code." - "For system reset funcionality use system_reset()") -void mbed_reset(void) { + "For system reset funcionality use system_reset()") +void mbed_reset(void) +{ mbed_interface_reset(); } -WEAK int mbed_uid(char *uid) { +WEAK int mbed_uid(char *uid) +{ return mbed_interface_uid(uid); } #endif -WEAK void mbed_mac_address(char *mac) { +WEAK void mbed_mac_address(char *mac) +{ #if DEVICE_SEMIHOST char uid[DEVICE_ID_LENGTH + 1]; int i; @@ -93,7 +103,7 @@ WEAK void mbed_mac_address(char *mac) { #if defined(DEVICE_MAC_OFFSET) p += DEVICE_MAC_OFFSET; #endif - for (i=0; i<6; i++) { + for (i = 0; i < 6; i++) { int byte; sscanf(p, "%2x", &byte); mac[i] = byte; diff --git a/platform/mbed_interface.h b/platform/mbed_interface.h index 94baa34f775..48594916e8f 100644 --- a/platform/mbed_interface.h +++ b/platform/mbed_interface.h @@ -135,7 +135,7 @@ void mbed_die(void); * @endcode * */ -void mbed_error_printf(const char* format, ...); +void mbed_error_printf(const char *format, ...); /** Print out an error message. Similar to mbed_error_printf * but uses a va_list. @@ -146,7 +146,7 @@ void mbed_error_printf(const char* format, ...); * @param arg Variable arguments list * */ -void mbed_error_vfprintf(const char * format, va_list arg); +void mbed_error_vfprintf(const char *format, va_list arg); /** @}*/ #ifdef __cplusplus diff --git a/platform/mbed_mem_trace.cpp b/platform/mbed_mem_trace.cpp index 17326f78e57..7b7b3aa3234 100644 --- a/platform/mbed_mem_trace.cpp +++ b/platform/mbed_mem_trace.cpp @@ -41,7 +41,8 @@ static SingletonPtr mem_trace_mutex; * Public interface *****************************************************************************/ -void mbed_mem_trace_set_callback(mbed_mem_trace_cb_t cb) { +void mbed_mem_trace_set_callback(mbed_mem_trace_cb_t cb) +{ mem_trace_cb = cb; } @@ -57,7 +58,8 @@ void mbed_mem_trace_unlock() mem_trace_mutex->unlock(); } -void *mbed_mem_trace_malloc(void *res, size_t size, void *caller) { +void *mbed_mem_trace_malloc(void *res, size_t size, void *caller) +{ if (mem_trace_cb) { if (TRACE_FIRST_LOCK()) { mem_trace_cb(MBED_MEM_TRACE_MALLOC, res, caller, size); @@ -66,7 +68,8 @@ void *mbed_mem_trace_malloc(void *res, size_t size, void *caller) { return res; } -void *mbed_mem_trace_realloc(void *res, void *ptr, size_t size, void *caller) { +void *mbed_mem_trace_realloc(void *res, void *ptr, size_t size, void *caller) +{ if (mem_trace_cb) { if (TRACE_FIRST_LOCK()) { mem_trace_cb(MBED_MEM_TRACE_REALLOC, res, caller, ptr, size); @@ -75,7 +78,8 @@ void *mbed_mem_trace_realloc(void *res, void *ptr, size_t size, void *caller) { return res; } -void *mbed_mem_trace_calloc(void *res, size_t num, size_t size, void *caller) { +void *mbed_mem_trace_calloc(void *res, size_t num, size_t size, void *caller) +{ if (mem_trace_cb) { if (TRACE_FIRST_LOCK()) { mem_trace_cb(MBED_MEM_TRACE_CALLOC, res, caller, num, size); @@ -84,7 +88,8 @@ void *mbed_mem_trace_calloc(void *res, size_t num, size_t size, void *caller) { return res; } -void mbed_mem_trace_free(void *ptr, void *caller) { +void mbed_mem_trace_free(void *ptr, void *caller) +{ if (mem_trace_cb) { if (TRACE_FIRST_LOCK()) { mem_trace_cb(MBED_MEM_TRACE_FREE, NULL, caller, ptr); @@ -92,20 +97,21 @@ void mbed_mem_trace_free(void *ptr, void *caller) { } } -void mbed_mem_trace_default_callback(uint8_t op, void *res, void *caller, ...) { +void mbed_mem_trace_default_callback(uint8_t op, void *res, void *caller, ...) +{ va_list va; size_t temp_s1, temp_s2; void *temp_ptr; va_start(va, caller); - switch(op) { + switch (op) { case MBED_MEM_TRACE_MALLOC: temp_s1 = va_arg(va, size_t); printf(MBED_MEM_DEFAULT_TRACER_PREFIX "m:%p;%p-%u\n", res, caller, temp_s1); break; case MBED_MEM_TRACE_REALLOC: - temp_ptr = va_arg(va, void*); + temp_ptr = va_arg(va, void *); temp_s1 = va_arg(va, size_t); printf(MBED_MEM_DEFAULT_TRACER_PREFIX "r:%p;%p-%p;%u\n", res, caller, temp_ptr, temp_s1); break; @@ -117,7 +123,7 @@ void mbed_mem_trace_default_callback(uint8_t op, void *res, void *caller, ...) { break; case MBED_MEM_TRACE_FREE: - temp_ptr = va_arg(va, void*); + temp_ptr = va_arg(va, void *); printf(MBED_MEM_DEFAULT_TRACER_PREFIX "f:%p;%p-%p\n", res, caller, temp_ptr); break; diff --git a/platform/mbed_mem_trace.h b/platform/mbed_mem_trace.h index 6b604a08a7b..1fe2e99a905 100644 --- a/platform/mbed_mem_trace.h +++ b/platform/mbed_mem_trace.h @@ -63,7 +63,7 @@ enum { * - for calloc: cb(MBED_MEM_TRACE_CALLOC, res, caller, nmemb, size). * - for free: cb(MBED_MEM_TRACE_FREE, NULL, caller, ptr). */ -typedef void (*mbed_mem_trace_cb_t)(uint8_t op, void *res, void* caller, ...); +typedef void (*mbed_mem_trace_cb_t)(uint8_t op, void *res, void *caller, ...); /** * Set the callback used by the memory tracer (use NULL for disable tracing). diff --git a/platform/mbed_mktime.c b/platform/mbed_mktime.c index cb1280c9c21..68e3b9f62d6 100644 --- a/platform/mbed_mktime.c +++ b/platform/mbed_mktime.c @@ -20,7 +20,7 @@ #define SECONDS_BY_MINUTES 60 #define MINUTES_BY_HOUR 60 #define SECONDS_BY_HOUR (SECONDS_BY_MINUTES * MINUTES_BY_HOUR) -#define HOURS_BY_DAY 24 +#define HOURS_BY_DAY 24 #define SECONDS_BY_DAY (SECONDS_BY_HOUR * HOURS_BY_DAY) #define LAST_VALID_YEAR 206 @@ -29,48 +29,49 @@ #define EDGE_TIMESTAMP_4_YEAR_LEAP_YEAR_SUPPORT 3133695 // 6th of February 1970 at 06:28:15 /* - * 2 dimensional array containing the number of seconds elapsed before a given + * 2 dimensional array containing the number of seconds elapsed before a given * month. * The second index map to the month while the first map to the type of year: - * - 0: non leap year + * - 0: non leap year * - 1: leap year */ static const uint32_t seconds_before_month[2][12] = { { 0, 31 * SECONDS_BY_DAY, - (31 + 28) * SECONDS_BY_DAY, - (31 + 28 + 31) * SECONDS_BY_DAY, - (31 + 28 + 31 + 30) * SECONDS_BY_DAY, - (31 + 28 + 31 + 30 + 31) * SECONDS_BY_DAY, - (31 + 28 + 31 + 30 + 31 + 30) * SECONDS_BY_DAY, - (31 + 28 + 31 + 30 + 31 + 30 + 31) * SECONDS_BY_DAY, - (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31) * SECONDS_BY_DAY, - (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30) * SECONDS_BY_DAY, - (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31) * SECONDS_BY_DAY, - (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30) * SECONDS_BY_DAY, + (31 + 28) *SECONDS_BY_DAY, + (31 + 28 + 31) *SECONDS_BY_DAY, + (31 + 28 + 31 + 30) *SECONDS_BY_DAY, + (31 + 28 + 31 + 30 + 31) *SECONDS_BY_DAY, + (31 + 28 + 31 + 30 + 31 + 30) *SECONDS_BY_DAY, + (31 + 28 + 31 + 30 + 31 + 30 + 31) *SECONDS_BY_DAY, + (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31) *SECONDS_BY_DAY, + (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30) *SECONDS_BY_DAY, + (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31) *SECONDS_BY_DAY, + (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30) *SECONDS_BY_DAY, }, { 0, 31 * SECONDS_BY_DAY, - (31 + 29) * SECONDS_BY_DAY, - (31 + 29 + 31) * SECONDS_BY_DAY, - (31 + 29 + 31 + 30) * SECONDS_BY_DAY, - (31 + 29 + 31 + 30 + 31) * SECONDS_BY_DAY, - (31 + 29 + 31 + 30 + 31 + 30) * SECONDS_BY_DAY, - (31 + 29 + 31 + 30 + 31 + 30 + 31) * SECONDS_BY_DAY, - (31 + 29 + 31 + 30 + 31 + 30 + 31 + 31) * SECONDS_BY_DAY, - (31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30) * SECONDS_BY_DAY, - (31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31) * SECONDS_BY_DAY, - (31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30) * SECONDS_BY_DAY, + (31 + 29) *SECONDS_BY_DAY, + (31 + 29 + 31) *SECONDS_BY_DAY, + (31 + 29 + 31 + 30) *SECONDS_BY_DAY, + (31 + 29 + 31 + 30 + 31) *SECONDS_BY_DAY, + (31 + 29 + 31 + 30 + 31 + 30) *SECONDS_BY_DAY, + (31 + 29 + 31 + 30 + 31 + 30 + 31) *SECONDS_BY_DAY, + (31 + 29 + 31 + 30 + 31 + 30 + 31 + 31) *SECONDS_BY_DAY, + (31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30) *SECONDS_BY_DAY, + (31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31) *SECONDS_BY_DAY, + (31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30) *SECONDS_BY_DAY, } }; -bool _rtc_is_leap_year(int year, rtc_leap_year_support_t leap_year_support) { - /* - * since in practice, the value manipulated by this algorithm lie in the +bool _rtc_is_leap_year(int year, rtc_leap_year_support_t leap_year_support) +{ + /* + * since in practice, the value manipulated by this algorithm lie in the * range: [70 : 206] the algorithm can be reduced to: year % 4 with exception for 200 (year 2100 is not leap year). - * The algorithm valid over the full range of value is: + * The algorithm valid over the full range of value is: year = 1900 + year; if (year % 4) { @@ -82,7 +83,7 @@ bool _rtc_is_leap_year(int year, rtc_leap_year_support_t leap_year_support) { } return true; - */ + */ if (leap_year_support == RTC_FULL_LEAP_YEAR_SUPPORT && year == 200) { return false; // 2100 is not a leap year } @@ -90,7 +91,8 @@ bool _rtc_is_leap_year(int year, rtc_leap_year_support_t leap_year_support) { return (year) % 4 ? false : true; } -bool _rtc_maketime(const struct tm* time, time_t * seconds, rtc_leap_year_support_t leap_year_support) { +bool _rtc_maketime(const struct tm *time, time_t *seconds, rtc_leap_year_support_t leap_year_support) +{ if (seconds == NULL || time == NULL) { return false; } @@ -111,12 +113,12 @@ bool _rtc_maketime(const struct tm* time, time_t * seconds, rtc_leap_year_suppor /* Check if we are within valid range. */ if (time->tm_year == LAST_VALID_YEAR) { if ((leap_year_support == RTC_FULL_LEAP_YEAR_SUPPORT && result > EDGE_TIMESTAMP_FULL_LEAP_YEAR_SUPPORT) || - (leap_year_support == RTC_4_YEAR_LEAP_YEAR_SUPPORT && result > EDGE_TIMESTAMP_4_YEAR_LEAP_YEAR_SUPPORT)) { - return false; + (leap_year_support == RTC_4_YEAR_LEAP_YEAR_SUPPORT && result > EDGE_TIMESTAMP_4_YEAR_LEAP_YEAR_SUPPORT)) { + return false; } } - if (time->tm_year > 70) { + if (time->tm_year > 70) { /* Valid in the range [70:206]. */ uint32_t count_of_leap_days = ((time->tm_year - 1) / 4) - (70 / 4); if (leap_year_support == RTC_FULL_LEAP_YEAR_SUPPORT) { @@ -133,7 +135,8 @@ bool _rtc_maketime(const struct tm* time, time_t * seconds, rtc_leap_year_suppor return true; } -bool _rtc_localtime(time_t timestamp, struct tm* time_info, rtc_leap_year_support_t leap_year_support) { +bool _rtc_localtime(time_t timestamp, struct tm *time_info, rtc_leap_year_support_t leap_year_support) +{ if (time_info == NULL) { return false; } @@ -154,7 +157,7 @@ bool _rtc_localtime(time_t timestamp, struct tm* time_info, rtc_leap_year_suppor /* Years start at 70. */ time_info->tm_year = 70; - while (true) { + while (true) { if (_rtc_is_leap_year(time_info->tm_year, leap_year_support) && seconds >= 366) { ++time_info->tm_year; seconds -= 366; diff --git a/platform/mbed_mktime.h b/platform/mbed_mktime.h index f877512b9d2..eed21a9fc3f 100644 --- a/platform/mbed_mktime.h +++ b/platform/mbed_mktime.h @@ -90,7 +90,7 @@ bool _rtc_is_leap_year(int year, rtc_leap_year_support_t leap_year_support); * @note Full and partial leap years support. * @note For use by the HAL only */ -bool _rtc_maketime(const struct tm* time, time_t * seconds, rtc_leap_year_support_t leap_year_support); +bool _rtc_maketime(const struct tm *time, time_t *seconds, rtc_leap_year_support_t leap_year_support); /* Convert a given time in seconds since epoch into calendar time. * @@ -118,7 +118,7 @@ bool _rtc_maketime(const struct tm* time, time_t * seconds, rtc_leap_year_suppor * @note For use by the HAL only. * @note Full and partial leap years support. */ -bool _rtc_localtime(time_t timestamp, struct tm* time_info, rtc_leap_year_support_t leap_year_support); +bool _rtc_localtime(time_t timestamp, struct tm *time_info, rtc_leap_year_support_t leap_year_support); /** @}*/ diff --git a/platform/mbed_retarget.cpp b/platform/mbed_retarget.cpp index 93362e82b69..5cfa60fc008 100644 --- a/platform/mbed_retarget.cpp +++ b/platform/mbed_retarget.cpp @@ -101,10 +101,11 @@ static SingletonPtr filehandle_mutex; namespace mbed { void mbed_set_unbuffered_stream(std::FILE *_file); -void remove_filehandle(FileHandle *file) { +void remove_filehandle(FileHandle *file) +{ filehandle_mutex->lock(); /* Remove all open filehandles for this */ - for (unsigned int fh_i = 0; fh_i < sizeof(filehandles)/sizeof(*filehandles); fh_i++) { + for (unsigned int fh_i = 0; fh_i < sizeof(filehandles) / sizeof(*filehandles); fh_i++) { if (filehandles[fh_i] == file) { filehandles[fh_i] = NULL; } @@ -128,28 +129,36 @@ class DirectSerial : public FileHandle { DirectSerial(PinName tx, PinName rx, int baud); virtual ssize_t write(const void *buffer, size_t size); virtual ssize_t read(void *buffer, size_t size); - virtual off_t seek(off_t offset, int whence = SEEK_SET) { + virtual off_t seek(off_t offset, int whence = SEEK_SET) + { return -ESPIPE; } - virtual off_t size() { + virtual off_t size() + { return -EINVAL; } - virtual int isatty() { + virtual int isatty() + { return true; } - virtual int close() { + virtual int close() + { return 0; } virtual short poll(short events) const; }; -DirectSerial::DirectSerial(PinName tx, PinName rx, int baud) { - if (stdio_uart_inited) return; +DirectSerial::DirectSerial(PinName tx, PinName rx, int baud) +{ + if (stdio_uart_inited) { + return; + } serial_init(&stdio_uart, tx, rx); serial_baud(&stdio_uart, baud); } -ssize_t DirectSerial::write(const void *buffer, size_t size) { +ssize_t DirectSerial::write(const void *buffer, size_t size) +{ const unsigned char *buf = static_cast(buffer); for (size_t i = 0; i < size; i++) { serial_putc(&stdio_uart, buf[i]); @@ -157,7 +166,8 @@ ssize_t DirectSerial::write(const void *buffer, size_t size) { return size; } -ssize_t DirectSerial::read(void *buffer, size_t size) { +ssize_t DirectSerial::read(void *buffer, size_t size) +{ unsigned char *buf = static_cast(buffer); if (size == 0) { return 0; @@ -166,7 +176,8 @@ ssize_t DirectSerial::read(void *buffer, size_t size) { return 1; } -short DirectSerial::poll(short events) const { +short DirectSerial::poll(short events) const +{ short revents = 0; if ((events & POLLIN) && serial_readable(&stdio_uart)) { revents |= POLLIN; @@ -181,18 +192,32 @@ class Sink : public FileHandle { public: virtual ssize_t write(const void *buffer, size_t size); virtual ssize_t read(void *buffer, size_t size); - virtual off_t seek(off_t offset, int whence = SEEK_SET) { return ESPIPE; } - virtual off_t size() { return -EINVAL; } - virtual int isatty() { return true; } - virtual int close() { return 0; } + virtual off_t seek(off_t offset, int whence = SEEK_SET) + { + return ESPIPE; + } + virtual off_t size() + { + return -EINVAL; + } + virtual int isatty() + { + return true; + } + virtual int close() + { + return 0; + } }; -ssize_t Sink::write(const void *buffer, size_t size) { +ssize_t Sink::write(const void *buffer, size_t size) +{ // Just swallow the data - this is historical non-DEVICE_SERIAL behaviour return size; } -ssize_t Sink::read(void *buffer, size_t size) { +ssize_t Sink::read(void *buffer, size_t size) +{ // Produce 1 zero byte - historical behaviour returned 1 without touching // the buffer unsigned char *buf = static_cast(buffer); @@ -201,17 +226,17 @@ ssize_t Sink::read(void *buffer, size_t size) { } -MBED_WEAK FileHandle* mbed::mbed_target_override_console(int fd) +MBED_WEAK FileHandle *mbed::mbed_target_override_console(int fd) { return NULL; } -MBED_WEAK FileHandle* mbed::mbed_override_console(int fd) +MBED_WEAK FileHandle *mbed::mbed_override_console(int fd) { return NULL; } -static FileHandle* default_console() +static FileHandle *default_console() { #if DEVICE_SERIAL # if MBED_CONF_PLATFORM_STDIO_BUFFERED_SERIAL @@ -226,7 +251,8 @@ static FileHandle* default_console() } /* Locate the default console for stdout, stdin, stderr */ -static FileHandle* get_console(int fd) { +static FileHandle *get_console(int fd) +{ FileHandle *fh = mbed_override_console(fd); if (fh) { return fh; @@ -239,7 +265,8 @@ static FileHandle* get_console(int fd) { } /* Deal with the fact C library may not _open descriptors 0, 1, 2 - auto bind */ -static FileHandle* get_fhc(int fd) { +static FileHandle *get_fhc(int fd) +{ if (fd >= OPEN_MAX) { return NULL; } @@ -257,27 +284,29 @@ static FileHandle* get_fhc(int fd) { * @param error is a negative error code returned from an mbed function and * will be negated to store a positive error code in errno */ -static int handle_open_errors(int error, unsigned filehandle_idx) { +static int handle_open_errors(int error, unsigned filehandle_idx) +{ errno = -error; // Free file handle filehandles[filehandle_idx] = NULL; return -1; } -static inline int openflags_to_posix(int openflags) { +static inline int openflags_to_posix(int openflags) +{ int posix = openflags; #ifdef __ARMCC_VERSION if (openflags & OPEN_PLUS) { posix = O_RDWR; - } else if(openflags & OPEN_W) { + } else if (openflags & OPEN_W) { posix = O_WRONLY; - } else if(openflags & OPEN_A) { - posix = O_WRONLY|O_APPEND; + } else if (openflags & OPEN_A) { + posix = O_WRONLY | O_APPEND; } else { posix = O_RDONLY; } /* a, w, a+, w+ all create if file does not already exist */ - if (openflags & (OPEN_A|OPEN_W)) { + if (openflags & (OPEN_A | OPEN_W)) { posix |= O_CREAT; } /* w and w+ truncate */ @@ -286,26 +315,41 @@ static inline int openflags_to_posix(int openflags) { } #elif defined(__ICCARM__) switch (openflags & _LLIO_RDWRMASK) { - case _LLIO_RDONLY: posix = O_RDONLY; break; - case _LLIO_WRONLY: posix = O_WRONLY; break; - case _LLIO_RDWR : posix = O_RDWR ; break; + case _LLIO_RDONLY: + posix = O_RDONLY; + break; + case _LLIO_WRONLY: + posix = O_WRONLY; + break; + case _LLIO_RDWR : + posix = O_RDWR ; + break; + } + if (openflags & _LLIO_CREAT) { + posix |= O_CREAT; + } + if (openflags & _LLIO_APPEND) { + posix |= O_APPEND; + } + if (openflags & _LLIO_TRUNC) { + posix |= O_TRUNC; } - if (openflags & _LLIO_CREAT ) posix |= O_CREAT; - if (openflags & _LLIO_APPEND) posix |= O_APPEND; - if (openflags & _LLIO_TRUNC ) posix |= O_TRUNC; #elif defined(TOOLCHAIN_GCC) posix &= ~O_BINARY; #endif return posix; } -static int reserve_filehandle() { +static int reserve_filehandle() +{ // find the first empty slot in filehandles, after the slots reserved for stdin/stdout/stderr filehandle_mutex->lock(); int fh_i; for (fh_i = 3; fh_i < OPEN_MAX; fh_i++) { /* Take a next free filehandle slot available. */ - if (filehandles[fh_i] == NULL) break; + if (filehandles[fh_i] == NULL) { + break; + } } if (fh_i >= OPEN_MAX) { /* Too many file handles have been opened */ @@ -319,7 +363,8 @@ static int reserve_filehandle() { return fh_i; } -int mbed::bind_to_fd(FileHandle *fh) { +int mbed::bind_to_fd(FileHandle *fh) +{ int fh_i = reserve_filehandle(); if (fh_i < 0) { return fh_i; @@ -332,7 +377,8 @@ int mbed::bind_to_fd(FileHandle *fh) { return fh_i; } -static int unbind_from_fd(int fd, FileHandle *fh) { +static int unbind_from_fd(int fd, FileHandle *fh) +{ if (filehandles[fd] == fh) { filehandles[fd] = NULL; return 0; @@ -344,7 +390,7 @@ static int unbind_from_fd(int fd, FileHandle *fh) { #ifndef __IAR_SYSTEMS_ICC__ /* IAR provides fdopen itself */ -extern "C" std::FILE* fdopen(int fildes, const char *mode) +extern "C" std::FILE *fdopen(int fildes, const char *mode) { // This is to avoid scanf and the bloat it brings. char buf[1 + sizeof fildes]; /* @(integer) */ @@ -381,18 +427,19 @@ std::FILE *fdopen(FileHandle *fh, const char *mode) } } -/* @brief standard c library fopen() retargeting function. +/* @brief standard c library fopen() retargeting function. * * This function is invoked by the standard c library retargeting to handle fopen() * * @return * On success, a valid FILEHANDLE is returned. * On failure, -1 is returned and errno is set to an appropriate value e.g. - * ENOENT file not found (default errno setting) - * EMFILE the maximum number of open files was exceeded. + * ENOENT file not found (default errno setting) + * EMFILE the maximum number of open files was exceeded. * * */ -extern "C" FILEHANDLE PREFIX(_open)(const char *name, int openflags) { +extern "C" FILEHANDLE PREFIX(_open)(const char *name, int openflags) +{ #if defined(__MICROLIB) && (__ARMCC_VERSION>5030000) #if !defined(MBED_CONF_RTOS_PRESENT) // valid only for mbed 2 @@ -439,7 +486,8 @@ extern "C" FILEHANDLE PREFIX(_open)(const char *name, int openflags) { return open(name, openflags_to_posix(openflags)); } -extern "C" int open(const char *name, int oflag, ...) { +extern "C" int open(const char *name, int oflag, ...) +{ int fh_i = reserve_filehandle(); if (fh_i < 0) { return fh_i; @@ -475,12 +523,14 @@ extern "C" int open(const char *name, int oflag, ...) { return fh_i; } -extern "C" int PREFIX(_close)(FILEHANDLE fh) { +extern "C" int PREFIX(_close)(FILEHANDLE fh) +{ return close(fh); } -extern "C" int close(int fh) { - FileHandle* fhc = get_fhc(fh); +extern "C" int close(int fh) +{ + FileHandle *fhc = get_fhc(fh); filehandles[fh] = NULL; if (fhc == NULL) { errno = EBADF; @@ -496,7 +546,8 @@ extern "C" int close(int fh) { } } -static bool convert_crlf(int fd) { +static bool convert_crlf(int fd) +{ #if MBED_CONF_PLATFORM_STDIO_CONVERT_TTY_NEWLINES return isatty(fd); #elif MBED_CONF_PLATFORM_STDIO_CONVERT_NEWLINES @@ -507,9 +558,11 @@ static bool convert_crlf(int fd) { } #if defined(__ICCARM__) -extern "C" size_t __write (int fh, const unsigned char *buffer, size_t length) { +extern "C" size_t __write(int fh, const unsigned char *buffer, size_t length) +{ #else -extern "C" int PREFIX(_write)(FILEHANDLE fh, const unsigned char *buffer, unsigned int length, int mode) { +extern "C" int PREFIX(_write)(FILEHANDLE fh, const unsigned char *buffer, unsigned int length, int mode) +{ #endif #if defined(MBED_TRAP_ERRORS_ENABLED) && MBED_TRAP_ERRORS_ENABLED && defined(MBED_CONF_RTOS_PRESENT) @@ -586,9 +639,10 @@ extern "C" int PREFIX(_write)(FILEHANDLE fh, const unsigned char *buffer, unsign #endif } -extern "C" ssize_t write(int fh, const void *buf, size_t length) { +extern "C" ssize_t write(int fh, const void *buf, size_t length) +{ - FileHandle* fhc = get_fhc(fh); + FileHandle *fhc = get_fhc(fh); if (fhc == NULL) { errno = EBADF; return -1; @@ -604,20 +658,24 @@ extern "C" ssize_t write(int fh, const void *buf, size_t length) { } #if defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) -extern "C" void PREFIX(_exit)(int return_code) { - while(1) {} +extern "C" void PREFIX(_exit)(int return_code) +{ + while (1) {} } -extern "C" void _ttywrch(int ch) { +extern "C" void _ttywrch(int ch) +{ char c = ch; write(STDOUT_FILENO, &c, 1); } #endif #if defined(__ICCARM__) -extern "C" size_t __read (int fh, unsigned char *buffer, size_t length) { +extern "C" size_t __read(int fh, unsigned char *buffer, size_t length) +{ #else -extern "C" int PREFIX(_read)(FILEHANDLE fh, unsigned char *buffer, unsigned int length, int mode) { +extern "C" int PREFIX(_read)(FILEHANDLE fh, unsigned char *buffer, unsigned int length, int mode) +{ #endif #if defined(MBED_TRAP_ERRORS_ENABLED) && MBED_TRAP_ERRORS_ENABLED && defined(MBED_CONF_RTOS_PRESENT) @@ -644,7 +702,7 @@ extern "C" int PREFIX(_read)(FILEHANDLE fh, unsigned char *buffer, unsigned int return bytes_read; } if ((c == '\r' && stdio_in_prev[fh] != '\n') || - (c == '\n' && stdio_in_prev[fh] != '\r')) { + (c == '\n' && stdio_in_prev[fh] != '\r')) { stdio_in_prev[fh] = c; *buffer = '\n'; break; @@ -676,9 +734,10 @@ extern "C" int PREFIX(_read)(FILEHANDLE fh, unsigned char *buffer, unsigned int #endif } -extern "C" ssize_t read(int fh, void *buf, size_t length) { +extern "C" ssize_t read(int fh, void *buf, size_t length) +{ - FileHandle* fhc = get_fhc(fh); + FileHandle *fhc = get_fhc(fh); if (fhc == NULL) { errno = EBADF; return -1; @@ -703,8 +762,9 @@ extern "C" int _isatty(FILEHANDLE fh) return isatty(fh); } -extern "C" int isatty(int fh) { - FileHandle* fhc = get_fhc(fh); +extern "C" int isatty(int fh) +{ + FileHandle *fhc = get_fhc(fh); if (fhc == NULL) { errno = EBADF; return 0; @@ -741,8 +801,9 @@ int _lseek(FILEHANDLE fh, int offset, int whence) return off; } -extern "C" off_t lseek(int fh, off_t offset, int whence) { - FileHandle* fhc = get_fhc(fh); +extern "C" off_t lseek(int fh, off_t offset, int whence) +{ + FileHandle *fhc = get_fhc(fh); if (fhc == NULL) { errno = EBADF; return -1; @@ -757,13 +818,15 @@ extern "C" off_t lseek(int fh, off_t offset, int whence) { } #ifdef __ARMCC_VERSION -extern "C" int PREFIX(_ensure)(FILEHANDLE fh) { +extern "C" int PREFIX(_ensure)(FILEHANDLE fh) +{ return fsync(fh); } #endif -extern "C" int fsync(int fh) { - FileHandle* fhc = get_fhc(fh); +extern "C" int fsync(int fh) +{ + FileHandle *fhc = get_fhc(fh); if (fhc == NULL) { errno = EBADF; return -1; @@ -779,8 +842,9 @@ extern "C" int fsync(int fh) { } #ifdef __ARMCC_VERSION -extern "C" long PREFIX(_flen)(FILEHANDLE fh) { - FileHandle* fhc = get_fhc(fh); +extern "C" long PREFIX(_flen)(FILEHANDLE fh) +{ + FileHandle *fhc = get_fhc(fh); if (fhc == NULL) { errno = EBADF; return -1; @@ -813,7 +877,8 @@ extern "C" MBED_WEAK __value_in_regs struct __initial_stackheap _mbed_user_setup return r; } -extern "C" __value_in_regs struct __initial_stackheap __user_setup_stackheap(uint32_t R0, uint32_t R1, uint32_t R2, uint32_t R3) { +extern "C" __value_in_regs struct __initial_stackheap __user_setup_stackheap(uint32_t R0, uint32_t R1, uint32_t R2, uint32_t R3) +{ return _mbed_user_setup_stackheap(R0, R1, R2, R3); } @@ -821,13 +886,15 @@ extern "C" __value_in_regs struct __initial_stackheap __user_setup_stackheap(uin #if !defined(__ARMCC_VERSION) && !defined(__ICCARM__) -extern "C" int _fstat(int fh, struct stat *st) { +extern "C" int _fstat(int fh, struct stat *st) +{ return fstat(fh, st); } #endif -extern "C" int fstat(int fh, struct stat *st) { - FileHandle* fhc = get_fhc(fh); +extern "C" int fstat(int fh, struct stat *st) +{ + FileHandle *fhc = get_fhc(fh); if (fhc == NULL) { errno = EBADF; return -1; @@ -860,7 +927,8 @@ extern "C" int poll(struct pollfd fds[], nfds_t nfds, int timeout) } namespace std { -extern "C" int remove(const char *path) { +extern "C" int remove(const char *path) +{ FilePath fp(path); FileSystemHandle *fs = fp.fileSystem(); if (fs == NULL) { @@ -877,7 +945,8 @@ extern "C" int remove(const char *path) { } } -extern "C" int rename(const char *oldname, const char *newname) { +extern "C" int rename(const char *oldname, const char *newname) +{ FilePath fpOld(oldname); FilePath fpNew(newname); FileSystemHandle *fsOld = fpOld.fileSystem(); @@ -903,26 +972,30 @@ extern "C" int rename(const char *oldname, const char *newname) { } } -extern "C" char *tmpnam(char *s) { +extern "C" char *tmpnam(char *s) +{ errno = EBADF; return NULL; } -extern "C" FILE *tmpfile() { +extern "C" FILE *tmpfile() +{ errno = EBADF; return NULL; } } // namespace std #ifdef __ARMCC_VERSION -extern "C" char *_sys_command_string(char *cmd, int len) { +extern "C" char *_sys_command_string(char *cmd, int len) +{ return NULL; } #endif -extern "C" DIR *opendir(const char *path) { +extern "C" DIR *opendir(const char *path) +{ FilePath fp(path); - FileSystemHandle* fs = fp.fileSystem(); + FileSystemHandle *fs = fp.fileSystem(); if (fs == NULL) { errno = ENODEV; return NULL; @@ -938,7 +1011,8 @@ extern "C" DIR *opendir(const char *path) { return dir; } -extern "C" struct dirent *readdir(DIR *dir) { +extern "C" struct dirent *readdir(DIR *dir) +{ static struct dirent ent; int err = dir->read(&ent); if (err < 1) { @@ -951,7 +1025,8 @@ extern "C" struct dirent *readdir(DIR *dir) { return &ent; } -extern "C" int closedir(DIR *dir) { +extern "C" int closedir(DIR *dir) +{ int err = dir->close(); if (err < 0) { errno = -err; @@ -961,19 +1036,23 @@ extern "C" int closedir(DIR *dir) { } } -extern "C" void rewinddir(DIR *dir) { +extern "C" void rewinddir(DIR *dir) +{ dir->rewind(); } -extern "C" off_t telldir(DIR *dir) { +extern "C" off_t telldir(DIR *dir) +{ return dir->tell(); } -extern "C" void seekdir(DIR *dir, off_t off) { +extern "C" void seekdir(DIR *dir, off_t off) +{ dir->seek(off); } -extern "C" int mkdir(const char *path, mode_t mode) { +extern "C" int mkdir(const char *path, mode_t mode) +{ FilePath fp(path); FileSystemHandle *fs = fp.fileSystem(); if (fs == NULL) { @@ -990,7 +1069,8 @@ extern "C" int mkdir(const char *path, mode_t mode) { } } -extern "C" int stat(const char *path, struct stat *st) { +extern "C" int stat(const char *path, struct stat *st) +{ FilePath fp(path); FileSystemHandle *fs = fp.fileSystem(); if (fs == NULL) { @@ -1007,7 +1087,8 @@ extern "C" int stat(const char *path, struct stat *st) { } } -extern "C" int statvfs(const char *path, struct statvfs *buf) { +extern "C" int statvfs(const char *path, struct statvfs *buf) +{ FilePath fp(path); FileSystemHandle *fs = fp.fileSystem(); if (fs == NULL) { @@ -1028,12 +1109,14 @@ extern "C" int statvfs(const char *path, struct statvfs *buf) { /* prevents the exception handling name demangling code getting pulled in */ #include "mbed_error.h" namespace __gnu_cxx { - void __verbose_terminate_handler() { - error("Exception"); - } +void __verbose_terminate_handler() +{ + error("Exception"); +} } extern "C" WEAK void __cxa_pure_virtual(void); -extern "C" WEAK void __cxa_pure_virtual(void) { +extern "C" WEAK void __cxa_pure_virtual(void) +{ exit(1); } @@ -1061,31 +1144,33 @@ extern "C" int errno; // TARGET_NUMAKER_PFM_M453 targets/TARGET_NUVOTON/TARGET_M451/TARGET_NUMAKER_PFM_M453/TOOLCHAIN_GCC_ARM/m451_retarget.c // TARGET_STM32L4 targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L4/l4_retarget.c extern "C" void *__wrap__sbrk(int incr); -extern "C" caddr_t _sbrk(int incr) { +extern "C" caddr_t _sbrk(int incr) +{ return (caddr_t) __wrap__sbrk(incr); } #else // Linker defined symbol used by _sbrk to indicate where heap should start. extern "C" uint32_t __end__; // Weak attribute allows user to override, e.g. to use external RAM for dynamic memory. -extern "C" WEAK caddr_t _sbrk(int incr) { - static unsigned char* heap = (unsigned char*)&__end__; - unsigned char* prev_heap = heap; - unsigned char* new_heap = heap + incr; +extern "C" WEAK caddr_t _sbrk(int incr) +{ + static unsigned char *heap = (unsigned char *)&__end__; + unsigned char *prev_heap = heap; + unsigned char *new_heap = heap + incr; #if defined(TARGET_CORTEX_A) - if (new_heap >= (unsigned char*)&__HeapLimit) { /* __HeapLimit is end of heap section */ + if (new_heap >= (unsigned char *)&__HeapLimit) { /* __HeapLimit is end of heap section */ #else - if (new_heap >= (unsigned char*)__get_MSP()) { + if (new_heap >= (unsigned char *)__get_MSP()) { #endif errno = ENOMEM; - return (caddr_t)-1; + return (caddr_t) -1; } // Additional heap checking if set if (mbed_heap_size && (new_heap >= mbed_heap_start + mbed_heap_size)) { errno = ENOMEM; - return (caddr_t)-1; + return (caddr_t) -1; } heap = new_heap; @@ -1095,10 +1180,12 @@ extern "C" WEAK caddr_t _sbrk(int incr) { #endif #if defined(TOOLCHAIN_GCC_ARM) || defined(TOOLCHAIN_GCC_CR) -extern "C" void _exit(int return_code) { +extern "C" void _exit(int return_code) +{ #else namespace std { -extern "C" void exit(int return_code) { +extern "C" void exit(int return_code) +{ #endif #if DEVICE_STDIO_MESSAGES @@ -1132,16 +1219,19 @@ extern "C" void exit(int return_code) { // More informations about this topic for ARMCC here: // http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/6449.html extern "C" { -int __aeabi_atexit(void *object, void (*dtor)(void* /*this*/), void *handle) { - return 1; -} + int __aeabi_atexit(void *object, void (*dtor)(void * /*this*/), void *handle) + { + return 1; + } -int __cxa_atexit(void (*dtor)(void* /*this*/), void *object, void *handle) { - return 1; -} + int __cxa_atexit(void (*dtor)(void * /*this*/), void *object, void *handle) + { + return 1; + } -void __cxa_finalize(void *handle) { -} + void __cxa_finalize(void *handle) + { + } } // end of extern "C" @@ -1157,25 +1247,27 @@ void __cxa_finalize(void *handle) { * * To overcome this limitation, exit and atexit are overriden here. */ -extern "C"{ +extern "C" { -/** - * @brief Retarget of exit for GCC. - * @details Unlike the standard version, this function doesn't call any function - * registered with atexit before calling _exit. - */ -void __wrap_exit(int return_code) { - _exit(return_code); -} + /** + * @brief Retarget of exit for GCC. + * @details Unlike the standard version, this function doesn't call any function + * registered with atexit before calling _exit. + */ + void __wrap_exit(int return_code) + { + _exit(return_code); + } -/** - * @brief Retarget atexit from GCC. - * @details This function will always fail and never register any handler to be - * called at exit. - */ -int __wrap_atexit(void (*func)()) { - return 1; -} + /** + * @brief Retarget atexit from GCC. + * @details This function will always fail and never register any handler to be + * called at exit. + */ + int __wrap_atexit(void (*func)()) + { + return 1; + } } @@ -1185,20 +1277,22 @@ int __wrap_atexit(void (*func)()) { namespace mbed { -void mbed_set_unbuffered_stream(std::FILE *_file) { +void mbed_set_unbuffered_stream(std::FILE *_file) +{ #if defined (__ICCARM__) char buf[2]; - std::setvbuf(_file,buf,_IONBF,NULL); + std::setvbuf(_file, buf, _IONBF, NULL); #else setbuf(_file, NULL); #endif } -int mbed_getc(std::FILE *_file){ +int mbed_getc(std::FILE *_file) +{ #if defined(__IAR_SYSTEMS_ICC__ ) && (__VER__ < 8000000) /*This is only valid for unbuffered streams*/ int res = std::fgetc(_file); - if (res>=0){ + if (res >= 0) { _file->_Mode = (unsigned short)(_file->_Mode & ~ 0x1000);/* Unset read mode */ _file->_Rend = _file->_Wend; _file->_Next = _file->_Wend; @@ -1209,18 +1303,19 @@ int mbed_getc(std::FILE *_file){ #endif } -char* mbed_gets(char*s, int size, std::FILE *_file){ +char *mbed_gets(char *s, int size, std::FILE *_file) +{ #if defined(__IAR_SYSTEMS_ICC__ ) && (__VER__ < 8000000) /*This is only valid for unbuffered streams*/ - char *str = fgets(s,size,_file); - if (str!=NULL){ + char *str = fgets(s, size, _file); + if (str != NULL) { _file->_Mode = (unsigned short)(_file->_Mode & ~ 0x1000);/* Unset read mode */ _file->_Rend = _file->_Wend; _file->_Next = _file->_Wend; } return str; #else - return std::fgets(s,size,_file); + return std::fgets(s, size, _file); #endif } @@ -1238,9 +1333,10 @@ extern "C" WEAK void __iar_file_Mtxlock(__iar_Rmtx *mutex) {} extern "C" WEAK void __iar_file_Mtxunlock(__iar_Rmtx *mutex) {} #if defined(__IAR_SYSTEMS_ICC__ ) && (__VER__ >= 8000000) #pragma section="__iar_tls$$DATA" -extern "C" WEAK void *__aeabi_read_tp (void) { - // Thread Local storage is not supported, using main thread memory for errno - return __section_begin("__iar_tls$$DATA"); +extern "C" WEAK void *__aeabi_read_tp(void) +{ + // Thread Local storage is not supported, using main thread memory for errno + return __section_begin("__iar_tls$$DATA"); } #endif #elif defined(__CC_ARM) @@ -1248,27 +1344,27 @@ extern "C" WEAK void *__aeabi_read_tp (void) { #elif defined (__GNUC__) struct _reent; // Stub out locks when an rtos is not present -extern "C" WEAK void __rtos_malloc_lock( struct _reent *_r ) {} -extern "C" WEAK void __rtos_malloc_unlock( struct _reent *_r ) {} -extern "C" WEAK void __rtos_env_lock( struct _reent *_r ) {} -extern "C" WEAK void __rtos_env_unlock( struct _reent *_r ) {} +extern "C" WEAK void __rtos_malloc_lock(struct _reent *_r) {} +extern "C" WEAK void __rtos_malloc_unlock(struct _reent *_r) {} +extern "C" WEAK void __rtos_env_lock(struct _reent *_r) {} +extern "C" WEAK void __rtos_env_unlock(struct _reent *_r) {} -extern "C" void __malloc_lock( struct _reent *_r ) +extern "C" void __malloc_lock(struct _reent *_r) { __rtos_malloc_lock(_r); } -extern "C" void __malloc_unlock( struct _reent *_r ) +extern "C" void __malloc_unlock(struct _reent *_r) { __rtos_malloc_unlock(_r); } -extern "C" void __env_lock( struct _reent *_r ) +extern "C" void __env_lock(struct _reent *_r) { __rtos_env_lock(_r); } -extern "C" void __env_unlock( struct _reent *_r ) +extern "C" void __env_unlock(struct _reent *_r) { __rtos_env_unlock(_r); } @@ -1321,10 +1417,10 @@ extern "C" void __cxa_guard_abort(int *guard_object_p) // provide the implementation for these. Note: this needs to use the wrappers // instead of malloc()/free() as the caller address would point to wrappers, // not the caller of "new" or "delete". -extern "C" void* malloc_wrapper(size_t size, const void* caller); -extern "C" void free_wrapper(void *ptr, const void* caller); - -void *operator new(std::size_t count) +extern "C" void *malloc_wrapper(size_t size, const void *caller); +extern "C" void free_wrapper(void *ptr, const void *caller); + +void *operator new (std::size_t count) { void *buffer = malloc_wrapper(count, MBED_CALLER_ADDR()); if (NULL == buffer) { @@ -1342,17 +1438,17 @@ void *operator new[](std::size_t count) return buffer; } -void *operator new(std::size_t count, const std::nothrow_t& tag) +void *operator new (std::size_t count, const std::nothrow_t &tag) { return malloc_wrapper(count, MBED_CALLER_ADDR()); } -void *operator new[](std::size_t count, const std::nothrow_t& tag) +void *operator new[](std::size_t count, const std::nothrow_t &tag) { return malloc_wrapper(count, MBED_CALLER_ADDR()); } -void operator delete(void *ptr) +void operator delete (void *ptr) { free_wrapper(ptr, MBED_CALLER_ADDR()); } @@ -1365,10 +1461,10 @@ void operator delete[](void *ptr) #include -extern "C" void* malloc_wrapper(struct _reent * r, size_t size, void * caller); -extern "C" void free_wrapper(struct _reent * r, void * ptr, void * caller); +extern "C" void *malloc_wrapper(struct _reent *r, size_t size, void *caller); +extern "C" void free_wrapper(struct _reent *r, void *ptr, void *caller); -void *operator new(std::size_t count) +void *operator new (std::size_t count) { void *buffer = malloc_wrapper(_REENT, count, MBED_CALLER_ADDR()); if (NULL == buffer) { @@ -1386,17 +1482,17 @@ void *operator new[](std::size_t count) return buffer; } -void *operator new(std::size_t count, const std::nothrow_t& tag) +void *operator new (std::size_t count, const std::nothrow_t &tag) { return malloc_wrapper(_REENT, count, MBED_CALLER_ADDR()); } -void *operator new[](std::size_t count, const std::nothrow_t& tag) +void *operator new[](std::size_t count, const std::nothrow_t &tag) { return malloc_wrapper(_REENT, count, MBED_CALLER_ADDR()); } -void operator delete(void *ptr) +void operator delete (void *ptr) { free_wrapper(_REENT, ptr, MBED_CALLER_ADDR()); } @@ -1408,7 +1504,7 @@ void operator delete[](void *ptr) #else -void *operator new(std::size_t count) +void *operator new (std::size_t count) { void *buffer = malloc(count); if (NULL == buffer) { @@ -1426,17 +1522,17 @@ void *operator new[](std::size_t count) return buffer; } -void *operator new(std::size_t count, const std::nothrow_t& tag) +void *operator new (std::size_t count, const std::nothrow_t &tag) { return malloc(count); } -void *operator new[](std::size_t count, const std::nothrow_t& tag) +void *operator new[](std::size_t count, const std::nothrow_t &tag) { return malloc(count); } -void operator delete(void *ptr) +void operator delete (void *ptr) { free(ptr); } @@ -1467,7 +1563,7 @@ extern "C" clock_t clock() } // temporary - Default to 1MHz at 32 bits if target does not have us_ticker_get_info -MBED_WEAK const ticker_info_t* us_ticker_get_info() +MBED_WEAK const ticker_info_t *us_ticker_get_info() { static const ticker_info_t info = { 1000000, @@ -1477,7 +1573,7 @@ MBED_WEAK const ticker_info_t* us_ticker_get_info() } // temporary - Default to 1MHz at 32 bits if target does not have lp_ticker_get_info -MBED_WEAK const ticker_info_t* lp_ticker_get_info() +MBED_WEAK const ticker_info_t *lp_ticker_get_info() { static const ticker_info_t info = { 1000000, diff --git a/platform/mbed_retarget.h b/platform/mbed_retarget.h index e4837a7bfb6..0752fa5a2e5 100644 --- a/platform/mbed_retarget.h +++ b/platform/mbed_retarget.h @@ -90,7 +90,7 @@ class DirHandle; * @param fd file descriptor - STDIN_FILENO, STDOUT_FILENO or STDERR_FILENO * @return pointer to FileHandle to override normal stream otherwise NULL */ -FileHandle* mbed_target_override_console(int fd); +FileHandle *mbed_target_override_console(int fd); /** Applications may implement this to change stdin, stdout, stderr. * @@ -112,7 +112,7 @@ FileHandle* mbed_target_override_console(int fd); * @param fd file descriptor - STDIN_FILENO, STDOUT_FILENO or STDERR_FILENO * @return pointer to FileHandle to override normal stream otherwise NULL */ -FileHandle* mbed_override_console(int fd); +FileHandle *mbed_override_console(int fd); } @@ -465,7 +465,7 @@ struct statvfs { * consistency where structure may be different with different toolchains */ struct dirent { - char d_name[NAME_MAX+1]; ///< Name of file + char d_name[NAME_MAX + 1]; ///< Name of file uint8_t d_type; ///< Type of file }; @@ -493,9 +493,9 @@ extern "C" { int open(const char *path, int oflag, ...); #ifndef __IAR_SYSTEMS_ICC__ /* IAR provides fdopen itself */ #if __cplusplus - std::FILE* fdopen(int fildes, const char *mode); + std::FILE *fdopen(int fildes, const char *mode); #else - FILE* fdopen(int fildes, const char *mode); + FILE *fdopen(int fildes, const char *mode); #endif #endif ssize_t write(int fildes, const void *buf, size_t nbyte); @@ -508,12 +508,12 @@ extern "C" { int close(int fildes); int stat(const char *path, struct stat *st); int statvfs(const char *path, struct statvfs *buf); - DIR *opendir(const char*); + DIR *opendir(const char *); struct dirent *readdir(DIR *); - int closedir(DIR*); - void rewinddir(DIR*); - long telldir(DIR*); - void seekdir(DIR*, long); + int closedir(DIR *); + void rewinddir(DIR *); + long telldir(DIR *); + void seekdir(DIR *, long); int mkdir(const char *name, mode_t n); #if __cplusplus }; // extern "C" @@ -533,7 +533,7 @@ namespace mbed { * * @returns a pointer to FILE */ -std::FILE* fdopen(mbed::FileHandle *fh, const char *mode); +std::FILE *fdopen(mbed::FileHandle *fh, const char *mode); /** Bind an mbed FileHandle to a POSIX file descriptor * diff --git a/platform/mbed_rtc_time.cpp b/platform/mbed_rtc_time.cpp index b77e2efa54b..714448c0d71 100644 --- a/platform/mbed_rtc_time.cpp +++ b/platform/mbed_rtc_time.cpp @@ -50,8 +50,8 @@ time_t time(time_t *timer) set_time(0); } } - - time_t t = (time_t)-1; + + time_t t = (time_t) -1; if (_rtc_read != NULL) { t = _rtc_read(); } @@ -63,7 +63,8 @@ time_t time(time_t *timer) return t; } -void set_time(time_t t) { +void set_time(time_t t) +{ _mutex->lock(); if (_rtc_init != NULL) { _rtc_init(); @@ -74,7 +75,8 @@ void set_time(time_t t) { _mutex->unlock(); } -void attach_rtc(time_t (*read_rtc)(void), void (*write_rtc)(time_t), void (*init_rtc)(void), int (*isenabled_rtc)(void)) { +void attach_rtc(time_t (*read_rtc)(void), void (*write_rtc)(time_t), void (*init_rtc)(void), int (*isenabled_rtc)(void)) +{ _mutex->lock(); _rtc_read = read_rtc; _rtc_write = write_rtc; diff --git a/platform/mbed_sdk_boot.c b/platform/mbed_sdk_boot.c index 4799e2c5315..32658ef60c4 100644 --- a/platform/mbed_sdk_boot.c +++ b/platform/mbed_sdk_boot.c @@ -30,14 +30,14 @@ * mbed_main(), it is not meant for user code, but for the SDK itself to perform * initializations before main() is called. */ -MBED_WEAK void mbed_main(void) +MBED_WEAK void mbed_main(void) { } /* This function can be implemented by the target to perform higher level target initialization */ -MBED_WEAK void mbed_sdk_init(void) +MBED_WEAK void mbed_sdk_init(void) { } @@ -56,7 +56,7 @@ void mbed_copy_nvic(void) #if !defined(__CORTEX_M0) && !defined(__CORTEX_A9) #ifdef NVIC_RAM_VECTOR_ADDRESS uint32_t *old_vectors = (uint32_t *)SCB->VTOR; - uint32_t *vectors = (uint32_t*)NVIC_RAM_VECTOR_ADDRESS; + uint32_t *vectors = (uint32_t *)NVIC_RAM_VECTOR_ADDRESS; for (int i = 0; i < NVIC_NUM_VECTORS; i++) { vectors[i] = old_vectors[i]; } @@ -71,19 +71,19 @@ void mbed_copy_nvic(void) int $Super$$main(void); -int $Sub$$main(void) +int $Sub$$main(void) { mbed_main(); return $Super$$main(); } -void _platform_post_stackheap_init(void) +void _platform_post_stackheap_init(void) { mbed_copy_nvic(); mbed_sdk_init(); } -#elif defined (__GNUC__) +#elif defined (__GNUC__) extern int __real_main(void); @@ -95,7 +95,7 @@ void software_init_hook(void) } -int __wrap_main(void) +int __wrap_main(void) { mbed_main(); return __real_main(); @@ -105,8 +105,8 @@ int __wrap_main(void) int __low_level_init(void) { - mbed_copy_nvic(); - return 1; + mbed_copy_nvic(); + return 1; } #endif diff --git a/platform/mbed_semihost_api.c b/platform/mbed_semihost_api.c index 06c6777ab8d..f655862c3a0 100644 --- a/platform/mbed_semihost_api.c +++ b/platform/mbed_semihost_api.c @@ -44,7 +44,8 @@ #define USR_DISABLEDEBUG (RESERVED_FOR_USER_APPLICATIONS + 5) #if DEVICE_LOCALFILESYSTEM -FILEHANDLE semihost_open(const char* name, int openmode) { +FILEHANDLE semihost_open(const char *name, int openmode) +{ uint32_t args[3]; args[0] = (uint32_t)name; args[1] = (uint32_t)openmode; @@ -52,12 +53,16 @@ FILEHANDLE semihost_open(const char* name, int openmode) { return __semihost(SYS_OPEN, args); } -int semihost_close(FILEHANDLE fh) { +int semihost_close(FILEHANDLE fh) +{ return __semihost(SYS_CLOSE, &fh); } -int semihost_write(FILEHANDLE fh, const unsigned char* buffer, unsigned int length, int mode) { - if (length == 0) return 0; +int semihost_write(FILEHANDLE fh, const unsigned char *buffer, unsigned int length, int mode) +{ + if (length == 0) { + return 0; + } uint32_t args[3]; args[0] = (uint32_t)fh; @@ -66,7 +71,8 @@ int semihost_write(FILEHANDLE fh, const unsigned char* buffer, unsigned int leng return __semihost(SYS_WRITE, args); } -int semihost_read(FILEHANDLE fh, unsigned char* buffer, unsigned int length, int mode) { +int semihost_read(FILEHANDLE fh, unsigned char *buffer, unsigned int length, int mode) +{ uint32_t args[3]; args[0] = (uint32_t)fh; args[1] = (uint32_t)buffer; @@ -74,33 +80,39 @@ int semihost_read(FILEHANDLE fh, unsigned char* buffer, unsigned int length, int return __semihost(SYS_READ, args); } -int semihost_istty(FILEHANDLE fh) { +int semihost_istty(FILEHANDLE fh) +{ return __semihost(SYS_ISTTY, &fh); } -int semihost_seek(FILEHANDLE fh, long position) { +int semihost_seek(FILEHANDLE fh, long position) +{ uint32_t args[2]; args[0] = (uint32_t)fh; args[1] = (uint32_t)position; return __semihost(SYS_SEEK, args); } -int semihost_ensure(FILEHANDLE fh) { +int semihost_ensure(FILEHANDLE fh) +{ return __semihost(SYS_ENSURE, &fh); } -long semihost_flen(FILEHANDLE fh) { +long semihost_flen(FILEHANDLE fh) +{ return __semihost(SYS_FLEN, &fh); } -int semihost_remove(const char *name) { +int semihost_remove(const char *name) +{ uint32_t args[2]; args[0] = (uint32_t)name; args[1] = (uint32_t)strlen(name); return __semihost(SYS_REMOVE, args); } -int semihost_rename(const char *old_name, const char *new_name) { +int semihost_rename(const char *old_name, const char *new_name) +{ uint32_t args[4]; args[0] = (uint32_t)old_name; args[1] = (uint32_t)strlen(old_name); @@ -110,35 +122,41 @@ int semihost_rename(const char *old_name, const char *new_name) { } #endif -int semihost_exit(void) { +int semihost_exit(void) +{ uint32_t args[4]; return __semihost(SYS_EXIT, args); } -int semihost_uid(char *uid) { +int semihost_uid(char *uid) +{ uint32_t args[2]; args[0] = (uint32_t)uid; args[1] = DEVICE_ID_LENGTH + 1; return __semihost(USR_UID, &args); } -int semihost_reset(void) { +int semihost_reset(void) +{ // Does not normally return, however if used with older firmware versions // that do not support this call it will return -1. return __semihost(USR_RESET, NULL); } -int semihost_vbus(void) { +int semihost_vbus(void) +{ return __semihost(USR_VBUS, NULL); } -int semihost_powerdown(void) { +int semihost_powerdown(void) +{ return __semihost(USR_POWERDOWN, NULL); } #if DEVICE_DEBUG_AWARENESS -int semihost_connected(void) { +int semihost_connected(void) +{ return (CoreDebug->DHCSR & CoreDebug_DHCSR_C_DEBUGEN_Msk) ? 1 : 0; } @@ -146,12 +164,14 @@ int semihost_connected(void) { // These processors cannot know if the interface is connect, assume so: static int is_debugger_attached = 1; -int semihost_connected(void) { +int semihost_connected(void) +{ return is_debugger_attached; } #endif -int semihost_disabledebug(void) { +int semihost_disabledebug(void) +{ uint32_t args[1]; #if !(DEVICE_DEBUG_AWARENESS) is_debugger_attached = 0; diff --git a/platform/mbed_semihost_api.h b/platform/mbed_semihost_api.h index 611cce69c07..2f20c8cbb24 100644 --- a/platform/mbed_semihost_api.h +++ b/platform/mbed_semihost_api.h @@ -29,8 +29,9 @@ extern "C" { #if !defined(__CC_ARM) && !defined(__ARMCC_VERSION) #if defined(__ICCARM__) -static inline int __semihost(int reason, const void *arg) { - return __semihosting(reason, (void*)arg); +static inline int __semihost(int reason, const void *arg) +{ + return __semihosting(reason, (void *)arg); } #else @@ -44,17 +45,18 @@ static inline int __semihost(int reason, const void *arg) { # define AngelSWIAsm swi #endif -static inline int __semihost(int reason, const void *arg) { +static inline int __semihost(int reason, const void *arg) +{ int value; - asm volatile ( - "mov r0, %1" "\n\t" - "mov r1, %2" "\n\t" - AngelSWIInsn " %a3" "\n\t" - "mov %0, r0" - : "=r" (value) /* output operands */ - : "r" (reason), "r" (arg), "i" (AngelSWI) /* input operands */ - : "r0", "r1", "r2", "r3", "ip", "lr", "memory", "cc" /* list of clobbered registers */ + asm volatile( + "mov r0, %1" "\n\t" + "mov r1, %2" "\n\t" + AngelSWIInsn " %a3" "\n\t" + "mov %0, r0" + : "=r"(value) /* output operands */ + : "r"(reason), "r"(arg), "i"(AngelSWI) /* input operands */ + : "r0", "r1", "r2", "r3", "ip", "lr", "memory", "cc" /* list of clobbered registers */ ); return value; @@ -63,14 +65,14 @@ static inline int __semihost(int reason, const void *arg) { #endif #if DEVICE_LOCALFILESYSTEM -FILEHANDLE semihost_open(const char* name, int openmode); -int semihost_close (FILEHANDLE fh); -int semihost_read (FILEHANDLE fh, unsigned char* buffer, unsigned int length, int mode); -int semihost_write (FILEHANDLE fh, const unsigned char* buffer, unsigned int length, int mode); +FILEHANDLE semihost_open(const char *name, int openmode); +int semihost_close(FILEHANDLE fh); +int semihost_read(FILEHANDLE fh, unsigned char *buffer, unsigned int length, int mode); +int semihost_write(FILEHANDLE fh, const unsigned char *buffer, unsigned int length, int mode); int semihost_ensure(FILEHANDLE fh); -long semihost_flen (FILEHANDLE fh); -int semihost_seek (FILEHANDLE fh, long position); -int semihost_istty (FILEHANDLE fh); +long semihost_flen(FILEHANDLE fh); +int semihost_seek(FILEHANDLE fh, long position); +int semihost_istty(FILEHANDLE fh); int semihost_remove(const char *name); int semihost_rename(const char *old_name, const char *new_name); diff --git a/platform/mbed_stats.c b/platform/mbed_stats.c index 106394be42c..b96b06ac868 100644 --- a/platform/mbed_stats.c +++ b/platform/mbed_stats.c @@ -24,7 +24,7 @@ void mbed_stats_stack_get(mbed_stats_stack_t *stats) osKernelLock(); thread_n = osThreadEnumerate(threads, thread_n); - for(i = 0; i < thread_n; i++) { + for (i = 0; i < thread_n; i++) { uint32_t stack_size = osThreadGetStackSize(threads[i]); stats->max_size += stack_size - osThreadGetStackSpace(threads[i]); stats->reserved_size += stack_size; @@ -38,7 +38,7 @@ void mbed_stats_stack_get(mbed_stats_stack_t *stats) size_t mbed_stats_stack_get_each(mbed_stats_stack_t *stats, size_t count) { - memset(stats, 0, count*sizeof(mbed_stats_stack_t)); + memset(stats, 0, count * sizeof(mbed_stats_stack_t)); size_t i = 0; #if MBED_STACK_STATS_ENABLED && MBED_CONF_RTOS_PRESENT @@ -50,7 +50,7 @@ size_t mbed_stats_stack_get_each(mbed_stats_stack_t *stats, size_t count) osKernelLock(); count = osThreadEnumerate(threads, count); - for(i = 0; i < count; i++) { + for (i = 0; i < count; i++) { uint32_t stack_size = osThreadGetStackSize(threads[i]); stats[i].max_size = stack_size - osThreadGetStackSpace(threads[i]); stats[i].reserved_size = stack_size; diff --git a/platform/mbed_wait_api.h b/platform/mbed_wait_api.h index a58509f741a..65a9786c30b 100644 --- a/platform/mbed_wait_api.h +++ b/platform/mbed_wait_api.h @@ -5,7 +5,7 @@ * \defgroup platform_wait_api wait_api functions * @{ */ - + /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * diff --git a/platform/mbed_wait_api_no_rtos.c b/platform/mbed_wait_api_no_rtos.c index a78dd8bc799..c29ba17217d 100644 --- a/platform/mbed_wait_api_no_rtos.c +++ b/platform/mbed_wait_api_no_rtos.c @@ -21,15 +21,18 @@ #include "platform/mbed_wait_api.h" #include "hal/us_ticker_api.h" -void wait(float s) { +void wait(float s) +{ wait_us(s * 1000000.0f); } -void wait_ms(int ms) { +void wait_ms(int ms) +{ wait_us(ms * 1000); } -void wait_us(int us) { +void wait_us(int us) +{ const ticker_data_t *const ticker = get_us_ticker_data(); uint32_t start = ticker_read(ticker); while ((ticker_read(ticker) - start) < (uint32_t)us); diff --git a/platform/mbed_wait_api_rtos.cpp b/platform/mbed_wait_api_rtos.cpp index 3c082f2fe69..b5359378400 100644 --- a/platform/mbed_wait_api_rtos.cpp +++ b/platform/mbed_wait_api_rtos.cpp @@ -24,15 +24,18 @@ #include "platform/mbed_critical.h" #include "platform/mbed_power_mgmt.h" -void wait(float s) { +void wait(float s) +{ wait_us(s * 1000000.0f); } -void wait_ms(int ms) { +void wait_ms(int ms) +{ wait_us(ms * 1000); } -void wait_us(int us) { +void wait_us(int us) +{ const ticker_data_t *const ticker = get_us_ticker_data(); uint32_t start = ticker_read(ticker); diff --git a/rtos/EventFlags.h b/rtos/EventFlags.h index 0571ec7b856..fed36f9a3bb 100644 --- a/rtos/EventFlags.h +++ b/rtos/EventFlags.h @@ -36,9 +36,9 @@ namespace rtos { * \defgroup rtos_EventFlags EventFlags class * @{ */ - + /** The EventFlags class is used to signal or wait for an arbitrary event or events. - @note + @note EventFlags support 31 flags so the MSB flag is ignored, it is used to return an error code (@a osFlagsError) @note Memory considerations: The EventFlags control structures will be created on current thread's stack, both for the mbed OS diff --git a/rtos/Kernel.cpp b/rtos/Kernel.cpp index 2562556cfff..c4b1534edf9 100644 --- a/rtos/Kernel.cpp +++ b/rtos/Kernel.cpp @@ -26,7 +26,8 @@ namespace rtos { -uint64_t Kernel::get_ms_count() { +uint64_t Kernel::get_ms_count() +{ // CMSIS-RTOS 2.1.0 and 2.1.1 differ in the time type. We assume // our header at least matches the implementation, so we don't try looking // at the run-time version report. (There's no compile-time version report) @@ -36,7 +37,7 @@ uint64_t Kernel::get_ms_count() { // 2.1.x who knows? We assume could go back to uint64_t if (sizeof osKernelGetTickCount() == sizeof(uint64_t)) { return osKernelGetTickCount(); - } else /* assume 32-bit */ { + } else { /* assume 32-bit */ // Based on suggestion in CMSIS-RTOS 2.1.1 docs, but with reentrancy // protection for the tick memory. We use critical section rather than a // mutex, as hopefully this method can be callable from interrupt later - diff --git a/rtos/Mail.h b/rtos/Mail.h index c0fdc76fc43..0dd133fa4da 100644 --- a/rtos/Mail.h +++ b/rtos/Mail.h @@ -42,7 +42,7 @@ namespace rtos { * \defgroup rtos_Mail Mail class * @{ */ - + /** The Mail class allow to control, send, receive, or wait for mail. A mail is a memory block that is send to a thread or interrupt service routine. @tparam T data type of a single message element. @@ -67,7 +67,8 @@ class Mail : private mbed::NonCopyable > { * * @note You may call this function from ISR context. */ - bool empty() const { + bool empty() const + { return _queue.empty(); } @@ -77,7 +78,8 @@ class Mail : private mbed::NonCopyable > { * * @note You may call this function from ISR context. */ - bool full() const { + bool full() const + { return _queue.full(); } @@ -87,7 +89,8 @@ class Mail : private mbed::NonCopyable > { @note You may call this function from ISR context if the millisec parameter is set to 0. */ - T* alloc(uint32_t millisec=0) { + T *alloc(uint32_t millisec = 0) + { return _pool.alloc(); } @@ -97,7 +100,8 @@ class Mail : private mbed::NonCopyable > { @note You may call this function from ISR context if the millisec parameter is set to 0. */ - T* calloc(uint32_t millisec=0) { + T *calloc(uint32_t millisec = 0) + { return _pool.calloc(); } @@ -107,7 +111,8 @@ class Mail : private mbed::NonCopyable > { @note You may call this function from ISR context. */ - osStatus put(T *mptr) { + osStatus put(T *mptr) + { return _queue.put(mptr); } @@ -117,7 +122,8 @@ class Mail : private mbed::NonCopyable > { @note You may call this function from ISR context if the millisec parameter is set to 0. */ - osEvent get(uint32_t millisec=osWaitForever) { + osEvent get(uint32_t millisec = osWaitForever) + { osEvent evt = _queue.get(millisec); if (evt.status == osEventMessage) { evt.status = osEventMail; @@ -131,7 +137,8 @@ class Mail : private mbed::NonCopyable > { @note You may call this function from ISR context. */ - osStatus free(T *mptr) { + osStatus free(T *mptr) + { return _pool.free(mptr); } diff --git a/rtos/MemoryPool.h b/rtos/MemoryPool.h index bfcd392ecc9..37374d5ca97 100644 --- a/rtos/MemoryPool.h +++ b/rtos/MemoryPool.h @@ -37,7 +37,7 @@ namespace rtos { * \defgroup rtos_MemoryPool MemoryPool class * @{ */ - + /** Define and manage fixed-size memory pools of objects of a given type. @tparam T data type of a single object (element). @tparam queue_sz maximum number of objects (elements) in the memory pool. @@ -48,13 +48,14 @@ namespace rtos { */ template class MemoryPool : private mbed::NonCopyable > { - MBED_STATIC_ASSERT(pool_sz > 0, "Invalid memory pool size. Must be greater than 0."); + MBED_STATIC_ASSERT(pool_sz > 0, "Invalid memory pool size. Must be greater than 0."); public: /** Create and Initialize a memory pool. * * @note You cannot call this function from ISR context. */ - MemoryPool() { + MemoryPool() + { memset(_pool_mem, 0, sizeof(_pool_mem)); memset(&_obj_mem, 0, sizeof(_obj_mem)); osMemoryPoolAttr_t attr = { 0 }; @@ -70,7 +71,8 @@ class MemoryPool : private mbed::NonCopyable > { * * @note You cannot call this function from ISR context. */ - ~MemoryPool() { + ~MemoryPool() + { osMemoryPoolDelete(_id); } @@ -79,8 +81,9 @@ class MemoryPool : private mbed::NonCopyable > { @note You may call this function from ISR context. */ - T* alloc(void) { - return (T*)osMemoryPoolAlloc(_id, 0); + T *alloc(void) + { + return (T *)osMemoryPoolAlloc(_id, 0); } /** Allocate a memory block of type T from a memory pool and set memory block to zero. @@ -88,8 +91,9 @@ class MemoryPool : private mbed::NonCopyable > { @note You may call this function from ISR context. */ - T* calloc(void) { - T *item = (T*)osMemoryPoolAlloc(_id, 0); + T *calloc(void) + { + T *item = (T *)osMemoryPoolAlloc(_id, 0); if (item != NULL) { memset(item, 0, sizeof(T)); } @@ -104,8 +108,9 @@ class MemoryPool : private mbed::NonCopyable > { @note You may call this function from ISR context. */ - osStatus free(T *block) { - return osMemoryPoolFree(_id, (void*)block); + osStatus free(T *block) + { + return osMemoryPoolFree(_id, (void *)block); } private: diff --git a/rtos/Mutex.cpp b/rtos/Mutex.cpp index edc2cdcb52a..02eb0432fea 100644 --- a/rtos/Mutex.cpp +++ b/rtos/Mutex.cpp @@ -50,7 +50,8 @@ void Mutex::constructor(const char *name) MBED_ASSERT(_id); } -osStatus Mutex::lock(uint32_t millisec) { +osStatus Mutex::lock(uint32_t millisec) +{ osStatus status = osMutexAcquire(_id, millisec); if (osOK == status) { _count++; @@ -58,11 +59,13 @@ osStatus Mutex::lock(uint32_t millisec) { return status; } -bool Mutex::trylock() { +bool Mutex::trylock() +{ return trylock_for(0); } -bool Mutex::trylock_for(uint32_t millisec) { +bool Mutex::trylock_for(uint32_t millisec) +{ osStatus status = lock(millisec); if (status == osOK) { return true; @@ -73,7 +76,8 @@ bool Mutex::trylock_for(uint32_t millisec) { return false; } -bool Mutex::trylock_until(uint64_t millisec) { +bool Mutex::trylock_until(uint64_t millisec) +{ uint64_t now = Kernel::get_ms_count(); if (now >= millisec) { @@ -86,16 +90,19 @@ bool Mutex::trylock_until(uint64_t millisec) { } } -osStatus Mutex::unlock() { +osStatus Mutex::unlock() +{ _count--; return osMutexRelease(_id); } -osThreadId Mutex::get_owner() { +osThreadId Mutex::get_owner() +{ return osMutexGetOwner(_id); } -Mutex::~Mutex() { +Mutex::~Mutex() +{ osMutexDelete(_id); } diff --git a/rtos/Mutex.h b/rtos/Mutex.h index 39fb4f84e77..6569cfbf610 100644 --- a/rtos/Mutex.h +++ b/rtos/Mutex.h @@ -51,7 +51,7 @@ typedef mbed::ScopedLock ScopedMutexLock; * \defgroup rtos_Mutex Mutex class * @{ */ - + /** The Mutex class is used to synchronize the execution of threads. This is for example used to protect access to a shared resource. @@ -89,7 +89,7 @@ class Mutex : private mbed::NonCopyable { @note You cannot call this function from ISR context. */ - osStatus lock(uint32_t millisec=osWaitForever); + osStatus lock(uint32_t millisec = osWaitForever); /** Try to lock the mutex, and return immediately @return true if the mutex was acquired, false otherwise. diff --git a/rtos/Queue.h b/rtos/Queue.h index 0190c047f84..3804a6523a7 100644 --- a/rtos/Queue.h +++ b/rtos/Queue.h @@ -38,7 +38,7 @@ namespace rtos { * \defgroup rtos_EventFlags EventFlags class * @{ */ - + /** The Queue class allow to control, send, receive, or wait for messages. A message can be a integer or pointer value to a certain type T that is send to a thread or interrupt service routine. @@ -56,21 +56,23 @@ class Queue : private mbed::NonCopyable > { * * @note You cannot call this function from ISR context. */ - Queue() { + Queue() + { memset(&_obj_mem, 0, sizeof(_obj_mem)); osMessageQueueAttr_t attr = { 0 }; attr.mq_mem = _queue_mem; attr.mq_size = sizeof(_queue_mem); attr.cb_mem = &_obj_mem; attr.cb_size = sizeof(_obj_mem); - _id = osMessageQueueNew(queue_sz, sizeof(T*), &attr); + _id = osMessageQueueNew(queue_sz, sizeof(T *), &attr); MBED_ASSERT(_id); } /** Queue destructor * * @note You cannot call this function from ISR context. */ - ~Queue() { + ~Queue() + { osMessageQueueDelete(_id); } @@ -80,7 +82,8 @@ class Queue : private mbed::NonCopyable > { * * @note You may call this function from ISR context. */ - bool empty() const { + bool empty() const + { return osMessageQueueGetCount(_id) == 0; } @@ -90,7 +93,8 @@ class Queue : private mbed::NonCopyable > { * * @note You may call this function from ISR context. */ - bool full() const { + bool full() const + { return osMessageQueueGetSpace(_id) == 0; } @@ -106,7 +110,8 @@ class Queue : private mbed::NonCopyable > { @note You may call this function from ISR context if the millisec parameter is set to 0. */ - osStatus put(T* data, uint32_t millisec=0, uint8_t prio=0) { + osStatus put(T *data, uint32_t millisec = 0, uint8_t prio = 0) + { return osMessageQueuePut(_id, &data, prio, millisec); } @@ -121,7 +126,8 @@ class Queue : private mbed::NonCopyable > { @note You may call this function from ISR context if the millisec parameter is set to 0. */ - osEvent get(uint32_t millisec=osWaitForever) { + osEvent get(uint32_t millisec = osWaitForever) + { osEvent event; T *data = NULL; osStatus_t res = osMessageQueueGet(_id, &data, NULL, millisec); @@ -149,7 +155,7 @@ class Queue : private mbed::NonCopyable > { private: osMessageQueueId_t _id; - char _queue_mem[queue_sz * (sizeof(T*) + sizeof(mbed_rtos_storage_message_t))]; + char _queue_mem[queue_sz * (sizeof(T *) + sizeof(mbed_rtos_storage_message_t))]; mbed_rtos_storage_msg_queue_t _obj_mem; }; /** @}*/ diff --git a/rtos/RtosTimer.cpp b/rtos/RtosTimer.cpp index 3e6c19718be..c6d617176c3 100644 --- a/rtos/RtosTimer.cpp +++ b/rtos/RtosTimer.cpp @@ -28,7 +28,8 @@ namespace rtos { -void RtosTimer::constructor(mbed::Callback func, os_timer_type type) { +void RtosTimer::constructor(mbed::Callback func, os_timer_type type) +{ _function = func; memset(&_obj_mem, 0, sizeof(_obj_mem)); osTimerAttr_t attr = { 0 }; @@ -38,15 +39,18 @@ void RtosTimer::constructor(mbed::Callback func, os_timer_type type) { MBED_ASSERT(_id); } -osStatus RtosTimer::start(uint32_t millisec) { +osStatus RtosTimer::start(uint32_t millisec) +{ return osTimerStart(_id, millisec); } -osStatus RtosTimer::stop(void) { +osStatus RtosTimer::stop(void) +{ return osTimerStop(_id); } -RtosTimer::~RtosTimer() { +RtosTimer::~RtosTimer() +{ osTimerDelete(_id); } diff --git a/rtos/RtosTimer.h b/rtos/RtosTimer.h index 27e0c5aeee9..ecf666f0327 100644 --- a/rtos/RtosTimer.h +++ b/rtos/RtosTimer.h @@ -37,7 +37,7 @@ namespace rtos { * \defgroup rtos_RtosTimer RtosTimer class * @{ */ - + /** The RtosTimer class allow creating and and controlling of timer functions in the system. A timer function is called when a time period expires whereby both on-shot and periodic timers are possible. A timer can be started, restarted, or stopped. @@ -97,13 +97,14 @@ class RtosTimer : private mbed::NonCopyable { @note You cannot call this function from ISR context. */ MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Replaced with RtosTimer(Callback, os_timer_type)") + "Replaced with RtosTimer(Callback, os_timer_type)") MBED_DEPRECATED_SINCE("mbed-os-5.2", - "The RtosTimer has been superseded by the EventQueue. See RtosTimer.h for more details") - RtosTimer(void (*func)(void const *argument), os_timer_type type=osTimerPeriodic, void *argument=NULL) { + "The RtosTimer has been superseded by the EventQueue. See RtosTimer.h for more details") + RtosTimer(void (*func)(void const *argument), os_timer_type type = osTimerPeriodic, void *argument = NULL) + { constructor(mbed::callback((void (*)(void *))func, argument), type); } - + /** Create timer. @param func function to be executed by this timer. @param type osTimerOnce for one-shot or osTimerPeriodic for periodic behaviour. (default: osTimerPeriodic) @@ -113,11 +114,12 @@ class RtosTimer : private mbed::NonCopyable { @note You cannot call this function from ISR context. */ MBED_DEPRECATED_SINCE("mbed-os-5.2", - "The RtosTimer has been superseded by the EventQueue. See RtosTimer.h for more details") - RtosTimer(mbed::Callback func, os_timer_type type=osTimerPeriodic) { + "The RtosTimer has been superseded by the EventQueue. See RtosTimer.h for more details") + RtosTimer(mbed::Callback func, os_timer_type type = osTimerPeriodic) + { constructor(func, type); } - + /** Create timer. @param obj pointer to the object to call the member function on. @param method member function to be executed by this timer. @@ -132,11 +134,12 @@ class RtosTimer : private mbed::NonCopyable { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "The RtosTimer constructor does not support cv-qualifiers. Replaced by " - "RtosTimer(callback(obj, method), os_timer_type).") + "The RtosTimer constructor does not support cv-qualifiers. Replaced by " + "RtosTimer(callback(obj, method), os_timer_type).") MBED_DEPRECATED_SINCE("mbed-os-5.2", - "The RtosTimer has been superseded by the EventQueue. See RtosTimer.h for more details") - RtosTimer(T *obj, M method, os_timer_type type=osTimerPeriodic) { + "The RtosTimer has been superseded by the EventQueue. See RtosTimer.h for more details") + RtosTimer(T *obj, M method, os_timer_type type = osTimerPeriodic) + { constructor(mbed::callback(obj, method), type); } diff --git a/rtos/Semaphore.cpp b/rtos/Semaphore.cpp index 4e7bcb3744e..ed1433c30d1 100644 --- a/rtos/Semaphore.cpp +++ b/rtos/Semaphore.cpp @@ -27,15 +27,18 @@ namespace rtos { -Semaphore::Semaphore(int32_t count) { +Semaphore::Semaphore(int32_t count) +{ constructor(count, 0xffff); } -Semaphore::Semaphore(int32_t count, uint16_t max_count) { +Semaphore::Semaphore(int32_t count, uint16_t max_count) +{ constructor(count, max_count); } -void Semaphore::constructor(int32_t count, uint16_t max_count) { +void Semaphore::constructor(int32_t count, uint16_t max_count) +{ memset(&_obj_mem, 0, sizeof(_obj_mem)); osSemaphoreAttr_t attr = { 0 }; attr.cb_mem = &_obj_mem; @@ -44,7 +47,8 @@ void Semaphore::constructor(int32_t count, uint16_t max_count) { MBED_ASSERT(_id != NULL); } -int32_t Semaphore::wait(uint32_t millisec) { +int32_t Semaphore::wait(uint32_t millisec) +{ osStatus_t stat = osSemaphoreAcquire(_id, millisec); switch (stat) { case osOK: @@ -58,7 +62,8 @@ int32_t Semaphore::wait(uint32_t millisec) { } } -int32_t Semaphore::wait_until(uint64_t millisec) { +int32_t Semaphore::wait_until(uint64_t millisec) +{ uint64_t now = Kernel::get_ms_count(); if (now >= millisec) { @@ -71,11 +76,13 @@ int32_t Semaphore::wait_until(uint64_t millisec) { } } -osStatus Semaphore::release(void) { +osStatus Semaphore::release(void) +{ return osSemaphoreRelease(_id); } -Semaphore::~Semaphore() { +Semaphore::~Semaphore() +{ osSemaphoreDelete(_id); } diff --git a/rtos/Semaphore.h b/rtos/Semaphore.h index 4584792290b..0bcd788de9e 100644 --- a/rtos/Semaphore.h +++ b/rtos/Semaphore.h @@ -49,7 +49,7 @@ class Semaphore : private mbed::NonCopyable { @note You cannot call this function from ISR context. */ - Semaphore(int32_t count=0); + Semaphore(int32_t count = 0); /** Create and Initialize a Semaphore object used for managing resources. @param count number of available resources @@ -65,7 +65,7 @@ class Semaphore : private mbed::NonCopyable { @note You may call this function from ISR context if the millisec parameter is set to 0. */ - int32_t wait(uint32_t millisec=osWaitForever); + int32_t wait(uint32_t millisec = osWaitForever); /** Wait until a Semaphore resource becomes available. @param millisec absolute timeout time, referenced to Kernel::get_ms_count() diff --git a/rtos/TARGET_CORTEX/SysTimer.cpp b/rtos/TARGET_CORTEX/SysTimer.cpp index fc2e06bc363..00d1ad45015 100644 --- a/rtos/TARGET_CORTEX/SysTimer.cpp +++ b/rtos/TARGET_CORTEX/SysTimer.cpp @@ -42,7 +42,7 @@ namespace rtos { namespace internal { SysTimer::SysTimer() : - TimerEvent(get_lp_ticker_data()), _start_time(0), _tick(0) + TimerEvent(get_lp_ticker_data()), _start_time(0), _tick(0) { _start_time = ticker_read_us(_ticker_data); } diff --git a/rtos/TARGET_CORTEX/TARGET_CORTEX_M/mbed_rtx_fault_handler.c b/rtos/TARGET_CORTEX/TARGET_CORTEX_M/mbed_rtx_fault_handler.c index 4cb3762b1d6..115a7ee7e18 100644 --- a/rtos/TARGET_CORTEX/TARGET_CORTEX_M/mbed_rtx_fault_handler.c +++ b/rtos/TARGET_CORTEX/TARGET_CORTEX_M/mbed_rtx_fault_handler.c @@ -39,51 +39,51 @@ extern serial_t stdio_uart; //This is a handler function called from Fault handler to print the error information out. //This runs in fault context and uses special functions(defined in mbed_rtx_fault_handler.c) to print the information without using C-lib support. -__NO_RETURN void mbed_fault_handler (uint32_t fault_type, void *mbed_fault_context_in, void *osRtxInfoIn) +__NO_RETURN void mbed_fault_handler(uint32_t fault_type, void *mbed_fault_context_in, void *osRtxInfoIn) { fault_print_init(); - fault_print_str("\n++ MbedOS Fault Handler ++\n\nFaultType: ",NULL); - - switch( fault_type ) { - case HARD_FAULT_EXCEPTION: - fault_print_str("HardFault",NULL); - break; - case MEMMANAGE_FAULT_EXCEPTION: - fault_print_str("MemManageFault",NULL); - break; - case BUS_FAULT_EXCEPTION: - fault_print_str("BusFault",NULL); - break; - case USAGE_FAULT_EXCEPTION: - fault_print_str("UsageFault",NULL); - break; - default: - fault_print_str("Unknown Fault",NULL); - break; + fault_print_str("\n++ MbedOS Fault Handler ++\n\nFaultType: ", NULL); + + switch (fault_type) { + case HARD_FAULT_EXCEPTION: + fault_print_str("HardFault", NULL); + break; + case MEMMANAGE_FAULT_EXCEPTION: + fault_print_str("MemManageFault", NULL); + break; + case BUS_FAULT_EXCEPTION: + fault_print_str("BusFault", NULL); + break; + case USAGE_FAULT_EXCEPTION: + fault_print_str("UsageFault", NULL); + break; + default: + fault_print_str("Unknown Fault", NULL); + break; } - fault_print_str("\n\nContext:",NULL); + fault_print_str("\n\nContext:", NULL); print_context_info(); - - fault_print_str("\n\nThread Info:\nCurrent:",NULL); + + fault_print_str("\n\nThread Info:\nCurrent:", NULL); print_thread(((osRtxInfo_t *)osRtxInfoIn)->thread.run.curr); - - fault_print_str("\nNext:",NULL); + + fault_print_str("\nNext:", NULL); print_thread(((osRtxInfo_t *)osRtxInfoIn)->thread.run.next); - - fault_print_str("\nWait Threads:",NULL); + + fault_print_str("\nWait Threads:", NULL); osRtxThread_t *threads = ((osRtxInfo_t *)osRtxInfoIn)->thread.wait_list; print_threads_info(threads); - - fault_print_str("\nDelay Threads:",NULL); + + fault_print_str("\nDelay Threads:", NULL); threads = ((osRtxInfo_t *)osRtxInfoIn)->thread.delay_list; print_threads_info(threads); - - fault_print_str("\nIdle Thread:",NULL); + + fault_print_str("\nIdle Thread:", NULL); threads = ((osRtxInfo_t *)osRtxInfoIn)->thread.idle; print_threads_info(threads); - - fault_print_str("\n\n-- MbedOS Fault Handler --\n\n",NULL); - + + fault_print_str("\n\n-- MbedOS Fault Handler --\n\n", NULL); + /* Just spin here, we have already crashed */ for (;;) {} } @@ -91,33 +91,33 @@ __NO_RETURN void mbed_fault_handler (uint32_t fault_type, void *mbed_fault_conte void print_context_info() { //Context Regs - fault_print_str( "\nR0 : %" - "\nR1 : %" - "\nR2 : %" - "\nR3 : %" - "\nR4 : %" - "\nR5 : %" - "\nR6 : %" - "\nR7 : %" - "\nR8 : %" - "\nR9 : %" - "\nR10 : %" - "\nR11 : %" - "\nR12 : %" - "\nSP : %" - "\nLR : %" - "\nPC : %" - "\nxPSR : %" - "\nPSP : %" + fault_print_str("\nR0 : %" + "\nR1 : %" + "\nR2 : %" + "\nR3 : %" + "\nR4 : %" + "\nR5 : %" + "\nR6 : %" + "\nR7 : %" + "\nR8 : %" + "\nR9 : %" + "\nR10 : %" + "\nR11 : %" + "\nR12 : %" + "\nSP : %" + "\nLR : %" + "\nPC : %" + "\nxPSR : %" + "\nPSP : %" "\nMSP : %", (uint32_t *)&mbed_fault_context); - + //Capture CPUID to get core/cpu info - fault_print_str("\nCPUID: %",(uint32_t *)&SCB->CPUID); - + fault_print_str("\nCPUID: %", (uint32_t *)&SCB->CPUID); + #if !defined(TARGET_M0) && !defined(TARGET_M0P) //Capture fault information registers to infer the cause of exception uint32_t FSR[7] = {0}; - + FSR[0] = SCB->HFSR; //Split/Capture CFSR into MMFSR, BFSR, UFSR FSR[1] = 0xFF & SCB->CFSR;//MMFSR @@ -132,45 +132,45 @@ void print_context_info() "\nUFSR : %" "\nDFSR : %" "\nAFSR : %" - "\nSHCSR: %",FSR); - + "\nSHCSR: %", FSR); + //Print MMFAR only if its valid as indicated by MMFSR - if(FSR[1] & 0x80) { - fault_print_str("\nMMFAR: %",(uint32_t *)&SCB->MMFAR); + if (FSR[1] & 0x80) { + fault_print_str("\nMMFAR: %", (uint32_t *)&SCB->MMFAR); } //Print BFAR only if its valid as indicated by BFSR - if(FSR[2] & 0x80) { - fault_print_str("\nBFAR : %",(uint32_t *)&SCB->BFAR); + if (FSR[2] & 0x80) { + fault_print_str("\nBFAR : %", (uint32_t *)&SCB->BFAR); } #endif //Print Mode - if(mbed_fault_context.EXC_RETURN & 0x8) { + if (mbed_fault_context.EXC_RETURN & 0x8) { fault_print_str("\nMode : Thread", NULL); //Print Priv level in Thread mode - We capture CONTROL reg which reflects the privilege. - //Note that the CONTROL register captured still reflects the privilege status of the + //Note that the CONTROL register captured still reflects the privilege status of the //thread mode eventhough we are in Handler mode by the time we capture it. - if(mbed_fault_context.CONTROL & 0x1) { - fault_print_str("\nPriv : User", NULL); + if (mbed_fault_context.CONTROL & 0x1) { + fault_print_str("\nPriv : User", NULL); } else { - fault_print_str("\nPriv : Privileged", NULL); - } + fault_print_str("\nPriv : Privileged", NULL); + } } else { - fault_print_str("\nMode : Handler", NULL); - fault_print_str("\nPriv : Privileged", NULL); + fault_print_str("\nMode : Handler", NULL); + fault_print_str("\nPriv : Privileged", NULL); } //Print Return Stack - if(mbed_fault_context.EXC_RETURN & 0x4) { - fault_print_str("\nStack: PSP", NULL); + if (mbed_fault_context.EXC_RETURN & 0x4) { + fault_print_str("\nStack: PSP", NULL); } else { - fault_print_str("\nStack: MSP", NULL); + fault_print_str("\nStack: MSP", NULL); } } /* Prints thread info from a list */ void print_threads_info(osRtxThread_t *threads) { - while(threads != NULL) { - print_thread( threads ); + while (threads != NULL) { + print_thread(threads); threads = threads->thread_next; } } @@ -180,11 +180,11 @@ void print_thread(osRtxThread_t *thread) { uint32_t data[5]; - data[0]=thread->state; - data[1]=thread->thread_addr; - data[2]=thread->stack_size; - data[3]=(uint32_t)thread->stack_mem; - data[4]=thread->sp; + data[0] = thread->state; + data[1] = thread->thread_addr; + data[2] = thread->stack_size; + data[3] = (uint32_t)thread->stack_mem; + data[4] = thread->sp; fault_print_str("\nState: % EntryFn: % Stack Size: % Mem: % SP: %", data); } @@ -195,12 +195,12 @@ void fault_print_init() if (!stdio_uart_inited) { serial_init(&stdio_uart, STDIO_UART_TX, STDIO_UART_RX); } -#endif +#endif } -/* Limited print functionality which prints the string out to -stdout/uart without using stdlib by directly calling serial-api -and also uses less resources +/* Limited print functionality which prints the string out to +stdout/uart without using stdlib by directly calling serial-api +and also uses less resources The fmtstr contains the format string for printing and for every % found in that it fetches a uint32 value from values buffer and prints it in hex format. @@ -211,12 +211,12 @@ void fault_print_str(char *fmtstr, uint32_t *values) int i = 0; int idx = 0; int vidx = 0; - char hex_str[9]={0}; - - while(fmtstr[i] != '\0') { - if(fmtstr[i]=='%') { - hex_to_str(values[vidx++],hex_str); - for(idx=7; idx>=0; idx--) { + char hex_str[9] = {0}; + + while (fmtstr[i] != '\0') { + if (fmtstr[i] == '%') { + hex_to_str(values[vidx++], hex_str); + for (idx = 7; idx >= 0; idx--) { serial_putc(&stdio_uart, hex_str[idx]); } } else { @@ -224,7 +224,7 @@ void fault_print_str(char *fmtstr, uint32_t *values) } i++; } -#endif +#endif } /* Converts a uint32 to hex char string */ @@ -232,11 +232,13 @@ void hex_to_str(uint32_t value, char *hex_str) { char hex_char_map[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; int i = 0; - + //Return without converting if hex_str is not provided - if(hex_str == NULL) return; - - for(i=7; i>=0; i--) { + if (hex_str == NULL) { + return; + } + + for (i = 7; i >= 0; i--) { hex_str[i] = hex_char_map[(value & (0xf << (i * 4))) >> (i * 4)]; } } diff --git a/rtos/TARGET_CORTEX/TARGET_CORTEX_M/mbed_rtx_fault_handler.h b/rtos/TARGET_CORTEX/TARGET_CORTEX_M/mbed_rtx_fault_handler.h index 54c85c736f1..4ac45c71fa1 100644 --- a/rtos/TARGET_CORTEX/TARGET_CORTEX_M/mbed_rtx_fault_handler.h +++ b/rtos/TARGET_CORTEX/TARGET_CORTEX_M/mbed_rtx_fault_handler.h @@ -18,27 +18,27 @@ //WARNING: DO NOT CHANGE THIS STRUCT WITHOUT MAKING CORRESPONDING CHANGES in except.S files. //Offset of these registers are used by fault handler in except.S typedef struct { - uint32_t R0; - uint32_t R1; - uint32_t R2; - uint32_t R3; - uint32_t R4; - uint32_t R5; - uint32_t R6; - uint32_t R7; - uint32_t R8; - uint32_t R9; - uint32_t R10; - uint32_t R11; - uint32_t R12; - uint32_t SP; - uint32_t LR; - uint32_t PC; - uint32_t xPSR; - uint32_t PSP; - uint32_t MSP; - uint32_t EXC_RETURN; - uint32_t CONTROL; + uint32_t R0; + uint32_t R1; + uint32_t R2; + uint32_t R3; + uint32_t R4; + uint32_t R5; + uint32_t R6; + uint32_t R7; + uint32_t R8; + uint32_t R9; + uint32_t R10; + uint32_t R11; + uint32_t R12; + uint32_t SP; + uint32_t LR; + uint32_t PC; + uint32_t xPSR; + uint32_t PSP; + uint32_t MSP; + uint32_t EXC_RETURN; + uint32_t CONTROL; } mbed_fault_context_t; //Fault type definitions @@ -50,5 +50,5 @@ typedef struct { //This is a handler function called from Fault handler to print the error information out. //This runs in fault context and uses special functions(defined in mbed_rtx_fault_handler.c) to print the information without using C-lib support. -__NO_RETURN void mbed_fault_handler (uint32_t fault_type, void *mbed_fault_context_in, void *osRtxInfoIn); +__NO_RETURN void mbed_fault_handler(uint32_t fault_type, void *mbed_fault_context_in, void *osRtxInfoIn); diff --git a/rtos/TARGET_CORTEX/mbed_boot.c b/rtos/TARGET_CORTEX/mbed_boot.c index 4198b532255..107ad5dba60 100644 --- a/rtos/TARGET_CORTEX/mbed_boot.c +++ b/rtos/TARGET_CORTEX/mbed_boot.c @@ -180,7 +180,7 @@ unsigned char *mbed_stack_isr_start = 0; uint32_t mbed_stack_isr_size = 0; WEAK void mbed_main(void); -void pre_main (void); +void pre_main(void); osThreadAttr_t _main_thread_attr; @@ -201,54 +201,54 @@ osMutexAttr_t singleton_mutex_attr; #if defined(__ICCARM__) && \ (defined(HEAP_START) || defined(HEAP_SIZE) || \ defined(ISR_STACK_START) && defined(ISR_STACK_SIZE)) - #error "No custom layout allowed for IAR. Use .icf file instead" +#error "No custom layout allowed for IAR. Use .icf file instead" #endif #if defined(HEAP_START) && !defined(HEAP_SIZE) - #error "HEAP_SIZE must be defined if HEAP_START is defined" +#error "HEAP_SIZE must be defined if HEAP_START is defined" #endif #if defined(ISR_STACK_START) && !defined(ISR_STACK_SIZE) - #error "ISR_STACK_SIZE must be defined if ISR_STACK_START is defined" +#error "ISR_STACK_SIZE must be defined if ISR_STACK_START is defined" #endif #if defined(HEAP_SIZE) && !defined(HEAP_START) - #error "HEAP_START must be defined if HEAP_SIZE is defined" +#error "HEAP_START must be defined if HEAP_SIZE is defined" #endif /* IAR - INITIAL_SP and HEAP_START ignored as described in Memory layout notes above */ #if !defined(__ICCARM__) && !defined(INITIAL_SP) && !defined(HEAP_START) - #error "no target defined" +#error "no target defined" #endif /* Interrupt stack and heap always defined for IAR * Main thread defined here */ #if defined(__ICCARM__) - #pragma section="CSTACK" - #pragma section="HEAP" - #define HEAP_START ((unsigned char*)__section_begin("HEAP")) - #define HEAP_SIZE ((uint32_t)__section_size("HEAP")) - #define ISR_STACK_START ((unsigned char*)__section_begin("CSTACK")) - #define ISR_STACK_SIZE ((uint32_t)__section_size("CSTACK")) +#pragma section="CSTACK" +#pragma section="HEAP" +#define HEAP_START ((unsigned char*)__section_begin("HEAP")) +#define HEAP_SIZE ((uint32_t)__section_size("HEAP")) +#define ISR_STACK_START ((unsigned char*)__section_begin("CSTACK")) +#define ISR_STACK_SIZE ((uint32_t)__section_size("CSTACK")) #endif /* Define heap region if it has not been defined already */ #if !defined(HEAP_START) - #if defined(__ICCARM__) - #error "Heap should already be defined for IAR" - #elif defined(__CC_ARM) || (defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)) - extern uint32_t Image$$RW_IRAM1$$ZI$$Limit[]; - #define HEAP_START ((unsigned char*)Image$$RW_IRAM1$$ZI$$Limit) - #define HEAP_SIZE ((uint32_t)((uint32_t)INITIAL_SP - (uint32_t)HEAP_START)) - #elif defined(__GNUC__) - extern uint32_t __end__[]; - #define HEAP_START ((unsigned char*)__end__) - #define HEAP_SIZE ((uint32_t)((uint32_t)INITIAL_SP - (uint32_t)HEAP_START)) - #endif +#if defined(__ICCARM__) +#error "Heap should already be defined for IAR" +#elif defined(__CC_ARM) || (defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)) +extern uint32_t Image$$RW_IRAM1$$ZI$$Limit[]; +#define HEAP_START ((unsigned char*)Image$$RW_IRAM1$$ZI$$Limit) +#define HEAP_SIZE ((uint32_t)((uint32_t)INITIAL_SP - (uint32_t)HEAP_START)) +#elif defined(__GNUC__) +extern uint32_t __end__[]; +#define HEAP_START ((unsigned char*)__end__) +#define HEAP_SIZE ((uint32_t)((uint32_t)INITIAL_SP - (uint32_t)HEAP_START)) +#endif #endif /* Define stack sizes if they haven't been set already */ #if !defined(ISR_STACK_SIZE) - #define ISR_STACK_SIZE ((uint32_t)1024) +#define ISR_STACK_SIZE ((uint32_t)1024) #endif /* @@ -258,7 +258,8 @@ osMutexAttr_t singleton_mutex_attr; * -mbed_stack_isr_start * -mbed_stack_isr_size */ -void mbed_set_stack_heap(void) { +void mbed_set_stack_heap(void) +{ unsigned char *free_start = HEAP_START; uint32_t free_size = HEAP_SIZE; @@ -288,7 +289,7 @@ static void mbed_cpy_nvic(void) #if !defined(__CORTEX_M0) && !defined(__CORTEX_A9) #ifdef NVIC_RAM_VECTOR_ADDRESS uint32_t *old_vectors = (uint32_t *)SCB->VTOR; - uint32_t *vectors = (uint32_t*)NVIC_RAM_VECTOR_ADDRESS; + uint32_t *vectors = (uint32_t *)NVIC_RAM_VECTOR_ADDRESS; for (int i = 0; i < NVIC_NUM_VECTORS; i++) { vectors[i] = old_vectors[i]; } @@ -302,7 +303,8 @@ static void mbed_cpy_nvic(void) * mbed_main(), it is not meant for user code, but for the SDK itself to perform * initializations before main() is called. */ -WEAK void mbed_main(void) { +WEAK void mbed_main(void) +{ } @@ -310,7 +312,8 @@ WEAK void mbed_main(void) { * RTX is started. */ void mbed_sdk_init(void); -WEAK void mbed_sdk_init(void) { +WEAK void mbed_sdk_init(void) +{ } void mbed_start_main(void) @@ -335,7 +338,8 @@ void mbed_start_main(void) /* Common for both ARMC and MICROLIB */ int $Super$$main(void); -int $Sub$$main(void) { +int $Sub$$main(void) +{ mbed_main(); return $Super$$main(); } @@ -343,10 +347,11 @@ int $Sub$$main(void) { #if defined (__MICROLIB) /******************** MICROLIB ********************/ int main(void); -void _main_init (void) __attribute__((section(".ARM.Collect$$$$000000FF"))); +void _main_init(void) __attribute__((section(".ARM.Collect$$$$000000FF"))); void $Super$$__cpp_initialize__aeabi_(void); -void _main_init (void) { +void _main_init(void) +{ mbed_set_stack_heap(); /* Copy the vector table to RAM only if uVisor is not in use. */ #if !(defined(FEATURE_UVISOR) && defined(TARGET_UVISOR_SUPPORTED)) @@ -382,10 +387,10 @@ void pre_main() #include extern __value_in_regs struct __argc_argv __rt_lib_init(unsigned heapbase, unsigned heaptop); extern __value_in_regs struct __initial_stackheap __user_setup_stackheap(void); -extern void _platform_post_stackheap_init (void); -extern int main(int argc, char* argv[]); +extern void _platform_post_stackheap_init(void); +extern int main(int argc, char *argv[]); -void pre_main (void) +void pre_main(void) { singleton_mutex_attr.name = "singleton_mutex"; singleton_mutex_attr.attr_bits = osMutexRecursive | osMutexPrioInherit | osMutexRobust; @@ -411,7 +416,8 @@ __asm(".global __use_no_semihosting\n\t"); #endif /* Called by the C library */ -void __rt_entry (void) { +void __rt_entry(void) +{ __user_setup_stackheap(); mbed_set_stack_heap(); /* Copy the vector table to RAM only if uVisor is not in use. */ @@ -438,7 +444,7 @@ typedef void *mutex; #define OS_MUTEX_STATIC_NUM 8 mutex _static_mutexes[OS_MUTEX_STATIC_NUM] = {NULL}; mbed_rtos_storage_mutex_t _static_mutexes_mem[OS_MUTEX_STATIC_NUM] = {NULL}; - + int _mutex_initialize(mutex *m) { osMutexAttr_t attr; @@ -450,7 +456,7 @@ int _mutex_initialize(mutex *m) core_util_critical_section_enter(); for (int i = 0; i < OS_MUTEX_STATIC_NUM; i++) { if (_static_mutexes[i] == NULL) { - _static_mutexes[i] = (mutex)-1; // dummy value to reserve slot + _static_mutexes[i] = (mutex) - 1; // dummy value to reserve slot slot = &_static_mutexes[i]; //Use the static attrs attr.cb_size = sizeof(mbed_rtos_storage_mutex_t); @@ -470,7 +476,7 @@ int _mutex_initialize(mutex *m) /* Mutex pool exhausted, try using HEAP */ attr.cb_size = sizeof(mbed_rtos_storage_mutex_t); - attr.cb_mem = (void*)malloc(attr.cb_size); + attr.cb_mem = (void *)malloc(attr.cb_size); if (attr.cb_mem == NULL) { osRtxErrorNotify(osRtxErrorClibSpace, m); return 0; @@ -485,7 +491,8 @@ int _mutex_initialize(mutex *m) return 1; } -void _mutex_free(mutex *m) { +void _mutex_free(mutex *m) +{ mutex *slot = NULL; core_util_critical_section_enter(); for (int i = 0; i < OS_MUTEX_STATIC_NUM; i++) { @@ -510,8 +517,8 @@ void _mutex_free(mutex *m) { #endif /* ARMC */ #elif defined (__GNUC__) /******************** GCC ********************/ -extern int main(int argc, char* argv[]); -extern void __libc_init_array (void); +extern int main(int argc, char *argv[]); +extern void __libc_init_array(void); extern int __real_main(void); osMutexId_t malloc_mutex_id; @@ -526,7 +533,8 @@ osMutexAttr_t env_mutex_attr; #include "uvisor-lib/uvisor-lib.h" #endif/* FEATURE_UVISOR */ -int __wrap_main(void) { +int __wrap_main(void) +{ mbed_main(); return __real_main(); } @@ -581,22 +589,22 @@ void software_init_hook(void) /* Opaque declaration of _reent structure */ struct _reent; -void __rtos_malloc_lock( struct _reent *_r ) +void __rtos_malloc_lock(struct _reent *_r) { osMutexAcquire(malloc_mutex_id, osWaitForever); } -void __rtos_malloc_unlock( struct _reent *_r ) +void __rtos_malloc_unlock(struct _reent *_r) { osMutexRelease(malloc_mutex_id); } -void __rtos_env_lock( struct _reent *_r ) +void __rtos_env_lock(struct _reent *_r) { osMutexAcquire(env_mutex_id, osWaitForever); } -void __rtos_env_unlock( struct _reent *_r ) +void __rtos_env_unlock(struct _reent *_r) { osMutexRelease(env_mutex_id); } @@ -605,11 +613,11 @@ void __rtos_env_unlock( struct _reent *_r ) #if defined(__ICCARM__) /******************** IAR ********************/ -extern void* __vector_table; +extern void *__vector_table; extern int __low_level_init(void); extern void __iar_data_init3(void); -extern __weak void __iar_init_core( void ); -extern __weak void __iar_init_vfp( void ); +extern __weak void __iar_init_core(void); +extern __weak void __iar_init_vfp(void); extern void __iar_dynamic_initialization(void); extern void mbed_sdk_init(void); extern int main(void); @@ -638,7 +646,7 @@ void pre_main(void) } #pragma required=__vector_table -void __iar_program_start( void ) +void __iar_program_start(void) { __iar_init_core(); __iar_init_vfp(); @@ -649,21 +657,21 @@ void __iar_program_start( void ) if (low_level_init_needed_local) { __iar_data_init3(); - /* Copy the vector table to RAM only if uVisor is not in use. */ + /* Copy the vector table to RAM only if uVisor is not in use. */ #if !(defined(FEATURE_UVISOR) && defined(TARGET_UVISOR_SUPPORTED)) - mbed_cpy_nvic(); + mbed_cpy_nvic(); #endif - mbed_sdk_init(); - } + mbed_sdk_init(); + } - mbed_set_stack_heap(); + mbed_set_stack_heap(); - /* Store in a global variable after RAM has been initialized */ - low_level_init_needed = low_level_init_needed_local; + /* Store in a global variable after RAM has been initialized */ + low_level_init_needed = low_level_init_needed_local; - osKernelInitialize(); + osKernelInitialize(); - mbed_start_main(); + mbed_start_main(); } /* Thread safety */ @@ -684,7 +692,7 @@ void __iar_system_Mtxinit(__iar_Rmtx *mutex) /* Initialize a system lock */ attr.cb_size = sizeof(std_mutex_sys[index]); attr.attr_bits = osMutexRecursive | osMutexPrioInherit | osMutexRobust; std_mutex_id_sys[index] = osMutexNew(&attr); - *mutex = (__iar_Rmtx*)&std_mutex_id_sys[index]; + *mutex = (__iar_Rmtx *)&std_mutex_id_sys[index]; return; } } @@ -695,18 +703,18 @@ void __iar_system_Mtxinit(__iar_Rmtx *mutex) /* Initialize a system lock */ void __iar_system_Mtxdst(__iar_Rmtx *mutex) /* Destroy a system lock */ { - osMutexDelete(*(osMutexId_t*)*mutex); + osMutexDelete(*(osMutexId_t *)*mutex); *mutex = 0; } void __iar_system_Mtxlock(__iar_Rmtx *mutex) /* Lock a system lock */ { - osMutexAcquire(*(osMutexId_t*)*mutex, osWaitForever); + osMutexAcquire(*(osMutexId_t *)*mutex, osWaitForever); } void __iar_system_Mtxunlock(__iar_Rmtx *mutex) /* Unlock a system lock */ { - osMutexRelease(*(osMutexId_t*)*mutex); + osMutexRelease(*(osMutexId_t *)*mutex); } void __iar_file_Mtxinit(__iar_Rmtx *mutex) /* Initialize a file lock */ @@ -720,7 +728,7 @@ void __iar_file_Mtxinit(__iar_Rmtx *mutex) /* Initialize a file lock */ attr.cb_size = sizeof(std_mutex_file[index]); attr.attr_bits = osMutexRecursive | osMutexPrioInherit | osMutexRobust; std_mutex_id_file[index] = osMutexNew(&attr); - *mutex = (__iar_Rmtx*)&std_mutex_id_file[index]; + *mutex = (__iar_Rmtx *)&std_mutex_id_file[index]; return; } } @@ -730,18 +738,18 @@ void __iar_file_Mtxinit(__iar_Rmtx *mutex) /* Initialize a file lock */ void __iar_file_Mtxdst(__iar_Rmtx *mutex) /* Destroy a file lock */ { - osMutexDelete(*(osMutexId_t*)*mutex); + osMutexDelete(*(osMutexId_t *)*mutex); *mutex = 0; } void __iar_file_Mtxlock(__iar_Rmtx *mutex) /* Lock a file lock */ { - osMutexAcquire(*(osMutexId_t*)*mutex, osWaitForever); + osMutexAcquire(*(osMutexId_t *)*mutex, osWaitForever); } void __iar_file_Mtxunlock(__iar_Rmtx *mutex) /* Unlock a file lock */ { - osMutexRelease(*(osMutexId_t*)*mutex); + osMutexRelease(*(osMutexId_t *)*mutex); } #endif diff --git a/rtos/TARGET_CORTEX/mbed_rtx_handlers.c b/rtos/TARGET_CORTEX/mbed_rtx_handlers.c index ebbd3979e30..e877d34ff15 100644 --- a/rtos/TARGET_CORTEX/mbed_rtx_handlers.c +++ b/rtos/TARGET_CORTEX/mbed_rtx_handlers.c @@ -31,47 +31,47 @@ extern void rtos_idle_loop(void); extern void thread_terminate_hook(osThreadId_t id); -__NO_RETURN void osRtxIdleThread (void *argument) +__NO_RETURN void osRtxIdleThread(void *argument) { for (;;) { - rtos_idle_loop(); + rtos_idle_loop(); } } -__NO_RETURN uint32_t osRtxErrorNotify (uint32_t code, void *object_id) +__NO_RETURN uint32_t osRtxErrorNotify(uint32_t code, void *object_id) { osThreadId_t tid = osThreadGetId(); switch (code) { - case osRtxErrorStackUnderflow: - // Stack underflow detected for thread (thread_id=object_id) - // Note: "overflow" is printed instead of "underflow" due to end user familiarity with overflow errors - error("CMSIS-RTOS error: Stack overflow (status: 0x%X, task ID: 0x%X, task name: %s)\n\r", - code, object_id, osThreadGetName(object_id)); - break; - case osRtxErrorISRQueueOverflow: - // ISR Queue overflow detected when inserting object (object_id) - error("CMSIS-RTOS error: ISR Queue overflow (status: 0x%X, task ID: 0x%X, object ID: 0x%X)\n\r", - code, tid, object_id); - break; - case osRtxErrorTimerQueueOverflow: - // User Timer Callback Queue overflow detected for timer (timer_id=object_id) - error("CMSIS-RTOS error: User Timer Callback Queue overflow (status: 0x%X, task ID: 0x%X, timer ID: 0x%X)\n\r", - code, tid, object_id); - break; - case osRtxErrorClibSpace: - // Standard C/C++ library libspace not available: increase OS_THREAD_LIBSPACE_NUM - error("CMSIS-RTOS error: STD C/C++ library libspace not available (status: 0x%X, task ID: 0x%X)\n\r", - code, tid); - break; - case osRtxErrorClibMutex: - // Standard C/C++ library mutex initialization failed - error("CMSIS-RTOS error: STD C/C++ library mutex initialization failed (status: 0x%X, task ID: 0x%X)\n\r", - code, tid); - break; - default: - error("CMSIS-RTOS error: Unknown (status: 0x%X, task ID: 0x%X)\n\r", code, tid); - break; + case osRtxErrorStackUnderflow: + // Stack underflow detected for thread (thread_id=object_id) + // Note: "overflow" is printed instead of "underflow" due to end user familiarity with overflow errors + error("CMSIS-RTOS error: Stack overflow (status: 0x%X, task ID: 0x%X, task name: %s)\n\r", + code, object_id, osThreadGetName(object_id)); + break; + case osRtxErrorISRQueueOverflow: + // ISR Queue overflow detected when inserting object (object_id) + error("CMSIS-RTOS error: ISR Queue overflow (status: 0x%X, task ID: 0x%X, object ID: 0x%X)\n\r", + code, tid, object_id); + break; + case osRtxErrorTimerQueueOverflow: + // User Timer Callback Queue overflow detected for timer (timer_id=object_id) + error("CMSIS-RTOS error: User Timer Callback Queue overflow (status: 0x%X, task ID: 0x%X, timer ID: 0x%X)\n\r", + code, tid, object_id); + break; + case osRtxErrorClibSpace: + // Standard C/C++ library libspace not available: increase OS_THREAD_LIBSPACE_NUM + error("CMSIS-RTOS error: STD C/C++ library libspace not available (status: 0x%X, task ID: 0x%X)\n\r", + code, tid); + break; + case osRtxErrorClibMutex: + // Standard C/C++ library mutex initialization failed + error("CMSIS-RTOS error: STD C/C++ library mutex initialization failed (status: 0x%X, task ID: 0x%X)\n\r", + code, tid); + break; + default: + error("CMSIS-RTOS error: Unknown (status: 0x%X, task ID: 0x%X)\n\r", code, tid); + break; } /* That shouldn't be reached */ @@ -80,52 +80,52 @@ __NO_RETURN uint32_t osRtxErrorNotify (uint32_t code, void *object_id) #if defined(MBED_TRAP_ERRORS_ENABLED) && MBED_TRAP_ERRORS_ENABLED -static const char* error_msg(int32_t status) +static const char *error_msg(int32_t status) { switch (status) { - case osError: - return "Unspecified RTOS error"; - case osErrorTimeout: - return "Operation not completed within the timeout period"; - case osErrorResource: - return "Resource not available"; - case osErrorParameter: - return "Parameter error"; - case osErrorNoMemory: - return "System is out of memory"; - case osErrorISR: - return "Not allowed in ISR context"; - default: - return "Unknown"; + case osError: + return "Unspecified RTOS error"; + case osErrorTimeout: + return "Operation not completed within the timeout period"; + case osErrorResource: + return "Resource not available"; + case osErrorParameter: + return "Parameter error"; + case osErrorNoMemory: + return "System is out of memory"; + case osErrorISR: + return "Not allowed in ISR context"; + default: + return "Unknown"; } } -void EvrRtxKernelError (int32_t status) +void EvrRtxKernelError(int32_t status) { error("Kernel error %i: %s\r\n", status, error_msg(status)); } -void EvrRtxThreadError (osThreadId_t thread_id, int32_t status) +void EvrRtxThreadError(osThreadId_t thread_id, int32_t status) { error("Thread %p error %i: %s\r\n", thread_id, status, error_msg(status)); } -void EvrRtxTimerError (osTimerId_t timer_id, int32_t status) +void EvrRtxTimerError(osTimerId_t timer_id, int32_t status) { error("Timer %p error %i: %s\r\n", timer_id, status, error_msg(status)); } -void EvrRtxEventFlagsError (osEventFlagsId_t ef_id, int32_t status) +void EvrRtxEventFlagsError(osEventFlagsId_t ef_id, int32_t status) { error("Event %p error %i: %s\r\n", ef_id, status, error_msg(status)); } -void EvrRtxMutexError (osMutexId_t mutex_id, int32_t status) +void EvrRtxMutexError(osMutexId_t mutex_id, int32_t status) { error("Mutex %p error %i: %s\r\n", mutex_id, status, error_msg(status)); } -void EvrRtxSemaphoreError (osSemaphoreId_t semaphore_id, int32_t status) +void EvrRtxSemaphoreError(osSemaphoreId_t semaphore_id, int32_t status) { // Ignore semaphore overflow, the count will saturate with a returned error if (status == osRtxErrorSemaphoreCountLimit) { @@ -135,12 +135,12 @@ void EvrRtxSemaphoreError (osSemaphoreId_t semaphore_id, int32_t status) error("Semaphore %p error %i\r\n", semaphore_id, status); } -void EvrRtxMemoryPoolError (osMemoryPoolId_t mp_id, int32_t status) +void EvrRtxMemoryPoolError(osMemoryPoolId_t mp_id, int32_t status) { error("Memory Pool %p error %i\r\n", mp_id, status); } -void EvrRtxMessageQueueError (osMessageQueueId_t mq_id, int32_t status) +void EvrRtxMessageQueueError(osMessageQueueId_t mq_id, int32_t status) { error("Message Queue %p error %i\r\n", mq_id, status); } @@ -148,7 +148,7 @@ void EvrRtxMessageQueueError (osMessageQueueId_t mq_id, int32_t status) #endif // RTX hook which gets called when a thread terminates, using the event function to call hook -void EvrRtxThreadExit (void) +void EvrRtxThreadExit(void) { osThreadId_t thread_id = osThreadGetId(); thread_terminate_hook(thread_id); @@ -157,7 +157,7 @@ void EvrRtxThreadExit (void) #endif } -void EvrRtxThreadTerminate (osThreadId_t thread_id) +void EvrRtxThreadTerminate(osThreadId_t thread_id) { thread_terminate_hook(thread_id); #if (!defined(EVR_RTX_DISABLE) && (OS_EVR_THREAD != 0) && !defined(EVR_RTX_THREAD_TERMINATE_DISABLE) && defined(RTE_Compiler_EventRecorder)) diff --git a/rtos/TARGET_CORTEX/mbed_rtx_idle.cpp b/rtos/TARGET_CORTEX/mbed_rtx_idle.cpp index 6e568e415c0..cc4a5f89bfc 100644 --- a/rtos/TARGET_CORTEX/mbed_rtx_idle.cpp +++ b/rtos/TARGET_CORTEX/mbed_rtx_idle.cpp @@ -42,7 +42,7 @@ static rtos::internal::SysTimer *os_timer; static uint64_t os_timer_data[sizeof(rtos::internal::SysTimer) / 8]; /// Enable System Timer. -int32_t OS_Tick_Enable (void) +int32_t OS_Tick_Enable(void) { // Do not use SingletonPtr since this relies on the RTOS if (NULL == os_timer) { @@ -57,7 +57,7 @@ int32_t OS_Tick_Enable (void) } /// Disable System Timer. -int32_t OS_Tick_Disable (void) +int32_t OS_Tick_Disable(void) { os_timer->cancel_tick(); @@ -65,7 +65,7 @@ int32_t OS_Tick_Disable (void) } /// Acknowledge System Timer IRQ. -int32_t OS_Tick_AcknowledgeIRQ (void) +int32_t OS_Tick_AcknowledgeIRQ(void) { os_timer->schedule_tick(); @@ -73,24 +73,27 @@ int32_t OS_Tick_AcknowledgeIRQ (void) } /// Get System Timer count. -uint32_t OS_Tick_GetCount (void) +uint32_t OS_Tick_GetCount(void) { return os_timer->get_time() & 0xFFFFFFFF; } // Get OS Tick IRQ number. -int32_t OS_Tick_GetIRQn (void) { - return -1; +int32_t OS_Tick_GetIRQn(void) +{ + return -1; } // Get OS Tick overflow status. -uint32_t OS_Tick_GetOverflow (void) { - return 0; +uint32_t OS_Tick_GetOverflow(void) +{ + return 0; } // Get OS Tick interval. -uint32_t OS_Tick_GetInterval (void) { - return 1000; +uint32_t OS_Tick_GetInterval(void) +{ + return 1000; } static void default_idle_hook(void) diff --git a/rtos/Thread.cpp b/rtos/Thread.cpp index 70e20e3d12d..8360f39e026 100644 --- a/rtos/Thread.cpp +++ b/rtos/Thread.cpp @@ -44,7 +44,8 @@ extern "C" void thread_terminate_hook(osThreadId_t id) namespace rtos { void Thread::constructor(osPriority priority, - uint32_t stack_size, unsigned char *stack_mem, const char *name) { + uint32_t stack_size, unsigned char *stack_mem, const char *name) +{ const uintptr_t unaligned_mem = reinterpret_cast(stack_mem); const uintptr_t aligned_mem = ALIGN_UP(unaligned_mem, 8); @@ -59,11 +60,12 @@ void Thread::constructor(osPriority priority, _attr.priority = priority; _attr.stack_size = aligned_size; _attr.name = name ? name : "application_unnamed_thread"; - _attr.stack_mem = reinterpret_cast(aligned_mem); + _attr.stack_mem = reinterpret_cast(aligned_mem); } void Thread::constructor(Callback task, - osPriority priority, uint32_t stack_size, unsigned char *stack_mem, const char *name) { + osPriority priority, uint32_t stack_size, unsigned char *stack_mem, const char *name) +{ constructor(priority, stack_size, stack_mem, name); switch (start(task)) { @@ -80,7 +82,8 @@ void Thread::constructor(Callback task, } } -osStatus Thread::start(Callback task) { +osStatus Thread::start(Callback task) +{ _mutex.lock(); if ((_tid != 0) || _finished) { @@ -89,7 +92,7 @@ osStatus Thread::start(Callback task) { } if (_attr.stack_mem == NULL) { - _attr.stack_mem = new uint32_t[_attr.stack_size/sizeof(uint32_t)]; + _attr.stack_mem = new uint32_t[_attr.stack_size / sizeof(uint32_t)]; MBED_ASSERT(_attr.stack_mem != NULL); } @@ -105,8 +108,8 @@ osStatus Thread::start(Callback task) { _tid = osThreadNew(Thread::_thunk, this, &_attr); if (_tid == NULL) { if (_dynamic_stack) { - delete[] (uint32_t *)(_attr.stack_mem); - _attr.stack_mem = (uint32_t*)NULL; + delete[](uint32_t *)(_attr.stack_mem); + _attr.stack_mem = (uint32_t *)NULL; } _mutex.unlock(); _join_sem.release(); @@ -117,7 +120,8 @@ osStatus Thread::start(Callback task) { return osOK; } -osStatus Thread::terminate() { +osStatus Thread::terminate() +{ osStatus_t ret = osOK; _mutex.lock(); @@ -139,7 +143,8 @@ osStatus Thread::terminate() { return ret; } -osStatus Thread::join() { +osStatus Thread::join() +{ int32_t ret = _join_sem.wait(); if (ret < 0) { return osError; @@ -157,7 +162,8 @@ osStatus Thread::join() { return osOK; } -osStatus Thread::set_priority(osPriority priority) { +osStatus Thread::set_priority(osPriority priority) +{ osStatus_t ret; _mutex.lock(); @@ -167,7 +173,8 @@ osStatus Thread::set_priority(osPriority priority) { return ret; } -osPriority Thread::get_priority() { +osPriority Thread::get_priority() +{ osPriority_t ret; _mutex.lock(); @@ -177,11 +184,13 @@ osPriority Thread::get_priority() { return ret; } -int32_t Thread::signal_set(int32_t flags) { +int32_t Thread::signal_set(int32_t flags) +{ return osThreadFlagsSet(_tid, flags); } -Thread::State Thread::get_state() { +Thread::State Thread::get_state() +{ uint8_t state = osThreadTerminated; _mutex.lock(); @@ -198,7 +207,7 @@ Thread::State Thread::get_state() { State user_state; - switch(state) { + switch (state) { case osThreadInactive: user_state = Inactive; break; @@ -246,7 +255,8 @@ Thread::State Thread::get_state() { return user_state; } -uint32_t Thread::stack_size() { +uint32_t Thread::stack_size() +{ uint32_t size = 0; _mutex.lock(); @@ -258,7 +268,8 @@ uint32_t Thread::stack_size() { return size; } -uint32_t Thread::free_stack() { +uint32_t Thread::free_stack() +{ uint32_t size = 0; _mutex.lock(); @@ -273,7 +284,8 @@ uint32_t Thread::free_stack() { return size; } -uint32_t Thread::used_stack() { +uint32_t Thread::used_stack() +{ uint32_t size = 0; _mutex.lock(); @@ -288,7 +300,8 @@ uint32_t Thread::used_stack() { return size; } -uint32_t Thread::max_stack() { +uint32_t Thread::max_stack() +{ uint32_t size = 0; _mutex.lock(); @@ -296,8 +309,9 @@ uint32_t Thread::max_stack() { #if defined(MBED_OS_BACKEND_RTX5) os_thread_t *thread = (os_thread_t *)_tid; uint32_t high_mark = 0; - while (((uint32_t *)(thread->stack_mem))[high_mark] == 0xE25A2EA5) + while (((uint32_t *)(thread->stack_mem))[high_mark] == 0xE25A2EA5) { high_mark++; + } size = thread->stack_size - (high_mark * sizeof(uint32_t)); #else size = osThreadGetStackSize(_tid) - osThreadGetStackSpace(_tid); @@ -308,15 +322,18 @@ uint32_t Thread::max_stack() { return size; } -const char *Thread::get_name() { +const char *Thread::get_name() +{ return _attr.name; } -int32_t Thread::signal_clr(int32_t flags) { +int32_t Thread::signal_clr(int32_t flags) +{ return osThreadFlagsClear(flags); } -osEvent Thread::signal_wait(int32_t signals, uint32_t millisec) { +osEvent Thread::signal_wait(int32_t signals, uint32_t millisec) +{ uint32_t res; osEvent evt; uint32_t options = osFlagsWaitAll; @@ -349,11 +366,13 @@ osEvent Thread::signal_wait(int32_t signals, uint32_t millisec) { return evt; } -osStatus Thread::wait(uint32_t millisec) { +osStatus Thread::wait(uint32_t millisec) +{ return osDelay(millisec); } -osStatus Thread::wait_until(uint64_t millisec) { +osStatus Thread::wait_until(uint64_t millisec) +{ // CMSIS-RTOS 2.1.0 and 2.1.1 differ in the time type, which we determine // by looking at the return type of osKernelGetTickCount. We assume // our header at least matches the implementation, so we don't try looking @@ -382,34 +401,39 @@ osStatus Thread::wait_until(uint64_t millisec) { } } -osStatus Thread::yield() { +osStatus Thread::yield() +{ return osThreadYield(); } -osThreadId Thread::gettid() { +osThreadId Thread::gettid() +{ return osThreadGetId(); } -void Thread::attach_idle_hook(void (*fptr)(void)) { +void Thread::attach_idle_hook(void (*fptr)(void)) +{ rtos_attach_idle_hook(fptr); } -void Thread::attach_terminate_hook(void (*fptr)(osThreadId_t id)) { +void Thread::attach_terminate_hook(void (*fptr)(osThreadId_t id)) +{ terminate_hook = fptr; } -Thread::~Thread() { +Thread::~Thread() +{ // terminate is thread safe terminate(); if (_dynamic_stack) { - delete[] (uint32_t*)(_attr.stack_mem); - _attr.stack_mem = (uint32_t*)NULL; + delete[](uint32_t *)(_attr.stack_mem); + _attr.stack_mem = (uint32_t *)NULL; } } -void Thread::_thunk(void * thread_ptr) +void Thread::_thunk(void *thread_ptr) { - Thread *t = (Thread*)thread_ptr; + Thread *t = (Thread *)thread_ptr; t->_task(); t->_mutex.lock(); t->_tid = (osThreadId)NULL; diff --git a/rtos/Thread.h b/rtos/Thread.h index ce245dcc63d..588f21e5d4f 100644 --- a/rtos/Thread.h +++ b/rtos/Thread.h @@ -83,9 +83,10 @@ class Thread : private mbed::NonCopyable { @note You cannot call this function from ISR context. */ - Thread(osPriority priority=osPriorityNormal, - uint32_t stack_size=OS_STACK_SIZE, - unsigned char *stack_mem=NULL, const char *name=NULL) { + Thread(osPriority priority = osPriorityNormal, + uint32_t stack_size = OS_STACK_SIZE, + unsigned char *stack_mem = NULL, const char *name = NULL) + { constructor(priority, stack_size, stack_mem, name); } @@ -109,12 +110,13 @@ class Thread : private mbed::NonCopyable { @note You cannot call this function from ISR context. */ MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Thread-spawning constructors hide errors. " - "Replaced by thread.start(task).") + "Thread-spawning constructors hide errors. " + "Replaced by thread.start(task).") Thread(mbed::Callback task, - osPriority priority=osPriorityNormal, - uint32_t stack_size=OS_STACK_SIZE, - unsigned char *stack_mem=NULL) { + osPriority priority = osPriorityNormal, + uint32_t stack_size = OS_STACK_SIZE, + unsigned char *stack_mem = NULL) + { constructor(task, priority, stack_size, stack_mem); } @@ -140,12 +142,13 @@ class Thread : private mbed::NonCopyable { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Thread-spawning constructors hide errors. " - "Replaced by thread.start(callback(task, argument)).") + "Thread-spawning constructors hide errors. " + "Replaced by thread.start(callback(task, argument)).") Thread(T *argument, void (T::*task)(), - osPriority priority=osPriorityNormal, - uint32_t stack_size=OS_STACK_SIZE, - unsigned char *stack_mem=NULL) { + osPriority priority = osPriorityNormal, + uint32_t stack_size = OS_STACK_SIZE, + unsigned char *stack_mem = NULL) + { constructor(mbed::callback(task, argument), priority, stack_size, stack_mem); } @@ -172,12 +175,13 @@ class Thread : private mbed::NonCopyable { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Thread-spawning constructors hide errors. " - "Replaced by thread.start(callback(task, argument)).") + "Thread-spawning constructors hide errors. " + "Replaced by thread.start(callback(task, argument)).") Thread(T *argument, void (*task)(T *), - osPriority priority=osPriorityNormal, - uint32_t stack_size=OS_STACK_SIZE, - unsigned char *stack_mem=NULL) { + osPriority priority = osPriorityNormal, + uint32_t stack_size = OS_STACK_SIZE, + unsigned char *stack_mem = NULL) + { constructor(mbed::callback(task, argument), priority, stack_size, stack_mem); } @@ -204,12 +208,13 @@ class Thread : private mbed::NonCopyable { @note You cannot call this function from ISR context. */ MBED_DEPRECATED_SINCE("mbed-os-5.1", - "Thread-spawning constructors hide errors. " - "Replaced by thread.start(callback(task, argument)).") - Thread(void (*task)(void const *argument), void *argument=NULL, - osPriority priority=osPriorityNormal, - uint32_t stack_size=OS_STACK_SIZE, - unsigned char *stack_mem=NULL) { + "Thread-spawning constructors hide errors. " + "Replaced by thread.start(callback(task, argument)).") + Thread(void (*task)(void const *argument), void *argument = NULL, + osPriority priority = osPriorityNormal, + uint32_t stack_size = OS_STACK_SIZE, + unsigned char *stack_mem = NULL) + { constructor(mbed::callback((void (*)(void *))task, argument), priority, stack_size, stack_mem); } @@ -234,9 +239,10 @@ class Thread : private mbed::NonCopyable { */ template MBED_DEPRECATED_SINCE("mbed-os-5.1", - "The start function does not support cv-qualifiers. " - "Replaced by thread.start(callback(obj, method)).") - osStatus start(T *obj, M method) { + "The start function does not support cv-qualifiers. " + "Replaced by thread.start(callback(obj, method)).") + osStatus start(T *obj, M method) + { return start(mbed::callback(obj, method)); } @@ -307,28 +313,28 @@ class Thread : private mbed::NonCopyable { @note You cannot call this function from ISR context. */ State get_state(); - + /** Get the total stack memory size for this Thread @return the total stack memory size in bytes @note You cannot call this function from ISR context. */ uint32_t stack_size(); - + /** Get the currently unused stack memory for this Thread @return the currently unused stack memory in bytes @note You cannot call this function from ISR context. */ uint32_t free_stack(); - + /** Get the currently used stack memory for this Thread @return the currently used stack memory in bytes @note You cannot call this function from ISR context. */ uint32_t used_stack(); - + /** Get the maximum stack memory usage to date for this Thread @return the maximum stack memory usage to date in bytes @@ -358,7 +364,7 @@ class Thread : private mbed::NonCopyable { @note You cannot call this function from ISR context. */ - static osEvent signal_wait(int32_t signals, uint32_t millisec=osWaitForever); + static osEvent signal_wait(int32_t signals, uint32_t millisec = osWaitForever); /** Wait for a specified time period in milliseconds Being tick-based, the delay will be up to the specified time - eg for @@ -424,16 +430,16 @@ class Thread : private mbed::NonCopyable { private: // Required to share definitions without // delegated constructors - void constructor(osPriority priority=osPriorityNormal, - uint32_t stack_size=OS_STACK_SIZE, - unsigned char *stack_mem=NULL, - const char *name=NULL); + void constructor(osPriority priority = osPriorityNormal, + uint32_t stack_size = OS_STACK_SIZE, + unsigned char *stack_mem = NULL, + const char *name = NULL); void constructor(mbed::Callback task, - osPriority priority=osPriorityNormal, - uint32_t stack_size=OS_STACK_SIZE, - unsigned char *stack_mem=NULL, - const char *name=NULL); - static void _thunk(void * thread_ptr); + osPriority priority = osPriorityNormal, + uint32_t stack_size = OS_STACK_SIZE, + unsigned char *stack_mem = NULL, + const char *name = NULL); + static void _thunk(void *thread_ptr); mbed::Callback _task; osThreadId_t _tid; diff --git a/rtos/rtos_idle.h b/rtos/rtos_idle.h index c2894c23e30..0d2256182d4 100644 --- a/rtos/rtos_idle.h +++ b/rtos/rtos_idle.h @@ -35,7 +35,7 @@ extern "C" { * \defgroup rtos_Idle Idle hook function * @{ */ -/** +/** @note Sets the hook function called by idle task @param fptr Hook function pointer.